@tangle-network/sdk-provider-cli-base 0.13.207 → 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`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/sdk-provider-cli-base",
3
- "version": "0.13.207",
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": "35b13c72e9b97ee18ae7d61182a30a872cf552b9",
83
- "mergedAt": "2026-11-24T12:34:25-08:00"
82
+ "sourceSha": "b00ae6aafc5629f76335a8171049a6530f7f13f2",
83
+ "mergedAt": "2026-11-24T13:11:06-08:00"
84
84
  },
85
85
  "scripts": {
86
86
  "build": "tsdown",