@tangle-network/agent-provider-tangle 1.2.2 → 1.3.0

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
@@ -11,7 +11,8 @@ Disabled attachments and aliases present in the profile are refused, including d
11
11
  Per-turn backend overrides accept the same canonical attachment contract.
12
12
  Remote managers still require an authenticated coordination URL reachable from the Sandbox.
13
13
  Catalog support does not establish successful tool execution against a particular deployment.
14
- The provider fails closed when the configured backend or its catalog entry cannot be read.
14
+ The provider propagates catalog transport and validation errors unchanged, before provisioning.
15
+ A successfully read catalog without the selected backend reports its capabilities as unsupported.
15
16
  Newer SDKs may also provide `getBackend()` as a lookup over the same catalog.
16
17
 
17
18
  ```ts
@@ -155,6 +156,28 @@ The adapter bounds each complete serialized frame to 1 MiB of UTF-8, including k
155
156
  It retains accepted content without truncation in the event data and original provider event.
156
157
  Identifiers, usage metadata, and structural JSON limits retain their existing bounds.
157
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
+
158
181
  ## Two capability documents
159
182
 
160
183
  Capabilities are derived in two stages, and the two stages answer different questions.
@@ -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 {
@@ -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";
@@ -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) {
@@ -288,17 +288,14 @@ export function createTangleProvider(options) {
288
288
  async function resolveBackend(client, backendType) {
289
289
  if (backendType === undefined)
290
290
  return undefined;
291
- try {
292
- if (client.getBackend)
293
- return await client.getBackend(backendType);
294
- if (!client.listBackends)
295
- return undefined;
296
- const catalog = await client.listBackends();
297
- return catalog.backends.find((backend) => backend.type === backendType);
298
- }
299
- catch {
291
+ // A failed read is not evidence that the selected backend lacks support.
292
+ // Preserve the transport or validation error before any create effect.
293
+ if (client.getBackend)
294
+ return await client.getBackend(backendType);
295
+ if (!client.listBackends)
300
296
  return undefined;
301
- }
297
+ const catalog = await client.listBackends();
298
+ return catalog.backends.find((backend) => backend.type === backendType);
302
299
  }
303
300
  function assertProviderOperationOptions(options, label) {
304
301
  if (options === undefined)
@@ -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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-provider-tangle",
3
- "version": "1.2.2",
3
+ "version": "1.3.0",
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",