@tangle-network/sdk-provider-cli-base 0.13.204 → 0.13.205
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.
|
@@ -102,6 +102,7 @@ declare class HermesProviderAdapter extends CliProviderAdapterBase<HermesConfig,
|
|
|
102
102
|
protected readonly profileHarness: HarnessId;
|
|
103
103
|
private activeSessionId?;
|
|
104
104
|
private readonly streamMarker;
|
|
105
|
+
private readonly exportToolTurns;
|
|
105
106
|
protected readonly defaultCliPath = "hermes";
|
|
106
107
|
protected isBenignNonZeroExit({
|
|
107
108
|
exitCode,
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { Bt as textDeltaEvents, C as plaintextResponseParser, F as isLocalMcpConfig, I as localMcpArgv, It as finalTextEvent, L as localMcpEnv, O as recordCliTokenUsage, Rt as sessionObservedEvents, 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-D9Za3lQC.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";
|
|
5
5
|
import { dirname, join } from "node:path";
|
|
6
|
+
import { isRecord } from "@tangle-network/agent-core";
|
|
6
7
|
import { z } from "zod";
|
|
7
8
|
import { DatabaseSync } from "node:sqlite";
|
|
8
9
|
//#region src/adapters/hermes/native-connection.ts
|
|
@@ -57,12 +58,74 @@ function resolveHermesNativeConnection(config, explicitModel) {
|
|
|
57
58
|
};
|
|
58
59
|
}
|
|
59
60
|
//#endregion
|
|
61
|
+
//#region src/adapters/hermes/session-tools.ts
|
|
62
|
+
/**
|
|
63
|
+
* Tool events for the calls one turn made, read from `hermes sessions export`.
|
|
64
|
+
*
|
|
65
|
+
* The export holds every stored row of the session. An assistant row lists
|
|
66
|
+
* its calls under `tool_calls` (`id`, `function.name`, `function.arguments`
|
|
67
|
+
* as JSON text) and each result is a `tool` row naming its `tool_call_id`. A
|
|
68
|
+
* row belongs to this turn when the session stored it after the turn's CLI
|
|
69
|
+
* launched (`timestamp`, in epoch seconds): a resumed session's earlier rows,
|
|
70
|
+
* and the copies a compaction makes of them, keep their own times.
|
|
71
|
+
*
|
|
72
|
+
* The export keeps a tool's result but not Hermes's verdict on it, so each
|
|
73
|
+
* finished call is reported completed with the result the model received.
|
|
74
|
+
*/
|
|
75
|
+
function exportedToolEvents(state, session, launchedAtMs) {
|
|
76
|
+
const events = [];
|
|
77
|
+
const rows = Array.isArray(session.messages) ? session.messages : [];
|
|
78
|
+
for (const row of rows) {
|
|
79
|
+
if (!isRecord(row) || typeof row.timestamp !== "number" || row.timestamp * 1e3 < launchedAtMs) continue;
|
|
80
|
+
if (row.role === "assistant" && Array.isArray(row.tool_calls)) for (const call of row.tool_calls) {
|
|
81
|
+
const fn = isRecord(call) ? call.function : void 0;
|
|
82
|
+
if (!isRecord(call) || !isRecord(fn) || typeof call.id !== "string" || typeof fn.name !== "string" || state.toolCalls.has(call.id)) continue;
|
|
83
|
+
events.push(...toolStartEvents(state, {
|
|
84
|
+
id: call.id,
|
|
85
|
+
name: fn.name,
|
|
86
|
+
input: toolArguments(fn.arguments)
|
|
87
|
+
}));
|
|
88
|
+
}
|
|
89
|
+
else if (row.role === "tool" && typeof row.tool_call_id === "string") {
|
|
90
|
+
if (state.toolCalls.get(row.tool_call_id)?.status !== "running") continue;
|
|
91
|
+
events.push(...toolResultEvents(state, {
|
|
92
|
+
id: row.tool_call_id,
|
|
93
|
+
content: row.content,
|
|
94
|
+
isError: false
|
|
95
|
+
}));
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return events;
|
|
99
|
+
}
|
|
100
|
+
/** The arguments object the model sent; text that is not one stays readable under `arguments`. */
|
|
101
|
+
function toolArguments(raw) {
|
|
102
|
+
if (isRecord(raw)) return raw;
|
|
103
|
+
if (typeof raw !== "string" || !raw) return {};
|
|
104
|
+
try {
|
|
105
|
+
const parsed = JSON.parse(raw);
|
|
106
|
+
if (isRecord(parsed)) return parsed;
|
|
107
|
+
} catch {}
|
|
108
|
+
return { arguments: raw };
|
|
109
|
+
}
|
|
110
|
+
//#endregion
|
|
60
111
|
//#region src/adapters/hermes/stream-parser.ts
|
|
61
112
|
/** Hermes emits its stream marker only on the packaged quiet chat path. A
|
|
62
|
-
* custom or older CLI can print a JSON answer without selecting this protocol.
|
|
63
|
-
|
|
113
|
+
* custom or older CLI can print a JSON answer without selecting this protocol.
|
|
114
|
+
* `onAcknowledged` runs once the CLI has selected it: from then on stdout names
|
|
115
|
+
* every tool the turn runs. */
|
|
116
|
+
function hermesStreamParser(marker, plaintext, state, onEvent, onAcknowledged) {
|
|
64
117
|
let streaming = false;
|
|
65
118
|
let finished = false;
|
|
119
|
+
const openCalls = /* @__PURE__ */ new Map();
|
|
120
|
+
let textFollowsTool = false;
|
|
121
|
+
function emit(events) {
|
|
122
|
+
for (const event of events) onEvent?.(event);
|
|
123
|
+
}
|
|
124
|
+
function openTextPart() {
|
|
125
|
+
state.textPartId = void 0;
|
|
126
|
+
state.textPartFrom = state.textBuffer.length;
|
|
127
|
+
textFollowsTool = false;
|
|
128
|
+
}
|
|
66
129
|
function fail(message) {
|
|
67
130
|
state.terminalStatus = "failed";
|
|
68
131
|
state.failure ??= {
|
|
@@ -91,6 +154,7 @@ function hermesStreamParser(marker, plaintext, state, onEvent) {
|
|
|
91
154
|
const { line } = event;
|
|
92
155
|
if (!streaming && line === marker) {
|
|
93
156
|
streaming = true;
|
|
157
|
+
onAcknowledged?.();
|
|
94
158
|
return;
|
|
95
159
|
}
|
|
96
160
|
if (!streaming) {
|
|
@@ -105,14 +169,49 @@ function hermesStreamParser(marker, plaintext, state, onEvent) {
|
|
|
105
169
|
} catch {
|
|
106
170
|
return;
|
|
107
171
|
}
|
|
108
|
-
|
|
109
|
-
|
|
172
|
+
const callId = typeof frame.tool_call_id === "string" && frame.tool_call_id ? frame.tool_call_id : void 0;
|
|
173
|
+
if (frame.type === "text" && typeof frame.text === "string") {
|
|
174
|
+
let text = frame.text;
|
|
175
|
+
if (textFollowsTool) {
|
|
176
|
+
text = text.replace(/^\n+/, "");
|
|
177
|
+
if (!text) return;
|
|
178
|
+
if (state.textBuffer) state.textBuffer += "\n\n";
|
|
179
|
+
openTextPart();
|
|
180
|
+
}
|
|
181
|
+
emit(textDeltaEvents(state, text));
|
|
182
|
+
} else if (frame.type === "tool_use" && typeof frame.name === "string") {
|
|
183
|
+
const id = callId ?? randomUUID();
|
|
184
|
+
if (!callId) {
|
|
185
|
+
const open = openCalls.get(frame.name) ?? [];
|
|
186
|
+
open.push(id);
|
|
187
|
+
openCalls.set(frame.name, open);
|
|
188
|
+
}
|
|
189
|
+
textFollowsTool = true;
|
|
190
|
+
emit(toolStartEvents(state, {
|
|
191
|
+
id,
|
|
192
|
+
name: frame.name,
|
|
193
|
+
input: frame.input
|
|
194
|
+
}));
|
|
195
|
+
} else if (frame.type === "tool_result" && typeof frame.name === "string") {
|
|
196
|
+
const id = callId ?? openCalls.get(frame.name)?.shift();
|
|
197
|
+
if (!id) return;
|
|
198
|
+
emit(toolResultEvents(state, {
|
|
199
|
+
id,
|
|
200
|
+
content: frame.output,
|
|
201
|
+
isError: frame.is_error === true
|
|
202
|
+
}));
|
|
203
|
+
} else if (frame.type === "result") {
|
|
110
204
|
finished = true;
|
|
111
205
|
if (typeof frame.exit_code !== "number" || typeof frame.text !== "string" || !frame.text && frame.exit_code !== 0) {
|
|
112
206
|
fail(typeof frame.error === "string" ? frame.error : "Hermes did not complete the turn");
|
|
113
207
|
return;
|
|
114
208
|
}
|
|
115
|
-
if (
|
|
209
|
+
if (textFollowsTool) openTextPart();
|
|
210
|
+
const streamed = state.textBuffer.slice(state.textPartFrom ?? 0);
|
|
211
|
+
state.textBuffer = streamed;
|
|
212
|
+
state.textPartFrom = 0;
|
|
213
|
+
if (frame.text.trim() === streamed.trim()) state.textBuffer = frame.text;
|
|
214
|
+
else if (frame.text.startsWith(streamed)) emit(textSnapshotEvents(state, frame.text));
|
|
116
215
|
else {
|
|
117
216
|
const update = finalTextEvent(state, frame.text);
|
|
118
217
|
if (update.type === "message.part.updated") onEvent?.({
|
|
@@ -152,6 +251,7 @@ var HermesProviderAdapter = class extends CliProviderAdapterBase {
|
|
|
152
251
|
profileHarness = "hermes";
|
|
153
252
|
activeSessionId;
|
|
154
253
|
streamMarker = `tangle-hermes-stream-${randomUUID()}`;
|
|
254
|
+
exportToolTurns = /* @__PURE__ */ new WeakMap();
|
|
155
255
|
defaultCliPath = "hermes";
|
|
156
256
|
isBenignNonZeroExit({ exitCode, stderr, state }) {
|
|
157
257
|
if (exitCode === null || exitCode === 0) return false;
|
|
@@ -285,6 +385,8 @@ var HermesProviderAdapter = class extends CliProviderAdapterBase {
|
|
|
285
385
|
this.logger.warn("hermes: session export did not return JSON", { sessionId: hermesSessionId });
|
|
286
386
|
return;
|
|
287
387
|
}
|
|
388
|
+
const launchedAt = this.exportToolTurns.get(params.state);
|
|
389
|
+
if (launchedAt !== void 0) for (const event of exportedToolEvents(params.state, session, launchedAt)) params.onEvent?.(event);
|
|
288
390
|
recordCliTokenUsage(params.state, {
|
|
289
391
|
usage: {
|
|
290
392
|
input_tokens: session.input_tokens,
|
|
@@ -321,7 +423,8 @@ var HermesProviderAdapter = class extends CliProviderAdapterBase {
|
|
|
321
423
|
},
|
|
322
424
|
emptyFailureDetail: "hermes errored without producing a response body"
|
|
323
425
|
});
|
|
324
|
-
|
|
426
|
+
this.exportToolTurns.set(state, Date.now());
|
|
427
|
+
return process.env.HERMES_STREAM === "1" ? hermesStreamParser(this.streamMarker, plaintext, state, onEvent, () => this.exportToolTurns.delete(state)) : plaintext;
|
|
325
428
|
}
|
|
326
429
|
};
|
|
327
430
|
function parseHermesSessionId(stderr) {
|
|
@@ -89,6 +89,13 @@ declare class PrimeProviderAdapter extends AcpProviderAdapterBase<PrimeConfig, P
|
|
|
89
89
|
message: string;
|
|
90
90
|
missingBinary: boolean;
|
|
91
91
|
}): string;
|
|
92
|
+
/**
|
|
93
|
+
* prime-agent's `session/prompt` response reports no token usage, so each
|
|
94
|
+
* response is completed with the usage prime wrote to its session files for
|
|
95
|
+
* that prompt (see prompt-usage.ts). The files are read in the agent dir the
|
|
96
|
+
* process was started on, which the agent environment can set over the
|
|
97
|
+
* spec's.
|
|
98
|
+
*/
|
|
92
99
|
protected spawnBridge(request: AcpBridgeSpawn): RpcBridge;
|
|
93
100
|
/**
|
|
94
101
|
* A failed tool whose output carries a kernel-death marker (the ipython
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Yt as spawnAcpBridge, _t as prependPromptSection, w as AcpProviderAdapterBase } from "../../src-D9Za3lQC.mjs";
|
|
2
|
-
import { PRIME_AGENT_DIR_ENV_VAR, 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";
|
|
1
|
+
import { D as readCliTokenUsage, Yt as spawnAcpBridge, _t as prependPromptSection, w as AcpProviderAdapterBase } from "../../src-D9Za3lQC.mjs";
|
|
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";
|
|
5
5
|
import { z } from "zod";
|
|
@@ -135,6 +135,188 @@ function materializePrimeModelsConfig(agentDir, input, io = { write: writePrimeA
|
|
|
135
135
|
return target;
|
|
136
136
|
}
|
|
137
137
|
//#endregion
|
|
138
|
+
//#region src/adapters/prime/prompt-usage.ts
|
|
139
|
+
/**
|
|
140
|
+
* Token usage of one prime-agent prompt, read from prime's session files.
|
|
141
|
+
*
|
|
142
|
+
* prime-agent asks its model endpoint for usage on every call
|
|
143
|
+
* (`stream_options.include_usage`) and writes it on that call's assistant
|
|
144
|
+
* message row in a session file, but its ACP surface never reports it: the
|
|
145
|
+
* `session/prompt` response is `{stopReason}` and no `session/update` carries
|
|
146
|
+
* a count. The ACP session adapter records a turn's usage from the prompt
|
|
147
|
+
* response, so the response is completed here with the sum over the model
|
|
148
|
+
* calls the prompt made.
|
|
149
|
+
*/
|
|
150
|
+
/**
|
|
151
|
+
* Prints, as a JSON array, the usage of every model call the session files of
|
|
152
|
+
* an agent dir recorded at or after a time (argv: agent dir, epoch ms).
|
|
153
|
+
*
|
|
154
|
+
* A root session's file is `sessions/<id>.jsonl`; a subagent's is below
|
|
155
|
+
* `session-artifacts/` and its calls are in no root file's message rows, so
|
|
156
|
+
* both trees are read and each call is counted once. Rows are appended in
|
|
157
|
+
* time order and stamped when appended, so a prompt's rows are a file's tail:
|
|
158
|
+
* each file is read backwards and left at the first message row older than
|
|
159
|
+
* the time, which keeps a long session's history unread. A file last written
|
|
160
|
+
* well before the time is not opened; the margin covers filesystems that
|
|
161
|
+
* store modification times to the second.
|
|
162
|
+
*/
|
|
163
|
+
const MODEL_CALLS_SCRIPT = `
|
|
164
|
+
const fs = require("node:fs");
|
|
165
|
+
const path = require("node:path");
|
|
166
|
+
const [agentDir, sinceArg] = process.argv.slice(1);
|
|
167
|
+
const since = Number(sinceArg);
|
|
168
|
+
const CHUNK = 64 * 1024;
|
|
169
|
+
const MTIME_MARGIN_MS = 60 * 1000;
|
|
170
|
+
const calls = [];
|
|
171
|
+
function scan(file) {
|
|
172
|
+
const fd = fs.openSync(file, "r");
|
|
173
|
+
try {
|
|
174
|
+
const stat = fs.fstatSync(fd);
|
|
175
|
+
if (stat.mtimeMs < since - MTIME_MARGIN_MS) return;
|
|
176
|
+
let end = stat.size;
|
|
177
|
+
// The bytes after the read position that finish a line begun before it.
|
|
178
|
+
let rest = [];
|
|
179
|
+
while (end > 0) {
|
|
180
|
+
const start = Math.max(0, end - CHUNK);
|
|
181
|
+
const chunk = Buffer.alloc(end - start);
|
|
182
|
+
fs.readSync(fd, chunk, 0, chunk.length, start);
|
|
183
|
+
end = start;
|
|
184
|
+
// A read that starts mid-line leaves that line's bytes for the next read.
|
|
185
|
+
const first = start === 0 ? 0 : chunk.indexOf(10) + 1;
|
|
186
|
+
if (start !== 0 && first === 0) {
|
|
187
|
+
rest.unshift(chunk);
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
const whole = Buffer.concat([chunk.subarray(first), ...rest]);
|
|
191
|
+
rest = [chunk.subarray(0, first)];
|
|
192
|
+
const lines = whole.toString("utf8").split("\\n");
|
|
193
|
+
for (let index = lines.length - 1; index >= 0; index--) {
|
|
194
|
+
let row;
|
|
195
|
+
try {
|
|
196
|
+
row = JSON.parse(lines[index]);
|
|
197
|
+
} catch {
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
if (!row || row.type !== "message" || !row.message) continue;
|
|
201
|
+
const at = Date.parse(row.timestamp);
|
|
202
|
+
if (Number.isNaN(at)) continue;
|
|
203
|
+
if (at < since) return;
|
|
204
|
+
if (row.message.role === "assistant" && row.message.usage) {
|
|
205
|
+
calls.push(row.message.usage);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
} finally {
|
|
210
|
+
fs.closeSync(fd);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
function walk(dir, depth) {
|
|
214
|
+
let entries;
|
|
215
|
+
try {
|
|
216
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
217
|
+
} catch (error) {
|
|
218
|
+
if (error.code === "ENOENT" || error.code === "ENOTDIR") return;
|
|
219
|
+
throw error;
|
|
220
|
+
}
|
|
221
|
+
for (const entry of entries) {
|
|
222
|
+
const file = path.join(dir, entry.name);
|
|
223
|
+
if (entry.isDirectory()) {
|
|
224
|
+
if (depth < 16) walk(file, depth + 1);
|
|
225
|
+
} else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
|
|
226
|
+
scan(file);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
walk(path.join(agentDir, "sessions"), 0);
|
|
231
|
+
walk(path.join(agentDir, "session-artifacts"), 0);
|
|
232
|
+
process.stdout.write(JSON.stringify(calls));
|
|
233
|
+
`;
|
|
234
|
+
const COUNTS = [
|
|
235
|
+
"inputTokens",
|
|
236
|
+
"outputTokens",
|
|
237
|
+
"totalTokens",
|
|
238
|
+
"reasoningTokens",
|
|
239
|
+
"cacheReadInputTokens",
|
|
240
|
+
"cacheCreationInputTokens"
|
|
241
|
+
];
|
|
242
|
+
/**
|
|
243
|
+
* The sum of the model calls' token counts, or undefined when none reported
|
|
244
|
+
* any. prime-agent's own cost figure is left out: it prices a call from the
|
|
245
|
+
* models.json the adapter writes, where every price is zero.
|
|
246
|
+
*/
|
|
247
|
+
function sumModelCalls(calls) {
|
|
248
|
+
let total;
|
|
249
|
+
for (const call of calls) {
|
|
250
|
+
const usage = readCliTokenUsage({ usage: call });
|
|
251
|
+
if (!usage) continue;
|
|
252
|
+
total ??= {};
|
|
253
|
+
for (const key of COUNTS) {
|
|
254
|
+
const count = usage[key];
|
|
255
|
+
if (count !== void 0) total[key] = (total[key] ?? 0) + count;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return total;
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* The usage of the model calls `agentDir`'s session files recorded at or
|
|
262
|
+
* after `sinceMs`. `runAsOwner` runs a Node script as the agent dir's owner
|
|
263
|
+
* (the adapter's `runNodeAsSubprocess`), like every other read in that dir.
|
|
264
|
+
*/
|
|
265
|
+
async function readPromptUsage(agentDir, sinceMs, runAsOwner) {
|
|
266
|
+
const calls = JSON.parse(await runAsOwner("prime: cannot read the prompt's usage from the agent dir as its owner", MODEL_CALLS_SCRIPT, [agentDir, String(sinceMs)]));
|
|
267
|
+
return Array.isArray(calls) ? sumModelCalls(calls) : void 0;
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* `bridge` with each `session/prompt` response carrying the usage of the
|
|
271
|
+
* model calls that prompt made, as `tokenUsage`.
|
|
272
|
+
*
|
|
273
|
+
* The window opens when the prompt is sent, which the ACP session adapter
|
|
274
|
+
* does only after the session's previous prompt has answered, so one prompt's
|
|
275
|
+
* calls are never read into another's. A prompt that fails leaves the window
|
|
276
|
+
* open: the retry on the same process then reports the calls of both. A usage
|
|
277
|
+
* read that fails is reported to `onUnreadable` and the response is returned
|
|
278
|
+
* without usage, which stays distinct from a measured zero.
|
|
279
|
+
*/
|
|
280
|
+
function withPromptUsage(bridge, readUsage, onUnreadable) {
|
|
281
|
+
let since;
|
|
282
|
+
async function request(method, params, options) {
|
|
283
|
+
if (method !== "session/prompt") return bridge.request(method, params, options);
|
|
284
|
+
const opened = since ?? Date.now();
|
|
285
|
+
since = opened;
|
|
286
|
+
const result = await bridge.request(method, params, options);
|
|
287
|
+
since = void 0;
|
|
288
|
+
let tokenUsage;
|
|
289
|
+
try {
|
|
290
|
+
tokenUsage = await readUsage(opened);
|
|
291
|
+
} catch (error) {
|
|
292
|
+
onUnreadable(error);
|
|
293
|
+
}
|
|
294
|
+
return tokenUsage ? {
|
|
295
|
+
...result,
|
|
296
|
+
tokenUsage
|
|
297
|
+
} : result;
|
|
298
|
+
}
|
|
299
|
+
return {
|
|
300
|
+
request,
|
|
301
|
+
captureTurn: (path, metadata) => bridge.captureTurn(path, metadata),
|
|
302
|
+
notify: (method, params) => bridge.notify(method, params),
|
|
303
|
+
onNotification: (method, handler) => bridge.onNotification(method, handler),
|
|
304
|
+
onRequest: (method, handler) => bridge.onRequest(method, handler),
|
|
305
|
+
onClose: (handler) => bridge.onClose(handler),
|
|
306
|
+
close: (graceMs) => bridge.close(graceMs),
|
|
307
|
+
getStderrTail: () => bridge.getStderrTail(),
|
|
308
|
+
get pid() {
|
|
309
|
+
return bridge.pid;
|
|
310
|
+
},
|
|
311
|
+
get closed() {
|
|
312
|
+
return bridge.closed;
|
|
313
|
+
},
|
|
314
|
+
get process() {
|
|
315
|
+
return bridge.process;
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
//#endregion
|
|
138
320
|
//#region src/adapters/prime/types.ts
|
|
139
321
|
/**
|
|
140
322
|
* Typed session-fatal error for a dead IPython kernel. Callers must treat the
|
|
@@ -309,8 +491,18 @@ var PrimeProviderAdapter = class extends AcpProviderAdapterBase {
|
|
|
309
491
|
spawnFailureMessage(failure) {
|
|
310
492
|
return failure.missingBinary ? `prime: "${this.getCliPath()}" not found on PATH. The container image must ship the pinned Prime native CLI and prepared Python kernel — see packages/sdk-provider-cli-base/docs/prime.md.` : `prime: failed to spawn prime-agent: ${failure.message}`;
|
|
311
493
|
}
|
|
494
|
+
/**
|
|
495
|
+
* prime-agent's `session/prompt` response reports no token usage, so each
|
|
496
|
+
* response is completed with the usage prime wrote to its session files for
|
|
497
|
+
* that prompt (see prompt-usage.ts). The files are read in the agent dir the
|
|
498
|
+
* process was started on, which the agent environment can set over the
|
|
499
|
+
* spec's.
|
|
500
|
+
*/
|
|
312
501
|
spawnBridge(request) {
|
|
313
|
-
|
|
502
|
+
const bridge = (bridgeFactoryOverride ?? spawnAcpBridge)(request);
|
|
503
|
+
const agentDir = request.env?.[PRIME_AGENT_DIR_ENV_VAR$1];
|
|
504
|
+
if (!agentDir) return bridge;
|
|
505
|
+
return withPromptUsage(bridge, (sinceMs) => readPromptUsage(agentDir, sinceMs, (operation, script, args) => this.runNodeAsSubprocess(operation, script, args)), (error) => this.logger.warn("prime: the turn's token usage is not reported", { error: error instanceof Error ? error.message : String(error) }));
|
|
314
506
|
}
|
|
315
507
|
/**
|
|
316
508
|
* A failed tool whose output carries a kernel-death marker (the ipython
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangle-network/sdk-provider-cli-base",
|
|
3
|
-
"version": "0.13.
|
|
3
|
+
"version": "0.13.205",
|
|
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.220",
|
|
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.203",
|
|
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": "6033787eb5439bac0a76105dbe0e5c89f65eb6dd",
|
|
83
|
+
"mergedAt": "2026-11-24T11:26:41-08:00"
|
|
84
84
|
},
|
|
85
85
|
"scripts": {
|
|
86
86
|
"build": "tsdown",
|