@tangle-network/sdk-provider-cli-base 0.13.207 → 0.13.209
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 { Kt as CliProviderConfig, Ot as CliProviderAdapterBase, Wt as CliExecArgs, Xt as ExecutionState } from "../../index-gDCIpOnJ.mjs";
|
|
1
|
+
import { Dn as CliTurnSpawn, En as CliTurnProcess, Kt as CliProviderConfig, Ot as CliProviderAdapterBase, Wt as CliExecArgs, Xt as ExecutionState } from "../../index-gDCIpOnJ.mjs";
|
|
2
2
|
import { i as PreparedAttachment } from "../../prompt-input-CD7okX8T.mjs";
|
|
3
3
|
import { StreamParserConfig } from "@tangle-network/sdk-cli-runner";
|
|
4
4
|
import { InputPart, StreamEvent } from "@tangle-network/agent-interface";
|
|
@@ -60,6 +60,10 @@ declare class NanocodeProviderAdapter extends CliProviderAdapterBase<NanocodeCon
|
|
|
60
60
|
readonly provider = "nanocode";
|
|
61
61
|
protected readonly defaultCliPath = "nc";
|
|
62
62
|
private activeSessionId?;
|
|
63
|
+
/** A turn's follow, under its execution state and under the parser its process is spawned with. */
|
|
64
|
+
private readonly journalFollows;
|
|
65
|
+
/** The directory the store hangs from, above everything `nc` creates. */
|
|
66
|
+
private storeBase;
|
|
63
67
|
/** The store under the private runtime home, or a workspace fallback. */
|
|
64
68
|
private resolveNanocodeHome;
|
|
65
69
|
protected preparePromptInput(parts: InputPart[], workspaceRoot: string, sessionId: string): Promise<{
|
|
@@ -76,6 +80,8 @@ declare class NanocodeProviderAdapter extends CliProviderAdapterBase<NanocodeCon
|
|
|
76
80
|
systemPrompt?: string;
|
|
77
81
|
}): CliExecArgs;
|
|
78
82
|
protected buildExecEnv(config: NanocodeConfig): Record<string, string | undefined>;
|
|
83
|
+
/** Reads the turn's journal on a timer for as long as `nc` runs. */
|
|
84
|
+
protected spawnExecutionProcess(request: CliTurnSpawn<NanocodeConfig, NanocodeEvent>): Promise<CliTurnProcess>;
|
|
79
85
|
protected afterCliProcessExit(params: {
|
|
80
86
|
state: ExecutionState;
|
|
81
87
|
stderr: string;
|
|
@@ -1,18 +1,449 @@
|
|
|
1
|
-
import { Bt as textDeltaEvents, Rt as sessionObservedEvents, _t as prependPromptSection, k as CliProviderAdapterBase } from "../../src-D9Za3lQC.mjs";
|
|
1
|
+
import { Bt as textDeltaEvents, Ht as toolResultEvents, O as recordCliTokenUsage, Rt as sessionObservedEvents, Ut as toolStartEvents, _t as prependPromptSection, k as CliProviderAdapterBase } from "../../src-D9Za3lQC.mjs";
|
|
2
2
|
import { qualifyModelId } from "@tangle-network/agent-profile-materialize";
|
|
3
3
|
import { normalizeOpenAiCompatibleBaseUrl, resolveTangleRouterDefaults } from "@tangle-network/agent-interface";
|
|
4
|
-
import { join } from "node:path";
|
|
4
|
+
import { join, relative } from "node:path";
|
|
5
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, readdirSync, realpathSync } from "node:fs";
|
|
6
|
+
//#region src/adapters/nanocode/session-journal.ts
|
|
7
|
+
/** Bytes one `drain` reads, so a large append never holds the event loop long. */
|
|
8
|
+
const SLICE_BYTES = 4 * 1024 * 1024;
|
|
9
|
+
/** Bytes of one turn the reader follows, and of the journal it searches for a record. */
|
|
10
|
+
const MAX_BYTES = 64 * 1024 * 1024;
|
|
11
|
+
const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
|
|
12
|
+
const RECORD_KEY = /^b3:[0-9a-f]{64}$/;
|
|
13
|
+
const TOOL_STEP = /^tool-(\d+)-/;
|
|
14
|
+
const CHUNK_NAME_LENGTH = 64;
|
|
15
|
+
const NEWLINE = 10;
|
|
16
|
+
const COUNTS = [
|
|
17
|
+
"input",
|
|
18
|
+
"cached",
|
|
19
|
+
"cacheWrite",
|
|
20
|
+
"output",
|
|
21
|
+
"reasoning",
|
|
22
|
+
"total"
|
|
23
|
+
];
|
|
24
|
+
const NO_COUNTS = {
|
|
25
|
+
input: 0,
|
|
26
|
+
cached: 0,
|
|
27
|
+
cacheWrite: 0,
|
|
28
|
+
output: 0,
|
|
29
|
+
reasoning: 0,
|
|
30
|
+
total: 0
|
|
31
|
+
};
|
|
32
|
+
function isRecord(value) {
|
|
33
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
34
|
+
}
|
|
35
|
+
function parse(text) {
|
|
36
|
+
try {
|
|
37
|
+
return JSON.parse(text);
|
|
38
|
+
} catch {
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function count(value) {
|
|
43
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Reads the usage of one model call (the Responses shape, with its detail
|
|
47
|
+
* objects) or of a finished operation (nanocode's flat sum of them).
|
|
48
|
+
*/
|
|
49
|
+
function counts(usage) {
|
|
50
|
+
const flat = isRecord(usage) ? usage : {};
|
|
51
|
+
const input = isRecord(flat.input_tokens_details) ? flat.input_tokens_details : {};
|
|
52
|
+
const output = isRecord(flat.output_tokens_details) ? flat.output_tokens_details : {};
|
|
53
|
+
return {
|
|
54
|
+
input: count(flat.input_tokens),
|
|
55
|
+
cached: count(flat.cached_input_tokens ?? input.cached_tokens),
|
|
56
|
+
cacheWrite: count(flat.cache_write_input_tokens ?? input.cache_write_tokens),
|
|
57
|
+
output: count(flat.output_tokens),
|
|
58
|
+
reasoning: count(flat.reasoning_output_tokens ?? output.reasoning_tokens),
|
|
59
|
+
total: count(flat.total_tokens)
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
function combine(left, right, each) {
|
|
63
|
+
const result = { ...NO_COUNTS };
|
|
64
|
+
for (const key of COUNTS) result[key] = each(left[key], right[key]);
|
|
65
|
+
return result;
|
|
66
|
+
}
|
|
67
|
+
/** A tool's answer as text when it is all text, as `nc` showed it to the model. */
|
|
68
|
+
function outputContent(output) {
|
|
69
|
+
if (!Array.isArray(output)) return output;
|
|
70
|
+
const texts = output.map((part) => isRecord(part) ? part.text : void 0);
|
|
71
|
+
return texts.every((text) => typeof text === "string") ? texts.join("") : output;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* A free-form tool's text goes under `input`, the name the Responses wire
|
|
75
|
+
* gives it; a function tool's arguments are its JSON object.
|
|
76
|
+
*/
|
|
77
|
+
function toolInput(call) {
|
|
78
|
+
if (call.kind !== "function") return { input: call.input };
|
|
79
|
+
const parsed = typeof call.input === "string" ? parse(call.input) : call.input;
|
|
80
|
+
return isRecord(parsed) ? parsed : { arguments: call.input };
|
|
81
|
+
}
|
|
82
|
+
/** Steps in the order the model called them: `nc` numbers a tool step's key. */
|
|
83
|
+
function inCallOrder(steps) {
|
|
84
|
+
const order = (key) => Number(TOOL_STEP.exec(key)?.[1] ?? 0);
|
|
85
|
+
return Object.entries(isRecord(steps) ? steps : {}).sort(([left], [right]) => order(left) - order(right));
|
|
86
|
+
}
|
|
87
|
+
/** Each session journal's size under `sessions`, by session id. */
|
|
88
|
+
function journalSizes(sessions) {
|
|
89
|
+
const sizes = /* @__PURE__ */ new Map();
|
|
90
|
+
let names;
|
|
91
|
+
try {
|
|
92
|
+
names = readdirSync(sessions);
|
|
93
|
+
} catch {
|
|
94
|
+
return sizes;
|
|
95
|
+
}
|
|
96
|
+
for (const name of names) {
|
|
97
|
+
if (!name.endsWith(".jsonl")) continue;
|
|
98
|
+
try {
|
|
99
|
+
const entry = lstatSync(join(sessions, name));
|
|
100
|
+
if (entry.isFile()) sizes.set(name.slice(0, -6), entry.size);
|
|
101
|
+
} catch {}
|
|
102
|
+
}
|
|
103
|
+
return sizes;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Hands each complete line of the file's `[from, to)` to `onLine` with the
|
|
107
|
+
* offset it starts at, after the unfinished line `carry` holds from the bytes
|
|
108
|
+
* before; returns the bytes read and the line still unfinished.
|
|
109
|
+
*/
|
|
110
|
+
function readLines(descriptor, from, to, carry, onLine) {
|
|
111
|
+
const buffer = Buffer.allocUnsafe(to - from);
|
|
112
|
+
let read = 0;
|
|
113
|
+
while (read < buffer.length) {
|
|
114
|
+
const got = readSync(descriptor, buffer, read, buffer.length - read, from + read);
|
|
115
|
+
if (got === 0) break;
|
|
116
|
+
read += got;
|
|
117
|
+
}
|
|
118
|
+
const data = Buffer.concat([carry, buffer.subarray(0, read)]);
|
|
119
|
+
const dataAt = from - carry.length;
|
|
120
|
+
let lineStart = 0;
|
|
121
|
+
for (let newline = data.indexOf(NEWLINE); newline !== -1; newline = data.indexOf(NEWLINE, lineStart)) {
|
|
122
|
+
onLine(data.toString("utf8", lineStart, newline), dataAt + lineStart);
|
|
123
|
+
lineStart = newline + 1;
|
|
124
|
+
}
|
|
125
|
+
return {
|
|
126
|
+
read,
|
|
127
|
+
carry: Buffer.from(data.subarray(lineStart))
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
/** One line's records by key, when the line is a state's revision. */
|
|
131
|
+
function readRevision(line) {
|
|
132
|
+
const row = parse(line);
|
|
133
|
+
if (!Array.isArray(row)) return void 0;
|
|
134
|
+
const [head, state, ...inline] = row;
|
|
135
|
+
if (!isRecord(head) || !Array.isArray(head.records)) return void 0;
|
|
136
|
+
const written = /* @__PURE__ */ new Map();
|
|
137
|
+
let next = 0;
|
|
138
|
+
for (const record of head.records) {
|
|
139
|
+
if (!isRecord(record) || typeof record.key !== "string") continue;
|
|
140
|
+
written.set(record.key, typeof record.value === "string" ? record.value : inline[next++]);
|
|
141
|
+
}
|
|
142
|
+
return {
|
|
143
|
+
stateId: head.state_id,
|
|
144
|
+
state,
|
|
145
|
+
written
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* What one turn appends to its session's journal: the tool calls, in order,
|
|
150
|
+
* and the tokens of its model calls. Made before `nc` starts, so everything
|
|
151
|
+
* a journal gains afterwards is this turn's, on a new session or a resumed one.
|
|
152
|
+
*/
|
|
153
|
+
var NanocodeTurnJournal = class {
|
|
154
|
+
/** True when the last `drain` stopped before the journal's end. */
|
|
155
|
+
behind = false;
|
|
156
|
+
sessions;
|
|
157
|
+
anchor;
|
|
158
|
+
/** Each journal's size before the turn. */
|
|
159
|
+
sizes;
|
|
160
|
+
sessionId;
|
|
161
|
+
start = 0;
|
|
162
|
+
offset = 0;
|
|
163
|
+
stopped = false;
|
|
164
|
+
/** The bytes of a line `nc` has not finished writing. */
|
|
165
|
+
partial = Buffer.alloc(0);
|
|
166
|
+
/** The journal while a `drain` holds it open. */
|
|
167
|
+
descriptor;
|
|
168
|
+
/** The revision being read: where its line starts and the records it wrote. */
|
|
169
|
+
lineAt = 0;
|
|
170
|
+
written = /* @__PURE__ */ new Map();
|
|
171
|
+
/**
|
|
172
|
+
* What a later revision may name again: every chunk and chunk list the
|
|
173
|
+
* turn wrote, and each record a state has named.
|
|
174
|
+
*/
|
|
175
|
+
stored = /* @__PURE__ */ new Map();
|
|
176
|
+
/** Keys the journal was searched for, and the offset searched up to. */
|
|
177
|
+
searched = /* @__PURE__ */ new Map();
|
|
178
|
+
/** Steps already reported, by operation and step key. */
|
|
179
|
+
started = /* @__PURE__ */ new Set();
|
|
180
|
+
/** Calls not yet answered, oldest first, by the model's call id. */
|
|
181
|
+
waiting = /* @__PURE__ */ new Map();
|
|
182
|
+
waitingCount = 0;
|
|
183
|
+
callIdUses = /* @__PURE__ */ new Map();
|
|
184
|
+
/** Each operation's counts when first seen and now. */
|
|
185
|
+
operations = /* @__PURE__ */ new Map();
|
|
186
|
+
/**
|
|
187
|
+
* `home` is NANOCODE_HOME. The store belongs to the demoted `nc` child,
|
|
188
|
+
* which must not aim a read at another file: a journal is read only when
|
|
189
|
+
* its path reaches a regular file through no symbolic link below `anchor`.
|
|
190
|
+
*/
|
|
191
|
+
constructor(options) {
|
|
192
|
+
this.sessions = join(options.home, "sessions");
|
|
193
|
+
this.anchor = options.anchor;
|
|
194
|
+
this.sizes = journalSizes(this.sessions);
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Reads the complete lines the turn's journal gained since the last call
|
|
198
|
+
* and returns their tool calls and answers in order. The journal is the
|
|
199
|
+
* session `sessionId` names, which `nc exec` prints only as it ends; before
|
|
200
|
+
* that, the one journal that grew since the turn started, since a home
|
|
201
|
+
* serves one turn at a time. The first journal chosen is the one followed.
|
|
202
|
+
*/
|
|
203
|
+
drain(sessionId) {
|
|
204
|
+
const events = [];
|
|
205
|
+
this.behind = false;
|
|
206
|
+
if (this.stopped) return events;
|
|
207
|
+
if (this.sessionId === void 0) {
|
|
208
|
+
const chosen = sessionId ?? this.grownJournal();
|
|
209
|
+
if (chosen === void 0) return events;
|
|
210
|
+
this.sessionId = chosen;
|
|
211
|
+
this.start = this.sizes.get(chosen) ?? 0;
|
|
212
|
+
this.offset = this.start;
|
|
213
|
+
}
|
|
214
|
+
const descriptor = this.open(this.sessionId);
|
|
215
|
+
if (descriptor === void 0) return events;
|
|
216
|
+
this.descriptor = descriptor;
|
|
217
|
+
try {
|
|
218
|
+
const size = fstatSync(descriptor).size;
|
|
219
|
+
const end = Math.min(size, this.offset + SLICE_BYTES);
|
|
220
|
+
if (end > this.offset) {
|
|
221
|
+
const { read, carry } = readLines(descriptor, this.offset, end, this.partial, (line, at) => this.revision(line, at, events));
|
|
222
|
+
this.offset += read;
|
|
223
|
+
this.partial = carry;
|
|
224
|
+
this.behind = read > 0 && this.offset < size;
|
|
225
|
+
}
|
|
226
|
+
if (this.offset - this.start > MAX_BYTES) this.stopped = true;
|
|
227
|
+
} catch {
|
|
228
|
+
this.stopped = true;
|
|
229
|
+
this.behind = false;
|
|
230
|
+
} finally {
|
|
231
|
+
this.descriptor = void 0;
|
|
232
|
+
closeSync(descriptor);
|
|
233
|
+
}
|
|
234
|
+
return events;
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* How many reported calls have no answer yet. `nc` asks the model again
|
|
238
|
+
* only once it holds every answer, so the reply printed while this is not
|
|
239
|
+
* zero is ahead of the journal: the answers are about to be written.
|
|
240
|
+
*/
|
|
241
|
+
get unanswered() {
|
|
242
|
+
return this.stopped ? 0 : this.waitingCount;
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* The tokens of the model calls made since the turn started, subagents'
|
|
246
|
+
* included: per operation, what it counts now less what it counted when
|
|
247
|
+
* first seen, so an operation carried over from an earlier run adds only
|
|
248
|
+
* its new calls. Undefined when the journal shows no counted call, which is
|
|
249
|
+
* not a measured zero. A cache count is left out when it sums to zero:
|
|
250
|
+
* `nc` writes a zero for a model that reported none.
|
|
251
|
+
*/
|
|
252
|
+
usage() {
|
|
253
|
+
let sum = NO_COUNTS;
|
|
254
|
+
for (const { first, latest } of this.operations.values()) {
|
|
255
|
+
const added = combine(latest, first, (now, then) => Math.max(0, now - then));
|
|
256
|
+
sum = combine(sum, added, (a, b) => a + b);
|
|
257
|
+
}
|
|
258
|
+
if (COUNTS.every((key) => sum[key] === 0)) return void 0;
|
|
259
|
+
return {
|
|
260
|
+
input_tokens: Math.max(0, sum.input - sum.cached - sum.cacheWrite),
|
|
261
|
+
output_tokens: sum.output,
|
|
262
|
+
total_tokens: sum.total,
|
|
263
|
+
...sum.cached ? { cache_read_input_tokens: sum.cached } : {},
|
|
264
|
+
...sum.cacheWrite ? { cache_creation_input_tokens: sum.cacheWrite } : {},
|
|
265
|
+
...sum.reasoning ? { reasoning_output_tokens: sum.reasoning } : {}
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
grownJournal() {
|
|
269
|
+
const grown = [...journalSizes(this.sessions)].filter(([sessionId, size]) => size > (this.sizes.get(sessionId) ?? 0));
|
|
270
|
+
return grown.length === 1 ? grown[0]?.[0] : void 0;
|
|
271
|
+
}
|
|
272
|
+
open(sessionId) {
|
|
273
|
+
if (!SESSION_ID.test(sessionId)) return void 0;
|
|
274
|
+
const path = join(this.sessions, `${sessionId}.jsonl`);
|
|
275
|
+
let descriptor;
|
|
276
|
+
try {
|
|
277
|
+
const expected = join(realpathSync(this.anchor), relative(this.anchor, path));
|
|
278
|
+
if (realpathSync(path) !== expected) return void 0;
|
|
279
|
+
descriptor = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
280
|
+
if (fstatSync(descriptor).isFile()) return descriptor;
|
|
281
|
+
} catch {}
|
|
282
|
+
if (descriptor !== void 0) closeSync(descriptor);
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Finds records the revision being read names but no line kept in memory
|
|
286
|
+
* wrote: the journal before it holds them, from this turn or an earlier one.
|
|
287
|
+
*/
|
|
288
|
+
search(keys) {
|
|
289
|
+
const wanted = new Set(keys.filter((key) => !this.stored.has(key) && !this.written.has(key) && (this.searched.get(key) ?? 0) < this.lineAt));
|
|
290
|
+
if (wanted.size === 0 || this.descriptor === void 0) return;
|
|
291
|
+
for (const key of wanted) this.searched.set(key, this.lineAt);
|
|
292
|
+
const end = Math.min(this.lineAt, MAX_BYTES);
|
|
293
|
+
let carry = Buffer.alloc(0);
|
|
294
|
+
for (let at = 0; at < end && wanted.size > 0;) {
|
|
295
|
+
const slice = readLines(this.descriptor, at, Math.min(end, at + SLICE_BYTES), carry, (line) => {
|
|
296
|
+
const written = wanted.size > 0 && readRevision(line)?.written;
|
|
297
|
+
if (!written) return;
|
|
298
|
+
for (const [key, value] of written) if (wanted.delete(key)) this.stored.set(key, value);
|
|
299
|
+
});
|
|
300
|
+
if (slice.read === 0) break;
|
|
301
|
+
at += slice.read;
|
|
302
|
+
carry = slice.carry;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
/** The record a key names, put together from its chunks when it has them. */
|
|
306
|
+
record(key) {
|
|
307
|
+
this.search([key]);
|
|
308
|
+
const value = this.written.get(key) ?? this.stored.get(key);
|
|
309
|
+
if (value !== void 0) this.stored.set(key, value);
|
|
310
|
+
if (typeof value !== "string") return value;
|
|
311
|
+
if (!value.startsWith("%")) return parse(value);
|
|
312
|
+
const chunks = [];
|
|
313
|
+
for (let at = 1; at < value.length; at += CHUNK_NAME_LENGTH) chunks.push(`c:${value.slice(at, at + CHUNK_NAME_LENGTH)}`);
|
|
314
|
+
this.search(chunks);
|
|
315
|
+
let text = "";
|
|
316
|
+
for (const chunk of chunks) {
|
|
317
|
+
const part = this.stored.get(chunk);
|
|
318
|
+
if (typeof part !== "string") return void 0;
|
|
319
|
+
text += part;
|
|
320
|
+
}
|
|
321
|
+
return parse(text);
|
|
322
|
+
}
|
|
323
|
+
/** A state field: JSON after `=`, or the key of the record that holds it. */
|
|
324
|
+
field(value) {
|
|
325
|
+
if (typeof value !== "string") return value;
|
|
326
|
+
if (value.startsWith("=")) return parse(value.slice(1));
|
|
327
|
+
return RECORD_KEY.test(value) ? this.record(value) : value;
|
|
328
|
+
}
|
|
329
|
+
revision(line, at, events) {
|
|
330
|
+
const revision = readRevision(line);
|
|
331
|
+
if (!revision) return;
|
|
332
|
+
this.lineAt = at;
|
|
333
|
+
this.written = revision.written;
|
|
334
|
+
for (const [key, value] of revision.written) if (typeof value === "string") this.stored.set(key, value);
|
|
335
|
+
const durable = isRecord(revision.state) ? revision.state.nanocode_durable_state : void 0;
|
|
336
|
+
if (!isRecord(durable)) return;
|
|
337
|
+
const records = [];
|
|
338
|
+
for (const [key, value] of revision.written) {
|
|
339
|
+
if (!RECORD_KEY.test(key)) continue;
|
|
340
|
+
const record = typeof value === "string" ? this.record(key) : value;
|
|
341
|
+
if (isRecord(record)) records.push(record);
|
|
342
|
+
}
|
|
343
|
+
const active = Object.entries(isRecord(durable.operations) ? durable.operations : {}).filter((entry) => isRecord(entry[1]));
|
|
344
|
+
for (const [id, operation] of active) {
|
|
345
|
+
const latest = this.activeCounts(operation);
|
|
346
|
+
const first = this.operations.get(id)?.first ?? latest;
|
|
347
|
+
this.operations.set(id, {
|
|
348
|
+
first,
|
|
349
|
+
latest
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
for (const record of records) {
|
|
353
|
+
if (!isRecord(record.operations)) continue;
|
|
354
|
+
for (const [id, operation] of Object.entries(record.operations)) {
|
|
355
|
+
const finished = isRecord(operation) && isRecord(operation.status) && isRecord(operation.status.completed) ? this.field(operation.status.completed.output) : void 0;
|
|
356
|
+
if (!isRecord(finished) || finished.usage === void 0) continue;
|
|
357
|
+
this.operations.set(id, {
|
|
358
|
+
first: this.operations.get(id)?.first ?? NO_COUNTS,
|
|
359
|
+
latest: counts(finished.usage)
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
if (revision.stateId !== this.sessionId) return;
|
|
364
|
+
const early = records.filter((record) => (record.type === "custom_tool_call_output" || record.type === "function_call_output") && typeof record.call_id === "string").filter((answer) => !this.answer(answer, events));
|
|
365
|
+
for (const [id, operation] of active) for (const [key, step] of inCallOrder(operation.steps)) {
|
|
366
|
+
if (!isRecord(step) || step.kind !== "tool_call") continue;
|
|
367
|
+
if (this.started.has(`${id}/${key}`)) continue;
|
|
368
|
+
const call = this.field(step.input);
|
|
369
|
+
if (!isRecord(call) || typeof call.call_id !== "string" || typeof call.name !== "string") continue;
|
|
370
|
+
this.started.add(`${id}/${key}`);
|
|
371
|
+
const uses = (this.callIdUses.get(call.call_id) ?? 0) + 1;
|
|
372
|
+
this.callIdUses.set(call.call_id, uses);
|
|
373
|
+
const partId = uses === 1 ? call.call_id : `${call.call_id}#${uses}`;
|
|
374
|
+
const waiting = this.waiting.get(call.call_id) ?? [];
|
|
375
|
+
waiting.push(partId);
|
|
376
|
+
this.waiting.set(call.call_id, waiting);
|
|
377
|
+
this.waitingCount += 1;
|
|
378
|
+
events.push({
|
|
379
|
+
type: "tool_call",
|
|
380
|
+
id: partId,
|
|
381
|
+
name: call.name,
|
|
382
|
+
input: toolInput(call)
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
for (const answer of early) this.answer(answer, events);
|
|
386
|
+
}
|
|
387
|
+
/** What an operation in flight has counted: its retired calls, then those still listed. */
|
|
388
|
+
activeCounts(operation) {
|
|
389
|
+
const continuation = this.field(operation.continuation);
|
|
390
|
+
const state = isRecord(continuation) ? continuation.state : void 0;
|
|
391
|
+
const stats = isRecord(state) ? state.stats : void 0;
|
|
392
|
+
let sum = counts(isRecord(stats) ? stats.usage : void 0);
|
|
393
|
+
const steps = isRecord(operation.steps) ? operation.steps : {};
|
|
394
|
+
for (const step of Object.values(steps)) {
|
|
395
|
+
if (!isRecord(step) || step.kind !== "model_call") continue;
|
|
396
|
+
const completed = isRecord(step.status) ? this.field(step.status.completed) : void 0;
|
|
397
|
+
const response = isRecord(completed) ? completed.response : void 0;
|
|
398
|
+
if (isRecord(response)) sum = combine(sum, counts(response.usage), (a, b) => a + b);
|
|
399
|
+
}
|
|
400
|
+
return sum;
|
|
401
|
+
}
|
|
402
|
+
/** Reports the answer of the oldest unanswered call with its call id. */
|
|
403
|
+
answer(answer, events) {
|
|
404
|
+
const id = this.waiting.get(String(answer.call_id))?.shift();
|
|
405
|
+
if (id === void 0) return false;
|
|
406
|
+
this.waitingCount -= 1;
|
|
407
|
+
const content = outputContent(answer.output);
|
|
408
|
+
const first = Array.isArray(answer.output) ? answer.output[0] : content;
|
|
409
|
+
const header = isRecord(first) ? first.text : first;
|
|
410
|
+
events.push({
|
|
411
|
+
type: "tool_result",
|
|
412
|
+
id,
|
|
413
|
+
content,
|
|
414
|
+
isError: typeof header === "string" && header.startsWith("Script failed")
|
|
415
|
+
});
|
|
416
|
+
return true;
|
|
417
|
+
}
|
|
418
|
+
};
|
|
419
|
+
//#endregion
|
|
5
420
|
//#region src/adapters/nanocode/adapter.ts
|
|
421
|
+
/**
|
|
422
|
+
* How often a running turn's journal is read. `nc exec` streams no events, so
|
|
423
|
+
* a tool call reaches the stream within this of `nc` recording it.
|
|
424
|
+
*/
|
|
425
|
+
const JOURNAL_POLL_MS = 200;
|
|
426
|
+
/**
|
|
427
|
+
* How long reply text waits for a tool answer the journal has not shown.
|
|
428
|
+
* `nc` writes a model call's answers as it asks the model again, so a fast
|
|
429
|
+
* model's reply can reach stdout first; past this the text goes out anyway.
|
|
430
|
+
*/
|
|
431
|
+
const JOURNAL_LAG_MS = 2e3;
|
|
6
432
|
var NanocodeProviderAdapter = class extends CliProviderAdapterBase {
|
|
7
433
|
provider = "nanocode";
|
|
8
434
|
defaultCliPath = "nc";
|
|
9
435
|
activeSessionId;
|
|
436
|
+
/** A turn's follow, under its execution state and under the parser its process is spawned with. */
|
|
437
|
+
journalFollows = /* @__PURE__ */ new WeakMap();
|
|
438
|
+
/** The directory the store hangs from, above everything `nc` creates. */
|
|
439
|
+
storeBase() {
|
|
440
|
+
return this.config.runtimeHome?.trim() || process.env.AGENT_WORKSPACE_ROOT?.trim() || this.storagePath;
|
|
441
|
+
}
|
|
10
442
|
/** The store under the private runtime home, or a workspace fallback. */
|
|
11
443
|
resolveNanocodeHome() {
|
|
12
|
-
|
|
13
|
-
if (runtimeHome) return join(runtimeHome, ".nanocode");
|
|
444
|
+
if (this.config.runtimeHome?.trim()) return join(this.storeBase(), ".nanocode");
|
|
14
445
|
if (!this.activeSessionId) throw new Error("Nanocode native session id is required before resolving NANOCODE_HOME");
|
|
15
|
-
return join(
|
|
446
|
+
return join(this.storeBase(), ".nanocode", "sessions", this.activeSessionId);
|
|
16
447
|
}
|
|
17
448
|
async preparePromptInput(parts, workspaceRoot, sessionId) {
|
|
18
449
|
if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(sessionId)) throw new Error("Nanocode native session id is not a safe directory name");
|
|
@@ -55,9 +486,32 @@ var NanocodeProviderAdapter = class extends CliProviderAdapterBase {
|
|
|
55
486
|
if (model) env.NANOCODE_MODEL = model;
|
|
56
487
|
return env;
|
|
57
488
|
}
|
|
489
|
+
/** Reads the turn's journal on a timer for as long as `nc` runs. */
|
|
490
|
+
async spawnExecutionProcess(request) {
|
|
491
|
+
const follow = this.journalFollows.get(request.parser);
|
|
492
|
+
const turn = await super.spawnExecutionProcess(request);
|
|
493
|
+
if (!follow) return turn;
|
|
494
|
+
const timer = setInterval(() => {
|
|
495
|
+
try {
|
|
496
|
+
follow.read();
|
|
497
|
+
} catch (error) {
|
|
498
|
+
clearInterval(timer);
|
|
499
|
+
this.logger.warn("nanocode: stopped following the session journal", { error: error instanceof Error ? error.message : String(error) });
|
|
500
|
+
}
|
|
501
|
+
}, JOURNAL_POLL_MS);
|
|
502
|
+
timer.unref();
|
|
503
|
+
const stop = () => clearInterval(timer);
|
|
504
|
+
turn.exitPromise.then(stop, stop);
|
|
505
|
+
return turn;
|
|
506
|
+
}
|
|
58
507
|
async afterCliProcessExit(params) {
|
|
59
508
|
const sessionId = parseNanocodeSessionId(params.stderr);
|
|
60
509
|
if (sessionId) for (const event of sessionObservedEvents(params.state, "nanocode", sessionId)) params.onEvent?.(event);
|
|
510
|
+
const follow = this.journalFollows.get(params.state);
|
|
511
|
+
if (follow) {
|
|
512
|
+
follow.finish(sessionId);
|
|
513
|
+
recordCliTokenUsage(params.state, follow.journal.usage());
|
|
514
|
+
}
|
|
61
515
|
if (params.exit.success && params.state.textBuffer) params.onEvent?.({
|
|
62
516
|
type: "status",
|
|
63
517
|
status: "completed"
|
|
@@ -65,7 +519,43 @@ var NanocodeProviderAdapter = class extends CliProviderAdapterBase {
|
|
|
65
519
|
}
|
|
66
520
|
createEventParser(state, onEvent) {
|
|
67
521
|
let whitespace = "";
|
|
68
|
-
|
|
522
|
+
const emitText = (line) => {
|
|
523
|
+
const chunk = whitespace + line;
|
|
524
|
+
const text = chunk.trimEnd();
|
|
525
|
+
whitespace = chunk.slice(text.length);
|
|
526
|
+
if (text) for (const delta of textDeltaEvents(state, text)) onEvent?.(delta);
|
|
527
|
+
};
|
|
528
|
+
const journal = new NanocodeTurnJournal({
|
|
529
|
+
home: this.resolveNanocodeHome(),
|
|
530
|
+
anchor: this.storeBase()
|
|
531
|
+
});
|
|
532
|
+
const emitTools = (sessionId) => {
|
|
533
|
+
for (const event of journal.drain(sessionId)) {
|
|
534
|
+
const updates = event.type === "tool_call" ? toolStartEvents(state, event) : toolResultEvents(state, event);
|
|
535
|
+
for (const update of updates) onEvent?.(update);
|
|
536
|
+
}
|
|
537
|
+
};
|
|
538
|
+
let held = "";
|
|
539
|
+
let heldSince = 0;
|
|
540
|
+
const releaseText = () => {
|
|
541
|
+
const text = held;
|
|
542
|
+
held = "";
|
|
543
|
+
if (text) emitText(text);
|
|
544
|
+
};
|
|
545
|
+
const follow = {
|
|
546
|
+
journal,
|
|
547
|
+
read: () => {
|
|
548
|
+
emitTools();
|
|
549
|
+
if (journal.unanswered === 0 || Date.now() - heldSince > JOURNAL_LAG_MS) releaseText();
|
|
550
|
+
},
|
|
551
|
+
finish: (sessionId) => {
|
|
552
|
+
do
|
|
553
|
+
emitTools(sessionId);
|
|
554
|
+
while (journal.behind);
|
|
555
|
+
releaseText();
|
|
556
|
+
}
|
|
557
|
+
};
|
|
558
|
+
const parser = {
|
|
69
559
|
parseAs: "chunks",
|
|
70
560
|
transform: (raw) => ({
|
|
71
561
|
type: "text",
|
|
@@ -73,12 +563,15 @@ var NanocodeProviderAdapter = class extends CliProviderAdapterBase {
|
|
|
73
563
|
}),
|
|
74
564
|
onEvent: (event) => {
|
|
75
565
|
if (event.type !== "text") return;
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
566
|
+
if (!held) heldSince = Date.now();
|
|
567
|
+
held += event.line;
|
|
568
|
+
follow.read();
|
|
569
|
+
},
|
|
570
|
+
onComplete: () => follow.finish()
|
|
81
571
|
};
|
|
572
|
+
this.journalFollows.set(state, follow);
|
|
573
|
+
this.journalFollows.set(parser, follow);
|
|
574
|
+
return parser;
|
|
82
575
|
}
|
|
83
576
|
};
|
|
84
577
|
/** nanocode's catalog is the Router's `/models`, keyed `provider/model`; the
|
|
@@ -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
|
-
*
|
|
21
|
-
*
|
|
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
|
|
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
|
-
|
|
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
|
-
*
|
|
13
|
-
*
|
|
14
|
-
|
|
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
|
-
|
|
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.
|
|
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
|
-
|
|
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
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
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.
|
|
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.
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
120
|
-
|
|
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
|
|
289
|
+
let record;
|
|
124
290
|
try {
|
|
125
|
-
|
|
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 (!
|
|
135
|
-
const updates = "delta" in
|
|
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
|
|
270
|
-
name:
|
|
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.
|
|
3
|
+
"version": "0.13.209",
|
|
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.
|
|
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.
|
|
65
|
+
"@tangle-network/cli-agent-registry": "0.15.205",
|
|
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": "
|
|
83
|
-
"mergedAt": "2026-11-
|
|
82
|
+
"sourceSha": "ff9d729d5c34ff4f6bbfd0183f2a1dff605afa9a",
|
|
83
|
+
"mergedAt": "2026-11-24T13:25:56-08:00"
|
|
84
84
|
},
|
|
85
85
|
"scripts": {
|
|
86
86
|
"build": "tsdown",
|