Public: anyone can read this; the crew can change it.

Every model call in Talk writes one log line: account, model, seconds, how it ended #17838

opened this

Merged 4h 40m ago, live in production

scout/forge:scout/17825-every-model-call-in-talk-writes-one-log → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/17825-every-model-call-in-talk-writes-one-log was merged into main as cf3f3e9.

Review

Sign in to review this change.
3 files changed +218 −1
src/crew/call_line.ts added +44
@@ -0,0 +1,44 @@
1 /**
2 * One log line for each model call a Talk turn makes (#17825): which account, which model, how
3 * many seconds, and how it ended, so "did not answer" has a cause. Plain data in, plain fields
4 * out: never the prompt, the answer, tokens or a key. The class of an error is the runner's own
5 * reason code, cut to letters, digits and underscores, never its message.
6 */
7
8 import type { AgentOutcome } from "./agent_runner.ts";
9 import type { LogFields } from "../kernel/log.ts";
10
11 export interface CallEnd {
12 /** The account's name (what the operator called it), or `platform`. */
13 readonly account: string;
14 readonly model: string;
15 readonly ms: number;
16 /** What the runner returned; undefined when it threw. */
17 readonly outcome: AgentOutcome | undefined;
18 /** The provider's own refusal of the call (its credit is spent). */
19 readonly refused: boolean;
20 /** A person stopped it, or a restart cut it; read only where the call did not answer. */
21 readonly stopped: boolean;
22 }
23
24 /** How a call ended: answered, timed_out, refused, limit, stopped, or `error:<class>`. */
25 export function callOutcome(end: Pick<CallEnd, "outcome" | "refused" | "stopped">): string {
26 const { outcome } = end;
27 if (outcome?.ok === true) return "answered";
28 if (end.stopped) return "stopped";
29 if (outcome === undefined) return "error:threw";
30 if (outcome.reason === "timeout") return "timed_out";
31 if (end.refused || outcome.limit?.refused === true) return "refused";
32 if (outcome.limit !== undefined || outcome.reason === "rate_limited") return "limit";
33 return `error:${outcome.reason.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 40) || "unknown"}`;
34 }
35
36 /** The fields of the line, seconds to a tenth. */
37 export function callFields(end: CallEnd): LogFields {
38 return {
39 account: end.account,
40 model: end.model,
41 seconds: Math.round(end.ms / 100) / 10,
42 outcome: callOutcome(end),
43 };
44 }
src/crew/conversation.ts +27 −1
@@ -57,6 +57,7 @@ import { storedText } from "../kernel/blocked.ts";
5757 import { appendRunLog } from "../runs/log.ts";
5858 import { currentRunner, runAgent, type AgentOutcome, type HistoryTurn, type RunnerLimit } from "./agent_runner.ts";
5959 import { runAccount } from "./runner_env.ts";
60 import { callFields } from "./call_line.ts";
6061 import { CONVERSATION_BRIEF } from "./conversation_brief.ts";
6162 import { liveDelta, liveEnd, liveReset, liveSaid } from "./conversation_live.ts";
6263 import { callBook } from "./conversation_calls.ts";
@@ -916,6 +917,19 @@ function begin(
916917 const turn = (async (): Promise<void> => {
917918 let outcome: AgentOutcome | undefined;
918919 let unlisten = (): void => {};
920 // One line per call to the runner, written as it ends or throws (#17825).
921 const logCall = (startedAt: number, result: AgentOutcome | undefined): void =>
922 app.log.info(
923 "talk model call",
924 callFields({
925 account: on !== undefined ? on.name : picked.kind === "ready" ? picked.subscription.name : PLATFORM,
926 model: (on !== undefined ? choice!.model : options.model) ?? "default",
927 ms: performance.now() - startedAt,
928 outcome: result,
929 refused: result?.ok === false && (creditSpent(result.result) || creditSpent(streamed.at(-1)?.text ?? "")),
930 stopped: stopper.signal.aborted || options.signal.aborted,
931 }),
932 );
919933 try {
920934 const cwd = turnDir(app.config.dataDir);
921935 const configDir = sessionsDir(app.config.dataDir, options.configDir);
@@ -935,6 +949,7 @@ function begin(
935949 if (session !== undefined) appendRunLog(app.config.dataDir, runId, `resuming session ${session}`);
936950 // Whatever the run does (ends, throws, is stopped), the calls it made are stored.
937951 // A chosen connection runs on the OpenAI-compatible runner, whatever the forge's default is.
952 const callAt = performance.now();
938953 outcome = await (on !== undefined ? openaiRunner.run : runAgent)({
939954 binary: options.binary,
940955 cwd,
@@ -1005,7 +1020,18 @@ function begin(
10051020 if (said.kind === "thinking") put("tool", JSON.stringify({ thinking: said.text.slice(0, THINKING_CHARS) }));
10061021 else if (said.kind !== "tool" || !calls.said(said.text, said.id)) put(said.kind === "text" ? "agent" : "tool", said.text);
10071022 },
1008 }).finally(() => calls.flush());
1023 })
1024 .finally(() => calls.flush())
1025 .then(
1026 (o) => {
1027 logCall(callAt, o);
1028 return o;
1029 },
outdated

This runs once per turn, after the loop. Skipped loop (gone) logs error:threw; a fallback second call hides the first call's line. Log inside the loop around each run(...), with a start time taken just before it.

1030 (e: unknown) => {
1031 logCall(callAt, undefined);
1032 throw e;
1033 },
1034 );
10091035 const lost = !outcome.ok && lostSession(outcome.result);
10101036 // Only the outcome and the version are kept, never the text or the session (#8795).
10111037 if (session !== undefined && !options.signal.aborted)
outdated

stopped is true if the signal was aborted at any time, even after an answered call. Let a call that answered stay answered.

test/talk-call-line.test.ts added +147
@@ -0,0 +1,147 @@
1 /**
2 * Every model call in Talk writes one log line (#17825): account, model, seconds, how it ended.
3 * A fake runner ends each way; the line names the outcome and never the prompt, the answer or the
4 * credential. The numbered versions strip is not touched.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { createConversation, setClaudeSession } from "../src/core/conversations.ts";
12 import { saveConnection, removeConnection } from "../src/core/connections.ts";
13 import { setChoice } from "../src/core/model_choice.ts";
14 import { createUser, type User } from "../src/core/users.ts";
15 import { useRunner, type AgentOutcome } from "../src/crew/agent_runner.ts";
16 import { callOutcome } from "../src/crew/call_line.ts";
17 import { say, type ConversationOptions } from "../src/crew/conversation.ts";
18 import { serve, type Servers } from "../src/http/server.ts";
19 import { teeLines } from "../src/kernel/log.ts";
20 import { promote } from "./helpers/members.ts";
21
22 let dir: string;
23 let app: App;
24 let servers: Servers;
25 let user: User;
26 let next: Partial<AgentOutcome> | "throw" = {};
27 /** When set, each call takes the next of these instead of `next`. */
28 let queue: Partial<AgentOutcome>[] = [];
29 const lines: string[] = [];
30
31 const base: AgentOutcome = {
32 ok: true,
33 sessionId: "s1",
34 result: "SECRET-ANSWER",
35 costUsd: 0,
36 turns: 1,
37 tokensIn: 7,
38 tokensOut: 7,
39 contextTokens: 0,
40 contextWindow: 0,
41 reason: "completed",
42 };
43
44 beforeAll(async () => {
45 dir = await mkdtemp(join(tmpdir(), "forge-call-line-"));
46 useRunner({
47 run: async (): Promise<AgentOutcome> => {
48 if (next === "throw") throw new Error("boom SECRET-ERROR");
49 return { ...base, ...(queue.shift() ?? next) };
50 },
51 detect: async () => ({ ok: true, version: "fake" }),
52 resumes: true,
53 });
54 app = createApp({ dataDir: dir, port: 0 });
55 servers = await serve(app);
56 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "keeper", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
57 if (!made.ok) throw new Error(made.error);
58 promote(app.db, made.value);
59 user = made.value;
60 teeLines((_scope, message, line) => {
61 if (message === "talk model call") lines.push(line);
62 });
63 });
64 afterAll(async () => {
65 teeLines(undefined);
66 useRunner(undefined);
67 servers.stop();
68 app.close();
69 await rm(dir, { recursive: true, force: true });
70 });
71
72 /** Say one message, wait for the turn, return the one line it wrote. */
73 const call = async (end: Partial<AgentOutcome> | "throw"): Promise<string> => {
74 next = end;
75 lines.length = 0;
76 const conversation = createConversation(app.db, user.id);
77 if (!conversation.ok) throw new Error(conversation.error);
78 const options: ConversationOptions = { binary: "unused", localUrl: servers.url, budgetUsd: 1, timeoutMs: 30_000, model: "haiku", signal: new AbortController().signal };
79 const said = say(app, options, user.id, "PRIVATE-PROMPT", [], "queue", conversation.value.id);
80 if (!said.ok) throw new Error(said.error);
81 if (said.value.how === "started") await said.value.done;
82 expect(lines).toHaveLength(1);
83 return lines[0]!;
84 };
85
86 test("each way a call ends is one line with account, model, seconds and the outcome", async () => {
87 const cases: [Partial<AgentOutcome> | "throw", string][] = [
88 [{}, "outcome=answered"],
89 [{ ok: false, reason: "timeout", result: "" }, "outcome=timed_out"],
90 [{ ok: false, reason: "error", result: "API Error: 402 credit" }, "outcome=refused"],
91 [{ ok: false, reason: "error", result: "x", limit: { refused: true } }, "outcome=refused"],
92 [{ ok: false, reason: "error", result: "x", limit: { said: "5 hour limit" } }, "outcome=limit"],
93 [{ ok: false, reason: "exit 1", result: "SECRET-STDERR" }, "outcome=error:exit_1"],
94 ["throw", "outcome=error:threw"],
95 ];
96 for (const [end, outcome] of cases) {
97 const line = await call(end);
98 expect(line).toContain(outcome);
99 expect(line).toContain("account=platform");
100 expect(line).toContain("model=haiku");
101 expect(line).toMatch(/seconds=\d+(\.\d)?/);
102 for (const secret of ["PRIVATE-PROMPT", "SECRET-ANSWER", "SECRET-STDERR", "SECRET-ERROR", "tokens"]) expect(line).not.toContain(secret);
103 }
104 });
105
106 test("callOutcome cuts an error's class to plain characters", () => {
107 const o = (reason: string) => callOutcome({ outcome: { ...base, ok: false, reason }, refused: false, stopped: false });
108 expect(o("Exit 137: Killed!")).toBe("error:exit_137_killed");
109 expect(o("")).toBe("error:unknown");
110 });
111
112 /** Say one message in `conversationId`, wait for the turn. */
113 const sayIn = async (conversationId: string): Promise<void> => {
114 lines.length = 0;
115 const options: ConversationOptions = { binary: "unused", localUrl: servers.url, budgetUsd: 1, timeoutMs: 30_000, model: "haiku", signal: new AbortController().signal };
116 const said = say(app, options, user.id, "PRIVATE-PROMPT", [], "queue", conversationId);
117 if (!said.ok) throw new Error(said.error);
118 if (said.value.how === "started") await said.value.done;
119 };
120
121 test("a lost session then a fresh start is two calls, two lines", async () => {
122 const conversation = createConversation(app.db, user.id);
123 if (!conversation.ok) throw new Error(conversation.error);
124 setClaudeSession(app.db, user.id, conversation.value.id, "s-old");
125 next = {};
126 queue = [{ ok: false, reason: "error", result: "No conversation found with session ID: s-old" }, {}];
127 await sayIn(conversation.value.id);
128 expect(lines).toHaveLength(2);
129 expect(lines[0]).toContain("outcome=error:error");
130 expect(lines[1]).toContain("outcome=answered");
131 });
132
133 test("no runner call, no line: a removed chosen connection logs nothing", async () => {
134 const extra = saveConnection(app.db, app.config.dataDir, { name: "Brief", protocol: "openai", base: "http://127.0.0.1:9/v1", key: "", scope: "forge", userId: user.id, models: [{ id: "tiny" }], said: "1 models listed" });
135 if (!extra.ok) throw new Error(extra.error);
136 const conversation = createConversation(app.db, user.id);
137 if (!conversation.ok) throw new Error(conversation.error);
138 expect(setChoice(app.db, user, conversation.value.id, `${extra.value.id} tiny`).ok).toBe(true);
139 expect(removeConnection(app.db, user, extra.value.id)).toBe(true);
140 await sayIn(conversation.value.id);
141 expect(lines).toHaveLength(0);
142 });
143
144 test("a call that answered stays answered even when a stop came after", () => {
145 expect(callOutcome({ outcome: base, refused: false, stopped: true })).toBe("answered");
146 expect(callOutcome({ outcome: { ...base, ok: false, reason: "cancelled" }, refused: false, stopped: true })).toBe("stopped");
147 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs