@tangle-network/sdk-provider-cli-base 0.13.204 → 0.13.206

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.
@@ -7,12 +7,20 @@ import { StreamEvent } from "@tangle-network/agent-interface";
7
7
  * Exo (https://github.com/exoharness/exo), driven headless: `exo run` reads
8
8
  * an agent definition file, runs one `--prompt` turn of its built-in `basic`
9
9
  * loop as a local process in the workspace, and prints the thread id, the
10
- * reply and a stats line on stdout. The model key lives in Exo's vault.
10
+ * reply and a stats line on stdout. The turn's tool calls and token counts
11
+ * are in the thread's event log, which `exo thread events` prints. The model
12
+ * key lives in Exo's vault.
11
13
  */
12
14
  type ExoConfig = CliProviderConfig;
13
15
  type ExoEvent = {
16
+ type: "agent";
17
+ id: string;
18
+ } | {
14
19
  type: "thread";
15
20
  id: string;
21
+ } | {
22
+ type: "model";
23
+ name: string;
16
24
  } | {
17
25
  type: "text";
18
26
  line: string;
@@ -22,6 +30,8 @@ type ExoEvent = {
22
30
  declare class ExoProviderAdapter extends CliProviderAdapterBase<ExoConfig, ExoEvent> {
23
31
  readonly provider = "exo";
24
32
  protected readonly defaultCliPath = "exo";
33
+ /** Each running turn, under its stream parser and under its state. */
34
+ private readonly turns;
25
35
  /** Exo refuses a vault its mount exposes, so the home is never the workspace. */
26
36
  private home;
27
37
  private baseUrl;
@@ -37,6 +47,22 @@ declare class ExoProviderAdapter extends CliProviderAdapterBase<ExoConfig, ExoEv
37
47
  protected buildExecEnv(config: ExoConfig): Record<string, string | undefined>;
38
48
  /** Write the agent definition and the vault key into the home, then start the turn. */
39
49
  protected spawnExecutionProcess(request: CliTurnSpawn<ExoConfig, ExoEvent>): Promise<CliTurnProcess>;
50
+ /** Start the CLI, with the turn's event log opened at the moment before. */
51
+ private startTurn;
52
+ /**
53
+ * Read the log while the CLI runs, so a tool shows when it starts and not
54
+ * when the turn ends. Each event Exo logs is a new file in the thread's
55
+ * events directory; a change there wakes a read, and what is read always
56
+ * comes from `exo thread events`. A directory this process cannot see wakes
57
+ * nothing, and the turn's events are read when the CLI exits.
58
+ */
59
+ private watchLog;
60
+ /** Emit the tools the log gained since the last read and record its usage. */
61
+ private readLog;
62
+ /** Read what the log gained up to the CLI's exit, then emit the reply. */
63
+ protected afterCliProcessExit(params: {
64
+ state: ExecutionState;
65
+ }): Promise<void>;
40
66
  protected createEventParser(state: ExecutionState, onEvent?: (event: StreamEvent) => void): StreamParserConfig<ExoEvent>;
41
67
  }
42
68
  //#endregion
@@ -1,6 +1,138 @@
1
- import { C as plaintextResponseParser, Rt as sessionObservedEvents, k as CliProviderAdapterBase } from "../../src-D9Za3lQC.mjs";
1
+ import { C as plaintextResponseParser, Ht as toolResultEvents, O as recordCliTokenUsage, Rt as sessionObservedEvents, Ut as toolStartEvents, k as CliProviderAdapterBase } from "../../src-D9Za3lQC.mjs";
2
2
  import { normalizeOpenAiCompatibleBaseUrl, resolveTangleRouterDefaults } from "@tangle-network/agent-interface";
3
3
  import { join } from "node:path";
4
+ import { statSync } from "node:fs";
5
+ import { isRecord } from "@tangle-network/agent-core";
6
+ //#region src/adapters/exo/turn-log.ts
7
+ /** The event kinds a turn reads: model replies with their usage, and tools. */
8
+ const KINDS = [
9
+ "messages",
10
+ "tool_requested",
11
+ "tool_result"
12
+ ];
13
+ const count = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
14
+ const add = (total, more) => more === void 0 ? total : (total ?? 0) + more;
15
+ /**
16
+ * Event ids are UUIDv7, which sort by the millisecond they were made in, and
17
+ * a page holds the events after a cursor id. The smallest id of the turn's
18
+ * first millisecond is a cursor that leaves out every earlier turn of a
19
+ * resumed thread without reading them.
20
+ */
21
+ function firstEventIdAt(ms) {
22
+ const hex = Math.trunc(ms).toString(16).padStart(12, "0");
23
+ return `${hex.slice(0, 8)}-${hex.slice(8)}-7000-8000-000000000000`;
24
+ }
25
+ /**
26
+ * Whether a tool result is a failure by Exo's own rule (the `✗` of its
27
+ * compact transcript): a non-zero exit code, an error, or an error flag.
28
+ */
29
+ function toolFailed(result) {
30
+ if (!isRecord(result)) return false;
31
+ const code = result.exit_code;
32
+ return typeof code === "number" && code !== 0 || result.error !== void 0 && result.error !== null || result.is_error === true || result.isError === true;
33
+ }
34
+ /**
35
+ * Exo speaks Anthropic's wire to a model named `claude…` and an OpenAI wire to
36
+ * every other model. A prompt count from Anthropic's wire leaves out the
37
+ * tokens read from and written to the cache; one from an OpenAI wire includes
38
+ * them.
39
+ */
40
+ const promptLeavesOutCache = (model) => /^claude/iu.test(model ?? "");
41
+ var ExoTurnLog = class {
42
+ /** The newest event read; the next page starts after it. */
43
+ cursor;
44
+ /** The model's call ids this turn has used. A part is one call, so a reused id is not a part id. */
45
+ used = /* @__PURE__ */ new Set();
46
+ /** Under each call id, the parts still waiting for a result, oldest first. */
47
+ open = /* @__PURE__ */ new Map();
48
+ /** Exo's counts, summed over the turn's model calls. */
49
+ prompt;
50
+ completion;
51
+ cacheRead;
52
+ cacheWrite;
53
+ reasoning;
54
+ /** `startedAtMs` is a time after the thread's last turn and before this one's CLI starts. */
55
+ constructor(startedAtMs) {
56
+ this.cursor = firstEventIdAt(startedAtMs);
57
+ }
58
+ /** The `exo` arguments that print the turn's events not read yet. */
59
+ pageArgs(agent, thread) {
60
+ return [
61
+ ...[
62
+ "thread",
63
+ "events",
64
+ agent,
65
+ thread
66
+ ],
67
+ ...KINDS.flatMap((kind) => ["--type", kind]),
68
+ ...["--cursor", this.cursor]
69
+ ];
70
+ }
71
+ /**
72
+ * Reads one printed page: adds its model calls' tokens to the totals and
73
+ * returns its tool entries. Throws when `stdout` is not a page.
74
+ */
75
+ read(stdout) {
76
+ const page = JSON.parse(stdout);
77
+ if (!isRecord(page) || !Array.isArray(page.events)) throw new Error("exo thread events printed no event list");
78
+ const entries = [];
79
+ for (const event of page.events) {
80
+ if (!isRecord(event) || typeof event.id !== "string") continue;
81
+ this.cursor = event.id;
82
+ const data = isRecord(event.data) ? event.data : {};
83
+ const callId = data.tool_call_id;
84
+ if (data.type === "messages") this.countUsage(data.usage);
85
+ else if (typeof callId !== "string") continue;
86
+ else if (data.type === "tool_requested" && isRecord(data.request)) {
87
+ const id = this.used.has(callId) ? `${callId}:${event.id}` : callId;
88
+ this.used.add(callId);
89
+ this.open.set(callId, [...this.open.get(callId) ?? [], id]);
90
+ entries.push({
91
+ type: "start",
92
+ id,
93
+ name: String(data.request.function_name ?? ""),
94
+ input: data.request.arguments
95
+ });
96
+ } else if (data.type === "tool_result") {
97
+ const id = this.open.get(callId)?.shift();
98
+ if (id !== void 0) entries.push({
99
+ type: "result",
100
+ id,
101
+ result: data.result,
102
+ failed: toolFailed(data.result)
103
+ });
104
+ }
105
+ }
106
+ return entries;
107
+ }
108
+ countUsage(usage) {
109
+ if (!isRecord(usage)) return;
110
+ this.prompt = add(this.prompt, count(usage.prompt_tokens));
111
+ this.completion = add(this.completion, count(usage.completion_tokens));
112
+ this.cacheRead = add(this.cacheRead, count(usage.prompt_cached_tokens));
113
+ this.cacheWrite = add(this.cacheWrite, count(usage.prompt_cache_creation_tokens));
114
+ this.reasoning = add(this.reasoning, count(usage.completion_reasoning_tokens));
115
+ }
116
+ /**
117
+ * The tokens of the model calls read so far, summed, under the keys
118
+ * `recordCliTokenUsage` reads; the input count is the whole prompt, cached
119
+ * tokens included. `model` is the name the turn asked Exo for. Undefined
120
+ * until a call reported a count: an endpoint that reports none is not a
121
+ * turn that used none.
122
+ */
123
+ usage(model) {
124
+ if (this.prompt === void 0 && this.completion === void 0) return void 0;
125
+ const outsidePrompt = promptLeavesOutCache(model) ? (this.cacheRead ?? 0) + (this.cacheWrite ?? 0) : 0;
126
+ return {
127
+ input_tokens: this.prompt === void 0 ? void 0 : this.prompt + outsidePrompt,
128
+ output_tokens: this.completion,
129
+ cache_read_input_tokens: this.cacheRead,
130
+ cache_creation_input_tokens: this.cacheWrite,
131
+ reasoning_tokens: this.reasoning
132
+ };
133
+ }
134
+ };
135
+ //#endregion
4
136
  //#region src/adapters/exo/adapter.ts
5
137
  /** The vault secret the agent definition names, and the env it is read from. */
6
138
  const SECRET = "tangle-model";
@@ -10,6 +142,8 @@ const WRITE_FILE = "const fs = require(\"node:fs\"); fs.writeFileSync(process.ar
10
142
  var ExoProviderAdapter = class extends CliProviderAdapterBase {
11
143
  provider = "exo";
12
144
  defaultCliPath = "exo";
145
+ /** Each running turn, under its stream parser and under its state. */
146
+ turns = /* @__PURE__ */ new WeakMap();
13
147
  /** Exo refuses a vault its mount exposes, so the home is never the workspace. */
14
148
  home(config) {
15
149
  return join(config.runtimeHome?.trim() || this.storagePath, ".exo");
@@ -62,7 +196,7 @@ var ExoProviderAdapter = class extends CliProviderAdapterBase {
62
196
  const { config, env, execArgs, workspaceRoot } = request;
63
197
  await this.ensureSubprocessOwnedDir(this.home(config));
64
198
  await this.runNodeAsSubprocess("exo: cannot write the agent definition as the subprocess user", WRITE_FILE, [execArgs.args[1] ?? ""], execArgs.stdin);
65
- if (!config.apiKey) return super.spawnExecutionProcess(request);
199
+ if (!config.apiKey) return this.startTurn(request);
66
200
  const vault = (verb) => this.runCli({
67
201
  command: this.getCliPath(),
68
202
  args: [...[
@@ -85,7 +219,7 @@ var ExoProviderAdapter = class extends CliProviderAdapterBase {
85
219
  }
86
220
  const forget = () => vault("delete").catch(() => void 0);
87
221
  try {
88
- const turn = await super.spawnExecutionProcess(request);
222
+ const turn = await this.startTurn(request);
89
223
  turn.exitPromise.then(forget, forget);
90
224
  return turn;
91
225
  } catch (error) {
@@ -93,9 +227,102 @@ var ExoProviderAdapter = class extends CliProviderAdapterBase {
93
227
  throw error;
94
228
  }
95
229
  }
230
+ /** Start the CLI, with the turn's event log opened at the moment before. */
231
+ async startTurn(request) {
232
+ const { config, env, workspaceRoot } = request;
233
+ const turn = this.turns.get(request.parser);
234
+ if (turn) {
235
+ turn.log = new ExoTurnLog(Date.now());
236
+ turn.exo = (args) => this.runCli({
237
+ command: this.getCliPath(),
238
+ args,
239
+ cwd: workspaceRoot,
240
+ env,
241
+ timeoutMs: 15e3
242
+ });
243
+ const agents = join(this.home(config), "exoharness", "agents");
244
+ turn.eventsDir = (agent, thread) => join(agents, agent, "conversations", thread, "events");
245
+ }
246
+ const cli = await super.spawnExecutionProcess(request);
247
+ const unwatch = () => clearInterval(turn?.watch);
248
+ cli.exitPromise.then(unwatch, unwatch);
249
+ return cli;
250
+ }
251
+ /**
252
+ * Read the log while the CLI runs, so a tool shows when it starts and not
253
+ * when the turn ends. Each event Exo logs is a new file in the thread's
254
+ * events directory; a change there wakes a read, and what is read always
255
+ * comes from `exo thread events`. A directory this process cannot see wakes
256
+ * nothing, and the turn's events are read when the CLI exits.
257
+ */
258
+ watchLog(turn) {
259
+ const { agent, thread, eventsDir } = turn;
260
+ if (turn.watch || turn.exited || !agent || !thread || !eventsDir) return;
261
+ const dir = eventsDir(agent, thread);
262
+ let seen;
263
+ let queued = false;
264
+ turn.watch = setInterval(() => {
265
+ let changed;
266
+ try {
267
+ changed = statSync(dir).mtimeMs;
268
+ } catch {
269
+ return;
270
+ }
271
+ if (changed === seen) return;
272
+ seen = changed;
273
+ if (queued) return;
274
+ queued = true;
275
+ turn.reading = turn.reading.then(() => {
276
+ queued = false;
277
+ return this.readLog(turn);
278
+ });
279
+ }, 200);
280
+ turn.watch.unref();
281
+ }
282
+ /** Emit the tools the log gained since the last read and record its usage. */
283
+ async readLog(turn) {
284
+ const { agent, thread, log, exo, state } = turn;
285
+ if (!agent || !thread || !log || !exo) return;
286
+ try {
287
+ const page = await exo(log.pageArgs(agent, thread));
288
+ if (!page.exit.success) throw new Error(page.stderr.slice(-300) || "no event page");
289
+ for (const entry of log.read(page.stdout ?? "")) {
290
+ const events = entry.type === "start" ? toolStartEvents(state, entry) : toolResultEvents(state, {
291
+ id: entry.id,
292
+ content: entry.failed ? JSON.stringify(entry.result) : entry.result,
293
+ isError: entry.failed
294
+ });
295
+ for (const event of events) turn.onEvent?.(event);
296
+ }
297
+ recordCliTokenUsage(state, log.usage(turn.model));
298
+ } catch (error) {
299
+ this.logger.warn("exo: could not read the turn's event log", {
300
+ thread,
301
+ error: error instanceof Error ? error.message : String(error)
302
+ });
303
+ }
304
+ }
305
+ /** Read what the log gained up to the CLI's exit, then emit the reply. */
306
+ async afterCliProcessExit(params) {
307
+ const turn = this.turns.get(params.state);
308
+ if (!turn) return;
309
+ turn.exited = true;
310
+ clearInterval(turn.watch);
311
+ try {
312
+ await turn.reading;
313
+ await this.readLog(turn);
314
+ } finally {
315
+ turn.reply?.();
316
+ }
317
+ }
96
318
  createEventParser(state, onEvent) {
97
319
  let replying = false;
98
- return plaintextResponseParser(state, onEvent, {
320
+ const turn = {
321
+ state,
322
+ onEvent,
323
+ reading: Promise.resolve()
324
+ };
325
+ const plain = plaintextResponseParser(state, onEvent, {
99
326
  classify: (line) => {
100
327
  const reply = /^\[\d\d:\d\d:\d\d\] agent: (.*)$/u.exec(line);
101
328
  if (reply) {
@@ -110,20 +337,40 @@ var ExoProviderAdapter = class extends CliProviderAdapterBase {
110
337
  type: "text",
111
338
  line
112
339
  };
113
- const thread = /^thread: \S+ \(([0-9a-f-]{36})\)$/u.exec(line);
114
- return thread?.[1] ? {
115
- type: "thread",
116
- id: thread[1]
340
+ const named = /^(agent|thread): \S+ \(([0-9a-f-]{36})\)$/u.exec(line);
341
+ if (named?.[2]) return {
342
+ type: named[1] === "agent" ? "agent" : "thread",
343
+ id: named[2]
344
+ };
345
+ const model = /^model: (.+)$/u.exec(line);
346
+ return model?.[1] ? {
347
+ type: "model",
348
+ name: model[1]
117
349
  } : null;
118
350
  },
119
351
  map: (event, response) => {
120
- if (event.type === "thread") return sessionObservedEvents(state, "exo", event.id);
121
352
  if (event.type === "text") response.text(event.line);
122
- else response.error("exo ended the turn without a reply");
353
+ else if (event.type === "empty") response.error("exo ended the turn without a reply");
354
+ else if (event.type === "model") turn.model = event.name;
355
+ else {
356
+ turn[event.type] = event.id;
357
+ this.watchLog(turn);
358
+ if (event.type === "thread") return sessionObservedEvents(state, "exo", event.id);
359
+ }
123
360
  return [];
124
361
  },
125
362
  emptyFailureDetail: "exo exited without producing a reply"
126
363
  });
364
+ const parser = {
365
+ ...plain,
366
+ onComplete: () => {
367
+ if (turn.log && !turn.exited) turn.reply = () => plain.onComplete?.();
368
+ else plain.onComplete?.();
369
+ }
370
+ };
371
+ this.turns.set(parser, turn);
372
+ this.turns.set(state, turn);
373
+ return parser;
127
374
  }
128
375
  };
129
376
  //#endregion
@@ -102,6 +102,7 @@ declare class HermesProviderAdapter extends CliProviderAdapterBase<HermesConfig,
102
102
  protected readonly profileHarness: HarnessId;
103
103
  private activeSessionId?;
104
104
  private readonly streamMarker;
105
+ private readonly exportToolTurns;
105
106
  protected readonly defaultCliPath = "hermes";
106
107
  protected isBenignNonZeroExit({
107
108
  exitCode,
@@ -1,8 +1,9 @@
1
- import { Bt as textDeltaEvents, C as plaintextResponseParser, F as isLocalMcpConfig, I as localMcpArgv, It as finalTextEvent, L as localMcpEnv, O as recordCliTokenUsage, Rt as sessionObservedEvents, Vt as textSnapshotEvents, _t as prependPromptSection, ht as partitionImageAttachments, k as CliProviderAdapterBase } from "../../src-D9Za3lQC.mjs";
1
+ import { Bt as textDeltaEvents, C as plaintextResponseParser, F as isLocalMcpConfig, Ht as toolResultEvents, I as localMcpArgv, It as finalTextEvent, L as localMcpEnv, O as recordCliTokenUsage, Rt as sessionObservedEvents, Ut as toolStartEvents, Vt as textSnapshotEvents, _t as prependPromptSection, ht as partitionImageAttachments, k as CliProviderAdapterBase } from "../../src-D9Za3lQC.mjs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { resolveTangleRouterDefaults } from "@tangle-network/agent-interface";
4
4
  import { writeFile } from "node:fs/promises";
5
5
  import { dirname, join } from "node:path";
6
+ import { isRecord } from "@tangle-network/agent-core";
6
7
  import { z } from "zod";
7
8
  import { DatabaseSync } from "node:sqlite";
8
9
  //#region src/adapters/hermes/native-connection.ts
@@ -57,12 +58,74 @@ function resolveHermesNativeConnection(config, explicitModel) {
57
58
  };
58
59
  }
59
60
  //#endregion
61
+ //#region src/adapters/hermes/session-tools.ts
62
+ /**
63
+ * Tool events for the calls one turn made, read from `hermes sessions export`.
64
+ *
65
+ * The export holds every stored row of the session. An assistant row lists
66
+ * its calls under `tool_calls` (`id`, `function.name`, `function.arguments`
67
+ * as JSON text) and each result is a `tool` row naming its `tool_call_id`. A
68
+ * row belongs to this turn when the session stored it after the turn's CLI
69
+ * launched (`timestamp`, in epoch seconds): a resumed session's earlier rows,
70
+ * and the copies a compaction makes of them, keep their own times.
71
+ *
72
+ * The export keeps a tool's result but not Hermes's verdict on it, so each
73
+ * finished call is reported completed with the result the model received.
74
+ */
75
+ function exportedToolEvents(state, session, launchedAtMs) {
76
+ const events = [];
77
+ const rows = Array.isArray(session.messages) ? session.messages : [];
78
+ for (const row of rows) {
79
+ if (!isRecord(row) || typeof row.timestamp !== "number" || row.timestamp * 1e3 < launchedAtMs) continue;
80
+ if (row.role === "assistant" && Array.isArray(row.tool_calls)) for (const call of row.tool_calls) {
81
+ const fn = isRecord(call) ? call.function : void 0;
82
+ if (!isRecord(call) || !isRecord(fn) || typeof call.id !== "string" || typeof fn.name !== "string" || state.toolCalls.has(call.id)) continue;
83
+ events.push(...toolStartEvents(state, {
84
+ id: call.id,
85
+ name: fn.name,
86
+ input: toolArguments(fn.arguments)
87
+ }));
88
+ }
89
+ else if (row.role === "tool" && typeof row.tool_call_id === "string") {
90
+ if (state.toolCalls.get(row.tool_call_id)?.status !== "running") continue;
91
+ events.push(...toolResultEvents(state, {
92
+ id: row.tool_call_id,
93
+ content: row.content,
94
+ isError: false
95
+ }));
96
+ }
97
+ }
98
+ return events;
99
+ }
100
+ /** The arguments object the model sent; text that is not one stays readable under `arguments`. */
101
+ function toolArguments(raw) {
102
+ if (isRecord(raw)) return raw;
103
+ if (typeof raw !== "string" || !raw) return {};
104
+ try {
105
+ const parsed = JSON.parse(raw);
106
+ if (isRecord(parsed)) return parsed;
107
+ } catch {}
108
+ return { arguments: raw };
109
+ }
110
+ //#endregion
60
111
  //#region src/adapters/hermes/stream-parser.ts
61
112
  /** Hermes emits its stream marker only on the packaged quiet chat path. A
62
- * custom or older CLI can print a JSON answer without selecting this protocol. */
63
- function hermesStreamParser(marker, plaintext, state, onEvent) {
113
+ * custom or older CLI can print a JSON answer without selecting this protocol.
114
+ * `onAcknowledged` runs once the CLI has selected it: from then on stdout names
115
+ * every tool the turn runs. */
116
+ function hermesStreamParser(marker, plaintext, state, onEvent, onAcknowledged) {
64
117
  let streaming = false;
65
118
  let finished = false;
119
+ const openCalls = /* @__PURE__ */ new Map();
120
+ let textFollowsTool = false;
121
+ function emit(events) {
122
+ for (const event of events) onEvent?.(event);
123
+ }
124
+ function openTextPart() {
125
+ state.textPartId = void 0;
126
+ state.textPartFrom = state.textBuffer.length;
127
+ textFollowsTool = false;
128
+ }
66
129
  function fail(message) {
67
130
  state.terminalStatus = "failed";
68
131
  state.failure ??= {
@@ -91,6 +154,7 @@ function hermesStreamParser(marker, plaintext, state, onEvent) {
91
154
  const { line } = event;
92
155
  if (!streaming && line === marker) {
93
156
  streaming = true;
157
+ onAcknowledged?.();
94
158
  return;
95
159
  }
96
160
  if (!streaming) {
@@ -105,14 +169,49 @@ function hermesStreamParser(marker, plaintext, state, onEvent) {
105
169
  } catch {
106
170
  return;
107
171
  }
108
- if (frame.type === "text" && typeof frame.text === "string") for (const part of textDeltaEvents(state, frame.text)) onEvent?.(part);
109
- else if (frame.type === "result") {
172
+ const callId = typeof frame.tool_call_id === "string" && frame.tool_call_id ? frame.tool_call_id : void 0;
173
+ if (frame.type === "text" && typeof frame.text === "string") {
174
+ let text = frame.text;
175
+ if (textFollowsTool) {
176
+ text = text.replace(/^\n+/, "");
177
+ if (!text) return;
178
+ if (state.textBuffer) state.textBuffer += "\n\n";
179
+ openTextPart();
180
+ }
181
+ emit(textDeltaEvents(state, text));
182
+ } else if (frame.type === "tool_use" && typeof frame.name === "string") {
183
+ const id = callId ?? randomUUID();
184
+ if (!callId) {
185
+ const open = openCalls.get(frame.name) ?? [];
186
+ open.push(id);
187
+ openCalls.set(frame.name, open);
188
+ }
189
+ textFollowsTool = true;
190
+ emit(toolStartEvents(state, {
191
+ id,
192
+ name: frame.name,
193
+ input: frame.input
194
+ }));
195
+ } else if (frame.type === "tool_result" && typeof frame.name === "string") {
196
+ const id = callId ?? openCalls.get(frame.name)?.shift();
197
+ if (!id) return;
198
+ emit(toolResultEvents(state, {
199
+ id,
200
+ content: frame.output,
201
+ isError: frame.is_error === true
202
+ }));
203
+ } else if (frame.type === "result") {
110
204
  finished = true;
111
205
  if (typeof frame.exit_code !== "number" || typeof frame.text !== "string" || !frame.text && frame.exit_code !== 0) {
112
206
  fail(typeof frame.error === "string" ? frame.error : "Hermes did not complete the turn");
113
207
  return;
114
208
  }
115
- if (frame.text.startsWith(state.textBuffer)) for (const part of textSnapshotEvents(state, frame.text)) onEvent?.(part);
209
+ if (textFollowsTool) openTextPart();
210
+ const streamed = state.textBuffer.slice(state.textPartFrom ?? 0);
211
+ state.textBuffer = streamed;
212
+ state.textPartFrom = 0;
213
+ if (frame.text.trim() === streamed.trim()) state.textBuffer = frame.text;
214
+ else if (frame.text.startsWith(streamed)) emit(textSnapshotEvents(state, frame.text));
116
215
  else {
117
216
  const update = finalTextEvent(state, frame.text);
118
217
  if (update.type === "message.part.updated") onEvent?.({
@@ -152,6 +251,7 @@ var HermesProviderAdapter = class extends CliProviderAdapterBase {
152
251
  profileHarness = "hermes";
153
252
  activeSessionId;
154
253
  streamMarker = `tangle-hermes-stream-${randomUUID()}`;
254
+ exportToolTurns = /* @__PURE__ */ new WeakMap();
155
255
  defaultCliPath = "hermes";
156
256
  isBenignNonZeroExit({ exitCode, stderr, state }) {
157
257
  if (exitCode === null || exitCode === 0) return false;
@@ -285,6 +385,8 @@ var HermesProviderAdapter = class extends CliProviderAdapterBase {
285
385
  this.logger.warn("hermes: session export did not return JSON", { sessionId: hermesSessionId });
286
386
  return;
287
387
  }
388
+ const launchedAt = this.exportToolTurns.get(params.state);
389
+ if (launchedAt !== void 0) for (const event of exportedToolEvents(params.state, session, launchedAt)) params.onEvent?.(event);
288
390
  recordCliTokenUsage(params.state, {
289
391
  usage: {
290
392
  input_tokens: session.input_tokens,
@@ -321,7 +423,8 @@ var HermesProviderAdapter = class extends CliProviderAdapterBase {
321
423
  },
322
424
  emptyFailureDetail: "hermes errored without producing a response body"
323
425
  });
324
- return process.env.HERMES_STREAM === "1" ? hermesStreamParser(this.streamMarker, plaintext, state, onEvent) : plaintext;
426
+ this.exportToolTurns.set(state, Date.now());
427
+ return process.env.HERMES_STREAM === "1" ? hermesStreamParser(this.streamMarker, plaintext, state, onEvent, () => this.exportToolTurns.delete(state)) : plaintext;
325
428
  }
326
429
  };
327
430
  function parseHermesSessionId(stderr) {
@@ -89,6 +89,13 @@ declare class PrimeProviderAdapter extends AcpProviderAdapterBase<PrimeConfig, P
89
89
  message: string;
90
90
  missingBinary: boolean;
91
91
  }): string;
92
+ /**
93
+ * prime-agent's `session/prompt` response reports no token usage, so each
94
+ * response is completed with the usage prime wrote to its session files for
95
+ * that prompt (see prompt-usage.ts). The files are read in the agent dir the
96
+ * process was started on, which the agent environment can set over the
97
+ * spec's.
98
+ */
92
99
  protected spawnBridge(request: AcpBridgeSpawn): RpcBridge;
93
100
  /**
94
101
  * A failed tool whose output carries a kernel-death marker (the ipython
@@ -1,5 +1,5 @@
1
- import { Yt as spawnAcpBridge, _t as prependPromptSection, w as AcpProviderAdapterBase } from "../../src-D9Za3lQC.mjs";
2
- import { PRIME_AGENT_DIR_ENV_VAR, PRIME_AGENT_DIR_ENV_VARS, PRIME_HARNESS_STATE_ENV_DENYLIST, PRIME_HARNESS_STATE_ENV_DENYLIST as PRIME_HARNESS_STATE_ENV_DENYLIST$1, PRIME_KERNEL_DEAD_MARKERS, PRIME_KERNEL_ENV_PASSTHROUGH, PRIME_KERNEL_ENV_PASSTHROUGH as PRIME_KERNEL_ENV_PASSTHROUGH$1, PRIME_MCP_UNSUPPORTED_REASON, PrimeHarnessStateError, PrimeProfileError, assertPrimeModelAgreement, assertPrimeModelAgreement as assertPrimeModelAgreement$1, buildPiModelsConfig, hasPrimeProfileMaterial, matchPrimeKernelDeadMarker, materializePrimeProfileControls, materializePrimeProfileControls as materializePrimeProfileControls$1, primeAgentDirEnv, primeAgentDirEnv as primeAgentDirEnv$1, primeHarnessStatePath, primeProfileNeedsAgentDir, primeSubagentEntryId as subagentEntryId, primeThinkingLevel, primeThinkingLevel as primeThinkingLevel$1, prunePrimeProfileMaterial, readPrimeProfileControls, readPrimeProfileControls as readPrimeProfileControls$1, writePrimeAgentFile } from "@tangle-network/agent-profile-materialize";
1
+ import { D as readCliTokenUsage, Yt as spawnAcpBridge, _t as prependPromptSection, w as AcpProviderAdapterBase } from "../../src-D9Za3lQC.mjs";
2
+ import { PRIME_AGENT_DIR_ENV_VAR, PRIME_AGENT_DIR_ENV_VAR as PRIME_AGENT_DIR_ENV_VAR$1, PRIME_AGENT_DIR_ENV_VARS, PRIME_HARNESS_STATE_ENV_DENYLIST, PRIME_HARNESS_STATE_ENV_DENYLIST as PRIME_HARNESS_STATE_ENV_DENYLIST$1, PRIME_KERNEL_DEAD_MARKERS, PRIME_KERNEL_ENV_PASSTHROUGH, PRIME_KERNEL_ENV_PASSTHROUGH as PRIME_KERNEL_ENV_PASSTHROUGH$1, PRIME_MCP_UNSUPPORTED_REASON, PrimeHarnessStateError, PrimeProfileError, assertPrimeModelAgreement, assertPrimeModelAgreement as assertPrimeModelAgreement$1, buildPiModelsConfig, hasPrimeProfileMaterial, matchPrimeKernelDeadMarker, materializePrimeProfileControls, materializePrimeProfileControls as materializePrimeProfileControls$1, primeAgentDirEnv, primeAgentDirEnv as primeAgentDirEnv$1, primeHarnessStatePath, primeProfileNeedsAgentDir, primeSubagentEntryId as subagentEntryId, primeThinkingLevel, primeThinkingLevel as primeThinkingLevel$1, prunePrimeProfileMaterial, readPrimeProfileControls, readPrimeProfileControls as readPrimeProfileControls$1, writePrimeAgentFile } from "@tangle-network/agent-profile-materialize";
3
3
  import { isAbsolute, join, relative, sep } from "node:path";
4
4
  import { existsSync, lchownSync, lstatSync, mkdirSync } from "node:fs";
5
5
  import { z } from "zod";
@@ -135,6 +135,188 @@ function materializePrimeModelsConfig(agentDir, input, io = { write: writePrimeA
135
135
  return target;
136
136
  }
137
137
  //#endregion
138
+ //#region src/adapters/prime/prompt-usage.ts
139
+ /**
140
+ * Token usage of one prime-agent prompt, read from prime's session files.
141
+ *
142
+ * prime-agent asks its model endpoint for usage on every call
143
+ * (`stream_options.include_usage`) and writes it on that call's assistant
144
+ * message row in a session file, but its ACP surface never reports it: the
145
+ * `session/prompt` response is `{stopReason}` and no `session/update` carries
146
+ * a count. The ACP session adapter records a turn's usage from the prompt
147
+ * response, so the response is completed here with the sum over the model
148
+ * calls the prompt made.
149
+ */
150
+ /**
151
+ * Prints, as a JSON array, the usage of every model call the session files of
152
+ * an agent dir recorded at or after a time (argv: agent dir, epoch ms).
153
+ *
154
+ * A root session's file is `sessions/<id>.jsonl`; a subagent's is below
155
+ * `session-artifacts/` and its calls are in no root file's message rows, so
156
+ * both trees are read and each call is counted once. Rows are appended in
157
+ * time order and stamped when appended, so a prompt's rows are a file's tail:
158
+ * each file is read backwards and left at the first message row older than
159
+ * the time, which keeps a long session's history unread. A file last written
160
+ * well before the time is not opened; the margin covers filesystems that
161
+ * store modification times to the second.
162
+ */
163
+ const MODEL_CALLS_SCRIPT = `
164
+ const fs = require("node:fs");
165
+ const path = require("node:path");
166
+ const [agentDir, sinceArg] = process.argv.slice(1);
167
+ const since = Number(sinceArg);
168
+ const CHUNK = 64 * 1024;
169
+ const MTIME_MARGIN_MS = 60 * 1000;
170
+ const calls = [];
171
+ function scan(file) {
172
+ const fd = fs.openSync(file, "r");
173
+ try {
174
+ const stat = fs.fstatSync(fd);
175
+ if (stat.mtimeMs < since - MTIME_MARGIN_MS) return;
176
+ let end = stat.size;
177
+ // The bytes after the read position that finish a line begun before it.
178
+ let rest = [];
179
+ while (end > 0) {
180
+ const start = Math.max(0, end - CHUNK);
181
+ const chunk = Buffer.alloc(end - start);
182
+ fs.readSync(fd, chunk, 0, chunk.length, start);
183
+ end = start;
184
+ // A read that starts mid-line leaves that line's bytes for the next read.
185
+ const first = start === 0 ? 0 : chunk.indexOf(10) + 1;
186
+ if (start !== 0 && first === 0) {
187
+ rest.unshift(chunk);
188
+ continue;
189
+ }
190
+ const whole = Buffer.concat([chunk.subarray(first), ...rest]);
191
+ rest = [chunk.subarray(0, first)];
192
+ const lines = whole.toString("utf8").split("\\n");
193
+ for (let index = lines.length - 1; index >= 0; index--) {
194
+ let row;
195
+ try {
196
+ row = JSON.parse(lines[index]);
197
+ } catch {
198
+ continue;
199
+ }
200
+ if (!row || row.type !== "message" || !row.message) continue;
201
+ const at = Date.parse(row.timestamp);
202
+ if (Number.isNaN(at)) continue;
203
+ if (at < since) return;
204
+ if (row.message.role === "assistant" && row.message.usage) {
205
+ calls.push(row.message.usage);
206
+ }
207
+ }
208
+ }
209
+ } finally {
210
+ fs.closeSync(fd);
211
+ }
212
+ }
213
+ function walk(dir, depth) {
214
+ let entries;
215
+ try {
216
+ entries = fs.readdirSync(dir, { withFileTypes: true });
217
+ } catch (error) {
218
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") return;
219
+ throw error;
220
+ }
221
+ for (const entry of entries) {
222
+ const file = path.join(dir, entry.name);
223
+ if (entry.isDirectory()) {
224
+ if (depth < 16) walk(file, depth + 1);
225
+ } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
226
+ scan(file);
227
+ }
228
+ }
229
+ }
230
+ walk(path.join(agentDir, "sessions"), 0);
231
+ walk(path.join(agentDir, "session-artifacts"), 0);
232
+ process.stdout.write(JSON.stringify(calls));
233
+ `;
234
+ const COUNTS = [
235
+ "inputTokens",
236
+ "outputTokens",
237
+ "totalTokens",
238
+ "reasoningTokens",
239
+ "cacheReadInputTokens",
240
+ "cacheCreationInputTokens"
241
+ ];
242
+ /**
243
+ * The sum of the model calls' token counts, or undefined when none reported
244
+ * any. prime-agent's own cost figure is left out: it prices a call from the
245
+ * models.json the adapter writes, where every price is zero.
246
+ */
247
+ function sumModelCalls(calls) {
248
+ let total;
249
+ for (const call of calls) {
250
+ const usage = readCliTokenUsage({ usage: call });
251
+ if (!usage) continue;
252
+ total ??= {};
253
+ for (const key of COUNTS) {
254
+ const count = usage[key];
255
+ if (count !== void 0) total[key] = (total[key] ?? 0) + count;
256
+ }
257
+ }
258
+ return total;
259
+ }
260
+ /**
261
+ * The usage of the model calls `agentDir`'s session files recorded at or
262
+ * after `sinceMs`. `runAsOwner` runs a Node script as the agent dir's owner
263
+ * (the adapter's `runNodeAsSubprocess`), like every other read in that dir.
264
+ */
265
+ async function readPromptUsage(agentDir, sinceMs, runAsOwner) {
266
+ const calls = JSON.parse(await runAsOwner("prime: cannot read the prompt's usage from the agent dir as its owner", MODEL_CALLS_SCRIPT, [agentDir, String(sinceMs)]));
267
+ return Array.isArray(calls) ? sumModelCalls(calls) : void 0;
268
+ }
269
+ /**
270
+ * `bridge` with each `session/prompt` response carrying the usage of the
271
+ * model calls that prompt made, as `tokenUsage`.
272
+ *
273
+ * The window opens when the prompt is sent, which the ACP session adapter
274
+ * does only after the session's previous prompt has answered, so one prompt's
275
+ * calls are never read into another's. A prompt that fails leaves the window
276
+ * open: the retry on the same process then reports the calls of both. A usage
277
+ * read that fails is reported to `onUnreadable` and the response is returned
278
+ * without usage, which stays distinct from a measured zero.
279
+ */
280
+ function withPromptUsage(bridge, readUsage, onUnreadable) {
281
+ let since;
282
+ async function request(method, params, options) {
283
+ if (method !== "session/prompt") return bridge.request(method, params, options);
284
+ const opened = since ?? Date.now();
285
+ since = opened;
286
+ const result = await bridge.request(method, params, options);
287
+ since = void 0;
288
+ let tokenUsage;
289
+ try {
290
+ tokenUsage = await readUsage(opened);
291
+ } catch (error) {
292
+ onUnreadable(error);
293
+ }
294
+ return tokenUsage ? {
295
+ ...result,
296
+ tokenUsage
297
+ } : result;
298
+ }
299
+ return {
300
+ request,
301
+ captureTurn: (path, metadata) => bridge.captureTurn(path, metadata),
302
+ notify: (method, params) => bridge.notify(method, params),
303
+ onNotification: (method, handler) => bridge.onNotification(method, handler),
304
+ onRequest: (method, handler) => bridge.onRequest(method, handler),
305
+ onClose: (handler) => bridge.onClose(handler),
306
+ close: (graceMs) => bridge.close(graceMs),
307
+ getStderrTail: () => bridge.getStderrTail(),
308
+ get pid() {
309
+ return bridge.pid;
310
+ },
311
+ get closed() {
312
+ return bridge.closed;
313
+ },
314
+ get process() {
315
+ return bridge.process;
316
+ }
317
+ };
318
+ }
319
+ //#endregion
138
320
  //#region src/adapters/prime/types.ts
139
321
  /**
140
322
  * Typed session-fatal error for a dead IPython kernel. Callers must treat the
@@ -309,8 +491,18 @@ var PrimeProviderAdapter = class extends AcpProviderAdapterBase {
309
491
  spawnFailureMessage(failure) {
310
492
  return failure.missingBinary ? `prime: "${this.getCliPath()}" not found on PATH. The container image must ship the pinned Prime native CLI and prepared Python kernel — see packages/sdk-provider-cli-base/docs/prime.md.` : `prime: failed to spawn prime-agent: ${failure.message}`;
311
493
  }
494
+ /**
495
+ * prime-agent's `session/prompt` response reports no token usage, so each
496
+ * response is completed with the usage prime wrote to its session files for
497
+ * that prompt (see prompt-usage.ts). The files are read in the agent dir the
498
+ * process was started on, which the agent environment can set over the
499
+ * spec's.
500
+ */
312
501
  spawnBridge(request) {
313
- return (bridgeFactoryOverride ?? spawnAcpBridge)(request);
502
+ const bridge = (bridgeFactoryOverride ?? spawnAcpBridge)(request);
503
+ const agentDir = request.env?.[PRIME_AGENT_DIR_ENV_VAR$1];
504
+ if (!agentDir) return bridge;
505
+ return withPromptUsage(bridge, (sinceMs) => readPromptUsage(agentDir, sinceMs, (operation, script, args) => this.runNodeAsSubprocess(operation, script, args)), (error) => this.logger.warn("prime: the turn's token usage is not reported", { error: error instanceof Error ? error.message : String(error) }));
314
506
  }
315
507
  /**
316
508
  * A failed tool whose output carries a kernel-death marker (the ipython
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/sdk-provider-cli-base",
3
- "version": "0.13.204",
3
+ "version": "0.13.206",
4
4
  "description": "Base adapter for CLI-based AI agent providers",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",
@@ -62,7 +62,7 @@
62
62
  "@tangle-network/agent-interface": "^5.10.28",
63
63
  "@tangle-network/agent-profile-materialize": "1.1.220",
64
64
  "@tangle-network/agent-trace-contract": "^2.2.0",
65
- "@tangle-network/cli-agent-registry": "0.15.202",
65
+ "@tangle-network/cli-agent-registry": "0.15.203",
66
66
  "@tangle-network/sdk-cli-runner": "0.3.18",
67
67
  "@tangle-network/sdk-session-persistence": "0.7.17",
68
68
  "zod": "4.6.7"
@@ -79,8 +79,8 @@
79
79
  "registry": "https://registry.npmjs.org"
80
80
  },
81
81
  "tangleRelease": {
82
- "sourceSha": "4fbd1bafc6aedcc78abfba1d9679d33286fc62ac",
83
- "mergedAt": "2026-11-24T10:45:29-08:00"
82
+ "sourceSha": "4731feee617625a5bacad23efc422de2319cceb4",
83
+ "mergedAt": "2026-11-24T11:49:38-08:00"
84
84
  },
85
85
  "scripts": {
86
86
  "build": "tsdown",