@tangle-network/agent-provider-tangle 5.0.7 → 5.0.9

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.
@@ -10,5 +10,17 @@ export interface CommandModelCredentialResolverOptions {
10
10
  /** Compute a fixed deadline once at factory construction. */
11
11
  minimumValidityMs?: number;
12
12
  }
13
+ /**
14
+ * The resolver refused the binding itself — a deterministic refusal named on the error
15
+ * (bounded, from the command's last stderr line). Carries the same machine code as every
16
+ * credential route refusal, so a consumer classifies it terminal instead of retrying a
17
+ * refusal no retry can satisfy (#475).
18
+ */
19
+ export declare class TangleCommandCredentialRefusalError extends Error {
20
+ readonly code: "model_credential_refused";
21
+ /** The resolver's own bounded reason, safe to journal. */
22
+ readonly resolutionReason: string;
23
+ constructor(reason: string);
24
+ }
13
25
  /** The account owner selects, binds, refreshes, and stores credentials; this transport reads references. */
14
26
  export declare function createCommandModelCredentialResolver(options: CommandModelCredentialResolverOptions): TangleModelCredentialResolver;
@@ -3,6 +3,31 @@ import { spawn } from "node:child_process";
3
3
  import { profileCredentialSource } from "./model-credential-source.js";
4
4
  import { captureModelCredentials } from "./tangle-create-options.js";
5
5
  const MAX_COMMAND_OUTPUT_BYTES = 64 * 1024;
6
+ /** How much of the command's stderr is retained, and how much of its last line can surface. */
7
+ const MAX_COMMAND_STDERR_BYTES = 8 * 1024;
8
+ const MAX_STDERR_TAIL_CHARACTERS = 300;
9
+ /**
10
+ * The resolver refused the binding itself — a deterministic refusal named on the error
11
+ * (bounded, from the command's last stderr line). Carries the same machine code as every
12
+ * credential route refusal, so a consumer classifies it terminal instead of retrying a
13
+ * refusal no retry can satisfy (#475).
14
+ */
15
+ export class TangleCommandCredentialRefusalError extends Error {
16
+ code = "model_credential_refused";
17
+ /** The resolver's own bounded reason, safe to journal. */
18
+ resolutionReason;
19
+ constructor(reason) {
20
+ super(`Tangle credential command refused the route: ${reason}`);
21
+ this.name = "TangleCredentialRefusalError";
22
+ this.resolutionReason = reason;
23
+ }
24
+ }
25
+ /**
26
+ * Resolver refusals a retry cannot satisfy, from `acct sandbox resolve`'s ResolutionError lines.
27
+ * The list is deliberately narrow: anything unmatched stays the generic failure with its
28
+ * `stderrTail`, and the resolver can later grow an exit-code contract beside exit 75's capacity.
29
+ */
30
+ const RESOLUTION_REFUSAL = /(?:resume seat conflicts|already bound to a different (?:dispatch|profile)|not enrolled for the exact stage profile)/iu;
6
31
  /** The account owner selects, binds, refreshes, and stores credentials; this transport reads references. */
7
32
  export function createCommandModelCredentialResolver(options) {
8
33
  if (!Array.isArray(options.command) || options.command.length === 0 || options.command.length > 128 ||
@@ -41,7 +66,7 @@ export function createCommandModelCredentialResolver(options) {
41
66
  return (input) => {
42
67
  if (typeof input.profile === "string")
43
68
  throw new Error("Tangle credential command requires an inline profile");
44
- if (profileCredentialSource(input.profile) === "managed")
69
+ if (profileCredentialSource(input.profile) === "router")
45
70
  return undefined;
46
71
  if (typeof input.idempotencyKey !== "string" || input.idempotencyKey.length === 0) {
47
72
  throw new Error("Tangle credential command requires a stable create idempotencyKey");
@@ -67,6 +92,24 @@ export function createCommandModelCredentialResolver(options) {
67
92
  let settled = false;
68
93
  let outputBytes = 0;
69
94
  const chunks = [];
95
+ // The resolver's refusal reason travels on stderr, one line. Keep the tail bounded; the
96
+ // stdout bound governs the public reference, not this private diagnostic channel.
97
+ const stderrTail = [];
98
+ let stderrBytes = 0;
99
+ const lastStderrLine = () => {
100
+ const text = Buffer.concat(stderrTail).toString("utf8");
101
+ const line = text
102
+ .split("\n")
103
+ .map((value) => value.trimEnd())
104
+ .filter((value) => value.trim().length > 0)
105
+ // A fatal exit appends Node's own banner and stack lines after the program's output; the
106
+ // resolver's reason is its own prose line, never a runtime stack frame.
107
+ .filter((value) => !/^Node\.js v\d/u.test(value.trim()) && !/^\s+at\s/u.test(value))
108
+ .at(-1);
109
+ if (line === undefined)
110
+ return undefined;
111
+ return line.length > MAX_STDERR_TAIL_CHARACTERS ? line.slice(0, MAX_STDERR_TAIL_CHARACTERS) : line;
112
+ };
70
113
  const cleanup = () => {
71
114
  clearTimeout(timer);
72
115
  signal?.removeEventListener("abort", onAbort);
@@ -92,6 +135,15 @@ export function createCommandModelCredentialResolver(options) {
92
135
  }
93
136
  chunks.push(chunk);
94
137
  });
138
+ child.stderr.on("data", (chunk) => {
139
+ stderrBytes += chunk.length;
140
+ stderrTail.push(chunk);
141
+ // Keep only the bounded tail: the reason is the LAST line a resolver prints.
142
+ while (stderrBytes > MAX_COMMAND_STDERR_BYTES && stderrTail.length > 1) {
143
+ stderrBytes -= stderrTail[0].length;
144
+ stderrTail.shift();
145
+ }
146
+ });
95
147
  child.on("close", (code, terminationSignal) => {
96
148
  if (settled)
97
149
  return;
@@ -108,9 +160,15 @@ export function createCommandModelCredentialResolver(options) {
108
160
  return;
109
161
  }
110
162
  }
163
+ const stderrTailLine = lastStderrLine();
164
+ if (stderrTailLine !== undefined && RESOLUTION_REFUSAL.test(stderrTailLine)) {
165
+ fail(new TangleCommandCredentialRefusalError(stderrTailLine));
166
+ return;
167
+ }
111
168
  fail(Object.assign(new Error(`Tangle credential command failed (${code === null ? `signal ${terminationSignal}` : `exit ${code}`})`), {
112
169
  exitCode: code,
113
170
  terminationSignal,
171
+ ...(stderrTailLine === undefined ? {} : { stderrTail: stderrTailLine }),
114
172
  }));
115
173
  return;
116
174
  }
@@ -74,7 +74,7 @@ export function createHttpModelCredentialResolver(options) {
74
74
  return async (input) => {
75
75
  if (typeof input.profile === "string")
76
76
  throw new Error("Tangle credential broker requires an inline profile");
77
- if (profileCredentialSource(input.profile) === "managed")
77
+ if (profileCredentialSource(input.profile) === "router")
78
78
  return undefined;
79
79
  input.signal?.throwIfAborted();
80
80
  const { signal, ...data } = input;
@@ -1,4 +1,5 @@
1
1
  import type { AgentProfile } from "@tangle-network/agent-interface";
2
- export type ProfileCredentialSource = "managed" | "subscription";
2
+ /** The credential intent a profile can declare. `managed` is the deprecated spelling of `router`. */
3
+ export type ProfileCredentialSource = "router" | "api-key" | "subscription";
3
4
  /** Authored profile intent is independent of the harness, vendor, and available accounts. */
4
5
  export declare function profileCredentialSource(profile: AgentProfile): ProfileCredentialSource;
@@ -12,9 +12,11 @@ export function profileCredentialSource(profile) {
12
12
  throw new Error("Tangle profile model metadata must be an object");
13
13
  }
14
14
  const source = metadata?.credentialSource;
15
- if (source === undefined || source === "managed")
16
- return "managed";
15
+ if (source === undefined || source === "managed" || source === "router")
16
+ return "router";
17
+ if (source === "api-key")
18
+ return "api-key";
17
19
  if (source === "subscription")
18
20
  return "subscription";
19
- throw new Error('Tangle profile model.metadata.credentialSource must be "managed" or "subscription"');
21
+ throw new Error('Tangle profile model.metadata.credentialSource must be "router", "api-key", or "subscription"');
20
22
  }
@@ -171,6 +171,8 @@ export function sandboxOptionsFromCreateInput(input, defaultBackend, parsedWorks
171
171
  if (input.billingOwner !== undefined) {
172
172
  boundedIdentifier(input.billingOwner, "Tangle billing owner");
173
173
  }
174
+ const maxLifetimeSeconds = wholeSecondsOf(input.maxLifetimeMs, "maxLifetimeMs");
175
+ const idleTimeoutSeconds = wholeSecondsOf(input.idleTimeoutMs, "idleTimeoutMs");
174
176
  const resources = sandboxResourcesFromResourceRequest(input.resources);
175
177
  // Sandbox injects secrets by name from its own store. Accepting a name/value
176
178
  // record and dropping it would create an environment with no credentials and
@@ -190,6 +192,8 @@ export function sandboxOptionsFromCreateInput(input, defaultBackend, parsedWorks
190
192
  ...(resources ? { resources } : {}),
191
193
  ...(restore ?? {}),
192
194
  ...(input.env ? { env: input.env } : {}),
195
+ ...(maxLifetimeSeconds === undefined ? {} : { maxLifetimeSeconds }),
196
+ ...(idleTimeoutSeconds === undefined ? {} : { idleTimeoutSeconds }),
193
197
  ...(secrets === undefined ? {} : { secrets }),
194
198
  ...(proxySecrets === undefined ? {} : { proxySecrets }),
195
199
  ...(input.egress === undefined ? {} : { egressPolicy: sandboxEgressPolicy(input.egress) }),
@@ -280,6 +284,15 @@ export function assertMappedSecretNames(options) {
280
284
  selected.set(name, identity);
281
285
  }
282
286
  }
287
+ /** A lifetime field the Sandbox create accepts: whole, positive, safe seconds, or a refusal naming the field. */
288
+ function wholeSecondsOf(value, field) {
289
+ if (value === undefined)
290
+ return undefined;
291
+ if (!Number.isSafeInteger(value) || value < 1_000 || value % 1_000 !== 0) {
292
+ throw new Error(`Tangle create ${field} must be a positive whole number of seconds`);
293
+ }
294
+ return value / 1_000;
295
+ }
283
296
  export function assertCreateInputShape(input, parsedWorkspace) {
284
297
  if (!input || typeof input !== "object" || Array.isArray(input)) {
285
298
  throw new Error("Tangle create input must be an object");
@@ -294,6 +307,8 @@ export function assertCreateInputShape(input, parsedWorkspace) {
294
307
  "secrets",
295
308
  "egress",
296
309
  "billingOwner",
310
+ "maxLifetimeMs",
311
+ "idleTimeoutMs",
297
312
  "metadata",
298
313
  "name",
299
314
  "idempotencyKey",
@@ -64,7 +64,7 @@ export async function sandboxInstanceAsEnvironment(box, providerName, client, de
64
64
  const nativeReference = request?.nativeAuth?.cliAuth ?? persistedReference;
65
65
  const credentialHarness = request?.nativeAuth?.harness ?? request?.credentialHarness;
66
66
  const boundCredentialSource = request?.credentialSource ??
67
- (recordedCredentials !== undefined ? "subscription" : "managed");
67
+ (recordedCredentials !== undefined ? "subscription" : "router");
68
68
  const capabilities = frozenCapabilityDocument(AgentEnvironmentCapabilitiesSchema.parse(capabilitiesForSandbox(declaredCapabilities, support, deployment, confidentialVerifierOption(request?.confidentialAttestationVerifier))));
69
69
  const workspaceBranching = capabilities.branching.checkpoint &&
70
70
  capabilities.branching.fork &&
@@ -219,7 +219,7 @@ function environmentTurnPreparation(box, providerName, environmentId, request, d
219
219
  throw new Error("Tangle turn credential source differs from its environment; create a separate environment for that profile");
220
220
  }
221
221
  if (backend?.model?.cliAuth !== undefined && boundCredentialSource !== "subscription") {
222
- throw new Error("Tangle managed environment cannot inherit native subscription credentials");
222
+ throw new Error("Tangle router environment cannot inherit native subscription credentials");
223
223
  }
224
224
  if (backend?.model?.cliAuth !== undefined && !deployment.cliAuthReferences) {
225
225
  throw new Error("Tangle selected sandbox does not prove native credential reference support");
@@ -154,7 +154,12 @@ export function environmentEventFromSandboxEvent(event, expected = {}) {
154
154
  throw new Error("Tangle public stream exposed a private native identity event");
155
155
  }
156
156
  const identity = sandboxEventIdentity(event);
157
- const runFrameCarriesPublicResumeKey = expected.streamBound === true && record.type === "session.updated";
157
+ // A live `raw` frame's data is the harness event itself, whose own sessionID is the
158
+ // harness-native session — backend content, like session.updated's resume key, never a
159
+ // claim about the Runtime session this iterator is bound to. Replay envelopes keep the
160
+ // native id under `event`, so only the live shape needs the exemption (#328).
161
+ const runFrameCarriesPublicResumeKey = (expected.streamBound === true && record.type === "session.updated") ||
162
+ record.type === "raw";
158
163
  const identityBearingSessionIds = carriedSessionIds(runFrameCarriesPublicResumeKey
159
164
  ? { envelopeSessionId: identity.envelopeSessionId }
160
165
  : identity);
@@ -226,9 +226,9 @@ function sandboxPromptBackend(value) {
226
226
  ? {}
227
227
  : { metadata: sandboxPromptBackendMetadata(present.metadata) }),
228
228
  };
229
- if (backend.profile?.model?.metadata?.credentialSource === "managed" &&
229
+ if (backend.profile !== undefined && profileCredentialSource(backend.profile) === "router" &&
230
230
  (backend.model?.cliAuth !== undefined || backend.model?.authFiles !== undefined || backend.model?.authMode === "oauth")) {
231
- throw new Error("Tangle explicit managed profile cannot receive native subscription credentials");
231
+ throw new Error("Tangle explicit router profile cannot receive native subscription credentials");
232
232
  }
233
233
  if (backend.profile !== undefined)
234
234
  profileCredentialSource(backend.profile);
@@ -112,7 +112,7 @@ export function createTangleProvider(options) {
112
112
  assertProxySecretAliases(requestedProxySecrets, input.env, input.secrets);
113
113
  const requestedSecrets = structuredClone(Array.isArray(input.secrets) ? input.secrets : undefined);
114
114
  const requestedReason = requestedSecrets?.some((entry) => typeof entry !== "string" && "exposeInBox" in entry) ? input.metadata?.reason : undefined;
115
- const credentialSource = typeof input.profile === "string" ? "managed" : profileCredentialSource(input.profile);
115
+ const credentialSource = typeof input.profile === "string" ? "router" : profileCredentialSource(input.profile);
116
116
  const subscription = credentialSource === "subscription";
117
117
  if (Object.hasOwn(input.metadata ?? {}, "modelCredentials")) {
118
118
  throw new Error("Tangle credential selection owns metadata.modelCredentials");
@@ -169,7 +169,7 @@ export function createTangleProvider(options) {
169
169
  throw new Error("Tangle mapped create options must preserve the exact profile credential source");
170
170
  }
171
171
  if (!subscription && mappedOptions.backend?.model?.cliAuth !== undefined) {
172
- throw new Error("Tangle managed profile cannot provision native subscription credentials");
172
+ throw new Error("Tangle router profile cannot provision native subscription credentials");
173
173
  }
174
174
  const createOptions = deepFreeze(structuredClone({
175
175
  ...mappedOptions,
@@ -16,6 +16,19 @@ export declare class TangleDispatchNotAdmittedError extends Error {
16
16
  readonly activeExecutionId: string;
17
17
  constructor(sessionId: string, requestedExecutionId: string, activeExecutionId: string);
18
18
  }
19
+ /**
20
+ * Sandbox confirmed the dispatch but named an execution id other than the requested run's —
21
+ * a provider contract violation that repeats identically on every retry. Typed so the first
22
+ * occurrence can stop an invocation instead of looping as a transient (#475): the requested
23
+ * and returned ids are on the error, never only in prose.
24
+ */
25
+ export declare class TangleDispatchExecutionChangedError extends Error {
26
+ readonly code: "DISPATCH_EXECUTION_CHANGED";
27
+ readonly sessionId: string;
28
+ readonly requestedExecutionId: string;
29
+ readonly returnedExecutionId: string;
30
+ constructor(sessionId: string, requestedExecutionId: string, returnedExecutionId: string);
31
+ }
19
32
  export declare function sessionRefFromSandboxDispatch(dispatched: unknown, providerName: string, environmentId: string, expectedExecutionId: string | undefined, requestDigest?: `sha256:${string}` | undefined, expectedSessionId?: string | undefined, callerControlRef?: AgentExactRunControlRef | undefined): AgentSessionRef;
20
33
  export declare function retainedSessionControlRef(sessionId: string, executionId: string, provider: string, environmentId: string, requestDigest?: `sha256:${string}`, runId?: string): AgentExactRunControlRef;
21
34
  export declare function sessionPromptExecutionId(requestDigest: `sha256:${string}`): string;
@@ -25,6 +25,26 @@ export class TangleDispatchNotAdmittedError extends Error {
25
25
  this.activeExecutionId = activeExecutionId;
26
26
  }
27
27
  }
28
+ /**
29
+ * Sandbox confirmed the dispatch but named an execution id other than the requested run's —
30
+ * a provider contract violation that repeats identically on every retry. Typed so the first
31
+ * occurrence can stop an invocation instead of looping as a transient (#475): the requested
32
+ * and returned ids are on the error, never only in prose.
33
+ */
34
+ export class TangleDispatchExecutionChangedError extends Error {
35
+ code = "DISPATCH_EXECUTION_CHANGED";
36
+ sessionId;
37
+ requestedExecutionId;
38
+ returnedExecutionId;
39
+ constructor(sessionId, requestedExecutionId, returnedExecutionId) {
40
+ super("sandbox dispatch returned an execution id different from the requested run: " +
41
+ `requested ${requestedExecutionId}, Sandbox named ${returnedExecutionId}`);
42
+ this.name = "TangleDispatchExecutionChangedError";
43
+ this.sessionId = sessionId;
44
+ this.requestedExecutionId = requestedExecutionId;
45
+ this.returnedExecutionId = returnedExecutionId;
46
+ }
47
+ }
28
48
  export function sessionRefFromSandboxDispatch(dispatched, providerName, environmentId, expectedExecutionId, requestDigest = undefined, expectedSessionId = undefined, callerControlRef = undefined) {
29
49
  const record = dispatched && typeof dispatched === "object" && !Array.isArray(dispatched)
30
50
  ? dispatched
@@ -49,7 +69,7 @@ export function sessionRefFromSandboxDispatch(dispatched, providerName, environm
49
69
  boundedIdentifier(executionId, "Tangle active execution id");
50
70
  throw new TangleDispatchNotAdmittedError(id, expectedExecutionId, executionId);
51
71
  }
52
- throw new Error("sandbox dispatch returned an execution id different from the requested run");
72
+ throw new TangleDispatchExecutionChangedError(id, expectedExecutionId, executionId);
53
73
  }
54
74
  boundedIdentifier(executionId, "Tangle dispatched execution id");
55
75
  if (record.status !== undefined && typeof record.status !== "string") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-provider-tangle",
3
- "version": "5.0.7",
3
+ "version": "5.0.9",
4
4
  "description": "AgentEnvironmentProvider adapter for Tangle sandboxes",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -33,7 +33,7 @@
33
33
  "LICENSE"
34
34
  ],
35
35
  "dependencies": {
36
- "@tangle-network/agent-interface": "^5.10.10"
36
+ "@tangle-network/agent-interface": "^5.10.18"
37
37
  },
38
38
  "peerDependencies": {
39
39
  "@tangle-network/sandbox": ">=1.0.151 <2.0.0"