@tangle-network/sdk-provider-cli-base 0.13.205 → 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
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.206",
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": "4731feee617625a5bacad23efc422de2319cceb4",
83
+ "mergedAt": "2026-11-24T11:49:38-08:00"
84
84
  },
85
85
  "scripts": {
86
86
  "build": "tsdown",