@tangle-network/sdk-provider-cli-base 0.13.205 → 0.13.207

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
@@ -71,8 +71,9 @@ interface PrimeTurn extends AcpTurn<PrimeConfig> {
71
71
  * Kernel death closes the session with a typed failure.
72
72
  *
73
73
  * prime hosts one session per connection and has no `session/load`: a new
74
- * process opens a new ACP session, and the conversation resumes from prime's
75
- * own session files in the per-session agent dir.
74
+ * process opens a new ACP session and a new prime-agent session. It reads an
75
+ * earlier session's file only when the caller's flags name one (`--continue`,
76
+ * `--resume`), which prime-agent looks up in its session directory.
76
77
  */
77
78
  declare class PrimeProviderAdapter extends AcpProviderAdapterBase<PrimeConfig, PrimeTurn> {
78
79
  readonly provider = "prime";
@@ -85,6 +86,13 @@ declare class PrimeProviderAdapter extends AcpProviderAdapterBase<PrimeConfig, P
85
86
  sessionId: string;
86
87
  workspaceRoot: string;
87
88
  }): Promise<AcpProcessSpec>;
89
+ /**
90
+ * Where prime-agent keeps this session's own records. An agent dir of the
91
+ * session's own holds them where prime-agent puts them by default. A shared
92
+ * agent dir (continual mode) gives each session a directory inside it, so
93
+ * the model calls one session made are never read as another's.
94
+ */
95
+ private sessionRecordsDir;
88
96
  protected spawnFailureMessage(failure: {
89
97
  message: string;
90
98
  missingBinary: boolean;
@@ -92,9 +100,10 @@ declare class PrimeProviderAdapter extends AcpProviderAdapterBase<PrimeConfig, P
92
100
  /**
93
101
  * prime-agent's `session/prompt` response reports no token usage, so each
94
102
  * 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.
103
+ * that prompt (see prompt-usage.ts). The files are the session's own: those
104
+ * in the session directory the process was started with, and its subagents'
105
+ * in the agent dir the process was started on, which the agent environment
106
+ * can set over the spec's.
98
107
  */
99
108
  protected spawnBridge(request: AcpBridgeSpawn): RpcBridge;
100
109
  /**
@@ -148,22 +148,31 @@ function materializePrimeModelsConfig(agentDir, input, io = { write: writePrimeA
148
148
  * calls the prompt made.
149
149
  */
150
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).
151
+ * Prints, as a JSON array, the usage of every model call one session's files
152
+ * recorded at or after a time (argv: agent dir, session dir, epoch ms).
153
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.
154
+ * Nothing prime-agent writes names the ACP session a file belongs to, so the
155
+ * adapter starts each process with a session directory of the session's own
156
+ * (`--session-dir`). A root session's file is `<session dir>/<id>.jsonl`, one
157
+ * for each process the session has run. A subagent's file is below
158
+ * `<agent dir>/session-artifacts/<root id>/`, however deep it was spawned,
159
+ * and its calls are in no root file's message rows. So the session's calls
160
+ * are those in its root files and in the trees its root ids name, each
161
+ * counted once; another session's root files, and the trees their ids name,
162
+ * are never opened. prime-agent keeps a root session's other artifacts in
163
+ * `session-artifacts/<root id>/` beside the session directory, which is the
164
+ * same tree only when the session directory is the agent dir's default.
165
+ *
166
+ * Rows are appended in time order and stamped when appended, so a prompt's
167
+ * rows are a file's tail: each file is read backwards and left at the first
168
+ * message row older than the time, which keeps a long session's history
169
+ * unread. A file last written well before the time is not opened; the margin
170
+ * covers filesystems that store modification times to the second.
162
171
  */
163
172
  const MODEL_CALLS_SCRIPT = `
164
173
  const fs = require("node:fs");
165
174
  const path = require("node:path");
166
- const [agentDir, sinceArg] = process.argv.slice(1);
175
+ const [agentDir, sessionDir, sinceArg] = process.argv.slice(1);
167
176
  const since = Number(sinceArg);
168
177
  const CHUNK = 64 * 1024;
169
178
  const MTIME_MARGIN_MS = 60 * 1000;
@@ -210,15 +219,16 @@ function scan(file) {
210
219
  fs.closeSync(fd);
211
220
  }
212
221
  }
213
- function walk(dir, depth) {
214
- let entries;
222
+ function list(dir) {
215
223
  try {
216
- entries = fs.readdirSync(dir, { withFileTypes: true });
224
+ return fs.readdirSync(dir, { withFileTypes: true });
217
225
  } catch (error) {
218
- if (error.code === "ENOENT" || error.code === "ENOTDIR") return;
226
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") return [];
219
227
  throw error;
220
228
  }
221
- for (const entry of entries) {
229
+ }
230
+ function walk(dir, depth) {
231
+ for (const entry of list(dir)) {
222
232
  const file = path.join(dir, entry.name);
223
233
  if (entry.isDirectory()) {
224
234
  if (depth < 16) walk(file, depth + 1);
@@ -227,8 +237,16 @@ function walk(dir, depth) {
227
237
  }
228
238
  }
229
239
  }
230
- walk(path.join(agentDir, "sessions"), 0);
231
- walk(path.join(agentDir, "session-artifacts"), 0);
240
+ const artifactRoots = new Set([
241
+ path.resolve(agentDir, "session-artifacts"),
242
+ path.resolve(sessionDir, "..", "session-artifacts"),
243
+ ]);
244
+ for (const entry of list(sessionDir)) {
245
+ if (!entry.isFile() || !entry.name.endsWith(".jsonl")) continue;
246
+ scan(path.join(sessionDir, entry.name));
247
+ const rootId = entry.name.slice(0, -".jsonl".length);
248
+ for (const root of artifactRoots) walk(path.join(root, rootId), 0);
249
+ }
232
250
  process.stdout.write(JSON.stringify(calls));
233
251
  `;
234
252
  const COUNTS = [
@@ -258,21 +276,27 @@ function sumModelCalls(calls) {
258
276
  return total;
259
277
  }
260
278
  /**
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.
279
+ * The usage of the model calls one session's files recorded at or after
280
+ * `sinceMs`: the root files in `sessionDir` and its subagents' files in
281
+ * `agentDir`. `runAsOwner` runs a Node script as the agent dir's owner (the
282
+ * adapter's `runNodeAsSubprocess`), like every other read in that dir.
264
283
  */
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)]));
284
+ async function readPromptUsage(session, sinceMs, runAsOwner) {
285
+ const calls = JSON.parse(await runAsOwner("prime: cannot read the prompt's usage from the agent dir as its owner", MODEL_CALLS_SCRIPT, [
286
+ session.agentDir,
287
+ session.sessionDir,
288
+ String(sinceMs)
289
+ ]));
267
290
  return Array.isArray(calls) ? sumModelCalls(calls) : void 0;
268
291
  }
269
292
  /**
270
293
  * `bridge` with each `session/prompt` response carrying the usage of the
271
294
  * model calls that prompt made, as `tokenUsage`.
272
295
  *
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
296
+ * `readUsage` reads one session's files, and the window opens when the prompt
297
+ * is sent, which the ACP session adapter does only after the session's
298
+ * previous prompt has answered, so one prompt's calls are never read into
299
+ * another's. A prompt that fails leaves the window
276
300
  * open: the retry on the same process then reports the calls of both. A usage
277
301
  * read that fails is reported to `onUnreadable` and the response is returned
278
302
  * without usage, which stays distinct from a measured zero.
@@ -335,6 +359,8 @@ var PrimeKernelDeadError = class extends Error {
335
359
  //#endregion
336
360
  //#region src/adapters/prime/adapter.ts
337
361
  const DEFAULT_MODEL_PROVIDER = "tangle";
362
+ /** The prime-agent flag that names the directory a session's own file is written in. */
363
+ const SESSION_DIR_FLAG = "--session-dir";
338
364
  /**
339
365
  * Env vars the adapter sets on the spawned prime-agent. The bridge lays this
340
366
  * env over the sidecar's inherited one (sdk-cli-runner mergeSpawnEnv), so the
@@ -414,8 +440,9 @@ function __setPrimeBridgeFactoryForTesting(factory) {
414
440
  * Kernel death closes the session with a typed failure.
415
441
  *
416
442
  * prime hosts one session per connection and has no `session/load`: a new
417
- * process opens a new ACP session, and the conversation resumes from prime's
418
- * own session files in the per-session agent dir.
443
+ * process opens a new ACP session and a new prime-agent session. It reads an
444
+ * earlier session's file only when the caller's flags name one (`--continue`,
445
+ * `--resume`), which prime-agent looks up in its session directory.
419
446
  */
420
447
  var PrimeProviderAdapter = class extends AcpProviderAdapterBase {
421
448
  provider = "prime";
@@ -477,10 +504,12 @@ var PrimeProviderAdapter = class extends AcpProviderAdapterBase {
477
504
  }
478
505
  });
479
506
  const env = this.buildSpawnEnv(agentDir);
507
+ const args = this.buildSpawnArgs(config, modelId, profileArgs);
508
+ if (!args.includes(SESSION_DIR_FLAG)) args.push(SESSION_DIR_FLAG, this.sessionRecordsDir(agentDir, config, context.sessionId));
480
509
  return {
481
510
  command: this.getCliPath(),
482
511
  args: [
483
- ...this.buildSpawnArgs(config, modelId, profileArgs),
512
+ ...args,
484
513
  "--daemon-socket",
485
514
  env.PRIME_AGENT_DAEMON_SOCKET
486
515
  ],
@@ -488,21 +517,36 @@ var PrimeProviderAdapter = class extends AcpProviderAdapterBase {
488
517
  statusDetail: "Spawning prime-agent (ACP mode)"
489
518
  };
490
519
  }
520
+ /**
521
+ * Where prime-agent keeps this session's own records. An agent dir of the
522
+ * session's own holds them where prime-agent puts them by default. A shared
523
+ * agent dir (continual mode) gives each session a directory inside it, so
524
+ * the model calls one session made are never read as another's.
525
+ */
526
+ sessionRecordsDir(agentDir, config, sessionId) {
527
+ return config.continualHarnessState ? join(agentDir, "session-records", sessionId, "sessions") : join(agentDir, "sessions");
528
+ }
491
529
  spawnFailureMessage(failure) {
492
530
  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}`;
493
531
  }
494
532
  /**
495
533
  * prime-agent's `session/prompt` response reports no token usage, so each
496
534
  * 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.
535
+ * that prompt (see prompt-usage.ts). The files are the session's own: those
536
+ * in the session directory the process was started with, and its subagents'
537
+ * in the agent dir the process was started on, which the agent environment
538
+ * can set over the spec's.
500
539
  */
501
540
  spawnBridge(request) {
502
541
  const bridge = (bridgeFactoryOverride ?? spawnAcpBridge)(request);
503
542
  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) }));
543
+ const flag = request.args.lastIndexOf(SESSION_DIR_FLAG);
544
+ const sessionDir = flag < 0 ? void 0 : request.args[flag + 1];
545
+ if (!agentDir || !sessionDir) return bridge;
546
+ return withPromptUsage(bridge, (sinceMs) => readPromptUsage({
547
+ agentDir,
548
+ sessionDir
549
+ }, 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) }));
506
550
  }
507
551
  /**
508
552
  * 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.205",
3
+ "version": "0.13.207",
4
4
  "description": "Base adapter for CLI-based AI agent providers",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",
@@ -79,8 +79,8 @@
79
79
  "registry": "https://registry.npmjs.org"
80
80
  },
81
81
  "tangleRelease": {
82
- "sourceSha": "6033787eb5439bac0a76105dbe0e5c89f65eb6dd",
83
- "mergedAt": "2026-11-24T11:26:41-08:00"
82
+ "sourceSha": "35b13c72e9b97ee18ae7d61182a30a872cf552b9",
83
+ "mergedAt": "2026-11-24T12:34:25-08:00"
84
84
  },
85
85
  "scripts": {
86
86
  "build": "tsdown",