@tangle-network/agent-provider-tangle 1.2.3 → 1.3.1

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.
package/README.md CHANGED
@@ -156,6 +156,28 @@ The adapter bounds each complete serialized frame to 1 MiB of UTF-8, including k
156
156
  It retains accepted content without truncation in the event data and original provider event.
157
157
  Identifiers, usage metadata, and structural JSON limits retain their existing bounds.
158
158
 
159
+ ### Usage before the terminal receipt
160
+
161
+ Sandbox reports an execution's usage on its terminal `result` and `done` frames, and the adapter marks that receipt `usageMode: "cumulative"`.
162
+ Before the receipt, only the OpenCode harness forwards usage: its `step_finish` event arrives as a `raw` frame with that step's token counts.
163
+ The adapter attaches the execution's running total to each such frame as `usage` with `usageMode: "cumulative"`.
164
+ The running total uses the receipt's convention: input includes cache reads and writes, and output includes reasoning.
165
+ A consumer can therefore enforce a token limit while the execution runs.
166
+
167
+ The adapter reports a running total only on a stream that starts at the execution's first frame.
168
+ That is `environment.stream()` without `lastEventId`, and an exact `session.events()` replay without `since`.
169
+ A cursor replay and the session's live tail miss earlier steps, so their step frames carry no usage.
170
+ A step that repeats under a reconnect is counted once, by its OpenCode part id.
171
+ After a step reports counts without both totals, later step frames carry no usage, because no later total is known.
172
+ A step with an invalid count fails the stream.
173
+
174
+ The terminal receipt remains authoritative, and the adapter never rewrites it or the step totals to agree.
175
+ In 21 recorded production OpenCode executions, the last step total equaled the receipt in every counter.
176
+ If a receipt is lower than the streamed total, the cumulative sequence falls, and a consumer that folds cumulative usage can report the conflict.
177
+ Sum `usage` across events only when `usageMode` is `"delta"`.
178
+ Claude Code, Pi, and the other CLI backends forward no per-step usage, so their frames carry none.
179
+ Codex can forward its `turn.completed` record as a `raw` frame, but one Codex execution is one turn, so the adapter leaves that frame unchanged.
180
+
159
181
  ## Two capability documents
160
182
 
161
183
  Capabilities are derived in two stages, and the two stages answer different questions.
@@ -152,7 +152,7 @@ export function createTangleExactProcessProvider(input) {
152
152
  function exactSandboxOptions(input, defaults, providerName, identityDigest) {
153
153
  boundedString(input.image, "exact process image");
154
154
  boundedIdentifier(input.idempotencyKey, "exact process idempotencyKey");
155
- assertBoundedJson(input.metadata);
155
+ assertBoundedJson(input.metadata, "exact process metadata");
156
156
  if (!input.image.trim())
157
157
  throw new Error("exact process image is required");
158
158
  if (!IMMUTABLE_TANGLE_IMAGE.test(input.image)) {
@@ -12,8 +12,47 @@ export declare const MAX_JSON_DEPTH = 16;
12
12
  export declare const MAX_JSON_NODES = 8192;
13
13
  export declare function boundedIdentifier(value: unknown, label: string): string;
14
14
  export declare function boundedString(value: unknown, label: string): string;
15
+ /**
16
+ * The rule a value broke. Only the rules that COUNT something carry a limit; the rest are shape
17
+ * rejections, where nothing is oversized and saying so misdirects the reader.
18
+ */
19
+ export type JsonBoundRule = "string" | "array" | "entries" | "depth" | "nodes" | "key" | "undefined" | "number" | "type" | "cycle" | "prototype";
20
+ export interface JsonBoundViolation {
21
+ readonly rule: JsonBoundRule;
22
+ /** Object keys and array indices only. A path locates the value; it never carries one. */
23
+ readonly path: string;
24
+ readonly observed?: number;
25
+ readonly limit?: number;
26
+ readonly limitName?: string;
27
+ /** Position of the offending key among its object's own keys, for the `key` rule. */
28
+ readonly entry?: number;
29
+ /** A JavaScript type or constructor name — program text, not payload. */
30
+ readonly observedType?: string;
31
+ }
32
+ /**
33
+ * The first bound `value` breaks, in document order, or undefined when it breaks none.
34
+ *
35
+ * Document order matters: the walk is a LIFO stack, so children are pushed in reverse to make
36
+ * `pop` yield the order a reader sees in the value. A reason that named whichever sibling the
37
+ * stack happened to hold last would be a new way to mislead. Only the first violation is
38
+ * reported — later ones may exist.
39
+ */
40
+ export declare function firstJsonBoundViolation(value: unknown): JsonBoundViolation | undefined;
15
41
  export declare function isBoundedJson(value: unknown): boolean;
16
- export declare function assertBoundedJson(value: unknown): void;
42
+ /**
43
+ * One line naming the rule, where it broke, what was measured, and the limit — and never the
44
+ * value. Profile and metadata strings carry prompt text, mounted briefs, and through `env`,
45
+ * `mcp.*.env` and `headers` material adjacent to secrets, so no prefix, excerpt, or
46
+ * length-preserving echo of a value belongs in a reason a journal keeps.
47
+ */
48
+ export declare function describeJsonBoundViolation(violation: JsonBoundViolation): string;
49
+ /**
50
+ * `label` names WHICH field was rejected. agent-runtime's `errMessage` flattens a cause chain to
51
+ * `name: message`, so without it a run record cannot say whether the rejected value was the
52
+ * profile, the metadata, or a providerOptions map — which is how three children settled on five
53
+ * words that identified nothing.
54
+ */
55
+ export declare function assertBoundedJson(value: unknown, label?: string): void;
17
56
  /** Keep a late-created provider handle reachable when an abort wins the race. */
18
57
  export declare function attachCleanupHandle(error: unknown, handle: unknown, cleanupError?: unknown): void;
19
58
  export declare function exactProcessRequestDigest(input: CreateAgentExactProcessEnvironmentInput, providerName: string, options: TangleExactProcessOptions): `sha256:${string}`;
@@ -21,6 +60,6 @@ export declare function validateExactProcessCreateInput(input: CreateAgentExactP
21
60
  export declare function awaitWithSignal<T>(operation: Promise<T> | T | undefined, signal?: AbortSignal): Promise<T>;
22
61
  /** Await an operation and clean its result if abort wins before it resolves. */
23
62
  export declare function awaitWithSignalAndCleanup<T>(operation: () => Promise<T> | T, signal: AbortSignal | undefined, cleanup: (value: T) => Promise<void> | void): Promise<T>;
24
- export declare function cloneJson<T>(value: T): T;
63
+ export declare function cloneJson<T>(value: T, label?: string): T;
25
64
  export declare function safeIdentifier(value: unknown): string | undefined;
26
65
  export declare function safeString(value: unknown): string | undefined;
@@ -22,9 +22,38 @@ export function boundedString(value, label) {
22
22
  }
23
23
  return value;
24
24
  }
25
- export function isBoundedJson(value) {
25
+ /** A key or constructor name is author-chosen program text, so echoing it discloses nothing. It
26
+ * can still be long enough to turn a one-line reason into a dump, or carry a control character
27
+ * that breaks the line a journal writes it on. */
28
+ const MAX_PATH_SEGMENT_LENGTH = 48;
29
+ const MAX_PATH_LENGTH = 256;
30
+ const MAX_BOUND_MESSAGE_LENGTH = 512;
31
+ const PLAIN_KEY = /^[A-Za-z_$][A-Za-z0-9_$]*$/u;
32
+ const PLAIN_TYPE_NAME = /^[A-Za-z_$][A-Za-z0-9_$]{0,63}$/u;
33
+ function boundedPathSegment(key) {
34
+ const shortened = key.length > MAX_PATH_SEGMENT_LENGTH ? `${key.slice(0, MAX_PATH_SEGMENT_LENGTH)}...` : key;
35
+ return shortened.replace(/\p{C}/gu, "?");
36
+ }
37
+ function appendKeyToPath(path, key) {
38
+ const segment = boundedPathSegment(key);
39
+ if (!PLAIN_KEY.test(segment))
40
+ return `${path}[${JSON.stringify(segment)}]`;
41
+ return path === "" ? segment : `${path}.${segment}`;
42
+ }
43
+ function safeTypeName(value) {
44
+ return typeof value === "string" && PLAIN_TYPE_NAME.test(value) ? value : undefined;
45
+ }
46
+ /**
47
+ * The first bound `value` breaks, in document order, or undefined when it breaks none.
48
+ *
49
+ * Document order matters: the walk is a LIFO stack, so children are pushed in reverse to make
50
+ * `pop` yield the order a reader sees in the value. A reason that named whichever sibling the
51
+ * stack happened to hold last would be a new way to mislead. Only the first violation is
52
+ * reported — later ones may exist.
53
+ */
54
+ export function firstJsonBoundViolation(value) {
26
55
  const pending = [
27
- { value, depth: 0 },
56
+ { value, depth: 0, path: "" },
28
57
  ];
29
58
  const ancestors = new Set();
30
59
  let nodes = 0;
@@ -33,54 +62,141 @@ export function isBoundedJson(value) {
33
62
  if (!item)
34
63
  continue;
35
64
  nodes += 1;
36
- if (nodes > MAX_JSON_NODES)
37
- return false;
65
+ if (nodes > MAX_JSON_NODES) {
66
+ return { rule: "nodes", path: item.path, observed: nodes, limit: MAX_JSON_NODES, limitName: "MAX_JSON_NODES" };
67
+ }
38
68
  const current = item.value;
39
69
  if (item.leave) {
40
70
  ancestors.delete(current);
41
71
  continue;
42
72
  }
43
73
  if (current === undefined)
44
- return false;
74
+ return { rule: "undefined", path: item.path };
45
75
  if (current === null || typeof current === "boolean")
46
76
  continue;
47
77
  if (typeof current === "string") {
48
- if (current.length > MAX_STRING_LENGTH)
49
- return false;
78
+ if (current.length > MAX_STRING_LENGTH) {
79
+ return { rule: "string", path: item.path, observed: current.length, limit: MAX_STRING_LENGTH, limitName: "MAX_STRING_LENGTH" };
80
+ }
50
81
  continue;
51
82
  }
52
83
  if (typeof current === "number") {
53
84
  if (!Number.isFinite(current))
54
- return false;
85
+ return { rule: "number", path: item.path };
55
86
  continue;
56
87
  }
57
- if (typeof current !== "object" ||
58
- item.depth >= MAX_JSON_DEPTH ||
59
- ancestors.has(current))
60
- return false;
88
+ if (typeof current !== "object") {
89
+ return { rule: "type", path: item.path, observedType: safeTypeName(typeof current) };
90
+ }
91
+ if (item.depth >= MAX_JSON_DEPTH) {
92
+ return { rule: "depth", path: item.path, observed: item.depth, limit: MAX_JSON_DEPTH, limitName: "MAX_JSON_DEPTH" };
93
+ }
94
+ if (ancestors.has(current))
95
+ return { rule: "cycle", path: item.path };
61
96
  ancestors.add(current);
62
- pending.push({ value: current, depth: item.depth, leave: true });
97
+ pending.push({ value: current, depth: item.depth, path: item.path, leave: true });
63
98
  if (Array.isArray(current)) {
64
- if (current.length > MAX_ARRAY_LENGTH)
65
- return false;
66
- for (const entry of current)
67
- pending.push({ value: entry, depth: item.depth + 1 });
99
+ if (current.length > MAX_ARRAY_LENGTH) {
100
+ return { rule: "array", path: item.path, observed: current.length, limit: MAX_ARRAY_LENGTH, limitName: "MAX_ARRAY_LENGTH" };
101
+ }
102
+ for (let index = current.length - 1; index >= 0; index -= 1) {
103
+ pending.push({ value: current[index], depth: item.depth + 1, path: `${item.path}[${index}]` });
104
+ }
68
105
  continue;
69
106
  }
70
- if (Object.getPrototypeOf(current) !== Object.prototype && Object.getPrototypeOf(current) !== null)
71
- return false;
107
+ const prototype = Object.getPrototypeOf(current);
108
+ if (prototype !== Object.prototype && prototype !== null) {
109
+ return {
110
+ rule: "prototype",
111
+ path: item.path,
112
+ observedType: safeTypeName(prototype?.constructor?.name),
113
+ };
114
+ }
72
115
  const keys = Object.keys(current);
73
- if (keys.length > MAX_MAP_ENTRIES ||
74
- keys.some((key) => key.length > MAX_IDENTIFIER_LENGTH))
75
- return false;
76
- for (const key of keys)
77
- pending.push({ value: current[key], depth: item.depth + 1 });
116
+ if (keys.length > MAX_MAP_ENTRIES) {
117
+ return { rule: "entries", path: item.path, observed: keys.length, limit: MAX_MAP_ENTRIES, limitName: "MAX_MAP_ENTRIES" };
118
+ }
119
+ for (let index = 0; index < keys.length; index += 1) {
120
+ const key = keys[index];
121
+ if (key.length > MAX_IDENTIFIER_LENGTH) {
122
+ // The over-long key IS the value that broke this bound, so it is located by ordinal
123
+ // rather than echoed. Every other rule names a path whose segments are bounded keys.
124
+ return { rule: "key", path: item.path, entry: index, observed: key.length, limit: MAX_IDENTIFIER_LENGTH, limitName: "MAX_IDENTIFIER_LENGTH" };
125
+ }
126
+ }
127
+ for (let index = keys.length - 1; index >= 0; index -= 1) {
128
+ pending.push({
129
+ value: current[keys[index]],
130
+ depth: item.depth + 1,
131
+ path: appendKeyToPath(item.path, keys[index]),
132
+ });
133
+ }
134
+ }
135
+ return undefined;
136
+ }
137
+ export function isBoundedJson(value) {
138
+ return firstJsonBoundViolation(value) === undefined;
139
+ }
140
+ /**
141
+ * One line naming the rule, where it broke, what was measured, and the limit — and never the
142
+ * value. Profile and metadata strings carry prompt text, mounted briefs, and through `env`,
143
+ * `mcp.*.env` and `headers` material adjacent to secrets, so no prefix, excerpt, or
144
+ * length-preserving echo of a value belongs in a reason a journal keeps.
145
+ */
146
+ export function describeJsonBoundViolation(violation) {
147
+ const at = violation.path === ""
148
+ ? "(root)"
149
+ : violation.path.length > MAX_PATH_LENGTH
150
+ // The leaf is what a reader looks for, so a path too long to keep loses its head.
151
+ ? `...${violation.path.slice(violation.path.length - MAX_PATH_LENGTH)}`
152
+ : violation.path;
153
+ const limit = `limit ${violation.limit} (${violation.limitName})`;
154
+ switch (violation.rule) {
155
+ case "string":
156
+ return `string at ${at} is ${violation.observed} characters, ${limit}`;
157
+ case "array":
158
+ return `array at ${at} has ${violation.observed} entries, ${limit}`;
159
+ case "entries":
160
+ return `object at ${at} has ${violation.observed} entries, ${limit}`;
161
+ case "depth":
162
+ return `object at ${at} is at depth ${violation.observed}, ${limit}`;
163
+ case "nodes":
164
+ return `the walk reached ${violation.observed} nodes at ${at}, ${limit}`;
165
+ case "key":
166
+ return `key ${violation.entry} of the object at ${at} is ${violation.observed} characters, ${limit}`;
167
+ case "undefined":
168
+ return `undefined at ${at} has no JSON form`;
169
+ case "number":
170
+ return `number at ${at} is not finite`;
171
+ case "cycle":
172
+ return `cycle at ${at}: the value refers back to one of its own ancestors`;
173
+ case "prototype":
174
+ return violation.observedType === undefined
175
+ ? `object at ${at} has a prototype that is not Object.prototype`
176
+ : `object at ${at} has a ${violation.observedType} prototype, not a plain object prototype`;
177
+ case "type":
178
+ return violation.observedType === undefined
179
+ ? `value at ${at} has a type with no JSON form`
180
+ : `${violation.observedType} at ${at} has no JSON form`;
78
181
  }
79
- return true;
80
182
  }
81
- export function assertBoundedJson(value) {
82
- if (!isBoundedJson(value))
83
- throw new Error("value exceeds its JSON bound");
183
+ /**
184
+ * `label` names WHICH field was rejected. agent-runtime's `errMessage` flattens a cause chain to
185
+ * `name: message`, so without it a run record cannot say whether the rejected value was the
186
+ * profile, the metadata, or a providerOptions map — which is how three children settled on five
187
+ * words that identified nothing.
188
+ */
189
+ export function assertBoundedJson(value, label = "value") {
190
+ const violation = firstJsonBoundViolation(value);
191
+ if (violation === undefined)
192
+ return;
193
+ // A rule with no limit counted nothing: a Date, a cycle, a NaN and an absent value are not
194
+ // oversized, and "exceeds" sends the reader after a size problem that does not exist.
195
+ const verdict = violation.limit === undefined ? "violates" : "exceeds";
196
+ const message = `${label} ${verdict} its JSON bound: ${describeJsonBoundViolation(violation)}`;
197
+ throw new Error(message.length > MAX_BOUND_MESSAGE_LENGTH
198
+ ? `${message.slice(0, MAX_BOUND_MESSAGE_LENGTH - 3)}...`
199
+ : message);
84
200
  }
85
201
  /** Keep a late-created provider handle reachable when an abort wins the race. */
86
202
  export function attachCleanupHandle(error, handle, cleanupError) {
@@ -100,7 +216,7 @@ export function attachCleanupHandle(error, handle, cleanupError) {
100
216
  }
101
217
  export function exactProcessRequestDigest(input, providerName, options) {
102
218
  validateExactProcessCreateInput(input, providerName, options);
103
- assertBoundedJson(input.metadata);
219
+ assertBoundedJson(input.metadata, "exact process metadata");
104
220
  return canonicalCandidateDigest({
105
221
  provider: providerName,
106
222
  image: input.image,
@@ -143,12 +259,12 @@ export function validateExactProcessCreateInput(input, providerName, options) {
143
259
  if (!input.metadata || typeof input.metadata !== "object" || Array.isArray(input.metadata)) {
144
260
  throw new Error("exact process metadata must be a JSON object");
145
261
  }
146
- assertBoundedJson(input.metadata);
262
+ assertBoundedJson(input.metadata, "exact process metadata");
147
263
  if (input.providerOptions !== undefined) {
148
264
  if (!input.providerOptions || typeof input.providerOptions !== "object" || Array.isArray(input.providerOptions)) {
149
265
  throw new Error("Tangle exact process providerOptions must be a JSON object");
150
266
  }
151
- assertBoundedJson(input.providerOptions);
267
+ assertBoundedJson(input.providerOptions, "exact process providerOptions");
152
268
  if (Object.keys(input.providerOptions).length > 0) {
153
269
  throw new Error("Tangle exact process providerOptions are not supported");
154
270
  }
@@ -266,8 +382,8 @@ export async function awaitWithSignalAndCleanup(operation, signal, cleanup) {
266
382
  signal.removeEventListener("abort", listener);
267
383
  }
268
384
  }
269
- export function cloneJson(value) {
270
- assertBoundedJson(value);
385
+ export function cloneJson(value, label) {
386
+ assertBoundedJson(value, label);
271
387
  return structuredClone(value);
272
388
  }
273
389
  export function safeIdentifier(value) {
@@ -6,7 +6,7 @@ import { tangleRuntimeAttachments } from "./tangle-runtime-attachments.js";
6
6
  export function captureModelCredentials(value) {
7
7
  if (value === undefined)
8
8
  return undefined;
9
- assertBoundedJson(value);
9
+ assertBoundedJson(value, "Tangle modelCredentials");
10
10
  if (!value || typeof value !== "object" || Array.isArray(value) ||
11
11
  Object.keys(value).some((key) => key !== "apiKeyEnv" && key !== "baseUrl")) {
12
12
  throw new Error("Tangle modelCredentials accepts only apiKeyEnv and baseUrl");
@@ -137,7 +137,7 @@ export function assertNoInlineSecretValues(input, parsedWorkspace) {
137
137
  if (!input.providerOptions || typeof input.providerOptions !== "object" || Array.isArray(input.providerOptions)) {
138
138
  throw new Error("Tangle create providerOptions must be a JSON object");
139
139
  }
140
- assertBoundedJson(input.providerOptions);
140
+ assertBoundedJson(input.providerOptions, "Tangle create providerOptions");
141
141
  if (Object.keys(input.providerOptions).length > 0) {
142
142
  throw new Error("Tangle create providerOptions are not supported");
143
143
  }
@@ -152,7 +152,7 @@ export function assertNoInlineSecretValues(input, parsedWorkspace) {
152
152
  if (!input.resources.providerOptions || typeof input.resources.providerOptions !== "object" || Array.isArray(input.resources.providerOptions)) {
153
153
  throw new Error("Tangle resource providerOptions must be a JSON object");
154
154
  }
155
- assertBoundedJson(input.resources.providerOptions);
155
+ assertBoundedJson(input.resources.providerOptions, "Tangle create resources.providerOptions");
156
156
  if (Object.keys(input.resources.providerOptions).length > 0) {
157
157
  throw new Error("Tangle resource providerOptions are not supported");
158
158
  }
@@ -215,7 +215,7 @@ export function assertCreateInputShape(input, parsedWorkspace) {
215
215
  if (!input.profile || typeof input.profile !== "object" || Array.isArray(input.profile)) {
216
216
  throw new Error("Tangle profile must be an object or bounded reference");
217
217
  }
218
- assertBoundedJson(input.profile);
218
+ assertBoundedJson(input.profile, "Tangle create profile");
219
219
  }
220
220
  if (input.resources !== undefined) {
221
221
  if (!input.resources || typeof input.resources !== "object" || Array.isArray(input.resources)) {
@@ -237,7 +237,7 @@ export function assertMappedCreateOptions(options) {
237
237
  if (!options || typeof options !== "object" || Array.isArray(options)) {
238
238
  throw new Error("Tangle mapped create options must be an object");
239
239
  }
240
- assertBoundedJson(options);
240
+ assertBoundedJson(options, "Tangle mapped create options");
241
241
  if (options.backend?.runtimeAttachments !== undefined) {
242
242
  tangleRuntimeAttachments(options.backend.runtimeAttachments, options.backend.profile);
243
243
  }
@@ -289,14 +289,14 @@ function inlineAgentProfile(profile) {
289
289
  if (!profile || typeof profile !== "object" || Array.isArray(profile)) {
290
290
  throw new Error("Tangle inline AgentProfile must be an object");
291
291
  }
292
- assertBoundedJson(profile);
292
+ assertBoundedJson(profile, "Tangle inline AgentProfile");
293
293
  return profile;
294
294
  }
295
295
  function assertBoundedRecord(value, label) {
296
296
  if (!value || typeof value !== "object" || Array.isArray(value)) {
297
297
  throw new Error(`${label} must be a JSON object`);
298
298
  }
299
- assertBoundedJson(value);
299
+ assertBoundedJson(value, label);
300
300
  }
301
301
  function assertStringRecord(value, label) {
302
302
  if (!value || typeof value !== "object" || Array.isArray(value)) {
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { AgentTurnInputSchema } from "@tangle-network/agent-interface";
3
3
  import { AgentRunCancellationAcknowledgementSchema, AgentRunCancellationRequestSchema, agentRunCancellationAcknowledgementMatchesRequest, } from "@tangle-network/agent-interface";
4
+ import { createStepUsageFold } from "./tangle-step-usage.js";
4
5
  import { carriedSessionIds, environmentEventFromSandboxEvent, isSandboxConnectionMarker, sandboxEventIdentity, } from "./tangle-events.js";
5
6
  import { agentTurnResultFromPromptRecord, promptFromTurnInput, promptOptionsFromTurnInput, validatedSandboxPromptResult, } from "./tangle-prompt.js";
6
7
  import { retainedSessionControlRef, resolveRetainedSessionControlRef, sameRunControlRef, sessionPromptExecutionId, } from "./tangle-session-control.js";
@@ -96,6 +97,12 @@ export function sandboxSessionAsAgentSession(session, controlRef, provider, envi
96
97
  options?.signal?.throwIfAborted();
97
98
  const seenEventIds = new Set();
98
99
  const useExactExecutionStream = exactExecutionEvents !== undefined && executionId !== undefined;
100
+ // Only the exact replay without a cursor starts at the execution's first
101
+ // frame. A cursor replay and the session's live tail both miss earlier
102
+ // steps, so neither can report the execution's running total.
103
+ const stepUsage = useExactExecutionStream && options?.since === undefined
104
+ ? createStepUsageFold()
105
+ : undefined;
99
106
  const iterator = (useExactExecutionStream
100
107
  ? exactExecutionEvents({
101
108
  sessionId: session.id,
@@ -146,7 +153,7 @@ export function sandboxSessionAsAgentSession(session, controlRef, provider, envi
146
153
  continue;
147
154
  seenEventIds.add(converted.id);
148
155
  options?.signal?.throwIfAborted();
149
- yield converted;
156
+ yield stepUsage?.observe(converted) ?? converted;
150
157
  }
151
158
  }
152
159
  finally {
@@ -15,7 +15,7 @@ export function assertRecord(value, label) {
15
15
  if (!value || typeof value !== "object" || Array.isArray(value)) {
16
16
  throw new Error(`${label} must be a JSON object`);
17
17
  }
18
- assertBoundedJson(value);
18
+ assertBoundedJson(value, label);
19
19
  if (Object.keys(value).length > MAX_MAP_ENTRIES) {
20
20
  throw new Error(`${label} has too many entries`);
21
21
  }
@@ -14,6 +14,7 @@ import { dispatchEnvironmentRun } from "./tangle-environment-dispatch.js";
14
14
  import { sandboxSessionAsAgentSession } from "./tangle-environment-session.js";
15
15
  import { tangleInteractionResponder } from "./tangle-interaction-response.js";
16
16
  import { createExecutionUsageLog } from "./tangle-usage-log.js";
17
+ import { createStepUsageFold } from "./tangle-step-usage.js";
17
18
  import { observeTangleEnvironment } from "./tangle-observation.js";
18
19
  import { createTangleTerminalRegistry } from "./tangle-terminal.js";
19
20
  import { createTangleInteractiveAgentRegistry } from "./tangle-interactive.js";
@@ -48,7 +49,7 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
48
49
  if (!box.metadata || typeof box.metadata !== "object" || Array.isArray(box.metadata)) {
49
50
  throw new Error("Tangle environment metadata must be a JSON object");
50
51
  }
51
- assertBoundedJson(box.metadata);
52
+ assertBoundedJson(box.metadata, "Tangle environment metadata");
52
53
  }
53
54
  const support = sandboxCapabilitySupport(box, client, request?.resources);
54
55
  const deployment = await readDeploymentCapabilitySupport(box, operation);
@@ -113,6 +114,9 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
113
114
  input.signal?.throwIfAborted();
114
115
  const expectedExecutionId = executionIdFromTurnInput(input);
115
116
  const expectedSessionId = input.sessionId ?? input.controlRef?.sessionId;
117
+ // A turn resumed after a cursor starts past its first steps, so it cannot
118
+ // report the execution's running total.
119
+ const stepUsage = input.lastEventId === undefined ? createStepUsageFold() : undefined;
116
120
  const iterator = box.streamPrompt(promptFromTurnInput(input), promptOptionsFromTurnInput(input, {
117
121
  provider: providerName,
118
122
  environmentId,
@@ -133,9 +137,10 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
133
137
  ? { streamBound: true }
134
138
  : {}),
135
139
  });
140
+ // The log holds execution receipts, so it records before step usage is attached.
136
141
  usageLog.record(expectedExecutionId, converted.usage);
137
142
  input.signal?.throwIfAborted();
138
- yield converted;
143
+ yield stepUsage?.observe(converted) ?? converted;
139
144
  }
140
145
  }
141
146
  catch (error) {
@@ -60,7 +60,7 @@ export function assertUnreservedMetadata(metadata) {
60
60
  if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) {
61
61
  throw new Error("exact process metadata must be a JSON object");
62
62
  }
63
- assertBoundedJson(metadata);
63
+ assertBoundedJson(metadata, "exact process metadata");
64
64
  const reserved = [
65
65
  "capabilities",
66
66
  "customer_id",
@@ -145,7 +145,7 @@ function sandboxPromptBackend(value) {
145
145
  runtimeAttachments: tangleRuntimeAttachments(present.runtimeAttachments, backend.profile),
146
146
  });
147
147
  }
148
- assertBoundedJson(backend);
148
+ assertBoundedJson(backend, "Tangle prompt backend");
149
149
  return backend;
150
150
  }
151
151
  function sandboxPromptBackendModel(value) {
@@ -493,7 +493,7 @@ export function validatedSandboxPromptResult(result) {
493
493
  assertBoundedJson(Object.fromEntries(Object.entries(record).filter(([field]) => field !== "response" &&
494
494
  field !== "text" &&
495
495
  field !== "finalText" &&
496
- field !== "toolInvocations")));
496
+ field !== "toolInvocations")), "Tangle prompt result");
497
497
  if (typeof record.success !== "boolean") {
498
498
  throw new Error("Tangle prompt result omitted its success status");
499
499
  }
@@ -177,9 +177,9 @@ export function createTangleProvider(options) {
177
177
  signal?.throwIfAborted();
178
178
  assertCreateInputShape(input);
179
179
  assertNoInlineSecretValues(input);
180
- for (const value of Object.values(material)) {
180
+ for (const [field, value] of Object.entries(material)) {
181
181
  if (value !== undefined)
182
- assertBoundedJson(value);
182
+ assertBoundedJson(value, `Tangle create ${field}`);
183
183
  }
184
184
  const acceptedInput = Object.freeze({
185
185
  ...deepFreeze(structuredClone(material)),
@@ -228,13 +228,13 @@ export function createTangleProvider(options) {
228
228
  if (!query.providerOptions || typeof query.providerOptions !== "object" || Array.isArray(query.providerOptions)) {
229
229
  throw new Error("Tangle environment list providerOptions must be a JSON object");
230
230
  }
231
- assertBoundedJson(query.providerOptions);
231
+ assertBoundedJson(query.providerOptions, "Tangle environment list providerOptions");
232
232
  }
233
233
  if (query?.metadata !== undefined) {
234
234
  if (!query.metadata || typeof query.metadata !== "object" || Array.isArray(query.metadata)) {
235
235
  throw new Error("Tangle environment query metadata must be a JSON object");
236
236
  }
237
- assertBoundedJson(query.metadata);
237
+ assertBoundedJson(query.metadata, "Tangle environment query metadata");
238
238
  }
239
239
  const boxes = [];
240
240
  for (let offset = 0;; offset += SANDBOX_LIST_PAGE_SIZE) {
@@ -265,7 +265,7 @@ export function createTangleProvider(options) {
265
265
  if (!box.metadata || typeof box.metadata !== "object" || Array.isArray(box.metadata)) {
266
266
  throw new Error("Tangle environment metadata must be a JSON object");
267
267
  }
268
- assertBoundedJson(box.metadata);
268
+ assertBoundedJson(box.metadata, "Tangle environment metadata");
269
269
  }
270
270
  const nameMatches = query?.name === undefined || box.name === query.name;
271
271
  const metadataMatches = query?.metadata === undefined ||
@@ -4,7 +4,7 @@ export function execResultFromSandboxExecResult(result) {
4
4
  throw new Error("Tangle Sandbox exec returned no result");
5
5
  }
6
6
  const record = result;
7
- assertBoundedJson(record);
7
+ assertBoundedJson(record, "Tangle exec result");
8
8
  if (typeof record.exitCode !== "number" ||
9
9
  !Number.isSafeInteger(record.exitCode)) {
10
10
  throw new Error("Tangle Sandbox exec returned an invalid exit code");
@@ -23,7 +23,7 @@ export function tokenUsageFromData(data) {
23
23
  // Apply metadata limits only to fields used to compute usage.
24
24
  assertBoundedJson(Object.fromEntries(["usage", "tokenUsage", "costUsd", "totalCostUsd"]
25
25
  .filter((field) => Object.hasOwn(data, field))
26
- .map((field) => [field, data[field]])));
26
+ .map((field) => [field, data[field]])), "Tangle usage fields");
27
27
  if (data.usage !== undefined &&
28
28
  (!data.usage || typeof data.usage !== "object" || Array.isArray(data.usage))) {
29
29
  throw new Error("Tangle usage must be an object");
@@ -44,7 +44,7 @@ export function tokenUsageFromData(data) {
44
44
  : undefined;
45
45
  if (usageRecord === undefined)
46
46
  return undefined;
47
- assertBoundedJson(usageRecord);
47
+ assertBoundedJson(usageRecord, "Tangle token usage");
48
48
  const inputTokens = firstValidatedNumber(usageRecord, ["inputTokens", "tokensIn", "prompt_tokens"], "input token count", true);
49
49
  const outputTokens = firstValidatedNumber(usageRecord, ["outputTokens", "tokensOut", "completion_tokens"], "output token count", true);
50
50
  const totalTokens = firstValidatedNumber(usageRecord, ["totalTokens", "tokensTotal", "total_tokens"], "total token count", true);
@@ -7,7 +7,7 @@ export function sessionRefFromSandboxDispatch(dispatched, providerName, environm
7
7
  ? dispatched
8
8
  : undefined;
9
9
  if (record)
10
- assertBoundedJson(record);
10
+ assertBoundedJson(record, "Tangle dispatch record");
11
11
  const id = record?.sessionId ?? record?.id;
12
12
  if (!record || typeof id !== "string") {
13
13
  throw new Error("sandbox dispatch returned no session id");
@@ -0,0 +1,29 @@
1
+ import type { AgentEnvironmentEvent } from "@tangle-network/agent-interface/environment-provider";
2
+ /**
3
+ * Attaches an execution's running usage to the step frames of its stream.
4
+ *
5
+ * Sandbox reports an execution's usage on its terminal `result` and `done`
6
+ * frames. Before those frames, the only usage on the stream is the OpenCode
7
+ * harness's own `step_finish` event, which the sidecar forwards as a `raw`
8
+ * frame with that step's token counts. No other harness the sidecar runs
9
+ * forwards usage before the terminal frames, so their streams stay unchanged.
10
+ */
11
+ export interface StepUsageFold {
12
+ /**
13
+ * The event, carrying the execution's cumulative usage when it reports a
14
+ * step not yet counted. Every other event is returned unchanged.
15
+ */
16
+ observe(event: AgentEnvironmentEvent): AgentEnvironmentEvent;
17
+ }
18
+ /**
19
+ * Create the fold for one stream that starts at its execution's first frame.
20
+ *
21
+ * A cumulative total counts every step before it, so a stream that resumes
22
+ * after a cursor, or joins at a live tail, must not use this fold.
23
+ *
24
+ * The terminal receipt stays authoritative. Its usage is never replaced, and
25
+ * the step frames are never rewritten to agree with it. A receipt below the
26
+ * streamed total is therefore delivered as reported, and a consumer that folds
27
+ * cumulative usage sees the total fall instead of a silently lowered total.
28
+ */
29
+ export declare function createStepUsageFold(): StepUsageFold;
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Create the fold for one stream that starts at its execution's first frame.
3
+ *
4
+ * A cumulative total counts every step before it, so a stream that resumes
5
+ * after a cursor, or joins at a live tail, must not use this fold.
6
+ *
7
+ * The terminal receipt stays authoritative. Its usage is never replaced, and
8
+ * the step frames are never rewritten to agree with it. A receipt below the
9
+ * streamed total is therefore delivered as reported, and a consumer that folds
10
+ * cumulative usage sees the total fall instead of a silently lowered total.
11
+ */
12
+ export function createStepUsageFold() {
13
+ let total;
14
+ // A step whose counts are incomplete leaves every later total unknown.
15
+ let established = true;
16
+ const counted = new Set();
17
+ return {
18
+ observe(event) {
19
+ if (event.usage !== undefined || event.usageMode !== undefined) {
20
+ return event;
21
+ }
22
+ const step = openCodeStepUsage(event);
23
+ if (step === undefined || !established)
24
+ return event;
25
+ if (step.usage === undefined) {
26
+ established = false;
27
+ return event;
28
+ }
29
+ // The live stream and a reconnect replay can deliver one step twice.
30
+ if (step.id !== undefined) {
31
+ if (counted.has(step.id))
32
+ return event;
33
+ counted.add(step.id);
34
+ }
35
+ total = total === undefined ? step.usage : addUsage(total, step.usage);
36
+ return { ...event, usage: { ...total }, usageMode: "cumulative" };
37
+ },
38
+ };
39
+ }
40
+ /**
41
+ * The step an OpenCode `step_finish` frame reports, in either wire shape.
42
+ *
43
+ * The sidecar (agent-dev-container `packages/sdk-provider-opencode/src/cli-events.ts`)
44
+ * wraps the harness event as `{ type: "raw", backend: "opencode", event }`.
45
+ * The live run stream writes only `event` as the frame data; the execution
46
+ * replay writes the whole buffered envelope. Both frames carry one event id.
47
+ *
48
+ * `usage` is absent when the step reported counts without both totals.
49
+ */
50
+ function openCodeStepUsage(event) {
51
+ if (event.type !== "raw")
52
+ return undefined;
53
+ const envelope = event.data;
54
+ const harnessEvent = envelope.type === "raw"
55
+ ? envelope.backend === "opencode"
56
+ ? plainRecord(envelope.event)
57
+ : undefined
58
+ : envelope;
59
+ if (harnessEvent?.type !== "step_finish")
60
+ return undefined;
61
+ const part = plainRecord(harnessEvent.part);
62
+ if (part?.type !== "step-finish" || part.tokens === undefined) {
63
+ return undefined;
64
+ }
65
+ const id = typeof part.id === "string" && part.id.length > 0 ? part.id : event.id;
66
+ return {
67
+ ...(id === undefined ? {} : { id }),
68
+ ...optionalUsage(stepTokenUsage(part.tokens)),
69
+ };
70
+ }
71
+ /**
72
+ * One step's counts in the terminal receipt's convention.
73
+ *
74
+ * OpenCode reports cache and reasoning tokens beside `input` and `output`.
75
+ * The sidecar's receipt includes them in its totals (`recordStepUsage`), so
76
+ * the step's input total adds both cache counts and its output total adds
77
+ * reasoning. The class counts keep their own fields.
78
+ */
79
+ function stepTokenUsage(value) {
80
+ const tokens = plainRecord(value);
81
+ if (tokens === undefined) {
82
+ throw new Error("Tangle OpenCode step token counts must be an object");
83
+ }
84
+ const cache = tokens.cache === undefined ? {} : plainRecord(tokens.cache);
85
+ if (cache === undefined) {
86
+ throw new Error("Tangle OpenCode step cache counts must be an object");
87
+ }
88
+ const input = stepCount(tokens.input, "input");
89
+ const output = stepCount(tokens.output, "output");
90
+ const reasoning = stepCount(tokens.reasoning, "reasoning");
91
+ const total = stepCount(tokens.total, "total");
92
+ const cacheRead = stepCount(cache.read, "cache read");
93
+ const cacheWrite = stepCount(cache.write, "cache write");
94
+ if (input === undefined || output === undefined)
95
+ return undefined;
96
+ return {
97
+ inputTokens: safeSum(input, cacheRead ?? 0, cacheWrite ?? 0),
98
+ outputTokens: safeSum(output, reasoning ?? 0),
99
+ ...(total === undefined ? {} : { totalTokens: total }),
100
+ ...(cacheRead === undefined ? {} : { cacheReadInputTokens: cacheRead }),
101
+ ...(cacheWrite === undefined ? {} : { cacheCreationInputTokens: cacheWrite }),
102
+ ...(reasoning === undefined ? {} : { reasoningTokens: reasoning }),
103
+ };
104
+ }
105
+ function stepCount(value, label) {
106
+ if (value === undefined)
107
+ return undefined;
108
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
109
+ throw new Error(`Tangle OpenCode step ${label} token count is invalid`);
110
+ }
111
+ return value;
112
+ }
113
+ /** A count reported by either side is kept; one reported by neither stays absent. */
114
+ function addUsage(left, right) {
115
+ const optional = (key) => left[key] === undefined && right[key] === undefined
116
+ ? {}
117
+ : { [key]: safeSum(left[key] ?? 0, right[key] ?? 0) };
118
+ return {
119
+ inputTokens: safeSum(left.inputTokens, right.inputTokens),
120
+ outputTokens: safeSum(left.outputTokens, right.outputTokens),
121
+ ...optional("totalTokens"),
122
+ ...optional("cacheReadInputTokens"),
123
+ ...optional("cacheCreationInputTokens"),
124
+ ...optional("reasoningTokens"),
125
+ };
126
+ }
127
+ function safeSum(...values) {
128
+ const sum = values.reduce((left, right) => left + right, 0);
129
+ if (!Number.isSafeInteger(sum)) {
130
+ throw new Error("Tangle OpenCode step token total exceeded the safe integer range");
131
+ }
132
+ return sum;
133
+ }
134
+ function optionalUsage(usage) {
135
+ return usage === undefined ? {} : { usage };
136
+ }
137
+ function plainRecord(value) {
138
+ return value !== null && typeof value === "object" && !Array.isArray(value)
139
+ ? value
140
+ : undefined;
141
+ }
@@ -538,7 +538,7 @@ async function environmentFromChild(request, child, provider, createdAt, verifie
538
538
  let metadata;
539
539
  try {
540
540
  metadata =
541
- request.metadata === undefined ? undefined : cloneJson(request.metadata);
541
+ request.metadata === undefined ? undefined : cloneJson(request.metadata, "Tangle branch request metadata");
542
542
  }
543
543
  catch {
544
544
  return undefined;
@@ -77,9 +77,9 @@ export function forkMarkerMetadata(request, materialization = "snapshot") {
77
77
  request,
78
78
  ...(materialization === "snapshot" ? { materialization } : {}),
79
79
  };
80
- assertBoundedJson(marker);
80
+ assertBoundedJson(marker, "Tangle fork marker");
81
81
  return {
82
- ...(request.metadata === undefined ? {} : cloneJson(request.metadata)),
82
+ ...(request.metadata === undefined ? {} : cloneJson(request.metadata, "Tangle fork request metadata")),
83
83
  [FORK_METADATA_KEY]: marker,
84
84
  };
85
85
  }
@@ -13,7 +13,7 @@ export function checkpointRecordFromSnapshot(request, snapshot) {
13
13
  createdAt,
14
14
  ...(request.metadata === undefined
15
15
  ? {}
16
- : { metadata: cloneJson(request.metadata) }),
16
+ : { metadata: cloneJson(request.metadata, "Tangle recovery request metadata") }),
17
17
  });
18
18
  return {
19
19
  request,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-provider-tangle",
3
- "version": "1.2.3",
3
+ "version": "1.3.1",
4
4
  "description": "AgentEnvironmentProvider adapter for Tangle sandboxes",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -83,6 +83,8 @@
83
83
  "dist/tangle-result-values.js",
84
84
  "dist/tangle-session-control.d.ts",
85
85
  "dist/tangle-session-control.js",
86
+ "dist/tangle-step-usage.d.ts",
87
+ "dist/tangle-step-usage.js",
86
88
  "dist/tangle-types.d.ts",
87
89
  "dist/tangle-types.js",
88
90
  "dist/tangle-workspace-branching.d.ts",