@tangle-network/sdk-provider-cli-base 0.13.208 → 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
|
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",
|
|
@@ -62,7 +62,7 @@
|
|
|
62
62
|
"@tangle-network/agent-interface": "^5.10.28",
|
|
63
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-24T13:
|
|
82
|
+
"sourceSha": "ff9d729d5c34ff4f6bbfd0183f2a1dff605afa9a",
|
|
83
|
+
"mergedAt": "2026-11-24T13:25:56-08:00"
|
|
84
84
|
},
|
|
85
85
|
"scripts": {
|
|
86
86
|
"build": "tsdown",
|