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

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.
@@ -1,4 +1,4 @@
1
- import { Dn as CliTurnSpawn, En as CliTurnProcess, Kt as CliProviderConfig, Ot as CliProviderAdapterBase, Wt as CliExecArgs, Xt as ExecutionState, c as WorkspacePlanApplication, n as HarnessId } from "../../index-gDCIpOnJ.mjs";
1
+ import { Dn as CliTurnSpawn, En as CliTurnProcess, Gt as CliExecutionInput, Kt as CliProviderConfig, Ot as CliProviderAdapterBase, Wt as CliExecArgs, Xt as ExecutionState, c as WorkspacePlanApplication, n as HarnessId } from "../../index-gDCIpOnJ.mjs";
2
2
  import { StreamParserConfig } from "@tangle-network/sdk-cli-runner";
3
3
  import { CliAuthFile, ProviderConfig, StreamEvent } from "@tangle-network/agent-interface";
4
4
 
@@ -17,11 +17,18 @@ declare class OpenclawProviderAdapter extends CliProviderAdapterBase<OpenclawCon
17
17
  protected readonly profileHarness: HarnessId;
18
18
  protected readonly defaultCliPath = "openclaw";
19
19
  /**
20
- * Managed `~/.openclaw/openclaw.json` synthesized during initialize() and
21
- * materialized to disk by the sidecar via getManagedAuthFiles(). Empty when
22
- * the caller manages openclaw config itself.
20
+ * Whether the adapter synthesizes `~/.openclaw/openclaw.json`, decided during
21
+ * initialize(). False when the caller manages openclaw config itself.
23
22
  */
24
- private managedAuthFiles;
23
+ private managesConfig;
24
+ /**
25
+ * Each model's limits as the Router's catalog lists them, kept for the
26
+ * backend's life: a model whose limits were read keeps them when a later
27
+ * read fails.
28
+ */
29
+ private readonly modelLimits;
30
+ /** The key of each turn's tool reports, by the parser that takes them. */
31
+ private readonly toolReportKeys;
25
32
  /**
26
33
  * Openclaw reads NO credentials from env — it loads them from
27
34
  * `~/.openclaw/openclaw.json`. A managed sandbox provisions none, so without
@@ -32,8 +39,30 @@ declare class OpenclawProviderAdapter extends CliProviderAdapterBase<OpenclawCon
32
39
  * (authMode "config-only") or already supplied an `openclaw.json`.
33
40
  */
34
41
  protected afterInitialize(_config: ProviderConfig): Promise<void>;
42
+ /**
43
+ * The managed config and the plugin that reports tool calls. The sidecar
44
+ * writes them at initialization and again before each turn, passing the
45
+ * turn's input, so the config declares the model that turn runs. The call
46
+ * with a turn's input first reads the limits of the models it declares; the
47
+ * initialization call reads nothing and states the limits read so far.
48
+ */
35
49
  getManagedAuthFiles(): CliAuthFile[];
36
- private computeManagedAuthFiles;
50
+ getManagedAuthFiles(input: Pick<CliExecutionInput, "model">): Promise<CliAuthFile[]>;
51
+ /**
52
+ * Reads the limits of each model that has none yet from the Router's
53
+ * catalog, with the key the turn's model calls carry. This runs before a
54
+ * turn, so it must not hold or fail one: resolveRouterModelLimits bounds the
55
+ * request, answers from a catalog it read within the last minute, and stops
56
+ * asking an endpoint that failed for a minute.
57
+ *
58
+ * A model whose limits could not be read is declared without them, so until
59
+ * a later turn's read succeeds OpenClaw takes it to hold 128000 tokens and
60
+ * sends its own output cap (buildRouterOpenclawConfig). The same output cap
61
+ * goes out for a model the catalog lists with no verified cap: OpenClaw
62
+ * sends a cap with every request of a declared model, and a missing, null
63
+ * or zero `maxTokens` in the entry gets its default, so no entry sends none.
64
+ */
65
+ private readModelLimits;
37
66
  protected buildExecArgs(params: {
38
67
  message: string;
39
68
  config: OpenclawConfig;
@@ -1,19 +1,128 @@
1
- import { Bt as textDeltaEvents, It as finalTextEvent, O as recordCliTokenUsage, Rt as sessionObservedEvents, Vt as textSnapshotEvents, _t as prependPromptSection, h as nativeEffortArgs, k as CliProviderAdapterBase } from "../../src-D9Za3lQC.mjs";
1
+ import { Bt as textDeltaEvents, Ht as toolResultEvents, It as finalTextEvent, O as recordCliTokenUsage, Rt as sessionObservedEvents, Ut as toolStartEvents, Vt as textSnapshotEvents, _t as prependPromptSection, f as resolveRouterModelLimits, h as nativeEffortArgs, k as CliProviderAdapterBase } from "../../src-D9Za3lQC.mjs";
2
+ import { randomUUID } from "node:crypto";
2
3
  import { resolveTangleRouterDefaults } from "@tangle-network/agent-interface";
4
+ import { StringDecoder } from "node:string_decoder";
5
+ import { Transform } from "node:stream";
6
+ //#region src/adapters/openclaw/tool-reporter.ts
7
+ /**
8
+ * OpenClaw's `agent --json` reports the tools a turn ran only when the turn
9
+ * ends, and only as a count and their names. Its plugin hooks see each tool
10
+ * call as it starts and as it ends, with its arguments and its result, so the
11
+ * adapter installs the standalone plugin file below beside the config it
12
+ * manages. The plugin writes one stdout line per hook; the adapter's parser
13
+ * turns the lines into the turn's tool events.
14
+ *
15
+ * The plugin only reports. Its hooks return nothing, so OpenClaw runs each
16
+ * call as the model made it, and whatever fails inside a hook stays inside it:
17
+ * OpenClaw refuses a tool call whose start hook throws.
18
+ */
19
+ /** A standalone plugin file takes its id from its file name. */
20
+ const TOOL_REPORTER_ID = "tangle-sidecar-events";
21
+ /** The plugin file, relative to the home the sidecar writes managed files to. */
22
+ const TOOL_REPORTER_FILE = `.openclaw/${TOOL_REPORTER_ID}.mjs`;
23
+ /**
24
+ * Leads a stdout line the plugin wrote: the marker, the turn's key, a space
25
+ * and a ToolReport.
26
+ */
27
+ const TOOL_REPORT = "@openclaw/tool ";
28
+ /**
29
+ * The environment variable that gives the plugin a turn's key. Everything
30
+ * that runs in OpenClaw's process shares its stdout, so the marker alone would
31
+ * let any text printed there as a line pass for a tool call. The adapter draws
32
+ * a key per turn and takes only the lines that carry it. Neither the prompt
33
+ * nor a managed file holds the key, but it is no secret from the turn's own
34
+ * tools: a command the model runs inherits OpenClaw's environment and can
35
+ * read it.
36
+ */
37
+ const TOOL_REPORT_KEY_ENV = "OPENCLAW_SIDECAR_TOOL_REPORT_KEY";
38
+ /**
39
+ * The plugin's source. It is plain JavaScript without imports, so OpenClaw
40
+ * loads it from any directory. `String.raw` keeps its escapes as written; the
41
+ * line marker, the key's variable and the plugin id are the constants above.
42
+ */
43
+ const TOOL_REPORTER_SOURCE = String.raw`// Written by the Tangle sidecar beside the OpenClaw config it manages.
44
+ // Reports each tool call of a sidecar turn on stdout: one line when the call
45
+ // starts and one when it ends. It never blocks or changes a call.
46
+ const LINE = ${JSON.stringify(TOOL_REPORT)};
47
+ const KEY = ${JSON.stringify(TOOL_REPORT_KEY_ENV)};
48
+
49
+ // A tool result is { content: [{ type: "text", text }, ...], details }. Its
50
+ // text blocks are the output; any other block is named by its type.
51
+ function outputOf(result) {
52
+ if (result && Array.isArray(result.content))
53
+ return result.content
54
+ .map((block) =>
55
+ block && typeof block.text === "string"
56
+ ? block.text
57
+ : "[" + ((block && block.type) || "content") + "]",
58
+ )
59
+ .join("\n");
60
+ return typeof result === "string" ? result : JSON.stringify(result);
61
+ }
62
+
63
+ function report(phase, event) {
64
+ try {
65
+ // The sidecar gives each turn it launches a key and reads only the lines
66
+ // that carry it. Any other OpenClaw run that loads this config has none
67
+ // and keeps its stdout to itself.
68
+ const key = process.env[KEY];
69
+ if (!key) return;
70
+ const line = {
71
+ phase,
72
+ id: event.toolCallId,
73
+ name: event.toolName,
74
+ input: event.params,
75
+ };
76
+ if (phase === "result") {
77
+ line.output = outputOf(event.result);
78
+ if (typeof event.error === "string") line.error = event.error;
79
+ }
80
+ process.stdout.write(LINE + key + " " + JSON.stringify(line) + "\n");
81
+ } catch {
82
+ // OpenClaw refuses a tool call whose start hook throws. A report that
83
+ // cannot be written never decides whether a tool runs.
84
+ }
85
+ }
86
+
87
+ export default {
88
+ id: ${JSON.stringify(TOOL_REPORTER_ID)},
89
+ name: "Tangle sidecar events",
90
+ description: "Reports the tool calls of a Tangle sidecar turn.",
91
+ register(api) {
92
+ api.on("before_tool_call", (event) => {
93
+ report("start", event);
94
+ });
95
+ api.on("after_tool_call", (event) => {
96
+ report("result", event);
97
+ });
98
+ },
99
+ };
100
+ `;
101
+ //#endregion
3
102
  //#region src/adapters/openclaw/adapter.ts
4
103
  /** openclaw's default agent id; the synthesized config declares only it. */
5
104
  const OPENCLAW_AGENT_ID = "main";
105
+ /** openclaw's config, relative to the home the sidecar writes managed files to. */
106
+ const OPENCLAW_CONFIG_FILE = ".openclaw/openclaw.json";
6
107
  const PARTIAL_REPLY = "@openclaw/partial ";
108
+ const TOOL_REPORTER_NOTICE = `[plugins] ${TOOL_REPORTER_ID}: OpenClaw can't verify where this plugin came from`;
7
109
  var OpenclawProviderAdapter = class extends CliProviderAdapterBase {
8
110
  provider = "openclaw";
9
111
  profileHarness = "openclaw";
10
112
  defaultCliPath = "openclaw";
11
113
  /**
12
- * Managed `~/.openclaw/openclaw.json` synthesized during initialize() and
13
- * materialized to disk by the sidecar via getManagedAuthFiles(). Empty when
14
- * the caller manages openclaw config itself.
114
+ * Whether the adapter synthesizes `~/.openclaw/openclaw.json`, decided during
115
+ * initialize(). False when the caller manages openclaw config itself.
116
+ */
117
+ managesConfig = false;
118
+ /**
119
+ * Each model's limits as the Router's catalog lists them, kept for the
120
+ * backend's life: a model whose limits were read keeps them when a later
121
+ * read fails.
15
122
  */
16
- managedAuthFiles = [];
123
+ modelLimits = /* @__PURE__ */ new Map();
124
+ /** The key of each turn's tool reports, by the parser that takes them. */
125
+ toolReportKeys = /* @__PURE__ */ new WeakMap();
17
126
  /**
18
127
  * Openclaw reads NO credentials from env — it loads them from
19
128
  * `~/.openclaw/openclaw.json`. A managed sandbox provisions none, so without
@@ -24,20 +133,71 @@ var OpenclawProviderAdapter = class extends CliProviderAdapterBase {
24
133
  * (authMode "config-only") or already supplied an `openclaw.json`.
25
134
  */
26
135
  async afterInitialize(_config) {
27
- this.managedAuthFiles = this.computeManagedAuthFiles();
136
+ this.managesConfig = this.config.authMode !== "config-only" && !(this.config.authFiles ?? []).some((f) => f.path === OPENCLAW_CONFIG_FILE);
137
+ if (this.managesConfig) this.logger.debug("openclaw: synthesized managed router config");
28
138
  }
29
- getManagedAuthFiles() {
30
- return this.managedAuthFiles;
139
+ getManagedAuthFiles(input) {
140
+ if (!this.managesConfig) return input ? Promise.resolve([]) : [];
141
+ const models = routerModels([
142
+ this.config.model,
143
+ this.config.profile?.model?.default,
144
+ input?.model?.model
145
+ ]);
146
+ const files = () => {
147
+ const home = managedHome(this.config, this.agentEnvironmentValues());
148
+ return [{
149
+ path: OPENCLAW_CONFIG_FILE,
150
+ content: buildRouterOpenclawConfig({
151
+ models,
152
+ limits: this.modelLimits,
153
+ toolReporter: `${home}/${TOOL_REPORTER_FILE}`
154
+ }),
155
+ mode: 384
156
+ }, {
157
+ path: TOOL_REPORTER_FILE,
158
+ content: TOOL_REPORTER_SOURCE,
159
+ mode: 384
160
+ }];
161
+ };
162
+ return input ? this.readModelLimits(models).then(files) : files();
31
163
  }
32
- computeManagedAuthFiles() {
33
- if (this.config.authMode === "config-only") return [];
34
- if ((this.config.authFiles ?? []).some((f) => f.path === ".openclaw/openclaw.json")) return [];
35
- this.logger.debug("openclaw: synthesized managed router config");
36
- return [{
37
- path: ".openclaw/openclaw.json",
38
- content: buildRouterOpenclawConfig(),
39
- mode: 384
40
- }];
164
+ /**
165
+ * Reads the limits of each model that has none yet from the Router's
166
+ * catalog, with the key the turn's model calls carry. This runs before a
167
+ * turn, so it must not hold or fail one: resolveRouterModelLimits bounds the
168
+ * request, answers from a catalog it read within the last minute, and stops
169
+ * asking an endpoint that failed for a minute.
170
+ *
171
+ * A model whose limits could not be read is declared without them, so until
172
+ * a later turn's read succeeds OpenClaw takes it to hold 128000 tokens and
173
+ * sends its own output cap (buildRouterOpenclawConfig). The same output cap
174
+ * goes out for a model the catalog lists with no verified cap: OpenClaw
175
+ * sends a cap with every request of a declared model, and a missing, null
176
+ * or zero `maxTokens` in the entry gets its default, so no entry sends none.
177
+ */
178
+ async readModelLimits(models) {
179
+ const router = resolveTangleRouterDefaults();
180
+ const apiKey = this.config.apiKey || this.agentEnvironmentValues()[router.apiKeyEnvVar];
181
+ await Promise.all(models.filter((model) => !this.modelLimits.has(model)).map(async (model) => {
182
+ const result = await resolveRouterModelLimits({
183
+ baseUrl: router.baseUrl,
184
+ model,
185
+ cacheRevision: "",
186
+ ...apiKey ? { apiKey } : {}
187
+ });
188
+ if (result.status === "unavailable") {
189
+ this.logger.warn("openclaw model limits unavailable; openclaw runs the model on its own defaults", {
190
+ model,
191
+ reason: result.reason
192
+ });
193
+ return;
194
+ }
195
+ if (result.omittedMaxTokens) this.logger.warn("openclaw output cap not written; openclaw sends its own default", {
196
+ model,
197
+ reason: result.omittedMaxTokens
198
+ });
199
+ this.modelLimits.set(model, result.limits);
200
+ }));
41
201
  }
42
202
  buildExecArgs(params) {
43
203
  const args = ["agent"];
@@ -47,7 +207,7 @@ var OpenclawProviderAdapter = class extends CliProviderAdapterBase {
47
207
  const nativeSessionId = params.sessionId ?? params.mintedSessionId;
48
208
  if (nativeSessionId) args.push("--session-id", validateOpenclawSessionId(nativeSessionId));
49
209
  args.push(...nativeEffortArgs("openclaw", params.config.profile?.model?.reasoningEffort));
50
- if (params.model && this.managedAuthFiles.length > 0) args.push("--model", `tangle/${params.model}`);
210
+ if (params.model && this.managesConfig) args.push("--model", `tangle/${params.model}`);
51
211
  if (params.config.extraFlags?.length) args.push(...params.config.extraFlags);
52
212
  const fullMessage = prependPromptSection(params.systemPrompt, params.message);
53
213
  args.push("-m", fullMessage);
@@ -60,14 +220,13 @@ var OpenclawProviderAdapter = class extends CliProviderAdapterBase {
60
220
  buildExecEnv(config) {
61
221
  const env = this.agentEnvironmentValues();
62
222
  env.OPENCLAW_NONINTERACTIVE = "1";
63
- if (this.managedAuthFiles.length > 0) {
223
+ if (this.managesConfig) {
64
224
  env.OPENAI_API_KEY = void 0;
65
225
  env.ANTHROPIC_API_KEY = void 0;
66
226
  env.OPENROUTER_API_KEY = void 0;
67
227
  env.GEMINI_API_KEY = void 0;
68
228
  env.GOOGLE_API_KEY = void 0;
69
- const managedConfig = this.managedAuthFiles.find((f) => f.path.endsWith(".openclaw/openclaw.json"));
70
- if (managedConfig && !env.OPENCLAW_CONFIG_PATH) env.OPENCLAW_CONFIG_PATH = `${(config.runtimeHome?.trim() || env.SIDECAR_AGENT_HOME?.trim() || env.AGENT_WORKSPACE_ROOT?.trim() || "/home/agent").replace(/\/+$/, "")}/${managedConfig.path}`;
229
+ if (!env.OPENCLAW_CONFIG_PATH) env.OPENCLAW_CONFIG_PATH = `${managedHome(config, env)}/${OPENCLAW_CONFIG_FILE}`;
71
230
  }
72
231
  if (config.apiKey) env.OPENCODE_MODEL_API_KEY = config.apiKey;
73
232
  return env;
@@ -102,43 +261,53 @@ var OpenclawProviderAdapter = class extends CliProviderAdapterBase {
102
261
  }
103
262
  spawnExecutionProcess(request) {
104
263
  const sessionArg = request.execArgs.args.indexOf("--session-id");
105
- return super.spawnExecutionProcess({
264
+ const turn = super.spawnExecutionProcess({
106
265
  ...request,
107
266
  env: {
108
267
  ...request.env,
109
268
  OPENCLAW_SIDECAR_SESSION: sessionArg >= 0 ? request.execArgs.args[sessionArg + 1] : void 0,
110
- OPENCLAW_STREAM: process.env.OPENCLAW_STREAM === "1" ? "1" : void 0
269
+ OPENCLAW_STREAM: process.env.OPENCLAW_STREAM === "1" ? "1" : void 0,
270
+ [TOOL_REPORT_KEY_ENV]: this.toolReportKeys.get(request.parser)
111
271
  }
112
272
  });
273
+ return turn instanceof Promise ? turn.then(withoutToolReporterNotice) : withoutToolReporterNotice(turn);
113
274
  }
114
275
  createEventParser(state, onEvent) {
115
276
  const envelope = [];
116
- return {
277
+ const key = randomUUID();
278
+ const toolReport = `${TOOL_REPORT}${key} `;
279
+ let unkeyedReports = 0;
280
+ const parser = {
117
281
  parseAs: "lines",
118
282
  onEvent: (line) => {
119
- if (!line.startsWith(PARTIAL_REPLY)) {
120
- envelope.push(line);
283
+ const marker = [toolReport, PARTIAL_REPLY].find((prefix) => line.startsWith(prefix));
284
+ if (!marker) {
285
+ if (line.startsWith("@openclaw/tool ")) unkeyedReports += 1;
286
+ else envelope.push(line);
121
287
  return;
122
288
  }
123
- let partial;
289
+ let record;
124
290
  try {
125
- partial = JSON.parse(line.slice(18));
291
+ record = JSON.parse(line.slice(marker.length));
126
292
  } catch {
127
293
  onEvent?.({
128
294
  type: "warning",
129
295
  code: "OPENCLAW_PARSE_ERROR",
130
- message: "Malformed OpenClaw partial reply"
296
+ message: marker === toolReport ? "Malformed OpenClaw tool report" : "Malformed OpenClaw partial reply"
131
297
  });
132
298
  return;
133
299
  }
134
- if (!partial || typeof partial !== "object") return;
135
- const updates = "delta" in partial && typeof partial.delta === "string" ? textDeltaEvents(state, partial.delta) : "text" in partial && typeof partial.text === "string" ? openclawSnapshotEvents(state, partial.text) : [];
300
+ if (!record || typeof record !== "object") return;
301
+ const updates = marker === toolReport ? toolReportEvents(state, record) : "delta" in record && typeof record.delta === "string" ? textDeltaEvents(state, record.delta) : "text" in record && typeof record.text === "string" ? openclawSnapshotEvents(state, record.text) : [];
136
302
  for (const update of updates) onEvent?.(update);
137
303
  },
138
304
  onComplete: () => {
305
+ if (unkeyedReports) this.logger.warn("openclaw: ignored stdout lines shaped like tool reports without the turn's key", { lines: unkeyedReports });
139
306
  for (const event of this.flushEnvelope(state, envelope.join("\n"))) onEvent?.(event);
140
307
  }
141
308
  };
309
+ this.toolReportKeys.set(parser, key);
310
+ return parser;
142
311
  }
143
312
  flushEnvelope(state, trimmed) {
144
313
  if (!trimmed) return [];
@@ -165,7 +334,8 @@ var OpenclawProviderAdapter = class extends CliProviderAdapterBase {
165
334
  backend: this.provider,
166
335
  event: {
167
336
  provider: agentMeta.provider,
168
- model: agentMeta.model
337
+ model: agentMeta.model,
338
+ contextTokens: agentMeta.contextTokens
169
339
  }
170
340
  });
171
341
  events.push({
@@ -175,6 +345,46 @@ var OpenclawProviderAdapter = class extends CliProviderAdapterBase {
175
345
  return events;
176
346
  }
177
347
  };
348
+ /** The turn with its stderr read line by line, less TOOL_REPORTER_NOTICE. */
349
+ function withoutToolReporterNotice(turn) {
350
+ if (!turn.stderr) return turn;
351
+ const decoder = new StringDecoder("utf8");
352
+ let pending = "";
353
+ const kept = (lines) => lines.split("\n").filter((line) => !line.includes(TOOL_REPORTER_NOTICE)).join("\n") || void 0;
354
+ const stderr = new Transform({
355
+ transform(chunk, _encoding, done) {
356
+ const text = pending + decoder.write(chunk);
357
+ const complete = text.lastIndexOf("\n") + 1;
358
+ pending = text.slice(complete);
359
+ done(null, kept(text.slice(0, complete)));
360
+ },
361
+ flush(done) {
362
+ done(null, kept(pending + decoder.end()));
363
+ }
364
+ });
365
+ return {
366
+ ...turn,
367
+ stderr: turn.stderr.pipe(stderr)
368
+ };
369
+ }
370
+ /** The tool events of one line the tool-reporter plugin wrote. */
371
+ function toolReportEvents(state, report) {
372
+ const { name, input } = report;
373
+ if (typeof name !== "string") return [];
374
+ const start = (id) => toolStartEvents(state, {
375
+ id,
376
+ name,
377
+ input
378
+ });
379
+ if (report.phase === "start") return typeof report.id === "string" ? start(report.id) : [];
380
+ if (report.phase !== "result") return [];
381
+ const id = typeof report.id === "string" ? report.id : randomUUID();
382
+ return [...state.toolCalls.has(id) ? [] : start(id), ...toolResultEvents(state, {
383
+ id,
384
+ content: report.output ?? report.error ?? "",
385
+ isError: typeof report.error === "string"
386
+ })];
387
+ }
178
388
  function openclawSnapshotEvents(state, text) {
179
389
  if (text.startsWith(state.textBuffer)) return textSnapshotEvents(state, text);
180
390
  const event = finalTextEvent(state, text);
@@ -249,6 +459,18 @@ function validateOpenclawSessionId(value) {
249
459
  return value;
250
460
  }
251
461
  /**
462
+ * The home the sidecar writes managed files to: the backend's runtime home
463
+ * when it has one, otherwise the sidecar agent's. openclaw's own $HOME can
464
+ * differ, so every path into this home is absolute.
465
+ */
466
+ function managedHome(config, env) {
467
+ return (config.runtimeHome?.trim() || env.SIDECAR_AGENT_HOME?.trim() || env.AGENT_WORKSPACE_ROOT?.trim() || "/home/agent").replace(/\/+$/, "");
468
+ }
469
+ /** The router's default model and the given ones, each once. */
470
+ function routerModels(models) {
471
+ return [...new Set([resolveTangleRouterDefaults().model, ...models].filter((model) => !!model))];
472
+ }
473
+ /**
252
474
  * The `~/.openclaw/openclaw.json` that points openclaw's default agent at the
253
475
  * managed Tangle router, declared as the `openai-completions` provider
254
476
  * `tangle`. Its apiKey is an env template openclaw expands at load from the
@@ -256,8 +478,27 @@ function validateOpenclawSessionId(value) {
256
478
  * budget-scoped key, so a managed session needs no per-sub-CLI credentials.
257
479
  * The shape follows openclaw's config schema: top-level `models`/`agents`,
258
480
  * and agent records carry a `model` ref.
481
+ *
482
+ * `models` are the router's default and the models a turn can name. Each is
483
+ * declared with streamed usage: openclaw asks an endpoint it does not know
484
+ * for `stream_options.include_usage` only when the model's own entry says the
485
+ * endpoint supports it, and without that request the router sends no usage,
486
+ * so the turn's envelope carries no token counts.
487
+ *
488
+ * `limits` are the context window and output cap the router's catalog lists
489
+ * per model, under the names openclaw's model entry gives them. Openclaw
490
+ * fills in what an entry leaves out, and sends an output cap with every
491
+ * request of a declared model. Without `contextWindow` it takes the model to
492
+ * hold 128000 tokens, its default for a model its config declares (a model it
493
+ * knows only from `--model` gets 200000). Without `maxTokens` it sends half
494
+ * the window, no more than 32768 tokens and no less than 8192 or the window,
495
+ * whichever is smaller.
496
+ *
497
+ * `toolReporter` is the absolute path of the plugin file that reports each
498
+ * tool call (tool-reporter.ts); a standalone plugin file loads once it is
499
+ * listed and enabled.
259
500
  */
260
- function buildRouterOpenclawConfig() {
501
+ function buildRouterOpenclawConfig(options) {
261
502
  const router = resolveTangleRouterDefaults();
262
503
  const modelRef = `tangle/${router.model}`;
263
504
  const config = {
@@ -265,10 +506,12 @@ function buildRouterOpenclawConfig() {
265
506
  baseUrl: router.baseUrl,
266
507
  apiKey: `\${${router.apiKeyEnvVar}}`,
267
508
  api: "openai-completions",
268
- models: [{
269
- id: router.model,
270
- name: router.model
271
- }]
509
+ models: options.models.map((id) => ({
510
+ id,
511
+ name: id,
512
+ ...options.limits.get(id),
513
+ compat: { supportsUsageInStreaming: true }
514
+ }))
272
515
  } } },
273
516
  agents: {
274
517
  defaults: {
@@ -276,6 +519,10 @@ function buildRouterOpenclawConfig() {
276
519
  skipBootstrap: true
277
520
  },
278
521
  entries: { [OPENCLAW_AGENT_ID]: { model: modelRef } }
522
+ },
523
+ plugins: {
524
+ load: { paths: [options.toolReporter] },
525
+ entries: { [TOOL_REPORTER_ID]: { enabled: true } }
279
526
  }
280
527
  };
281
528
  return `${JSON.stringify(config, null, 2)}\n`;
@@ -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.206",
3
+ "version": "0.13.208",
4
4
  "description": "Base adapter for CLI-based AI agent providers",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",
@@ -60,9 +60,9 @@
60
60
  "@modelcontextprotocol/sdk": "^1.32.2",
61
61
  "@tangle-network/agent-core": "^1.0.3",
62
62
  "@tangle-network/agent-interface": "^5.10.28",
63
- "@tangle-network/agent-profile-materialize": "1.1.220",
63
+ "@tangle-network/agent-profile-materialize": "1.1.221",
64
64
  "@tangle-network/agent-trace-contract": "^2.2.0",
65
- "@tangle-network/cli-agent-registry": "0.15.203",
65
+ "@tangle-network/cli-agent-registry": "0.15.204",
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": "4731feee617625a5bacad23efc422de2319cceb4",
83
- "mergedAt": "2026-11-24T11:49:38-08:00"
82
+ "sourceSha": "b00ae6aafc5629f76335a8171049a6530f7f13f2",
83
+ "mergedAt": "2026-11-24T13:11:06-08:00"
84
84
  },
85
85
  "scripts": {
86
86
  "build": "tsdown",