/* Live events while pic runs: Pi's JSON mode shapes, or streamed text. */ #include #include #include #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; } static void auto_retry_end(pic_events *e, int success, const char *error) { if (!e->retrying) { return; } if (e->json) { fprintf(e->out, "{\"type\":\"auto_retry_end\",\"success\":%s,\"attempt\":%d", success ? "true" : "false", e->retrying); if (!success && error) { fputs(",\"finalError\":", e->out); js(e->out, error); } fputc('}', e->out); line_end(e); } e->retrying = 0; } static void sum_retry_finished(pic_events *e) { if (!e->sum_retrying) { return; } if (e->json) { fputs("{\"type\":\"summarization_retry_finished\"}", e->out); line_end(e); } e->sum_retrying = 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; e->retrying = 0; e->sum_active = 0; e->sum_retrying = 0; e->sum_source[0] = '\0'; e->sum_reason[0] = '\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); sum_retry_finished(e); e->sum_active = 0; auto_retry_end(e, 0, error ? error : "Retry cancelled"); 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); } auto_retry_end(e, 1, NULL); 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); e->retrying = attempt + 1; } else { auto_retry_end(e, 0, strcmp(stop, "aborted") == 0 ? "Retry cancelled" : error); } } 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); if (!will_retry) { e->retrying = 0; } } 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); } /* Pi's parentToolCallId: the call a nested call was made by (NULL: the model's own call). */ static void parent_field(FILE *out, const char *parent) { if (parent) { fputs(",\"parentToolCallId\":", out); js(out, parent); } } static void ev_tool_start(pic_store *s, const char *call_id, const char *tool, const char *args_json, const char *summary, const char *parent) { 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); parent_field(e->out, parent); 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_start(pic_store *s, const char *call_id, const char *tool, const char *args_json, const char *summary) { ev_tool_start(s, call_id, tool, args_json, summary, NULL); } void pic_ev_nested_start(pic_store *s, const char *call_id, const char *tool, const char *args_json, const char *parent) { ev_tool_start(s, call_id, tool, args_json, NULL, parent); } static void ev_tool_update(pic_store *s, const char *call_id, const char *tool, const char *args_json, const char *text, const char *parent) { 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); parent_field(e->out, parent); fputc('}', e->out); line_end(e); } void pic_ev_tool_update(pic_store *s, const char *call_id, const char *tool, const char *args_json, const char *text) { ev_tool_update(s, call_id, tool, args_json, text, NULL); } void pic_ev_nested_update(pic_store *s, const char *call_id, const char *tool, const char *args_json, const char *text, const char *parent) { ev_tool_update(s, call_id, tool, args_json, text, parent); } /* 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) { return; } if (e->sum_active) { pic_ev_summarization_retry_scheduled(s, attempt, max_attempts, delay_ms, error); return; } if (!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); e->retrying = attempt; } void pic_ev_summarization_begin(pic_store *s, const char *source, const char *reason) { pic_events *e = s->events; if (!e) { return; } e->sum_active = 1; (void)snprintf(e->sum_source, sizeof e->sum_source, "%s", source ? source : ""); (void)snprintf(e->sum_reason, sizeof e->sum_reason, "%s", reason ? reason : ""); } void pic_ev_summarization_retry_scheduled(pic_store *s, int attempt, int max_attempts, long delay_ms, const char *error) { pic_events *e = s->events; if (!e) { return; } e->sum_retrying = 1; if (!e->json) { return; } fprintf(e->out, "{\"type\":\"summarization_retry_scheduled\",\"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_retry_attempt_start(pic_store *s) { pic_events *e = s->events; if (!e || !e->json || !e->sum_active || !e->sum_retrying) { return; } fputs("{\"type\":\"summarization_retry_attempt_start\",\"source\":", e->out); js(e->out, e->sum_source[0] ? e->sum_source : "compaction"); if (strcmp(e->sum_source, "compaction") == 0 && e->sum_reason[0]) { fputs(",\"reason\":", e->out); js(e->out, e->sum_reason); } fputc('}', e->out); line_end(e); } void pic_ev_summarization_end(pic_store *s) { pic_events *e = s->events; if (!e) { return; } sum_retry_finished(e); e->sum_active = 0; } void pic_ev_entry_appended(pic_store *s, const char *entry_json) { pic_events *e = s->events; if (!e || !e->json || !entry_json || !*entry_json) { return; } fputs("{\"type\":\"entry_appended\",\"entry\":", e->out); fputs(entry_json, e->out); fputc('}', e->out); line_end(e); } static void emit_entries(pic_store *s, const char *session, int64_t submission, int64_t after) { pic_events *e = s->events; sqlite3_stmt *q = NULL; sqlite3_int64 cnt = 0; char saved[PIC_ERR_CAP], *arr; if (!e || !e->json || !session || !*session) { return; } if (after > 0) { if (sqlite3_prepare_v2(s->db, "SELECT count(*) FROM pic_entry WHERE seq > ?", -1, &q, NULL) == SQLITE_OK) { sqlite3_bind_int64(q, 1, after); if (sqlite3_step(q) == SQLITE_ROW) { cnt = sqlite3_column_int64(q, 0); } } sqlite3_finalize(q); q = NULL; } else if (submission > 0) { if (sqlite3_prepare_v2(s->db, "SELECT count(*) FROM pic_entry WHERE submission_id = ?", -1, &q, NULL) == SQLITE_OK) { sqlite3_bind_int64(q, 1, submission); if (sqlite3_step(q) == SQLITE_ROW) { cnt = sqlite3_column_int64(q, 0); } } sqlite3_finalize(q); q = NULL; } if (cnt <= 0) { return; } (void)snprintf(saved, sizeof saved, "%s", s->err); arr = pic_pi_entries(s, session, cnt < 1000000 ? (int)cnt + 1 : 0); (void)snprintf(s->err, sizeof s->err, "%s", saved); if (!arr) { return; } if (sqlite3_prepare_v2(s->db, "SELECT j.value FROM json_each(?1) j" " JOIN pic_entry x ON x.seq = CAST(json_extract(j.value, '$.id') AS INTEGER)" " WHERE x.seq > ?2 AND (?3 = 0 OR x.submission_id = ?3) ORDER BY x.seq", -1, &q, NULL) == SQLITE_OK) { sqlite3_bind_text(q, 1, arr, -1, SQLITE_STATIC); sqlite3_bind_int64(q, 2, after); sqlite3_bind_int64(q, 3, submission); while (sqlite3_step(q) == SQLITE_ROW) { pic_ev_entry_appended(s, (const char *)sqlite3_column_text(q, 0)); } } sqlite3_finalize(q); free(arr); } void pic_ev_entries_after(pic_store *s, int64_t submission, int64_t after) { pic_events *e = s->events; sqlite3_stmt *q = NULL; char sid[64] = ""; if (!e || !e->json || submission <= 0) { return; } if (sqlite3_prepare_v2(s->db, "SELECT session_id FROM pic_submission WHERE id = ?", -1, &q, NULL) == SQLITE_OK) { sqlite3_bind_int64(q, 1, submission); if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) { (void)snprintf(sid, sizeof sid, "%s", (const char *)sqlite3_column_text(q, 0)); } } sqlite3_finalize(q); if (sid[0]) { emit_entries(s, sid, submission, after); } } void pic_ev_session_entries_after(pic_store *s, const char *session, int64_t after) { emit_entries(s, session, 0, after); } static void ev_tool_end(pic_store *s, const char *call_id, const char *tool, const char *result, const char *images, int is_error, const char *parent) { 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"); parent_field(e->out, parent); 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) { ev_tool_end(s, call_id, tool, result, images, is_error, NULL); } void pic_ev_nested_end(pic_store *s, const char *call_id, const char *tool, const char *result, int is_error, const char *parent) { ev_tool_end(s, call_id, tool, result, NULL, is_error, parent); } 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); }