@parcha/agentrun-serve 0.1.0-beta.54 → 0.1.0-beta.55
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +110 -2
- package/README.md +266 -88
- package/dist/adapters.d.ts +10 -0
- package/dist/adapters.js +46 -0
- package/dist/agent-package.d.ts +3 -3
- package/dist/agent-package.js +6 -13
- package/dist/agents-store.js +6 -5
- package/dist/api-only.d.ts +16 -4
- package/dist/api-only.js +21 -7
- package/dist/cli.js +5 -3
- package/dist/composio-made.d.ts +26 -1
- package/dist/composio-made.js +39 -2
- package/dist/composio-preset.d.ts +3 -2
- package/dist/composio-preset.js +46 -14
- package/dist/computer-held-routes.js +2 -3
- package/dist/computer-setting.d.ts +4 -2
- package/dist/computer-setting.js +0 -2
- package/dist/computers-running.d.ts +8 -0
- package/dist/computers-running.js +27 -0
- package/dist/console/assets/backend-D5EmB4N3.js +166 -0
- package/dist/console/assets/index-DUYLaqiR.js +746 -0
- package/dist/console/assets/index-DYhU4adm.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/docker-host-addresses.d.ts +23 -3
- package/dist/docker-host-addresses.js +90 -18
- package/dist/exa-keyless.d.ts +2 -3
- package/dist/exa-keyless.js +43 -127
- package/dist/firecrawl-keyless.d.ts +41 -0
- package/dist/firecrawl-keyless.js +152 -0
- package/dist/handed-secret.d.ts +3 -1
- package/dist/handed-secret.js +4 -2
- package/dist/harness-keys.d.ts +98 -0
- package/dist/harness-keys.js +247 -0
- package/dist/harness-recipe-entry.d.ts +14 -9
- package/dist/harness-recipe-entry.js +25 -14
- package/dist/harness-table.d.ts +16 -1
- package/dist/harness-table.js +19 -7
- package/dist/harness.d.ts +4 -0
- package/dist/harness.js +12 -1
- package/dist/host-check.d.ts +2 -0
- package/dist/host-check.js +6 -0
- package/dist/import-summary.d.ts +1 -1
- package/dist/import-summary.js +1 -1
- package/dist/import.d.ts +5 -5
- package/dist/import.js +54 -67
- package/dist/keyless-mcp.d.ts +36 -0
- package/dist/keyless-mcp.js +127 -0
- package/dist/learn/audit.d.ts +3 -3
- package/dist/learn/audit.js +3 -3
- package/dist/learn/commit.d.ts +8 -7
- package/dist/learn/commit.js +60 -20
- package/dist/learn/compile.d.ts +4 -3
- package/dist/learn/compile.js +7 -5
- package/dist/learn/folder.d.ts +16 -3
- package/dist/learn/folder.js +46 -13
- package/dist/learn/promote.d.ts +37 -13
- package/dist/learn/promote.js +112 -40
- package/dist/learn/secrets.js +10 -2
- package/dist/learning-routes.d.ts +22 -17
- package/dist/learning-routes.js +40 -39
- package/dist/learning.js +2 -2
- package/dist/manifest.d.ts +10 -0
- package/dist/manifest.js +30 -0
- package/dist/mcp-pin-first.d.ts +4 -2
- package/dist/mcp-pin-first.js +5 -2
- package/dist/mcp-secret-writes.d.ts +16 -7
- package/dist/mcp-secret-writes.js +35 -27
- package/dist/mcp-servers-store.d.ts +30 -6
- package/dist/mcp-servers-store.js +112 -28
- package/dist/mcp-sources.d.ts +10 -2
- package/dist/mcp-sources.js +9 -2
- package/dist/mcp-store.d.ts +13 -7
- package/dist/mcp-store.js +12 -9
- package/dist/model-form.d.ts +3 -2
- package/dist/model-form.js +11 -7
- package/dist/model.d.ts +20 -4
- package/dist/model.js +68 -9
- package/dist/native/history.d.ts +1 -1
- package/dist/native/history.js +2 -2
- package/dist/ollama-provider.d.ts +92 -0
- package/dist/ollama-provider.js +495 -0
- package/dist/openapi/agentrun-v2.openapi.json +2 -2
- package/dist/openapi.js +127 -37
- package/dist/page.d.ts +11 -3
- package/dist/page.js +22 -7
- package/dist/place-offers.d.ts +17 -1
- package/dist/place-offers.js +46 -5
- package/dist/print.js +1 -1
- package/dist/purged-workflow.d.ts +35 -7
- package/dist/purged-workflow.js +73 -26
- package/dist/run-computer.d.ts +2 -0
- package/dist/run-computer.js +2 -0
- package/dist/run-files.d.ts +4 -0
- package/dist/run-files.js +4 -0
- package/dist/run-keys.d.ts +2 -4
- package/dist/run-keys.js +6 -7
- package/dist/run-launch.d.ts +4 -0
- package/dist/run-launch.js +4 -0
- package/dist/run-reads-over-store.d.ts +3 -2
- package/dist/run-reads-over-store.js +66 -2
- package/dist/run-secrets.js +5 -2
- package/dist/runner/adapter-loop.d.ts +6 -3
- package/dist/runner/adapter-loop.js +34 -15
- package/dist/runner/adapter-run-spec.d.ts +3 -0
- package/dist/runner/adapter-run-spec.js +5 -3
- package/dist/runner/audit.js +8 -4
- package/dist/runner/beside.d.ts +2 -1
- package/dist/runner/beside.js +6 -2
- package/dist/runner/claim-secrets.d.ts +5 -8
- package/dist/runner/claim-secrets.js +6 -0
- package/dist/runner/cli-run-spec.d.ts +1 -1
- package/dist/runner/cli-run-spec.js +38 -6
- package/dist/runner/harness-loops.d.ts +22 -9
- package/dist/runner/harness-loops.js +21 -11
- package/dist/runner/held.d.ts +3 -0
- package/dist/runner/learning-end.d.ts +1 -1
- package/dist/runner/learning-end.js +8 -3
- package/dist/runner/loop-contract.d.ts +5 -4
- package/dist/runner/main.js +4 -2
- package/dist/runner/mcp-claim.d.ts +3 -0
- package/dist/runner/mcp-claim.js +26 -2
- package/dist/runner/mcp-run.d.ts +3 -0
- package/dist/runner/mcp-run.js +2 -1
- package/dist/runner/metrics.d.ts +10 -10
- package/dist/runner/metrics.js +19 -38
- package/dist/runner/model-route.d.ts +3 -0
- package/dist/runner/model-route.js +6 -2
- package/dist/runner/promotion.d.ts +15 -9
- package/dist/runner/promotion.js +25 -15
- package/dist/runner/run-child-host.js +17 -7
- package/dist/runner/run-child.js +3 -1
- package/dist/runner/sdk-loop.js +2 -0
- package/dist/runner/workflow-loop.d.ts +2 -2
- package/dist/runner/workflow-loop.js +1 -2
- package/dist/runner/workflow-spec.d.ts +1 -1
- package/dist/runner/workflow-spec.js +6 -6
- package/dist/sdk/check.d.ts +4 -1
- package/dist/sdk/check.js +2 -1
- package/dist/sdk/runs.d.ts +2 -2
- package/dist/sdk/runs.js +8 -6
- package/dist/secret-cut.js +2 -1
- package/dist/secret-writes.d.ts +3 -2
- package/dist/secret-writes.js +1 -1
- package/dist/server.d.ts +44 -8
- package/dist/server.js +283 -108
- package/dist/standard-webhooks.d.ts +11 -0
- package/dist/standard-webhooks.js +20 -2
- package/dist/store/index.d.ts +1 -1
- package/dist/store/schema.js +5 -2
- package/dist/store/sqlite/store.js +90 -34
- package/dist/store/store.d.ts +54 -14
- package/dist/store-reads/journal.d.ts +7 -2
- package/dist/store-reads/journal.js +9 -6
- package/dist/store-reads/learning.d.ts +12 -9
- package/dist/store-reads/learning.js +18 -24
- package/dist/store-view.d.ts +0 -5
- package/dist/store-view.js +9 -8
- package/dist/template-eval.d.ts +49 -4
- package/dist/template-eval.js +168 -45
- package/dist/template-import.js +4 -2
- package/dist/templates.d.ts +5 -3
- package/dist/templates.js +19 -40
- package/dist/timeline/labels.d.ts +2 -2
- package/dist/timeline/labels.js +2 -2
- package/dist/timeline/timeline.d.ts +2 -2
- package/dist/timeline/timeline.js +1 -1
- package/dist/tool-plane.d.ts +17 -9
- package/dist/tool-plane.js +38 -17
- package/dist/tools.js +2 -2
- package/dist/trigger-launch-hook.d.ts +16 -8
- package/dist/trigger-launch-hook.js +32 -23
- package/dist/trigger-targets.d.ts +18 -8
- package/dist/trigger-targets.js +42 -19
- package/dist/triggers.d.ts +85 -23
- package/dist/triggers.js +303 -96
- package/dist/web-fake.js +3 -3
- package/dist/web-fetch-direct.d.ts +4 -0
- package/dist/web-fetch-direct.js +8 -1
- package/dist/web-fetch.d.ts +12 -3
- package/dist/web-fetch.js +47 -14
- package/dist/web-search.d.ts +33 -4
- package/dist/web-search.js +100 -41
- package/dist/webhooks.js +4 -5
- package/launcher/agentrun-serve +5 -1
- package/package.json +17 -13
- package/templates/README.md +2 -2
- package/dist/console/assets/index-B_85An2t.js +0 -745
- package/dist/console/assets/index-n1YsbnYh.css +0 -1
- package/dist/import-sources.d.ts +0 -116
- package/dist/import-sources.js +0 -693
package/dist/import-sources.js
DELETED
|
@@ -1,693 +0,0 @@
|
|
|
1
|
-
// The sessions Claude Code, Codex and pi keep under a person's home, read as one shape: where each ran, on which model,
|
|
2
|
-
// when, how it ended, what it cost when the source says, and its turns. Each reader reads one JSONL file a line at a
|
|
3
|
-
// time; a line that is not JSON, or not a record it knows, is passed over.
|
|
4
|
-
// Claude Code ~/.claude/projects/<cwd slug>/<session id>.jsonl, its subagents' in <session id>/subagents/ (childFiles)
|
|
5
|
-
// Codex ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl
|
|
6
|
-
// pi ~/.pi/agent/sessions/--<cwd>--/<time>_<session id>.jsonl
|
|
7
|
-
import { createReadStream } from "node:fs";
|
|
8
|
-
import { lstat, readdir } from "node:fs/promises";
|
|
9
|
-
import { basename, join } from "node:path";
|
|
10
|
-
import { createInterface } from "node:readline";
|
|
11
|
-
export const SOURCES = ["claude-code", "codex", "pi"];
|
|
12
|
-
/** The harness of serve that runs what each source ran. */
|
|
13
|
-
export const HARNESS_OF = {
|
|
14
|
-
"claude-code": "claude-agent",
|
|
15
|
-
codex: "codex",
|
|
16
|
-
pi: "pi",
|
|
17
|
-
};
|
|
18
|
-
/** Each source's name as a person reads it. */
|
|
19
|
-
export const SOURCE_NAMES = { "claude-code": "Claude Code", codex: "Codex", pi: "pi" };
|
|
20
|
-
/** The longest gap between two records counted as time at work, as WakaTime counts it: a longer gap is a session left
|
|
21
|
-
* open and counts nothing. Claude Code's Bash tool runs a call for up to 10 minutes with nothing written. */
|
|
22
|
-
export const ACTIVE_GAP_MS = 15 * 60_000;
|
|
23
|
-
/** The session files of `source` under `home`, never through a link. */
|
|
24
|
-
export async function sessionFiles(home, source, configRoot) {
|
|
25
|
-
const entries = async (dir) => readdir(dir, { withFileTypes: true }).catch(() => []);
|
|
26
|
-
const out = [];
|
|
27
|
-
if (source === "claude-code") {
|
|
28
|
-
const root = join(configRoot ?? join(home, ".claude"), "projects");
|
|
29
|
-
for (const project of await entries(root)) {
|
|
30
|
-
if (!project.isDirectory())
|
|
31
|
-
continue;
|
|
32
|
-
for (const file of await entries(join(root, project.name)))
|
|
33
|
-
if (file.isFile() && file.name.endsWith(".jsonl"))
|
|
34
|
-
out.push(join(root, project.name, file.name));
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
else if (source === "codex") {
|
|
38
|
-
const walk = async (dir, depth) => {
|
|
39
|
-
for (const entry of await entries(dir)) {
|
|
40
|
-
if (entry.isDirectory() && depth < 3)
|
|
41
|
-
await walk(join(dir, entry.name), depth + 1);
|
|
42
|
-
else if (entry.isFile() && depth === 3 && /^rollout-.*\.jsonl$/.test(entry.name))
|
|
43
|
-
out.push(join(dir, entry.name));
|
|
44
|
-
}
|
|
45
|
-
};
|
|
46
|
-
await walk(join(configRoot ?? join(home, ".codex"), "sessions"), 0);
|
|
47
|
-
}
|
|
48
|
-
else {
|
|
49
|
-
const root = join(home, ".pi", "agent", "sessions");
|
|
50
|
-
for (const project of await entries(root)) {
|
|
51
|
-
if (!project.isDirectory())
|
|
52
|
-
continue;
|
|
53
|
-
for (const file of await entries(join(root, project.name)))
|
|
54
|
-
if (file.isFile() && file.name.endsWith(".jsonl"))
|
|
55
|
-
out.push(join(root, project.name, file.name));
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
// A home whose source directory is itself a link is read as found (the person's own), but no file is a link.
|
|
59
|
-
const files = [];
|
|
60
|
-
for (const file of out.sort())
|
|
61
|
-
if ((await lstat(file).catch(() => null))?.isFile())
|
|
62
|
-
files.push(file);
|
|
63
|
-
return files;
|
|
64
|
-
}
|
|
65
|
-
/** Claude Code's subagents' session files under `home`, in <session id>/subagents/ (a workflow's a folder deeper), each
|
|
66
|
-
* with the session file it ran under (`of`): the one beside the folder it sits in. A session moved to another project
|
|
67
|
-
* folder keeps its id there, with copies of its subagents' files: each folder's are its own file's. Never through a
|
|
68
|
-
* link. */
|
|
69
|
-
export async function childFiles(home) {
|
|
70
|
-
const entries = async (dir) => readdir(dir, { withFileTypes: true }).catch(() => []);
|
|
71
|
-
const root = join(home, ".claude", "projects");
|
|
72
|
-
const out = [];
|
|
73
|
-
for (const project of await entries(root)) {
|
|
74
|
-
if (!project.isDirectory())
|
|
75
|
-
continue;
|
|
76
|
-
for (const session of await entries(join(root, project.name))) {
|
|
77
|
-
if (!session.isDirectory())
|
|
78
|
-
continue;
|
|
79
|
-
const walk = async (dir, depth) => {
|
|
80
|
-
for (const entry of await entries(dir)) {
|
|
81
|
-
if (entry.isDirectory() && depth < 3)
|
|
82
|
-
await walk(join(dir, entry.name), depth + 1);
|
|
83
|
-
else if (entry.isFile() && entry.name.endsWith(".jsonl"))
|
|
84
|
-
out.push({ file: join(dir, entry.name), of: join(root, project.name, `${session.name}.jsonl`) });
|
|
85
|
-
}
|
|
86
|
-
};
|
|
87
|
-
// The folder itself is no link: one that points elsewhere holds no subagent of this session's.
|
|
88
|
-
const subagents = join(root, project.name, session.name, "subagents");
|
|
89
|
-
if ((await lstat(subagents).catch(() => null))?.isDirectory())
|
|
90
|
-
await walk(subagents, 0);
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
return out.sort((a, b) => a.file.localeCompare(b.file));
|
|
94
|
-
}
|
|
95
|
-
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
96
|
-
const str = (value) => (typeof value === "string" && value !== "" ? value : undefined);
|
|
97
|
-
const timeOf = (value) => {
|
|
98
|
-
const at = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
|
|
99
|
-
return Number.isFinite(at) ? at : undefined;
|
|
100
|
-
};
|
|
101
|
-
/** Text from a string or a list of blocks; a block that is not text says what it was. */
|
|
102
|
-
const textOf = (value) => {
|
|
103
|
-
if (typeof value === "string")
|
|
104
|
-
return value;
|
|
105
|
-
if (!Array.isArray(value))
|
|
106
|
-
return isObject(value) && typeof value.text === "string" ? value.text : "";
|
|
107
|
-
return value
|
|
108
|
-
.map((block) => (typeof block === "string" ? block : isObject(block) ? (typeof block.text === "string" ? block.text : block.type === "image" || block.type === "input_image" ? "[image]" : textOf(block.content)) : ""))
|
|
109
|
-
.filter(Boolean)
|
|
110
|
-
.join("\n");
|
|
111
|
-
};
|
|
112
|
-
/** A usage's counts under the source's names for input, cache read, cache write and output; undefined unless input and
|
|
113
|
-
* output are counts (an absent cache count is 0). `cachedIn`: the source's input holds its cache reads and writes. */
|
|
114
|
-
const tokensOf = (usage, [input, cacheRead, cacheWrite, output], cachedIn = false) => {
|
|
115
|
-
if (!isObject(usage))
|
|
116
|
-
return undefined;
|
|
117
|
-
const count = (key, absent) => {
|
|
118
|
-
const value = usage[key] ?? absent;
|
|
119
|
-
return Number.isSafeInteger(value) && value >= 0 ? value : undefined;
|
|
120
|
-
};
|
|
121
|
-
const counts = { input: count(input), output: count(output), cacheRead: count(cacheRead, 0), cacheWrite: count(cacheWrite, 0) };
|
|
122
|
-
if (counts.input === undefined || counts.output === undefined || counts.cacheRead === undefined || counts.cacheWrite === undefined)
|
|
123
|
-
return undefined;
|
|
124
|
-
if (cachedIn)
|
|
125
|
-
counts.input -= counts.cacheRead + counts.cacheWrite;
|
|
126
|
-
return counts.input >= 0 ? counts : undefined;
|
|
127
|
-
};
|
|
128
|
-
/** `usage` with the part of its cache writes kept for an hour, when `long` is a count of at most its writes. */
|
|
129
|
-
const withLong = (usage, long) => usage && Number.isSafeInteger(long) && long >= 0 && long <= usage.cacheWrite ? { ...usage, cacheWrite1h: long } : usage;
|
|
130
|
-
/** The most of each count of two records of one request. */
|
|
131
|
-
const most = (a, b) => {
|
|
132
|
-
const long = Math.max(a.cacheWrite1h ?? -1, b.cacheWrite1h ?? -1);
|
|
133
|
-
return { input: Math.max(a.input, b.input), output: Math.max(a.output, b.output), cacheRead: Math.max(a.cacheRead, b.cacheRead), cacheWrite: Math.max(a.cacheWrite, b.cacheWrite), ...(long >= 0 ? { cacheWrite1h: long } : {}) };
|
|
134
|
-
};
|
|
135
|
-
const CLAUDE_TOKENS = ["input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens", "output_tokens"];
|
|
136
|
-
// OpenAI's input_tokens holds the cached tokens, and its output_tokens the reasoning.
|
|
137
|
-
const CODEX_TOKENS = ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens"];
|
|
138
|
-
const PI_TOKENS = ["input", "cacheRead", "cacheWrite", "output"];
|
|
139
|
-
const effortOf = (value) => (typeof value === "string" && /^[\w-]{1,32}$/.test(value) ? value : undefined);
|
|
140
|
-
const argsOf = (value) => {
|
|
141
|
-
if (isObject(value))
|
|
142
|
-
return value;
|
|
143
|
-
if (typeof value === "string") {
|
|
144
|
-
try {
|
|
145
|
-
const parsed = JSON.parse(value);
|
|
146
|
-
if (isObject(parsed))
|
|
147
|
-
return parsed;
|
|
148
|
-
}
|
|
149
|
-
catch {
|
|
150
|
-
// Not JSON: kept as the tool's one input.
|
|
151
|
-
}
|
|
152
|
-
return { input: value };
|
|
153
|
-
}
|
|
154
|
-
return {};
|
|
155
|
-
};
|
|
156
|
-
/** One session file of `source`, read whole; `turns: false` keeps only what a listing shows. `seen`: the records and
|
|
157
|
-
* responses an import has read already, across its files; a record in it (a copy a resumed session's file carries) adds
|
|
158
|
-
* nothing, and this file's are added to it. */
|
|
159
|
-
export async function readSession(file, source, { turns: keep = true, seen } = {}) {
|
|
160
|
-
const session = {
|
|
161
|
-
source,
|
|
162
|
-
id: "",
|
|
163
|
-
file,
|
|
164
|
-
state: "completed",
|
|
165
|
-
child: false,
|
|
166
|
-
turns: [],
|
|
167
|
-
users: 0,
|
|
168
|
-
activeMs: 0,
|
|
169
|
-
copies: 0,
|
|
170
|
-
};
|
|
171
|
-
let turns = [];
|
|
172
|
-
let first;
|
|
173
|
-
let last;
|
|
174
|
-
const names = new Map();
|
|
175
|
-
const priced = { sum: 0, unknown: false };
|
|
176
|
-
const provider = {};
|
|
177
|
-
const current = { keyed: new Map(), seen: seen ?? new Set(), copied: new Set() };
|
|
178
|
-
const codex = { events: false, held: [], records: false, responses: new Set(), items: new Map(), results: new Map() };
|
|
179
|
-
const titles = { summaries: [], uuids: new Set() };
|
|
180
|
-
const rememberUser = (turn) => {
|
|
181
|
-
if (turn.role === "user") {
|
|
182
|
-
session.users += 1;
|
|
183
|
-
session.firstPrompt ??= turn.text;
|
|
184
|
-
session.titleText ??= personsWords(turn.text);
|
|
185
|
-
}
|
|
186
|
-
};
|
|
187
|
-
const add = (turn) => {
|
|
188
|
-
rememberUser(turn);
|
|
189
|
-
if (keep)
|
|
190
|
-
turns.push(turn);
|
|
191
|
-
};
|
|
192
|
-
const record = source === "claude-code" ? claudeRecord : source === "codex" ? codexRecord : piRecord;
|
|
193
|
-
const lines = createInterface({
|
|
194
|
-
input: createReadStream(file, { encoding: "utf8" }),
|
|
195
|
-
crlfDelay: Number.POSITIVE_INFINITY,
|
|
196
|
-
});
|
|
197
|
-
for await (const line of lines) {
|
|
198
|
-
let value;
|
|
199
|
-
try {
|
|
200
|
-
value = JSON.parse(line);
|
|
201
|
-
}
|
|
202
|
-
catch {
|
|
203
|
-
continue;
|
|
204
|
-
}
|
|
205
|
-
if (!isObject(value))
|
|
206
|
-
continue;
|
|
207
|
-
const at = timeOf(value.timestamp);
|
|
208
|
-
// A copy of a record read already moves no time: its time was counted where it was first read.
|
|
209
|
-
const copy = record(value, at ?? last ?? 0, session, { add, names, turns, priced, provider, current, codex, titles }) === false;
|
|
210
|
-
if (copy)
|
|
211
|
-
session.copies += 1;
|
|
212
|
-
if (at !== undefined && !copy) {
|
|
213
|
-
first ??= at;
|
|
214
|
-
// A record older than the latest (a block a resumed file repeats) moves no time either.
|
|
215
|
-
if (last === undefined || at >= last) {
|
|
216
|
-
if (last !== undefined && at - last <= ACTIVE_GAP_MS)
|
|
217
|
-
session.activeMs += at - last;
|
|
218
|
-
last = at;
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
// Older Codex writes each of the person's turns twice, as a user_message event and as a user message; current Codex
|
|
223
|
-
// writes the user message alone. One source per file, so no turn counts twice.
|
|
224
|
-
if (!codex.events && codex.held.length) {
|
|
225
|
-
// Held indexes refer to the non-user turns as read. Merge both ordered lists once: inserting each user into
|
|
226
|
-
// the middle of the transcript shifts its remaining turns again and again on a long current-Codex session.
|
|
227
|
-
const ordered = [];
|
|
228
|
-
let next = 0;
|
|
229
|
-
for (const { index, turn } of codex.held) {
|
|
230
|
-
rememberUser(turn);
|
|
231
|
-
if (keep) {
|
|
232
|
-
while (next < index)
|
|
233
|
-
ordered.push(turns[next++]);
|
|
234
|
-
ordered.push(turn);
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
if (keep) {
|
|
238
|
-
while (next < turns.length)
|
|
239
|
-
ordered.push(turns[next++]);
|
|
240
|
-
turns = ordered;
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
if (!session.id)
|
|
244
|
-
session.id = source === "pi" ? basename(file, ".jsonl").split("_").pop() : basename(file, ".jsonl");
|
|
245
|
-
const sourceTitle = titles.custom ?? titles.ai ?? titles.summaries.findLast(({ leaf }) => leaf === undefined || titles.uuids.has(leaf))?.title;
|
|
246
|
-
if (sourceTitle)
|
|
247
|
-
session.sourceTitle = sourceTitle;
|
|
248
|
-
if (first !== undefined)
|
|
249
|
-
session.startedAt = new Date(first).toISOString();
|
|
250
|
-
if (last !== undefined)
|
|
251
|
-
session.endedAt = new Date(last).toISOString();
|
|
252
|
-
session.activeMs = Math.round(session.activeMs);
|
|
253
|
-
session.turns = turns;
|
|
254
|
-
const effort = mostEffortOf(turns);
|
|
255
|
-
if (effort)
|
|
256
|
-
session.effort = effort;
|
|
257
|
-
return session;
|
|
258
|
-
}
|
|
259
|
-
/** The effort most of `turns`' requests ran at, as the model of most requests is a run's model: the first seen of a tie. */
|
|
260
|
-
export function mostEffortOf(turns) {
|
|
261
|
-
const efforts = new Map();
|
|
262
|
-
for (const turn of turns)
|
|
263
|
-
if (turn.role === "assistant" && turn.effort)
|
|
264
|
-
efforts.set(turn.effort, (efforts.get(turn.effort) ?? 0) + 1);
|
|
265
|
-
let most;
|
|
266
|
-
for (const [effort, n] of efforts)
|
|
267
|
-
if (most === undefined || n > efforts.get(most))
|
|
268
|
-
most = effort;
|
|
269
|
-
return most;
|
|
270
|
-
}
|
|
271
|
-
const INTERRUPTED = /^\[Request interrupted by user/;
|
|
272
|
-
// The titles Claude Code writes into a session's file, each again as it changes, and the field each holds it in.
|
|
273
|
-
const CLAUDE_TITLES = new Map([
|
|
274
|
-
["custom-title", "customTitle"],
|
|
275
|
-
["ai-title", "aiTitle"],
|
|
276
|
-
["summary", "summary"],
|
|
277
|
-
]);
|
|
278
|
-
/** One of Claude Code's title records: kept by kind, the latest of each. A summary names the last message of the
|
|
279
|
-
* conversation it titles (leafUuid), which can be another session's: held until the file's end. */
|
|
280
|
-
function titleRecord(value, session, titles) {
|
|
281
|
-
// As written: the cut matches a key or a passphrase as the source wrote it, so the title is put on one line after it.
|
|
282
|
-
const title = str(value[CLAUDE_TITLES.get(value.type)])?.trim();
|
|
283
|
-
if (!title || (str(value.sessionId) && value.sessionId !== session.id))
|
|
284
|
-
return;
|
|
285
|
-
if (value.type === "custom-title")
|
|
286
|
-
titles.custom = title;
|
|
287
|
-
else if (value.type === "ai-title")
|
|
288
|
-
titles.ai = title;
|
|
289
|
-
else
|
|
290
|
-
titles.summaries.push({ title, ...(str(value.leafUuid) ? { leaf: value.leafUuid } : {}) });
|
|
291
|
-
}
|
|
292
|
-
// What Claude Code writes into a user message for the person's slash command (/clear, /model, /init, /resume …): the
|
|
293
|
-
// command's name, message and arguments, each in its own element, then its output and the preamble it puts before a
|
|
294
|
-
// local command's output. Only these elements, whole: a prompt the person wrote around them is theirs.
|
|
295
|
-
const CLI_ELEMENT = /<(command-name|command-message|command-args|local-command-stdout|local-command-stderr)>[\s\S]*?<\/\1>/g;
|
|
296
|
-
const CLI_PREAMBLE = /^Caveat: The messages below were generated by the user while running local commands\b/;
|
|
297
|
-
/** The person's own words in a user message's text, as they wrote them (spaces and lines kept, so a cut still matches
|
|
298
|
-
* a secret in them): none when the CLI wrote all of it (a slash command, its output, its preamble), or when there are
|
|
299
|
-
* no words at all. */
|
|
300
|
-
export function personsWords(text) {
|
|
301
|
-
const words = text.replace(CLI_ELEMENT, " ").trim();
|
|
302
|
-
const line = words.replace(/\s+/g, " ");
|
|
303
|
-
return line && !CLI_PREAMBLE.test(line) && !INTERRUPTED.test(line) ? words : undefined;
|
|
304
|
-
}
|
|
305
|
-
/** Claude Code's record; false for one read already (the import's earlier file, or this file's own repeat). */
|
|
306
|
-
function claudeRecord(value, at, session, { add, names, current, titles }) {
|
|
307
|
-
if (!session.id && str(value.sessionId))
|
|
308
|
-
session.id = value.sessionId;
|
|
309
|
-
if (!session.cwd && str(value.cwd))
|
|
310
|
-
session.cwd = value.cwd;
|
|
311
|
-
if (value.isSidechain === true)
|
|
312
|
-
session.child = true;
|
|
313
|
-
if (CLAUDE_TITLES.has(value.type))
|
|
314
|
-
return titleRecord(value, session, titles);
|
|
315
|
-
if (str(value.uuid))
|
|
316
|
-
titles.uuids.add(value.uuid);
|
|
317
|
-
if (value.type === "cost-state") {
|
|
318
|
-
// The last one is the session's: unknown when the CLI could not price a model it used.
|
|
319
|
-
session.costUsd = typeof value.totalCostUSD === "number" && Number.isFinite(value.totalCostUSD) && value.totalCostUSD >= 0 && value.hasUnknownModelCost !== true ? value.totalCostUSD : undefined;
|
|
320
|
-
return;
|
|
321
|
-
}
|
|
322
|
-
// A record written twice (a session carried on in its own file, or copied into a resumed one's) is read once, and moves
|
|
323
|
-
// no time a second time, whatever its type.
|
|
324
|
-
const uuid = str(value.uuid);
|
|
325
|
-
if (uuid && current.seen.has(`u:${uuid}`))
|
|
326
|
-
return false;
|
|
327
|
-
if (uuid)
|
|
328
|
-
current.seen.add(`u:${uuid}`);
|
|
329
|
-
if ((value.type !== "user" && value.type !== "assistant") || !isObject(value.message))
|
|
330
|
-
return;
|
|
331
|
-
if (value.isMeta === true || value.isCompactSummary === true || value.isVisibleInTranscriptOnly === true)
|
|
332
|
-
return;
|
|
333
|
-
const mark = uuid ? { uuids: [uuid] } : {};
|
|
334
|
-
const message = value.message;
|
|
335
|
-
if (value.type === "assistant") {
|
|
336
|
-
const model = str(message.model);
|
|
337
|
-
const synthetic = model === "<synthetic>";
|
|
338
|
-
if (model && !synthetic)
|
|
339
|
-
session.model = `anthropic/${model}`;
|
|
340
|
-
const blocks = Array.isArray(message.content) ? message.content : [{ type: "text", text: textOf(message.content) }];
|
|
341
|
-
const text = blocks
|
|
342
|
-
.filter((b) => isObject(b) && b.type === "text")
|
|
343
|
-
.map((b) => b.text)
|
|
344
|
-
.join("\n");
|
|
345
|
-
const calls = blocks
|
|
346
|
-
.filter((b) => isObject(b) && b.type === "tool_use")
|
|
347
|
-
.map((b) => ({
|
|
348
|
-
type: "toolCall",
|
|
349
|
-
id: String(b.id ?? ""),
|
|
350
|
-
name: String(b.name ?? ""),
|
|
351
|
-
arguments: argsOf(b.input),
|
|
352
|
-
}));
|
|
353
|
-
for (const call of calls)
|
|
354
|
-
names.set(call.id, call.name);
|
|
355
|
-
// The CLI's own turns (model <synthetic>): one marked an API error is a request that failed; any other ("No response
|
|
356
|
-
// requested.") is no request, kept as the CLI's note.
|
|
357
|
-
const failed = value.isApiErrorMessage === true;
|
|
358
|
-
if (synthetic && !failed) {
|
|
359
|
-
if (text)
|
|
360
|
-
add({ role: "note", author: "Claude Code", text, at, ...mark });
|
|
361
|
-
return;
|
|
362
|
-
}
|
|
363
|
-
session.state = failed ? "failed" : "completed";
|
|
364
|
-
// One request's blocks come as records of one message id, a parallel call's result between two of them: one turn.
|
|
365
|
-
// Each record repeats the request's usage, the final one the most of each count (an earlier record may hold only the
|
|
366
|
-
// stream's start).
|
|
367
|
-
const key = str(message.id);
|
|
368
|
-
const usage = withLong(tokensOf(message.usage, CLAUDE_TOKENS), isObject(message.usage) && isObject(message.usage.cache_creation) ? message.usage.cache_creation.ephemeral_1h_input_tokens : undefined);
|
|
369
|
-
const held = key ? current.keyed.get(key) : undefined;
|
|
370
|
-
if (held) {
|
|
371
|
-
held.text = [held.text, text].filter(Boolean).join("\n");
|
|
372
|
-
held.calls.push(...calls);
|
|
373
|
-
if (uuid)
|
|
374
|
-
held.uuids = [...(held.uuids ?? []), uuid];
|
|
375
|
-
if (usage)
|
|
376
|
-
held.usage = held.usage ? most(held.usage, usage) : usage;
|
|
377
|
-
return;
|
|
378
|
-
}
|
|
379
|
-
// A message an earlier file of the import holds: counted there, never again; its calls' results are copies too.
|
|
380
|
-
if (key && current.seen.has(`m:${key}`)) {
|
|
381
|
-
for (const call of calls)
|
|
382
|
-
current.copied.add(call.id);
|
|
383
|
-
return false;
|
|
384
|
-
}
|
|
385
|
-
if (!key && !text && calls.length === 0)
|
|
386
|
-
return;
|
|
387
|
-
const effort = effortOf(value.perTurnEffort) ?? effortOf(value.effort);
|
|
388
|
-
const turn = { role: "assistant", text, calls, at, ...(key ? { key } : {}), ...(session.model ? { model: session.model } : {}), ...(effort ? { effort } : {}), ...(usage ? { usage } : {}), ...(failed ? { error: text || "API error" } : {}), ...mark };
|
|
389
|
-
if (key) {
|
|
390
|
-
current.keyed.set(key, turn);
|
|
391
|
-
current.seen.add(`m:${key}`);
|
|
392
|
-
}
|
|
393
|
-
add(turn);
|
|
394
|
-
return;
|
|
395
|
-
}
|
|
396
|
-
if (typeof message.content === "string") {
|
|
397
|
-
if (INTERRUPTED.test(message.content))
|
|
398
|
-
session.state = "stopped";
|
|
399
|
-
else
|
|
400
|
-
session.state = "completed";
|
|
401
|
-
return add({ role: "user", text: message.content, at, ...mark });
|
|
402
|
-
}
|
|
403
|
-
if (!Array.isArray(message.content))
|
|
404
|
-
return;
|
|
405
|
-
const said = [];
|
|
406
|
-
let results = 0;
|
|
407
|
-
let copies = 0;
|
|
408
|
-
for (const block of message.content) {
|
|
409
|
-
if (!isObject(block))
|
|
410
|
-
continue;
|
|
411
|
-
if (block.type === "text" && typeof block.text === "string")
|
|
412
|
-
said.push(block.text);
|
|
413
|
-
else if (block.type === "tool_result") {
|
|
414
|
-
const id = String(block.tool_use_id ?? "");
|
|
415
|
-
results += 1;
|
|
416
|
-
if (current.copied.has(id)) {
|
|
417
|
-
copies += 1;
|
|
418
|
-
continue;
|
|
419
|
-
}
|
|
420
|
-
add({
|
|
421
|
-
role: "toolResult",
|
|
422
|
-
callId: id,
|
|
423
|
-
name: names.get(id) ?? "",
|
|
424
|
-
text: textOf(block.content),
|
|
425
|
-
isError: block.is_error === true,
|
|
426
|
-
at,
|
|
427
|
-
...mark,
|
|
428
|
-
});
|
|
429
|
-
}
|
|
430
|
-
}
|
|
431
|
-
if (said.length) {
|
|
432
|
-
const text = said.join("\n");
|
|
433
|
-
session.state = INTERRUPTED.test(text) ? "stopped" : "completed";
|
|
434
|
-
add({ role: "user", text, at, ...mark });
|
|
435
|
-
}
|
|
436
|
-
// Results of copied calls alone: a copy, which moves no time either.
|
|
437
|
-
if (results > 0 && copies === results && !said.length)
|
|
438
|
-
return false;
|
|
439
|
-
}
|
|
440
|
-
// The blocks the Codex CLI adds to a user message, each one of its own elements whole, an AGENTS.md as a heading over its
|
|
441
|
-
// <INSTRUCTIONS>; and the bare tags around an image. Only these: a prompt the person wrote as a tagged element is theirs,
|
|
442
|
-
// and a block the CLI adds later reads as text until it is named here.
|
|
443
|
-
const CODEX_BLOCK = /^\s*(?:#[^\n]*\n\s*)?<([A-Za-z_]+)(?:\s[^>]*)?>[\s\S]*<\/\1>\s*$/;
|
|
444
|
-
const CODEX_BLOCKS = new Set(["environment_context", "user_instructions", "INSTRUCTIONS", "turn_aborted", "subagent_notification", "skill", "user_shell_command", "user_action", "recommended_plugins", "codex_internal_context"]);
|
|
445
|
-
const IMAGE_TAG = /^\s*<\/?image\b[^>]*>\s*$/;
|
|
446
|
-
const typed = (text) => !CODEX_BLOCKS.has(CODEX_BLOCK.exec(text)?.[1] ?? "") && !IMAGE_TAG.test(text);
|
|
447
|
-
/** The person's words in a Codex user message: "" when the CLI wrote all of it. */
|
|
448
|
-
const wordsOf = (content) => textOf(Array.isArray(content) ? content.filter((block) => !isObject(block) || typeof block.text !== "string" || typed(block.text)) : content);
|
|
449
|
-
// The response items of the model's own output: each of one request, until its usage comes.
|
|
450
|
-
const CODEX_OUTPUTS = new Set(["reasoning", "function_call", "custom_tool_call", "web_search_call", "tool_search_call"]);
|
|
451
|
-
const CODEX_HEAD = /^(?:Command|Chunk ID|Exit code): /;
|
|
452
|
-
const CODEX_EXIT = /^(?:Exit code: |Process exited with code )(-?\d+)$/;
|
|
453
|
-
/** Whether a Codex tool call failed, as its output says, else undefined: a structured output's success flag or
|
|
454
|
-
* metadata.exit_code, the exit code in a shell call's head (the lines before "Output:"), or how a script ended. */
|
|
455
|
-
function codexFailed(output) {
|
|
456
|
-
if (isObject(output) && typeof output.success === "boolean")
|
|
457
|
-
return !output.success;
|
|
458
|
-
const text = textOf(isObject(output) && "content" in output ? output.content : output);
|
|
459
|
-
if (text.startsWith("{")) {
|
|
460
|
-
try {
|
|
461
|
-
const parsed = JSON.parse(text);
|
|
462
|
-
if (isObject(parsed) && isObject(parsed.metadata) && typeof parsed.metadata.exit_code === "number")
|
|
463
|
-
return parsed.metadata.exit_code !== 0;
|
|
464
|
-
}
|
|
465
|
-
catch {
|
|
466
|
-
// Not JSON: read as text.
|
|
467
|
-
}
|
|
468
|
-
}
|
|
469
|
-
const lines = text.split("\n", 64);
|
|
470
|
-
if (/^Script failed\b/.test(lines[0]))
|
|
471
|
-
return true;
|
|
472
|
-
if (/^Script completed\b/.test(lines[0]))
|
|
473
|
-
return false;
|
|
474
|
-
if (!CODEX_HEAD.test(lines[0]))
|
|
475
|
-
return undefined;
|
|
476
|
-
for (const line of lines) {
|
|
477
|
-
if (line === "Output:")
|
|
478
|
-
break;
|
|
479
|
-
const code = CODEX_EXIT.exec(line)?.[1];
|
|
480
|
-
if (code !== undefined)
|
|
481
|
-
return code !== "0";
|
|
482
|
-
}
|
|
483
|
-
return undefined;
|
|
484
|
-
}
|
|
485
|
-
function codexRecord(value, at, session, { add, names, provider, turns, current, codex }) {
|
|
486
|
-
const payload = isObject(value.payload) ? value.payload : {};
|
|
487
|
-
// One request's output items are one turn; its usage, when it comes, is that turn's. A usage with no request (a
|
|
488
|
-
// compaction's, one whose output is no item read here) is a turn of its own.
|
|
489
|
-
const answer = () => {
|
|
490
|
-
const turn = { role: "assistant", text: "", calls: [], at, ...(session.model ? { model: session.model } : {}), ...(current.effort ? { effort: current.effort } : {}) };
|
|
491
|
-
add(turn);
|
|
492
|
-
return turn;
|
|
493
|
-
};
|
|
494
|
-
const request = () => codex.open ?? (codex.open = codex.unpaid = answer());
|
|
495
|
-
const answered = (usage, response) => {
|
|
496
|
-
const tokens = tokensOf(usage, CODEX_TOKENS, true);
|
|
497
|
-
const turn = codex.unpaid ?? answer();
|
|
498
|
-
if (tokens)
|
|
499
|
-
turn.usage = tokens;
|
|
500
|
-
if (response)
|
|
501
|
-
turn.key = response;
|
|
502
|
-
codex.open = codex.unpaid = undefined;
|
|
503
|
-
};
|
|
504
|
-
if (value.type === "session_meta") {
|
|
505
|
-
if (str(payload.id))
|
|
506
|
-
session.id = payload.id;
|
|
507
|
-
if (str(payload.cwd))
|
|
508
|
-
session.cwd = payload.cwd;
|
|
509
|
-
if (str(payload.model_provider))
|
|
510
|
-
provider.name = payload.model_provider;
|
|
511
|
-
if (str(payload.parent_thread_id) || (isObject(payload.source) && isObject(payload.source.subagent)))
|
|
512
|
-
session.child = true;
|
|
513
|
-
const spawn = isObject(payload.source) && isObject(payload.source.subagent) && isObject(payload.source.subagent.thread_spawn) ? payload.source.subagent.thread_spawn : undefined;
|
|
514
|
-
const parent = str(payload.parent_thread_id) ?? str(spawn?.parent_thread_id);
|
|
515
|
-
if (parent)
|
|
516
|
-
session.parent = parent;
|
|
517
|
-
return;
|
|
518
|
-
}
|
|
519
|
-
if (value.type === "turn_context") {
|
|
520
|
-
const model = str(payload.model);
|
|
521
|
-
if (model)
|
|
522
|
-
session.model = model.includes("/") ? model : `${provider.name ?? "openai"}/${model}`;
|
|
523
|
-
if (!session.cwd && str(payload.cwd))
|
|
524
|
-
session.cwd = payload.cwd;
|
|
525
|
-
current.effort = effortOf(payload.effort);
|
|
526
|
-
// A new turn: a request left open (aborted) has no usage to come.
|
|
527
|
-
codex.open = codex.unpaid = undefined;
|
|
528
|
-
return;
|
|
529
|
-
}
|
|
530
|
-
// Each request's usage: a token_usage_record per response where the rollout has them (they also count requests no
|
|
531
|
-
// token_count reports, such as a compaction's), else each token_count whose total moved (one that repeats the last
|
|
532
|
-
// total is no new request).
|
|
533
|
-
if (value.type === "token_usage_record") {
|
|
534
|
-
codex.records = true;
|
|
535
|
-
const id = str(payload.response_id);
|
|
536
|
-
if (id && codex.responses.has(id))
|
|
537
|
-
return;
|
|
538
|
-
if (id)
|
|
539
|
-
codex.responses.add(id);
|
|
540
|
-
return answered(payload.usage, id);
|
|
541
|
-
}
|
|
542
|
-
if (value.type === "event_msg") {
|
|
543
|
-
if (payload.type === "user_message") {
|
|
544
|
-
codex.events = true;
|
|
545
|
-
if (str(payload.message))
|
|
546
|
-
add({ role: "user", text: payload.message, at });
|
|
547
|
-
}
|
|
548
|
-
else if (payload.type === "token_count") {
|
|
549
|
-
const info = isObject(payload.info) ? payload.info : undefined;
|
|
550
|
-
if (!info || codex.records)
|
|
551
|
-
return;
|
|
552
|
-
const total = isObject(info.total_token_usage) ? JSON.stringify(info.total_token_usage) : undefined;
|
|
553
|
-
if (total !== undefined && total === codex.total)
|
|
554
|
-
return;
|
|
555
|
-
codex.total = total;
|
|
556
|
-
answered(info.last_token_usage);
|
|
557
|
-
}
|
|
558
|
-
else if (payload.type === "item_completed" && isObject(payload.item) && str(payload.item.id)) {
|
|
559
|
-
// An item's id is its call's in some Codex versions: its status then says whether the call failed.
|
|
560
|
-
const { id, status, exit_code: code } = payload.item;
|
|
561
|
-
const failed = status === "failed" || (typeof code === "number" && code !== 0) ? true : status === "completed" ? false : undefined;
|
|
562
|
-
if (failed === undefined)
|
|
563
|
-
return;
|
|
564
|
-
codex.items.set(id, failed);
|
|
565
|
-
const result = codex.results.get(id);
|
|
566
|
-
if (result && !result.stated)
|
|
567
|
-
result.turn.isError = failed;
|
|
568
|
-
}
|
|
569
|
-
else if (payload.type === "task_complete")
|
|
570
|
-
session.state = "completed";
|
|
571
|
-
else if (payload.type === "turn_aborted")
|
|
572
|
-
session.state = "stopped";
|
|
573
|
-
else if (payload.type === "error")
|
|
574
|
-
session.state = "failed";
|
|
575
|
-
return;
|
|
576
|
-
}
|
|
577
|
-
if (value.type !== "response_item")
|
|
578
|
-
return;
|
|
579
|
-
if (payload.type === "message" && payload.role === "user") {
|
|
580
|
-
const text = wordsOf(payload.content);
|
|
581
|
-
if (text)
|
|
582
|
-
codex.held.push({ index: turns.length, turn: { role: "user", text, at } });
|
|
583
|
-
}
|
|
584
|
-
else if (payload.type === "message" && payload.role === "assistant") {
|
|
585
|
-
const text = textOf(payload.content);
|
|
586
|
-
if (text) {
|
|
587
|
-
const turn = request();
|
|
588
|
-
turn.text = [turn.text, text].filter(Boolean).join("\n");
|
|
589
|
-
}
|
|
590
|
-
}
|
|
591
|
-
else if (typeof payload.type === "string" && CODEX_OUTPUTS.has(payload.type)) {
|
|
592
|
-
const turn = request();
|
|
593
|
-
if (payload.type !== "function_call" && payload.type !== "custom_tool_call")
|
|
594
|
-
return;
|
|
595
|
-
const id = String(payload.call_id ?? payload.id ?? "");
|
|
596
|
-
const name = String(payload.name ?? "");
|
|
597
|
-
names.set(id, name);
|
|
598
|
-
turn.calls.push({
|
|
599
|
-
type: "toolCall",
|
|
600
|
-
id,
|
|
601
|
-
name,
|
|
602
|
-
arguments: argsOf(payload.type === "function_call" ? payload.arguments : payload.input),
|
|
603
|
-
});
|
|
604
|
-
}
|
|
605
|
-
else if (payload.type === "function_call_output" || payload.type === "custom_tool_call_output") {
|
|
606
|
-
const id = String(payload.call_id ?? "");
|
|
607
|
-
const output = isObject(payload.output) && "content" in payload.output ? payload.output.content : payload.output;
|
|
608
|
-
const stated = codexFailed(payload.output);
|
|
609
|
-
// The model saw a result: what it writes next is another request.
|
|
610
|
-
if (codex.open?.calls.some((call) => call.id === id))
|
|
611
|
-
codex.open = undefined;
|
|
612
|
-
const turn = {
|
|
613
|
-
role: "toolResult",
|
|
614
|
-
callId: id,
|
|
615
|
-
name: names.get(id) ?? "",
|
|
616
|
-
text: textOf(output),
|
|
617
|
-
isError: stated ?? codex.items.get(id) ?? false,
|
|
618
|
-
at,
|
|
619
|
-
};
|
|
620
|
-
codex.results.set(id, { turn, stated: stated !== undefined });
|
|
621
|
-
add(turn);
|
|
622
|
-
}
|
|
623
|
-
}
|
|
624
|
-
function piRecord(value, at, session, { add, priced, current }) {
|
|
625
|
-
if (value.type === "session") {
|
|
626
|
-
if (str(value.id))
|
|
627
|
-
session.id = value.id;
|
|
628
|
-
if (str(value.cwd))
|
|
629
|
-
session.cwd = value.cwd;
|
|
630
|
-
return;
|
|
631
|
-
}
|
|
632
|
-
if (value.type === "model_change") {
|
|
633
|
-
if (str(value.provider) && str(value.modelId))
|
|
634
|
-
session.model = `${value.provider}/${value.modelId}`;
|
|
635
|
-
return;
|
|
636
|
-
}
|
|
637
|
-
if (value.type === "thinking_level_change") {
|
|
638
|
-
current.effort = effortOf(value.thinkingLevel);
|
|
639
|
-
return;
|
|
640
|
-
}
|
|
641
|
-
if (value.type !== "message" || !isObject(value.message))
|
|
642
|
-
return;
|
|
643
|
-
const message = value.message;
|
|
644
|
-
const when = timeOf(message.timestamp) ?? at;
|
|
645
|
-
if (message.role === "user")
|
|
646
|
-
add({ role: "user", text: textOf(message.content), at: when });
|
|
647
|
-
else if (message.role === "toolResult")
|
|
648
|
-
add({
|
|
649
|
-
role: "toolResult",
|
|
650
|
-
callId: String(message.toolCallId ?? ""),
|
|
651
|
-
name: String(message.toolName ?? ""),
|
|
652
|
-
text: textOf(message.content),
|
|
653
|
-
isError: message.isError === true,
|
|
654
|
-
at: when,
|
|
655
|
-
});
|
|
656
|
-
else if (message.role === "assistant") {
|
|
657
|
-
if (str(message.provider) && str(message.model))
|
|
658
|
-
session.model = `${message.provider}/${message.model}`;
|
|
659
|
-
const blocks = Array.isArray(message.content) ? message.content : [];
|
|
660
|
-
const text = blocks
|
|
661
|
-
.filter((b) => isObject(b) && b.type === "text")
|
|
662
|
-
.map((b) => b.text)
|
|
663
|
-
.join("\n");
|
|
664
|
-
const calls = blocks
|
|
665
|
-
.filter((b) => isObject(b) && b.type === "toolCall")
|
|
666
|
-
.map((b) => ({
|
|
667
|
-
type: "toolCall",
|
|
668
|
-
id: String(b.id ?? ""),
|
|
669
|
-
name: String(b.name ?? ""),
|
|
670
|
-
arguments: argsOf(b.arguments),
|
|
671
|
-
}));
|
|
672
|
-
const usage = isObject(message.usage) && isObject(message.usage.cost) ? message.usage.cost : undefined;
|
|
673
|
-
const cost = typeof usage?.total === "number" && Number.isFinite(usage.total) && usage.total >= 0 ? usage.total : undefined;
|
|
674
|
-
// pi prices each request: the session's cost is their sum, unknown once one is not priced.
|
|
675
|
-
priced.sum += cost ?? 0;
|
|
676
|
-
priced.unknown ||= cost === undefined;
|
|
677
|
-
session.costUsd = priced.unknown ? undefined : priced.sum;
|
|
678
|
-
session.state = message.stopReason === "error" ? "failed" : message.stopReason === "aborted" ? "stopped" : "completed";
|
|
679
|
-
// A request cut before its end has only the start of its counts: unknown, as a live run's.
|
|
680
|
-
const tokens = message.stopReason === "aborted" ? undefined : withLong(tokensOf(message.usage, PI_TOKENS), isObject(message.usage) ? message.usage.cacheWrite1h : undefined);
|
|
681
|
-
add({
|
|
682
|
-
role: "assistant",
|
|
683
|
-
text,
|
|
684
|
-
calls,
|
|
685
|
-
at: when,
|
|
686
|
-
...(cost !== undefined ? { costUsd: cost } : {}),
|
|
687
|
-
...(session.model ? { model: session.model } : {}),
|
|
688
|
-
...(current.effort ? { effort: current.effort } : {}),
|
|
689
|
-
...(tokens ? { usage: tokens } : {}),
|
|
690
|
-
...(message.stopReason === "error" ? { error: str(message.errorMessage) ?? "unknown error" } : {}),
|
|
691
|
-
});
|
|
692
|
-
}
|
|
693
|
-
}
|