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

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 { Bt as textDeltaEvents, Ht as toolResultEvents, I as localMcpArgv, L as localMcpEnv, Lt as reasoningEvents, O as recordCliTokenUsage, Rt as sessionObservedEvents, S as jsonEventParser, Ut as toolStartEvents, k as CliProviderAdapterBase } from "../../src-D9Za3lQC.mjs";
1
+ import { Bt as textDeltaEvents, Ht as toolResultEvents, I as localMcpArgv, L as localMcpEnv, Lt as reasoningEvents, O as recordCliTokenUsage, Rt as sessionObservedEvents, S as jsonEventParser, Ut as toolStartEvents, k as CliProviderAdapterBase } from "../../src-B_4qa95r.mjs";
2
2
  //#region src/adapters/amp/types.ts
3
3
  /**
4
4
  * Type guard for AMP events.
@@ -1,4 +1,4 @@
1
- import { C as plaintextResponseParser, Ht as toolResultEvents, O as recordCliTokenUsage, Rt as sessionObservedEvents, Ut as toolStartEvents, k as CliProviderAdapterBase } from "../../src-D9Za3lQC.mjs";
1
+ import { C as plaintextResponseParser, Ht as toolResultEvents, O as recordCliTokenUsage, Rt as sessionObservedEvents, Ut as toolStartEvents, k as CliProviderAdapterBase } from "../../src-B_4qa95r.mjs";
2
2
  import { normalizeOpenAiCompatibleBaseUrl, resolveTangleRouterDefaults } from "@tangle-network/agent-interface";
3
3
  import { join } from "node:path";
4
4
  import { statSync } from "node:fs";
@@ -1,4 +1,4 @@
1
- import { Bt as textDeltaEvents, F as isLocalMcpConfig, Ht as toolResultEvents, I as localMcpArgv, L as localMcpEnv, Lt as reasoningEvents, O as recordCliTokenUsage, R as enabledInteractionKinds, Rt as sessionObservedEvents, S as jsonEventParser, Ut as toolStartEvents, W as withTurnInteractions, g as McpInteractionSupport, k as CliProviderAdapterBase, zt as streamPartBase } from "../../src-D9Za3lQC.mjs";
1
+ import { Bt as textDeltaEvents, F as isLocalMcpConfig, Ht as toolResultEvents, I as localMcpArgv, L as localMcpEnv, Lt as reasoningEvents, O as recordCliTokenUsage, R as enabledInteractionKinds, Rt as sessionObservedEvents, S as jsonEventParser, Ut as toolStartEvents, W as withTurnInteractions, g as McpInteractionSupport, k as CliProviderAdapterBase, zt as streamPartBase } from "../../src-B_4qa95r.mjs";
2
2
  import { createHash, randomUUID } from "node:crypto";
3
3
  import { InteractionKind } from "@tangle-network/agent-interface";
4
4
  import { mkdir, readFile, writeFile } from "node:fs/promises";
@@ -1,4 +1,4 @@
1
- import { Bt as textDeltaEvents, Ht as toolResultEvents, Lt as reasoningEvents, O as recordCliTokenUsage, Rt as sessionObservedEvents, S as jsonEventParser, Ut as toolStartEvents, _t as prependPromptSection, k as CliProviderAdapterBase } from "../../src-D9Za3lQC.mjs";
1
+ import { Bt as textDeltaEvents, Ht as toolResultEvents, Lt as reasoningEvents, O as recordCliTokenUsage, Rt as sessionObservedEvents, S as jsonEventParser, Ut as toolStartEvents, _t as prependPromptSection, k as CliProviderAdapterBase } from "../../src-B_4qa95r.mjs";
2
2
  import { isRecord } from "@tangle-network/agent-core";
3
3
  //#region src/adapters/grok/adapter.ts
4
4
  const DECLARE_MODEL = String.raw`d=$HOME/.grok; [ -z "$GROK_HOME" ] || d=$GROK_HOME
@@ -1,4 +1,4 @@
1
- import { Bt as textDeltaEvents, C as plaintextResponseParser, F as isLocalMcpConfig, Ht as toolResultEvents, I as localMcpArgv, It as finalTextEvent, L as localMcpEnv, O as recordCliTokenUsage, Rt as sessionObservedEvents, Ut as toolStartEvents, Vt as textSnapshotEvents, _t as prependPromptSection, ht as partitionImageAttachments, k as CliProviderAdapterBase } from "../../src-D9Za3lQC.mjs";
1
+ import { Bt as textDeltaEvents, C as plaintextResponseParser, F as isLocalMcpConfig, Ht as toolResultEvents, I as localMcpArgv, It as finalTextEvent, L as localMcpEnv, O as recordCliTokenUsage, Rt as sessionObservedEvents, Ut as toolStartEvents, Vt as textSnapshotEvents, _t as prependPromptSection, ht as partitionImageAttachments, k as CliProviderAdapterBase } from "../../src-B_4qa95r.mjs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { resolveTangleRouterDefaults } from "@tangle-network/agent-interface";
4
4
  import { writeFile } from "node:fs/promises";
@@ -1,4 +1,4 @@
1
- import { C as plaintextResponseParser, E as parseCliUsageLine, O as recordCliTokenUsage, Rt as sessionObservedEvents, _t as prependPromptSection, k as CliProviderAdapterBase } from "../../src-D9Za3lQC.mjs";
1
+ import { C as plaintextResponseParser, E as parseCliUsageLine, O as recordCliTokenUsage, Rt as sessionObservedEvents, _t as prependPromptSection, k as CliProviderAdapterBase } from "../../src-B_4qa95r.mjs";
2
2
  import { normalizeOpenAiCompatibleBaseUrl, resolveTangleRouterDefaults } from "@tangle-network/agent-interface";
3
3
  import { join } from "node:path";
4
4
  //#region src/adapters/nanoclaw/adapter.ts
@@ -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-B_4qa95r.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
- const runtimeHome = this.config.runtimeHome?.trim();
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(process.env.AGENT_WORKSPACE_ROOT?.trim() || this.storagePath, ".nanocode", "sessions", this.activeSessionId);
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
- return {
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
- const chunk = whitespace + event.line;
77
- const text = chunk.trimEnd();
78
- whitespace = chunk.slice(text.length);
79
- if (text) for (const delta of textDeltaEvents(state, text)) onEvent?.(delta);
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 { 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";
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-B_4qa95r.mjs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { resolveTangleRouterDefaults } from "@tangle-network/agent-interface";
4
4
  import { StringDecoder } from "node:string_decoder";
@@ -1,4 +1,4 @@
1
- import { D as readCliTokenUsage, Yt as spawnAcpBridge, _t as prependPromptSection, w as AcpProviderAdapterBase } from "../../src-D9Za3lQC.mjs";
1
+ import { D as readCliTokenUsage, Yt as spawnAcpBridge, _t as prependPromptSection, w as AcpProviderAdapterBase } from "../../src-B_4qa95r.mjs";
2
2
  import { PRIME_AGENT_DIR_ENV_VAR, PRIME_AGENT_DIR_ENV_VAR as PRIME_AGENT_DIR_ENV_VAR$1, PRIME_AGENT_DIR_ENV_VARS, PRIME_HARNESS_STATE_ENV_DENYLIST, PRIME_HARNESS_STATE_ENV_DENYLIST as PRIME_HARNESS_STATE_ENV_DENYLIST$1, PRIME_KERNEL_DEAD_MARKERS, PRIME_KERNEL_ENV_PASSTHROUGH, PRIME_KERNEL_ENV_PASSTHROUGH as PRIME_KERNEL_ENV_PASSTHROUGH$1, PRIME_MCP_UNSUPPORTED_REASON, PrimeHarnessStateError, PrimeProfileError, assertPrimeModelAgreement, assertPrimeModelAgreement as assertPrimeModelAgreement$1, buildPiModelsConfig, hasPrimeProfileMaterial, matchPrimeKernelDeadMarker, materializePrimeProfileControls, materializePrimeProfileControls as materializePrimeProfileControls$1, primeAgentDirEnv, primeAgentDirEnv as primeAgentDirEnv$1, primeHarnessStatePath, primeProfileNeedsAgentDir, primeSubagentEntryId as subagentEntryId, primeThinkingLevel, primeThinkingLevel as primeThinkingLevel$1, prunePrimeProfileMaterial, readPrimeProfileControls, readPrimeProfileControls as readPrimeProfileControls$1, writePrimeAgentFile } from "@tangle-network/agent-profile-materialize";
3
3
  import { isAbsolute, join, relative, sep } from "node:path";
4
4
  import { existsSync, lchownSync, lstatSync, mkdirSync } from "node:fs";
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { $ as secretSessionTurnQueue, A as TurnObserver, At as EXECUTION_ID_HEADER, B as readEphemeralContext, Bt as textDeltaEvents, C as plaintextResponseParser, Ct as InvalidAttachmentError, D as readCliTokenUsage, Dt as wasNeverLaunched, E as parseCliUsageLine, Et as rejectNotLaunched, F as isLocalMcpConfig, Ft as mapAcpSessionUpdate, G as SHARED_WORKSPACE_DIR_ENV, Gt as ACP_MIN_PROTOCOL_VERSION, H as turnInteractionEnabled, Ht as toolResultEvents, I as localMcpArgv, It as finalTextEvent, J as isLoopbackEndpoint, Jt as assertAcpTurnFinished, K as assertSealedNativeSearchPath, Kt as ACP_PROTOCOL_VERSION, L as localMcpEnv, Lt as reasoningEvents, M as endFailedTurn, Mt as MANAGED_QUOTE_VERSION_HEADER, N as recordTurnInterruption, Nt as executionCorrelationHeaders, O as recordCliTokenUsage, Ot as runtimeSecretsOverlay, P as createExecutionState, Pt as homeXdgEnv, Q as resolveReferences, R as enabledInteractionKinds, Rt as sessionObservedEvents, S as jsonEventParser, St as trackFilePart, T as accumulateCliTokenUsage, Tt as failureAfterCleanup, U as withEphemeralContext, Ut as toolStartEvents, V as turnEndReason, Vt as textSnapshotEvents, W as withTurnInteractions, Wt as trackReasoningBlock, X as joinQueue, Y as isPlainRecord, Yt as spawnAcpBridge, Z as requireRecord, _ as TerminalPlanSupport, _t as prependPromptSection, a as SECRET_REFERENCE, at as NATIVE_SESSION_CONTRACTS, b as brokerInteractionTools, bt as deterministicFilePartId, c as forgetSessionScopes, ct as isTrustedStoreBinary, d as findRouterCatalogEntry, dt as resolveExecutableRealpath, et as servableMcpServer, f as resolveRouterModelLimits, ft as MAX_INLINE_IMAGE_BYTES, g as McpInteractionSupport, gt as preparePromptInputParts, h as nativeEffortArgs, ht as partitionImageAttachments, i as PERMISSION_DECISION_TIMEOUT_MS, it as untilSettledOrAborted, j as createRepeatedToolFailureGuard, jt as EXECUTION_TRACE_HEADER, k as CliProviderAdapterBase, kt as EXECUTION_CORRELATION_HEADERS, l as secretMcpScope, lt as provenStoreBinary, m as kimiThinkingArgs, mt as PROMPT_SECTION_SEPARATOR, n as InteractionBroker, nt as sharedSecretMcpRefused, o as SECRET_REFERENCE_PREFIX, ot as SEALED_NATIVE_HOME_LAYOUT, p as resolveRouterModelReasoningEfforts, pt as MAX_TOTAL_INLINE_IMAGE_BYTES, q as directStdioMcpServers, qt as acpContentText, r as InteractionHttpBridge, rt as spawnUnderSecretMcpLease, s as codexDeveloperInstructionArgs, st as assertSealedNativeHome, t as CODEX_DISABLED_FEATURE_ARGS, tt as servableStdioServer, u as ROUTER_MODEL_CATALOG_TIMEOUT_MS, ut as refuseSecretLaunch, v as DEFAULT_INTERACTION_MCP_SERVER_NAME, vt as buildFileUrl, w as AcpProviderAdapterBase, wt as SessionRehydrationError, x as interactionMcpToolName, xt as inferMediaType, y as InteractionMcpServer, yt as deriveFilePart, z as interactionToggleEnabled, zt as streamPartBase } from "./src-D9Za3lQC.mjs";
1
+ import { $ as secretSessionTurnQueue, A as TurnObserver, At as EXECUTION_ID_HEADER, B as readEphemeralContext, Bt as textDeltaEvents, C as plaintextResponseParser, Ct as InvalidAttachmentError, D as readCliTokenUsage, Dt as wasNeverLaunched, E as parseCliUsageLine, Et as rejectNotLaunched, F as isLocalMcpConfig, Ft as mapAcpSessionUpdate, G as SHARED_WORKSPACE_DIR_ENV, Gt as ACP_MIN_PROTOCOL_VERSION, H as turnInteractionEnabled, Ht as toolResultEvents, I as localMcpArgv, It as finalTextEvent, J as isLoopbackEndpoint, Jt as assertAcpTurnFinished, K as assertSealedNativeSearchPath, Kt as ACP_PROTOCOL_VERSION, L as localMcpEnv, Lt as reasoningEvents, M as endFailedTurn, Mt as MANAGED_QUOTE_VERSION_HEADER, N as recordTurnInterruption, Nt as executionCorrelationHeaders, O as recordCliTokenUsage, Ot as runtimeSecretsOverlay, P as createExecutionState, Pt as homeXdgEnv, Q as resolveReferences, R as enabledInteractionKinds, Rt as sessionObservedEvents, S as jsonEventParser, St as trackFilePart, T as accumulateCliTokenUsage, Tt as failureAfterCleanup, U as withEphemeralContext, Ut as toolStartEvents, V as turnEndReason, Vt as textSnapshotEvents, W as withTurnInteractions, Wt as trackReasoningBlock, X as joinQueue, Y as isPlainRecord, Yt as spawnAcpBridge, Z as requireRecord, _ as TerminalPlanSupport, _t as prependPromptSection, a as SECRET_REFERENCE, at as NATIVE_SESSION_CONTRACTS, b as brokerInteractionTools, bt as deterministicFilePartId, c as forgetSessionScopes, ct as isTrustedStoreBinary, d as findRouterCatalogEntry, dt as resolveExecutableRealpath, et as servableMcpServer, f as resolveRouterModelLimits, ft as MAX_INLINE_IMAGE_BYTES, g as McpInteractionSupport, gt as preparePromptInputParts, h as nativeEffortArgs, ht as partitionImageAttachments, i as PERMISSION_DECISION_TIMEOUT_MS, it as untilSettledOrAborted, j as createRepeatedToolFailureGuard, jt as EXECUTION_TRACE_HEADER, k as CliProviderAdapterBase, kt as EXECUTION_CORRELATION_HEADERS, l as secretMcpScope, lt as provenStoreBinary, m as kimiThinkingArgs, mt as PROMPT_SECTION_SEPARATOR, n as InteractionBroker, nt as sharedSecretMcpRefused, o as SECRET_REFERENCE_PREFIX, ot as SEALED_NATIVE_HOME_LAYOUT, p as resolveRouterModelReasoningEfforts, pt as MAX_TOTAL_INLINE_IMAGE_BYTES, q as directStdioMcpServers, qt as acpContentText, r as InteractionHttpBridge, rt as spawnUnderSecretMcpLease, s as codexDeveloperInstructionArgs, st as assertSealedNativeHome, t as CODEX_DISABLED_FEATURE_ARGS, tt as servableStdioServer, u as ROUTER_MODEL_CATALOG_TIMEOUT_MS, ut as refuseSecretLaunch, v as DEFAULT_INTERACTION_MCP_SERVER_NAME, vt as buildFileUrl, w as AcpProviderAdapterBase, wt as SessionRehydrationError, x as interactionMcpToolName, xt as inferMediaType, y as InteractionMcpServer, yt as deriveFilePart, z as interactionToggleEnabled, zt as streamPartBase } from "./src-B_4qa95r.mjs";
2
2
  export { ACP_MIN_PROTOCOL_VERSION, ACP_PROTOCOL_VERSION, AcpProviderAdapterBase, CODEX_DISABLED_FEATURE_ARGS, CliProviderAdapterBase, DEFAULT_INTERACTION_MCP_SERVER_NAME, EXECUTION_CORRELATION_HEADERS, EXECUTION_ID_HEADER, EXECUTION_TRACE_HEADER, InteractionBroker, InteractionHttpBridge, InteractionMcpServer, InvalidAttachmentError, MANAGED_QUOTE_VERSION_HEADER, MAX_INLINE_IMAGE_BYTES, MAX_TOTAL_INLINE_IMAGE_BYTES, McpInteractionSupport, NATIVE_SESSION_CONTRACTS, PERMISSION_DECISION_TIMEOUT_MS, PROMPT_SECTION_SEPARATOR, ROUTER_MODEL_CATALOG_TIMEOUT_MS, SEALED_NATIVE_HOME_LAYOUT, SECRET_REFERENCE, SECRET_REFERENCE_PREFIX, SHARED_WORKSPACE_DIR_ENV, SessionRehydrationError, TerminalPlanSupport, TurnObserver, accumulateCliTokenUsage, acpContentText, assertAcpTurnFinished, assertSealedNativeHome, assertSealedNativeSearchPath, brokerInteractionTools, buildFileUrl, codexDeveloperInstructionArgs, createExecutionState, createRepeatedToolFailureGuard, deriveFilePart, deterministicFilePartId, directStdioMcpServers, enabledInteractionKinds, endFailedTurn, executionCorrelationHeaders, failureAfterCleanup, finalTextEvent, findRouterCatalogEntry, forgetSessionScopes, homeXdgEnv, inferMediaType, interactionMcpToolName, interactionToggleEnabled, isLocalMcpConfig, isLoopbackEndpoint, isPlainRecord, isTrustedStoreBinary, joinQueue, jsonEventParser, kimiThinkingArgs, localMcpArgv, localMcpEnv, mapAcpSessionUpdate, nativeEffortArgs, parseCliUsageLine, partitionImageAttachments, plaintextResponseParser, preparePromptInputParts, prependPromptSection, provenStoreBinary, readCliTokenUsage, readEphemeralContext, reasoningEvents, recordCliTokenUsage, recordTurnInterruption, refuseSecretLaunch, rejectNotLaunched, requireRecord, resolveExecutableRealpath, resolveReferences, resolveRouterModelLimits, resolveRouterModelReasoningEfforts, runtimeSecretsOverlay, secretMcpScope, secretSessionTurnQueue, servableMcpServer, servableStdioServer, sessionObservedEvents, sharedSecretMcpRefused, spawnAcpBridge, spawnUnderSecretMcpLease, streamPartBase, textDeltaEvents, textSnapshotEvents, toolResultEvents, toolStartEvents, trackFilePart, trackReasoningBlock, turnEndReason, turnInteractionEnabled, untilSettledOrAborted, wasNeverLaunched, withEphemeralContext, withTurnInteractions };
@@ -8,7 +8,7 @@ import { MAX_SECRET_PROFILE_REPLAY_CHARS, RESTORED_SESSION_CONTEXT_PREAMBLE, RES
8
8
  import { lchown, mkdir, open, readdir, writeFile } from "node:fs/promises";
9
9
  import path, { basename, dirname, isAbsolute, join, normalize, resolve } from "node:path";
10
10
  import * as fs$1 from "node:fs";
11
- import fs, { constants, lstatSync, readFileSync, readdirSync, realpathSync } from "node:fs";
11
+ import fs, { closeSync, constants, lstatSync, openSync, readFileSync, readSync, readdirSync, realpathSync } from "node:fs";
12
12
  import { execFile } from "node:child_process";
13
13
  import { isDeepStrictEqual, promisify } from "node:util";
14
14
  import { messageStorageDirOf } from "@tangle-network/cli-agent-registry";
@@ -2923,13 +2923,37 @@ function filesUnder(dir, prefix, out) {
2923
2923
  else out.push(rel);
2924
2924
  }
2925
2925
  }
2926
- function idsNow(home, stores) {
2926
+ /**
2927
+ * Whether the SQLite file's header says write-ahead mode: its write and read
2928
+ * format versions, bytes 18 and 19, are both 2. Read as plain bytes, so the
2929
+ * check takes no SQLite lock.
2930
+ */
2931
+ function inWalMode(path) {
2932
+ let fd;
2933
+ try {
2934
+ fd = openSync(path, "r");
2935
+ const header = Buffer.alloc(20);
2936
+ return readSync(fd, header, 0, 20, 0) === 20 && header[18] === 2 && header[19] === 2;
2937
+ } catch {
2938
+ return false;
2939
+ } finally {
2940
+ if (fd !== void 0) closeSync(fd);
2941
+ }
2942
+ }
2943
+ /**
2944
+ * The native session ids the declared stores under `home` name now: the
2945
+ * rows of a shared SQLite store's session table, or the ids in the paths of a
2946
+ * per-session store's files.
2947
+ */
2948
+ function storedSessionIds(home, stores) {
2927
2949
  const ids = /* @__PURE__ */ new Set();
2928
2950
  for (const store of stores) {
2929
2951
  const root = join(home, store.root);
2930
2952
  if (store.shared && store.write === "sqlite-wal") {
2953
+ const file = join(root, store.files[0] ?? "state.db");
2954
+ if (!inWalMode(file)) continue;
2931
2955
  try {
2932
- const db = new DatabaseSync(join(root, store.files[0] ?? "state.db"), { readOnly: true });
2956
+ const db = new DatabaseSync(file, { readOnly: true });
2933
2957
  try {
2934
2958
  for (const query of [
2935
2959
  "SELECT id FROM session",
@@ -2958,10 +2982,10 @@ function watchNewSessionIds(params) {
2958
2982
  const home = params.runtimeHome?.trim().replace(/\/+$/u, "");
2959
2983
  const contract = params.sessionContract;
2960
2984
  if (!home || contract?.identity.kind !== "first-event") return () => {};
2961
- const seen = idsNow(home, contract.stores);
2985
+ const seen = storedSessionIds(home, contract.stores);
2962
2986
  const timer = setInterval(() => {
2963
2987
  if (params.observer.nativeSessionObserved) return;
2964
- for (const id of idsNow(home, contract.stores)) {
2988
+ for (const id of storedSessionIds(home, contract.stores)) {
2965
2989
  if (seen.has(id)) continue;
2966
2990
  seen.add(id);
2967
2991
  params.observer.onEvent({
@@ -5011,4 +5035,4 @@ async function forgetSessionScopes(target) {
5011
5035
  //#endregion
5012
5036
  export { secretSessionTurnQueue as $, TurnObserver as A, EXECUTION_ID_HEADER as At, readEphemeralContext as B, textDeltaEvents as Bt, plaintextResponseParser as C, InvalidAttachmentError as Ct, readCliTokenUsage as D, wasNeverLaunched as Dt, parseCliUsageLine as E, rejectNotLaunched as Et, isLocalMcpConfig as F, mapAcpSessionUpdate as Ft, SHARED_WORKSPACE_DIR_ENV as G, ACP_MIN_PROTOCOL_VERSION as Gt, turnInteractionEnabled as H, toolResultEvents as Ht, localMcpArgv as I, finalTextEvent as It, isLoopbackEndpoint as J, assertAcpTurnFinished as Jt, assertSealedNativeSearchPath as K, ACP_PROTOCOL_VERSION as Kt, localMcpEnv as L, reasoningEvents as Lt, endFailedTurn as M, MANAGED_QUOTE_VERSION_HEADER as Mt, recordTurnInterruption as N, executionCorrelationHeaders as Nt, recordCliTokenUsage as O, runtimeSecretsOverlay as Ot, createExecutionState as P, homeXdgEnv as Pt, resolveReferences as Q, enabledInteractionKinds as R, sessionObservedEvents as Rt, jsonEventParser as S, trackFilePart as St, accumulateCliTokenUsage as T, failureAfterCleanup as Tt, withEphemeralContext as U, toolStartEvents as Ut, turnEndReason as V, textSnapshotEvents as Vt, withTurnInteractions as W, trackReasoningBlock as Wt, joinQueue as X, isPlainRecord as Y, spawnAcpBridge as Yt, requireRecord as Z, TerminalPlanSupport as _, prependPromptSection as _t, SECRET_REFERENCE$1 as a, NATIVE_SESSION_CONTRACTS$1 as at, brokerInteractionTools$1 as b, deterministicFilePartId as bt, forgetSessionScopes as c, isTrustedStoreBinary as ct, findRouterCatalogEntry as d, resolveExecutableRealpath as dt, servableMcpServer as et, resolveRouterModelLimits as f, MAX_INLINE_IMAGE_BYTES as ft, McpInteractionSupport as g, preparePromptInputParts as gt, nativeEffortArgs as h, partitionImageAttachments as ht, PERMISSION_DECISION_TIMEOUT_MS as i, untilSettledOrAborted as it, createRepeatedToolFailureGuard as j, EXECUTION_TRACE_HEADER as jt, CliProviderAdapterBase as k, EXECUTION_CORRELATION_HEADERS as kt, secretMcpScope as l, provenStoreBinary as lt, kimiThinkingArgs as m, PROMPT_SECTION_SEPARATOR as mt, InteractionBroker$1 as n, sharedSecretMcpRefused as nt, SECRET_REFERENCE_PREFIX$1 as o, SEALED_NATIVE_HOME_LAYOUT as ot, resolveRouterModelReasoningEfforts as p, MAX_TOTAL_INLINE_IMAGE_BYTES as pt, directStdioMcpServers as q, acpContentText as qt, InteractionHttpBridge as r, spawnUnderSecretMcpLease as rt, codexDeveloperInstructionArgs as s, assertSealedNativeHome as st, CODEX_DISABLED_FEATURE_ARGS as t, servableStdioServer as tt, ROUTER_MODEL_CATALOG_TIMEOUT_MS as u, refuseSecretLaunch as ut, DEFAULT_INTERACTION_MCP_SERVER_NAME as v, buildFileUrl as vt, AcpProviderAdapterBase as w, SessionRehydrationError as wt, interactionMcpToolName as x, inferMediaType as xt, InteractionMcpServer$1 as y, deriveFilePart as yt, interactionToggleEnabled as z, streamPartBase as zt };
5013
5037
 
5014
- //# sourceMappingURL=src-D9Za3lQC.mjs.map
5038
+ //# sourceMappingURL=src-B_4qa95r.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/sdk-provider-cli-base",
3
- "version": "0.13.208",
3
+ "version": "0.13.210",
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.204",
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": "b00ae6aafc5629f76335a8171049a6530f7f13f2",
83
- "mergedAt": "2026-11-24T13:11:06-08:00"
82
+ "sourceSha": "295d3b99ce919b7d33be93088eb2a28cd32e3ca5",
83
+ "mergedAt": "2026-11-24T13:59:54-08:00"
84
84
  },
85
85
  "scripts": {
86
86
  "build": "tsdown",