/* Live events while pic runs: Pi's JSON mode shapes, or streamed text. */
#include <stdio.h>
#include <string.h>
#include "events.h"
#include "pic.h"
void pic_events_init(pic_events *e, FILE *out, FILE *notes, int json, int stream) {
memset(e, 0, sizeof *e);
e->out = out;
e->notes = notes;
e->json = json;
e->stream = stream;
e->block = -1;
}
/* A JSON string: quotes, backslashes and control characters escaped; other
* bytes, UTF-8 included, pass through. */
static void jstr(FILE *f, const char *s, size_t n) {
static const char hex[] = "0123456789abcdef";
fputc('"', f);
for (size_t i = 0; s && i < n; i++) {
unsigned char c = (unsigned char)s[i];
if (c == '"' || c == '\\') {
fputc('\\', f);
fputc(c, f);
} else if (c == '\n') {
fputs("\\n", f);
} else if (c == '\r') {
fputs("\\r", f);
} else if (c == '\t') {
fputs("\\t", f);
} else if (c < 0x20) {
fprintf(f, "\\u00%c%c", hex[c >> 4], hex[c & 15]);
} else {
fputc(c, f);
}
}
fputc('"', f);
}
static void js(FILE *f, const char *s) { jstr(f, s ? s : "", s ? strlen(s) : 0); }
static void line_end(pic_events *e) {
fputc('\n', e->out);
fflush(e->out);
}
/* Text mode: finish a streamed line before anything else is written. */
static void settle(pic_events *e) {
if (!e->json && e->midline) {
fputc('\n', e->out);
fflush(e->out);
e->midline = 0;
}
}
static void turn_end(pic_events *e) {
if (e->turn_open && e->json) {
fputs("{\"type\":\"turn_end\"}", e->out);
line_end(e);
}
e->turn_open = 0;
}
void pic_ev_agent_start(pic_store *s, const char *request_key, const char *text, const char *images,
const char *conversation, const char *model, long context_window, const char *thinking) {
pic_events *e = s->events;
if (!e) {
return;
}
e->streamed = 0;
if (!e->json) {
return;
}
fputs("{\"type\":\"agent_start\",\"request\":", e->out);
js(e->out, request_key);
fputs(",\"conversation\":", e->out);
js(e->out, conversation);
fputs(",\"model\":", e->out);
js(e->out, model);
fprintf(e->out, ",\"contextWindow\":%ld", context_window);
if (thinking && *thinking) {
fputs(",\"thinkingLevel\":", e->out);
js(e->out, thinking);
}
fputc('}', e->out);
line_end(e);
pic_ev_user_message(s, text, images);
}
/* ",block..." for a JSON array of blocks, nothing for NULL or []. */
static void more_blocks(FILE *out, const char *images) {
size_t n = images ? strlen(images) : 0;
if (n > 2 && images[0] == '[' && images[n - 1] == ']') {
fputc(',', out);
fwrite(images + 1, 1, n - 2, out);
}
}
void pic_ev_user_message(pic_store *s, const char *text, const char *images) { pic_ev_user_message_from(s, text, images, NULL); }
void pic_ev_user_message_from(pic_store *s, const char *text, const char *images, const char *origin) {
pic_events *e = s->events;
if (!e) {
return;
}
if (!e->json) {
if (e->notes) {
settle(e);
fprintf(e->notes, "pic: delivered: %s\n", text);
fflush(e->notes);
}
return;
}
for (int i = 0; i < 2; i++) {
fputs(i ? "{\"type\":\"message_end\"" : "{\"type\":\"message_start\"", e->out);
fputs(",\"message\":{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":", e->out);
js(e->out, text);
fputc('}', e->out);
more_blocks(e->out, images);
fputs("]}", e->out);
if (origin && *origin) {
fputs(",\"origin\":", e->out);
js(e->out, origin);
}
fputc('}', e->out);
line_end(e);
}
}
void pic_ev_line(pic_store *s, const char *json) {
pic_events *e = s->events;
if (!e || !e->json || !json) {
return;
}
fputs(json, e->out);
line_end(e);
}
void pic_ev_agent_end(pic_store *s, const char *request_key, const char *status, const char *error,
const char *stop_reason, const char *verdict) {
pic_events *e = s->events;
if (!e) {
return;
}
settle(e);
turn_end(e);
if (!e->json) {
return;
}
fputs("{\"type\":\"agent_end\",\"messages\":[],\"request\":", e->out);
js(e->out, request_key);
fputs(",\"status\":", e->out);
js(e->out, status);
if (error) {
fputs(",\"errorMessage\":", e->out);
js(e->out, error);
}
if (stop_reason) {
fputs(",\"stopReason\":", e->out);
js(e->out, stop_reason);
}
if (verdict) {
fputs(",\"verdict\":", e->out);
js(e->out, verdict);
}
fputc('}', e->out);
line_end(e);
}
void pic_ev_turn_start(pic_store *s) {
pic_events *e = s->events;
if (!e) {
return;
}
turn_end(e);
e->turn_open = 1;
e->msg_open = 0;
e->block = -1;
if (e->json) {
fputs("{\"type\":\"turn_start\"}", e->out);
line_end(e);
}
}
static void message_start(pic_events *e) {
if (e->msg_open) {
return;
}
e->msg_open = 1;
e->block = -1;
if (e->json) {
fputs("{\"type\":\"message_start\",\"message\":{\"role\":\"assistant\",\"content\":[]}}", e->out);
line_end(e);
}
}
void pic_ev_delta(void *store, int thinking, const char *text, size_t len) {
pic_events *e = ((pic_store *)store)->events;
if (!thinking) {
pic_live_text(store, text, len);
}
if (!e || len == 0) {
return;
}
message_start(e);
if (e->block < 0 || e->thinking != thinking) {
e->block++;
e->thinking = thinking;
}
if (e->json) {
fprintf(e->out, "{\"type\":\"message_update\",\"assistantMessageEvent\":{\"type\":\"%s\",\"contentIndex\":%d,\"delta\":",
thinking ? "thinking_delta" : "text_delta", e->block);
jstr(e->out, text, len);
fputs("}}", e->out);
line_end(e);
} else if (e->stream && !thinking) {
fwrite(text, 1, len, e->out);
fflush(e->out);
e->midline = text[len - 1] != '\n';
e->streamed = 1;
}
}
void pic_ev_message_end(pic_store *s, const char *neutral, const char *stop_reason, const char *provider,
const char *api, const char *model, const char *usage) {
pic_events *e = s->events;
if (!e) {
return;
}
settle(e);
if (e->json) {
message_start(e);
fputs("{\"type\":\"message_end\",\"message\":{\"role\":\"assistant\",\"content\":", e->out);
fputs(neutral && *neutral ? neutral : "[]", e->out);
fputs(",\"stopReason\":", e->out);
js(e->out, stop_reason);
fputs(",\"provider\":", e->out);
js(e->out, provider);
fputs(",\"api\":", e->out);
js(e->out, api);
fputs(",\"model\":", e->out);
js(e->out, model);
if (usage && *usage) {
fputs(",\"usage\":", e->out);
fputs(usage, e->out);
}
fputs("}}", e->out);
line_end(e);
}
e->msg_open = 0;
}
static void message_failed(pic_store *s, const char *stop, const char *error, int attempt, int max_attempts,
int will_retry) {
pic_events *e = s->events;
if (!e) {
return;
}
settle(e);
if (e->json) {
message_start(e);
fprintf(e->out, "{\"type\":\"message_end\",\"message\":{\"role\":\"assistant\",\"content\":[],\"stopReason\":\"%s\","
"\"errorMessage\":",
stop);
js(e->out, error);
fputs("}}", e->out);
line_end(e);
if (will_retry) {
fprintf(e->out, "{\"type\":\"auto_retry_start\",\"attempt\":%d,\"maxAttempts\":%d,\"delayMs\":0,\"errorMessage\":",
attempt + 1, max_attempts);
js(e->out, error);
fputc('}', e->out);
line_end(e);
}
} else if (e->notes) {
fprintf(e->notes, "pic: %s%s\n", error,
will_retry ? (e->streamed ? "; trying again (the reply above is discarded)" : "; trying again") : "");
fflush(e->notes);
}
e->msg_open = 0;
}
void pic_ev_message_error(pic_store *s, const char *error, int attempt, int max_attempts, int will_retry) {
message_failed(s, "error", error, attempt, max_attempts, will_retry);
}
void pic_ev_key_failure(pic_store *s, const char *request_key, const char *provider, const char *credential,
const char *label, const char *state, int status, long long until_ms, const char *error) {
pic_events *e = s->events;
if (!e || !e->json) {
return;
}
settle(e);
fputs("{\"type\":\"key_failure\",\"request\":", e->out);
js(e->out, request_key);
fputs(",\"provider\":", e->out);
js(e->out, provider);
fputs(",\"credential\":", e->out);
js(e->out, credential);
fputs(",\"label\":", e->out);
js(e->out, label);
fputs(",\"state\":", e->out);
js(e->out, state);
fprintf(e->out, ",\"status\":%d", status);
if (until_ms > 0) {
fprintf(e->out, ",\"until\":%lld", until_ms);
}
fputs(",\"errorMessage\":", e->out);
js(e->out, error);
fputc('}', e->out);
line_end(e);
}
void pic_ev_message_aborted(pic_store *s) { message_failed(s, "aborted", "interrupted", 0, 0, 0); }
void pic_ev_tool_start(pic_store *s, const char *call_id, const char *tool, const char *args_json,
const char *summary) {
pic_events *e = s->events;
if (!e) {
return;
}
settle(e);
if (e->json) {
fputs("{\"type\":\"tool_execution_start\",\"toolCallId\":", e->out);
js(e->out, call_id);
fputs(",\"toolName\":", e->out);
js(e->out, tool);
fputs(",\"args\":", e->out);
fputs(args_json && *args_json ? args_json : "{}", e->out);
fputc('}', e->out);
line_end(e);
} else if (e->notes) {
const char *what = summary ? summary : "";
fprintf(e->notes, "-> %s %.*s%s\n", tool, 100, what, strlen(what) > 100 ? "..." : "");
fflush(e->notes);
}
}
void pic_ev_tool_update(pic_store *s, const char *call_id, const char *tool, const char *args_json,
const char *text) {
pic_events *e = s->events;
if (!e || !e->json) {
return;
}
fputs("{\"type\":\"tool_execution_update\",\"toolCallId\":", e->out);
js(e->out, call_id);
fputs(",\"toolName\":", e->out);
js(e->out, tool);
fputs(",\"args\":", e->out);
fputs(args_json && *args_json ? args_json : "{}", e->out);
fputs(",\"partialResult\":{\"content\":[{\"type\":\"text\",\"text\":", e->out);
js(e->out, text);
fputs("}],\"details\":{}}}", e->out);
line_end(e);
}
/* A transport retry about to wait delay_ms. */
void pic_ev_retry_wait(pic_store *s, int attempt, int max_attempts, long delay_ms, const char *error) {
pic_events *e = s->events;
if (!e || !e->json) {
return;
}
fprintf(e->out, "{\"type\":\"auto_retry_start\",\"attempt\":%d,\"maxAttempts\":%d,\"delayMs\":%ld,\"errorMessage\":",
attempt, max_attempts, delay_ms);
js(e->out, error);
fputc('}', e->out);
line_end(e);
}
void pic_ev_tool_end(pic_store *s, const char *call_id, const char *tool, const char *result, const char *images,
int is_error) {
pic_events *e = s->events;
if (!e || !e->json) {
return;
}
fputs("{\"type\":\"tool_execution_end\",\"toolCallId\":", e->out);
js(e->out, call_id);
fputs(",\"toolName\":", e->out);
js(e->out, tool);
fputs(",\"result\":{\"content\":[{\"type\":\"text\",\"text\":", e->out);
js(e->out, result);
fputc('}', e->out);
more_blocks(e->out, images);
fprintf(e->out, "]},\"isError\":%s}", is_error ? "true" : "false");
line_end(e);
}
void pic_ev_compaction_start(pic_store *s, const char *reason, long long tokens) {
pic_events *e = s->events;
if (!e) {
return;
}
settle(e);
if (e->json) {
fputs("{\"type\":\"compaction_start\",\"reason\":", e->out);
js(e->out, reason);
fputc('}', e->out);
line_end(e);
} else if (e->notes) {
fprintf(e->notes, "pic: compacting the conversation (%lld tokens)\n", tokens);
fflush(e->notes);
}
}
void pic_ev_compaction_end(pic_store *s, const char *reason, const char *summary, long long first_kept,
long long tokens_before, const char *error) {
pic_events *e = s->events;
if (!e || !e->json) {
return;
}
fputs("{\"type\":\"compaction_end\",\"reason\":", e->out);
js(e->out, reason);
if (summary) {
fputs(",\"result\":{\"summary\":", e->out);
js(e->out, summary);
fprintf(e->out, ",\"firstKeptEntryId\":\"%lld\",\"tokensBefore\":%lld}", first_kept, tokens_before);
}
fputs(",\"aborted\":false,\"willRetry\":false", e->out);
if (error) {
fputs(",\"errorMessage\":", e->out);
js(e->out, error);
}
fputc('}', e->out);
line_end(e);
}
void pic_ev_note(pic_store *s, const char *text) {
pic_events *e = s->events;
if (!e || e->json || !e->notes) {
return;
}
settle(e);
fprintf(e->notes, "pic: %s\n", text);
fflush(e->notes);
}