@tangle-network/agent-runtime 0.321.0 → 0.322.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.
Files changed (54) hide show
  1. package/dist/{activation-CXFl5YVE.js → activation-CBv_0LUh.js} +2 -2
  2. package/dist/{activation-CXFl5YVE.js.map → activation-CBv_0LUh.js.map} +1 -1
  3. package/dist/{activation-BxOOvwjo.d.ts → activation-CZGz2kuu.d.ts} +2 -2
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +2 -2
  6. package/dist/{coordination-driver-Bpn05N-Y.js → coordination-driver-C2Zm5lU4.js} +69 -2
  7. package/dist/coordination-driver-C2Zm5lU4.js.map +1 -0
  8. package/dist/{delegate-BHlcTOdK.js → delegate-BV7AVmbB.js} +2 -2
  9. package/dist/{delegate-BHlcTOdK.js.map → delegate-BV7AVmbB.js.map} +1 -1
  10. package/dist/durable.d.ts +1 -1
  11. package/dist/durable.js +2 -2
  12. package/dist/{graph-DE2dLhDI.js → graph-CH3YiPog.js} +4 -4
  13. package/dist/{graph-DE2dLhDI.js.map → graph-CH3YiPog.js.map} +1 -1
  14. package/dist/{improvement-cycle-CyChbojL.js → improvement-cycle-CD1h5GSM.js} +3 -3
  15. package/dist/{improvement-cycle-CyChbojL.js.map → improvement-cycle-CD1h5GSM.js.map} +1 -1
  16. package/dist/{index-BxiHetnG.d.ts → index-CGNQWpge.d.ts} +633 -545
  17. package/dist/index.d.ts +4 -4
  18. package/dist/index.js +7 -7
  19. package/dist/intelligence.d.ts +2 -2
  20. package/dist/intelligence.js +3 -3
  21. package/dist/kernel.d.ts +2 -2
  22. package/dist/kernel.js +9 -9
  23. package/dist/{loop-runner-bin-CT02Vzco.js → loop-runner-bin-CFxE376A.js} +3 -3
  24. package/dist/{loop-runner-bin-CT02Vzco.js.map → loop-runner-bin-CFxE376A.js.map} +1 -1
  25. package/dist/{loop-runner-bin-DInJZNgs.d.ts → loop-runner-bin-C_jaLCUO.d.ts} +2 -2
  26. package/dist/loop-runner-bin.d.ts +1 -1
  27. package/dist/loop-runner-bin.js +1 -1
  28. package/dist/mcp/bin.js +3 -3
  29. package/dist/mcp/index.d.ts +2 -2
  30. package/dist/mcp/index.js +4 -4
  31. package/dist/{openai-tools-DLTw576v.d.ts → openai-tools-D1PDoBOz.d.ts} +2 -2
  32. package/dist/profiles.d.ts +1 -1
  33. package/dist/{provision-supervisor-DvgBNtoJ.js → provision-supervisor-ftJZhqBU.js} +3 -3
  34. package/dist/{provision-supervisor-DvgBNtoJ.js.map → provision-supervisor-ftJZhqBU.js.map} +1 -1
  35. package/dist/{runtime-wLgjMOaj.js → runtime-EiTCboO2.js} +77 -12
  36. package/dist/runtime-EiTCboO2.js.map +1 -0
  37. package/dist/{search-executor-TEKWC579.js → search-executor-ECJ2TmC-.js} +2 -2
  38. package/dist/{search-executor-TEKWC579.js.map → search-executor-ECJ2TmC-.js.map} +1 -1
  39. package/dist/{server-qYhzITTm.js → server-C2k5wX4k.js} +3 -3
  40. package/dist/{server-qYhzITTm.js.map → server-C2k5wX4k.js.map} +1 -1
  41. package/dist/{supervise-C4bLIU7J.js → supervise-BjrRk-AN.js} +160 -122
  42. package/dist/supervise-BjrRk-AN.js.map +1 -0
  43. package/dist/{supervisor-bkq2b8k-.js → supervisor-BMMdI4T-.js} +224 -39
  44. package/dist/supervisor-BMMdI4T-.js.map +1 -0
  45. package/dist/testing.d.ts +1 -1
  46. package/dist/testing.js +12 -12
  47. package/dist/tui/index.d.ts +1 -1
  48. package/dist/tui/index.js +1 -1
  49. package/package.json +3 -3
  50. package/skills/profile-authoring/SKILL.md +1 -0
  51. package/dist/coordination-driver-Bpn05N-Y.js.map +0 -1
  52. package/dist/runtime-wLgjMOaj.js.map +0 -1
  53. package/dist/supervise-C4bLIU7J.js.map +0 -1
  54. package/dist/supervisor-bkq2b8k-.js.map +0 -1
@@ -11206,6 +11206,20 @@ function traceEvidenceFor(event) {
11206
11206
  };
11207
11207
  }
11208
11208
  //#endregion
11209
+ //#region src/runtime/supervise/credential-refusal.ts
11210
+ /**
11211
+ * The account owner refused an unsupported credential route before dispatch. This is the
11212
+ * provider SDK's machine contract, not an HTTP status, class-name guess, or prose match.
11213
+ */
11214
+ function isCredentialRefusal(error) {
11215
+ if (!(error instanceof Error)) return false;
11216
+ try {
11217
+ return Object.getOwnPropertyDescriptor(error, "code")?.value === "model_credential_refused";
11218
+ } catch {
11219
+ return false;
11220
+ }
11221
+ }
11222
+ //#endregion
11209
11223
  //#region src/runtime/supervise/trace-root.ts
11210
11224
  /**
11211
11225
  * Trace roots: one Merkle root over the events a turn archived, so a single event can be proven
@@ -11559,14 +11573,8 @@ function readString(value, key) {
11559
11573
  const read = Reflect.get(value, key);
11560
11574
  return typeof read === "string" ? read : void 0;
11561
11575
  }
11562
- /**
11563
- * Walk the cause chain (bounded, cycle-safe) and name the first cause whose structure decides.
11564
- *
11565
- * `phase` says whether a 4xx or a client deadline can mean "refused before it ran": only at
11566
- * admission. After admission the same status means the provider cannot resolve what it
11567
- * admitted, and the honest name is the refusal.
11568
- */
11569
- function classifyRetainedPendingCause(cause, phase = "execution") {
11576
+ const credentialAdmissionRefusals = /* @__PURE__ */ new WeakSet();
11577
+ function classifyPendingCause(cause, phase, onCredentialRefusal) {
11570
11578
  const seen = /* @__PURE__ */ new Set();
11571
11579
  const queue = [{
11572
11580
  value: cause,
@@ -11578,7 +11586,13 @@ function classifyRetainedPendingCause(cause, phase = "execution") {
11578
11586
  const { value, phase: at } = queue.shift();
11579
11587
  if (typeof value !== "object" || value === null || seen.has(value)) continue;
11580
11588
  seen.add(value);
11581
- if (value instanceof RetainedExecutionPendingError) return value.pendingCause;
11589
+ if (value instanceof RetainedExecutionPendingError) {
11590
+ if (credentialAdmissionRefusals.has(value)) {
11591
+ if (at === "execution") return "unobservable";
11592
+ onCredentialRefusal?.();
11593
+ }
11594
+ return value.pendingCause;
11595
+ }
11582
11596
  const name = readString(value, "name");
11583
11597
  const code = readString(value, "code");
11584
11598
  const status = readNumber(value, "status") ?? readNumber(value, "statusCode");
@@ -11592,6 +11606,11 @@ function classifyRetainedPendingCause(cause, phase = "execution") {
11592
11606
  }
11593
11607
  if (name === "ZodError" || Array.isArray(Reflect.get(value, "issues")) || code === "JSON_BOUND_VIOLATION") return at === "admission" ? "request-rejected" : "provider-contract";
11594
11608
  if (code === "DISPATCH_NOT_ADMITTED") return at === "admission" ? "request-rejected" : "provider-contract";
11609
+ if (isCredentialRefusal(value)) {
11610
+ if (at === "execution") return "unobservable";
11611
+ onCredentialRefusal?.();
11612
+ return "request-rejected";
11613
+ }
11595
11614
  if (code !== void 0 && transportCodes.has(code)) return "transport";
11596
11615
  if (name === "NetworkError" || name === "ServerError") return "transport";
11597
11616
  if (status === void 0 && at === "admission" && code !== void 0 && UNAVAILABLE_CODES.has(code.toLowerCase())) return "request-rejected";
@@ -11630,11 +11649,15 @@ var RetainedExecutionPendingError = class extends Error {
11630
11649
  pendingCause;
11631
11650
  phase;
11632
11651
  constructor(cause, pendingCause = "execution") {
11633
- const resolved = pendingCause === "admission" || pendingCause === "execution" ? classifyRetainedPendingCause(cause, pendingCause) : pendingCause;
11652
+ let credentialRefused = false;
11653
+ const resolved = pendingCause === "admission" || pendingCause === "execution" ? classifyPendingCause(cause, pendingCause, () => {
11654
+ credentialRefused = true;
11655
+ }) : pendingCause;
11634
11656
  super(causeMessages[resolved], { cause });
11635
11657
  this.name = "RetainedExecutionPendingError";
11636
11658
  this.pendingCause = resolved;
11637
11659
  this.phase = pendingCause === "admission" ? "admission" : "execution";
11660
+ if (credentialRefused) credentialAdmissionRefusals.add(this);
11638
11661
  }
11639
11662
  };
11640
11663
  /** The execution id of a leaf's later invocation, derived from its `execution-input` sequence so
@@ -11981,7 +12004,7 @@ function providerAsSandboxClient(provider, options = {}) {
11981
12004
  }
11982
12005
  return { async create(createOptions) {
11983
12006
  const defaults = options.defaults ?? {};
11984
- const sandboxInput = createInputFromSandboxOptions(createOptions);
12007
+ const sandboxInput = createInputFromSandboxOptions(createOptions, options.mapCreateOptions !== void 0);
11985
12008
  const customInput = options.mapCreateOptions?.(createOptions) ?? {};
11986
12009
  const mapped = {
11987
12010
  ...defaults,
@@ -12000,16 +12023,17 @@ function providerAsSandboxClient(provider, options = {}) {
12000
12023
  };
12001
12024
  if (mapped.backend === void 0) delete mapped.backend;
12002
12025
  if (mapped.profile === void 0) throw new ValidationError(`providerAsSandboxClient(${provider.name}): profile required in defaults or CreateSandboxOptions.backend.profile`);
12003
- if (options.requireSession) {
12004
- const capabilities = await provider.capabilities();
12005
- if (!capabilities.streaming.live || !capabilities.sessions.continue) throw new ValidationError(`providerAsSandboxClient(${provider.name}): live session continuation is required`);
12006
- }
12026
+ const needsMcp = hasRuntimeMcpAttachments(mapped);
12027
+ const capabilities = options.requireSession || needsMcp ? await provider.capabilities() : void 0;
12028
+ assertRuntimeMcpAttachments(provider.name, mapped, capabilities);
12029
+ if (options.requireSession && (!capabilities?.streaming.live || !capabilities.sessions.continue)) throw new ValidationError(`providerAsSandboxClient(${provider.name}): live session continuation is required`);
12007
12030
  const environment = await provider.create(mapped);
12008
12031
  if (options.requireSession && !environment.session) {
12009
12032
  if (options.workspaceRetention === void 0) await environment.destroy?.();
12010
12033
  throw new ValidationError(`providerAsSandboxClient(${provider.name}): session() is required`);
12011
12034
  }
12012
12035
  return environmentAsSandboxInstance(environment, {
12036
+ ...typeof mapped.profile === "string" ? {} : { profile: mapped.profile },
12013
12037
  requireTerminalEvent: options.requireTerminalEvent ?? true,
12014
12038
  ...options.workspaceRetention === void 0 ? {} : { workspaceRetention: options.workspaceRetention },
12015
12039
  ...options.retentionIdentity === void 0 ? {} : { retentionIdentity: options.retentionIdentity },
@@ -12996,7 +13020,10 @@ async function* streamProviderExecutor(args) {
12996
13020
  const verdict = await args.options.validator?.validate(result, {
12997
13021
  iteration: 0,
12998
13022
  ...args.node === void 0 ? {} : { node: args.node },
12999
- box: environmentAsSandboxInstance(environment, { requireTerminalEvent: args.options.requireTerminalEvent ?? true }),
13023
+ box: environmentAsSandboxInstance(environment, {
13024
+ profile: args.profile,
13025
+ requireTerminalEvent: args.options.requireTerminalEvent ?? true
13026
+ }),
13000
13027
  signal: linked
13001
13028
  });
13002
13029
  const deferCapture = ownerTakesCapture();
@@ -13194,7 +13221,7 @@ async function* streamProviderExecutor(args) {
13194
13221
  } else if (input > 0 || output > 0 || receipt.tokensKnown === false) pendingUnpricedWork = true;
13195
13222
  }
13196
13223
  }
13197
- /** Subscription selection needs the same complete profile on creation and every new turn. */
13224
+ /** Subscription selection needs its complete profile and one identity for each fresh turn. */
13198
13225
  function subscriptionTurnProfile(turn, profile) {
13199
13226
  if (profile.model?.metadata?.credentialSource !== "subscription") return turn;
13200
13227
  const backend = promptOptionsFromAgentTurnInput(turn).backend ?? {};
@@ -13202,14 +13229,26 @@ function subscriptionTurnProfile(turn, profile) {
13202
13229
  if (turn.profile !== void 0 && canonicalAgentProfileDigest(turn.profile) !== digest || backend.profile !== void 0 && canonicalAgentProfileDigest(backend.profile) !== digest) throw new ValidationError("provider subscription turn cannot replace its exact AgentProfile");
13203
13230
  return {
13204
13231
  ...turn,
13205
- profile
13232
+ profile,
13233
+ ...turn.turnId === void 0 && turn.lastEventId === void 0 && turn.controlRef === void 0 ? { turnId: randomUUID() } : {}
13206
13234
  };
13207
13235
  }
13236
+ function hasRuntimeMcpAttachments(input) {
13237
+ const mcp = input?.runtimeAttachments?.mcp;
13238
+ return mcp !== void 0 && Object.keys(mcp).length > 0;
13239
+ }
13240
+ function assertRuntimeMcpAttachments(provider, input, capabilities) {
13241
+ if (!hasRuntimeMcpAttachments(input)) return;
13242
+ const create = capabilities?.create;
13243
+ if (!create || !("runtimeAttachments" in create) || create.runtimeAttachments?.mcp !== true) throw new ValidationError(`provider ${provider} does not advertise create.runtimeAttachments.mcp; no environment was created`);
13244
+ }
13208
13245
  /** One retained dispatch owns creation, replay, result identity, and cancellation. */
13209
13246
  async function providerExecutionSource(args, turn, signal) {
13210
13247
  const selectedTurn = subscriptionTurnProfile(turn, args.profile);
13211
13248
  AgentTurnInputSchema.parse(selectedTurn);
13212
- const capabilities = args.retention ? await args.provider.capabilities() : void 0;
13249
+ const needsMcp = hasRuntimeMcpAttachments(args.options.defaults);
13250
+ const capabilities = args.retention || needsMcp ? await args.provider.capabilities() : void 0;
13251
+ assertRuntimeMcpAttachments(args.provider.name, args.options.defaults, capabilities);
13213
13252
  if (!(args.retention !== void 0 && capabilities?.retainedControl !== void 0)) {
13214
13253
  if (args.recovering) throw new Error(`provider ${args.provider.name} cannot recover retained executions`);
13215
13254
  const environment = await args.provider.create({
@@ -13506,7 +13545,44 @@ async function providerExecutionSource(args, turn, signal) {
13506
13545
  throw error;
13507
13546
  }
13508
13547
  }
13509
- function createInputFromSandboxOptions(options) {
13548
+ function createInputFromSandboxOptions(options, customMapping) {
13549
+ if (!customMapping) {
13550
+ const mapped = /* @__PURE__ */ new Set([
13551
+ "backend",
13552
+ "environment",
13553
+ "git",
13554
+ "cwd",
13555
+ "resources",
13556
+ "env",
13557
+ "secrets",
13558
+ "metadata",
13559
+ "name",
13560
+ "idempotencyKey"
13561
+ ]);
13562
+ const unsupported = Object.entries(options ?? {}).filter(([key, value]) => value !== void 0 && !mapped.has(key)).map(([key]) => key);
13563
+ for (const [prefix, value, keys] of [[
13564
+ "backend",
13565
+ options?.backend,
13566
+ [
13567
+ "type",
13568
+ "profile",
13569
+ "model"
13570
+ ]
13571
+ ], [
13572
+ "git",
13573
+ options?.git,
13574
+ ["url", "ref"]
13575
+ ]]) for (const [key, field] of Object.entries(value ?? {})) if (field !== void 0 && !keys.includes(key)) unsupported.push(`${prefix}.${key}`);
13576
+ const model = options?.backend?.model;
13577
+ if (model !== void 0) {
13578
+ for (const [key, value] of Object.entries(model)) if (value !== void 0 && !["provider", "model"].includes(key)) unsupported.push(`backend.model.${key}`);
13579
+ const profile = options?.backend?.profile;
13580
+ if (model.provider !== void 0 && model.provider !== profile?.model?.provider?.trim()) unsupported.push("backend.model.provider");
13581
+ if (model.model !== void 0 && model.model !== concreteProfileModel(profile ?? {})) unsupported.push("backend.model.model");
13582
+ }
13583
+ if (options?.secrets === "all") unsupported.push("secrets=all");
13584
+ if (unsupported.length > 0) throw new ValidationError(`providerAsSandboxClient: Sandbox create controls require mapCreateOptions: ${unsupported.join(", ")}`);
13585
+ }
13510
13586
  const profile = options?.backend?.profile;
13511
13587
  const backend = options?.backend?.type;
13512
13588
  const cwd = options?.cwd === void 0 ? void 0 : canonicalWorkspaceCwd({
@@ -13528,8 +13604,7 @@ function createInputFromSandboxOptions(options) {
13528
13604
  ...Array.isArray(options?.secrets) ? { secrets: options.secrets } : {},
13529
13605
  ...options?.metadata ? { metadata: options.metadata } : {},
13530
13606
  ...options?.name ? { name: options.name } : {},
13531
- ...options?.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {},
13532
- providerOptions: { sandboxCreateOptions: options ?? {} }
13607
+ ...options?.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}
13533
13608
  };
13534
13609
  }
13535
13610
  function environmentAsSandboxInstance(environment, options) {
@@ -13554,7 +13629,7 @@ function environmentAsSandboxInstance(environment, options) {
13554
13629
  },
13555
13630
  async *streamPrompt(message, promptOptions) {
13556
13631
  let terminal = false;
13557
- const input = turnInputFromPrompt(message, promptOptions);
13632
+ const input = turnInputFromPrompt(message, promptOptions, options.profile);
13558
13633
  providerSessionId = input.sessionId ?? null;
13559
13634
  noteControlRef(input.controlRef);
13560
13635
  let cancellation;
@@ -13616,7 +13691,7 @@ function environmentAsSandboxInstance(environment, options) {
13616
13691
  const usageLedger = createSandboxUsageLedger();
13617
13692
  let terminal = false;
13618
13693
  const failures = createProviderFailureLedger();
13619
- const input = turnInputFromPrompt(message, promptOptions);
13694
+ const input = turnInputFromPrompt(message, promptOptions, options.profile);
13620
13695
  providerSessionId = input.sessionId ?? null;
13621
13696
  noteControlRef(input.controlRef);
13622
13697
  for await (const event of environment.stream(input)) {
@@ -13643,14 +13718,14 @@ function environmentAsSandboxInstance(environment, options) {
13643
13718
  };
13644
13719
  },
13645
13720
  ...environment.dispatch && environment.session ? { async dispatchPrompt(message, promptOptions) {
13646
- const session = await environment.dispatch?.(turnInputFromPrompt(message, promptOptions));
13721
+ const session = await environment.dispatch?.(turnInputFromPrompt(message, promptOptions, options.profile));
13647
13722
  if (!session) throw new ValidationError("providerAsSandboxClient: dispatch returned no session");
13648
13723
  noteControlRef(session.controlRef);
13649
13724
  return sandboxDispatchResultFromSessionRef(session);
13650
13725
  } } : {},
13651
13726
  ...environment.session ? { session(id, sessionOptions) {
13652
13727
  noteControlRef(sessionOptions?.controlRef);
13653
- return sandboxSessionFromAgentSession(environment.session?.(id, sessionOptions), sessionOptions?.controlRef);
13728
+ return sandboxSessionFromAgentSession(environment.session?.(id, sessionOptions), sessionOptions?.controlRef, options.profile);
13654
13729
  } } : {},
13655
13730
  ...environment.read ? { read: environment.read.bind(environment) } : {},
13656
13731
  ...environment.write ? { write: environment.write.bind(environment) } : {},
@@ -13704,7 +13779,7 @@ function environmentAsSandboxInstance(environment, options) {
13704
13779
  }
13705
13780
  };
13706
13781
  }
13707
- function sandboxSessionFromAgentSession(session, expectedControlRef) {
13782
+ function sandboxSessionFromAgentSession(session, expectedControlRef, profile) {
13708
13783
  if (!session) throw new ValidationError("providerAsSandboxClient: session is unavailable");
13709
13784
  const controlRef = resolveSessionControlRef(session.controlRef, expectedControlRef);
13710
13785
  return {
@@ -13731,7 +13806,7 @@ function sandboxSessionFromAgentSession(session, expectedControlRef) {
13731
13806
  return promptResultFromAgentTurnResult(await session.result());
13732
13807
  },
13733
13808
  async prompt(message, options) {
13734
- return promptResultFromAgentTurnResult(await session.prompt(turnInputFromPrompt(message, options)));
13809
+ return promptResultFromAgentTurnResult(await session.prompt(turnInputFromPrompt(message, options, profile)));
13735
13810
  },
13736
13811
  ...session.respondToInteraction ? { async respondToInteraction(command, options) {
13737
13812
  assertInteractionCommandScope(command, controlRef);
@@ -13978,8 +14053,8 @@ function tokenUsageData(usage) {
13978
14053
  ...usage.cost !== void 0 ? { totalCostUsd: usage.cost } : {}
13979
14054
  };
13980
14055
  }
13981
- function turnInputFromPrompt(message, options) {
13982
- return {
14056
+ function turnInputFromPrompt(message, options, profile) {
14057
+ const input = {
13983
14058
  ...typeof message === "string" ? { prompt: message } : { parts: message },
13984
14059
  ...options?.sessionId ? { sessionId: options.sessionId } : {},
13985
14060
  ...options?.model ? { model: options.model } : {},
@@ -13994,6 +14069,7 @@ function turnInputFromPrompt(message, options) {
13994
14069
  ...options?.signal ? { signal: options.signal } : {},
13995
14070
  ...options?.backend ? { providerOptions: { backend: options.backend } } : {}
13996
14071
  };
14072
+ return profile === void 0 ? input : subscriptionTurnProfile(input, profile);
13997
14073
  }
13998
14074
  function resolveSessionControlRef(actual, expected, options = {}) {
13999
14075
  if (expected === void 0) {
@@ -21350,14 +21426,15 @@ function routerTurnRequestIdentity(identity, turnIndex) {
21350
21426
  * the recorded usage events are yielded; the terminal artifact is read from
21351
21427
  * `resultArtifact()` after the stream drains.
21352
21428
  */
21353
- const sandboxExecutor = (spec, ctx) => {
21429
+ const sandboxExecutor = (spec, ctx) => sandboxExecutorForPath(spec, ctx, "sandbox");
21430
+ function sandboxExecutorForPath(spec, ctx, modelPath) {
21354
21431
  if (spec.harness === null) throw new ValidationError$1("sandboxExecutor: harness is null (router/inline) — wrong executor");
21355
21432
  const harness = spec.harness;
21356
21433
  const seam = readSeam(ctx, sandboxSeamKey, "sandbox");
21357
21434
  if (!seam.sandboxClient || typeof seam.sandboxClient.create !== "function") throw new ValidationError$1("sandboxExecutor: SandboxSeam.sandboxClient.create required");
21358
21435
  const maxIterations = seam.maxIterations ?? 1;
21359
21436
  if (!Number.isFinite(maxIterations) || maxIterations <= 0) throw new ValidationError$1("sandboxExecutor: maxIterations must be > 0");
21360
- const sandboxTokenLimits = enforceTokenLimits(profileModelExecutionSettings(spec.profile, "sandboxExecutor").tokenLimits, "sandbox", "sandboxExecutor");
21437
+ const sandboxTokenLimits = enforceTokenLimits(profileModelExecutionSettings(spec.profile, "sandboxExecutor", modelPath).tokenLimits, "sandbox", "sandboxExecutor");
21361
21438
  const traceEnv = {
21362
21439
  ...workerLineage({
21363
21440
  harness,
@@ -21486,7 +21563,7 @@ const sandboxExecutor = (spec, ctx) => {
21486
21563
  return artifact;
21487
21564
  }
21488
21565
  }, sandboxMaterialization, sandboxBinding);
21489
- };
21566
+ }
21490
21567
  async function* streamSandboxLeaf(args) {
21491
21568
  const linked = linkAbort(args.signal, args.controller.signal);
21492
21569
  const agentRun = {
@@ -22285,6 +22362,7 @@ function createExecutor(config) {
22285
22362
  const sandboxClient = providerAsSandboxClient(provider, {
22286
22363
  defaults: {
22287
22364
  ...providerSeam.defaults ?? {},
22365
+ idempotencyKey: providerSeam.defaults?.idempotencyKey ?? seamed.node?.attemptId ?? randomUUID(),
22288
22366
  signal: seamed.signal
22289
22367
  },
22290
22368
  requireTerminalEvent: providerSeam.requireTerminalEvent,
@@ -22321,10 +22399,10 @@ function createExecutor(config) {
22321
22399
  }
22322
22400
  }
22323
22401
  };
22324
- const executor = sandboxExecutor({
22402
+ const executor = sandboxExecutorForPath({
22325
22403
  ...spec,
22326
22404
  harness
22327
- }, providerCtx);
22405
+ }, providerCtx, "provider");
22328
22406
  const wrapper = inheritRuntimeOwnedExecutorAttestation(executor, {
22329
22407
  ...executor,
22330
22408
  runtime: providerSeam.runtime ?? provider.name
@@ -26592,6 +26670,77 @@ function checkedSeatSelection(stage, selected) {
26592
26670
  return selected;
26593
26671
  }
26594
26672
  //#endregion
26673
+ //#region src/runtime/supervise/worker-events.ts
26674
+ const MAX_EVENTS = 256;
26675
+ const MAX_BYTES = 262144;
26676
+ /** One worker's already-redacted live output. Accounting stays on Scope's existing usage channel. */
26677
+ var WorkerEvents = class {
26678
+ #epoch = randomUUID();
26679
+ #entries = [];
26680
+ #next = 0;
26681
+ #capturing = false;
26682
+ start() {
26683
+ this.#capturing = true;
26684
+ }
26685
+ #bytes = 0;
26686
+ append(event, at) {
26687
+ let entry = {
26688
+ sequence: this.#next++,
26689
+ at,
26690
+ event: defaultRedactor(event)
26691
+ };
26692
+ let bytes;
26693
+ try {
26694
+ bytes = Buffer.byteLength(JSON.stringify(entry));
26695
+ } catch {
26696
+ entry = {
26697
+ sequence: entry.sequence,
26698
+ at,
26699
+ event: null,
26700
+ omitted: "event-not-serializable"
26701
+ };
26702
+ bytes = Buffer.byteLength(JSON.stringify(entry));
26703
+ }
26704
+ if (bytes > MAX_BYTES) {
26705
+ entry = {
26706
+ sequence: entry.sequence,
26707
+ at,
26708
+ event: null,
26709
+ omitted: "event-too-large"
26710
+ };
26711
+ bytes = Buffer.byteLength(JSON.stringify(entry));
26712
+ }
26713
+ this.#entries.push({
26714
+ entry,
26715
+ bytes
26716
+ });
26717
+ this.#bytes += bytes;
26718
+ while (this.#entries.length > MAX_EVENTS || this.#bytes > MAX_BYTES) this.#bytes -= this.#entries.shift().bytes;
26719
+ }
26720
+ read(cursor) {
26721
+ if (!this.#capturing) return {
26722
+ status: "unavailable",
26723
+ reason: "not-captured"
26724
+ };
26725
+ if (cursor && (!Number.isSafeInteger(cursor.next) || cursor.next < 0)) throw new Error("worker event cursor must name a non-negative safe integer");
26726
+ const reset = cursor !== void 0 && cursor.epoch !== this.#epoch;
26727
+ const first = this.#entries[0]?.entry.sequence ?? this.#next;
26728
+ const start = reset ? first : cursor?.next ?? first;
26729
+ if (!reset && start > this.#next) throw new Error("worker event cursor is ahead of this stream");
26730
+ return {
26731
+ status: "available",
26732
+ entries: this.#entries.filter(({ entry }) => entry.sequence >= start).map(({ entry }) => structuredClone(entry)),
26733
+ cursor: {
26734
+ epoch: this.#epoch,
26735
+ next: this.#next
26736
+ },
26737
+ reset,
26738
+ historyExpired: start < first || cursor === void 0 && first > 0,
26739
+ remaining: 0
26740
+ };
26741
+ }
26742
+ };
26743
+ //#endregion
26595
26744
  //#region src/runtime/supervise/scope.ts
26596
26745
  /**
26597
26746
  *
@@ -27309,6 +27458,7 @@ function createScope(args) {
27309
27458
  live.teardownAttempts += 1;
27310
27459
  });
27311
27460
  const live = {
27461
+ events: new WorkerEvents(),
27312
27462
  id,
27313
27463
  status: permit.granted ? "acquiring" : "queued",
27314
27464
  runtime: executor.runtime,
@@ -27756,6 +27906,37 @@ function createScope(args) {
27756
27906
  nextResolved,
27757
27907
  send,
27758
27908
  progress,
27909
+ observeTree: () => {
27910
+ const view = makeTreeView(args.parentId, children);
27911
+ const nodes = new Map((args.resumeFrom?.view.nodes ?? []).map((node) => [node.id, node]));
27912
+ for (const node of view.nodes) nodes.set(node.id, node);
27913
+ for (const child of children.values()) {
27914
+ const nested = child.readNestedScope?.();
27915
+ if (nested) for (const node of (nested.observeTree?.() ?? nested.view).nodes) nodes.set(node.id, node);
27916
+ }
27917
+ const all = [...nodes.values()];
27918
+ return {
27919
+ root: view.root,
27920
+ nodes: all,
27921
+ inFlight: all.filter((node) => [
27922
+ "queued",
27923
+ "acquiring",
27924
+ "running"
27925
+ ].includes(node.status)).length
27926
+ };
27927
+ },
27928
+ observeEvents: (nodeId, cursor) => {
27929
+ const child = children.get(nodeId);
27930
+ if (child) return child.events.read(cursor);
27931
+ for (const candidate of children.values()) {
27932
+ const page = (candidate.readNestedScope?.())?.observeEvents?.(nodeId, cursor);
27933
+ if (page && (page.status === "available" || page.reason !== "unknown-worker")) return page;
27934
+ }
27935
+ return {
27936
+ status: "unavailable",
27937
+ reason: args.resumeFrom?.view.nodes.some((node) => node.id === nodeId) ? "not-captured" : "unknown-worker"
27938
+ };
27939
+ },
27759
27940
  traceSource,
27760
27941
  interactive,
27761
27942
  cancel,
@@ -28611,6 +28792,7 @@ async function runChild(live, executor, childAbort, task, opts, pool, ticket, bl
28611
28792
  const ran = recovering ? executor.recover(task, childAbort.signal) : executor.execute(task, childAbort.signal);
28612
28793
  let artifact;
28613
28794
  if (isAsyncIterable(ran)) {
28795
+ live.events.start();
28614
28796
  const spend = await foldStream(ran, async (running) => {
28615
28797
  live.spent = running;
28616
28798
  live.lastActivityAt = now();
@@ -28621,7 +28803,7 @@ async function runChild(live, executor, childAbort, task, opts, pool, ticket, bl
28621
28803
  seq: nextProgressSeq(),
28622
28804
  at: new Date(now()).toISOString()
28623
28805
  });
28624
- }, childAbort.signal, priorSpent);
28806
+ }, childAbort.signal, priorSpent, (event) => live.events.append(event, now()));
28625
28807
  live.spent = spend;
28626
28808
  const reported = executor.resultArtifact();
28627
28809
  artifact = await retainOutput(reported, preserveUnknownTelemetry(spend, reported.spent));
@@ -28985,7 +29167,7 @@ function freezeCorrelation(value) {
28985
29167
  * turns deep from one that had produced nothing. It also means a worker that THROWS mid-stream
28986
29168
  * now reconciles its real partial spend instead of refunding work the provider already billed.
28987
29169
  */
28988
- async function foldStream(stream, onProgress, signal, priorSpent) {
29170
+ async function foldStream(stream, onProgress, signal, priorSpent, onEvent) {
28989
29171
  const totals = newUsageTotals(priorSpent);
28990
29172
  const iterator = stream[Symbol.asyncIterator]();
28991
29173
  try {
@@ -28993,6 +29175,7 @@ async function foldStream(stream, onProgress, signal, priorSpent) {
28993
29175
  const next = signal ? await awaitAbortable(Promise.resolve(iterator.next()), signal) : await iterator.next();
28994
29176
  if (next.done) break;
28995
29177
  const ev = next.value;
29178
+ if (ev.kind === "progress") onEvent?.(ev.progress);
28996
29179
  meterUsageEvent(totals, ev);
28997
29180
  await onProgress?.({
28998
29181
  ...addResourceSpend(totals.resources),
@@ -29712,6 +29895,7 @@ function upstreamUnavailableSignal(error) {
29712
29895
  const admission = retainedAdmissionCause(error);
29713
29896
  if (admission !== void 0) return upstreamUnavailableSignal(admission);
29714
29897
  if (!(error instanceof Error)) return void 0;
29898
+ if (isCredentialRefusal(error)) return void 0;
29715
29899
  if (isProviderSchemaRejection(error)) return void 0;
29716
29900
  if (error instanceof CheckUnavailableError) return "check-unavailable";
29717
29901
  if (error instanceof HarnessTurnFailedError) {
@@ -29776,6 +29960,7 @@ function classifyDriverFailure(error, signal) {
29776
29960
  if (admission !== void 0) return classifyDriverFailure(admission, signal);
29777
29961
  if (error instanceof Error && errorProperty(error, "name") === "AbortError") return "terminal";
29778
29962
  if (error instanceof Error && isProviderSchemaRejection(error)) return "terminal";
29963
+ if (isCredentialRefusal(error)) return "terminal";
29779
29964
  if (error instanceof HarnessTurnFailedError) {
29780
29965
  if (error.errorCode !== void 0 && DETERMINISTIC_BRIDGE_CODES.has(error.errorCode)) return "terminal";
29781
29966
  if (isUpstreamUnavailable(error)) return "unavailable";
@@ -29817,7 +30002,7 @@ function retainedAdmissionCause(error) {
29817
30002
  if (errorProperty(value, "name") === "RetainedRunProviderContractError") return void 0;
29818
30003
  const status = errorHttpStatus(value);
29819
30004
  if (status !== void 0 && status >= 400) return error.pendingCause === "request-rejected" || UNAVAILABLE_STATUSES.has(status) ? value : void 0;
29820
- if (error.pendingCause === "request-rejected" && (value instanceof AgentEvalError$1 || isProviderSchemaRejection(value) || isDispatchNotAdmitted(value) || capacityCode(value) !== void 0)) return value;
30005
+ if (error.pendingCause === "request-rejected" && (value instanceof AgentEvalError$1 || isProviderSchemaRejection(value) || isDispatchNotAdmitted(value) || isCredentialRefusal(value) || capacityCode(value) !== void 0)) return value;
29821
30006
  const members = Reflect.get(value, "errors");
29822
30007
  if (Array.isArray(members)) queue.push(...members.slice(0, 12 - steps));
29823
30008
  queue.push(value.cause);
@@ -31351,4 +31536,4 @@ function isNonEmptySpend(s) {
31351
31536
  //#endregion
31352
31537
  export { environmentReader as $, runtimeOwnedExecutorProviderEvidence as $i, captureWorkerTraceEvidence as $n, flatOtelSpan as $r, PEER_MAIL_WIRE_KEY as $t, scopeOwnerExecutorNodeContext as A, promptControlProfileMaterialization as Ai, resolveAgentEnvironmentProvider as An, persistHarnessTranscript as Ar, captureReusableExecutorConfig as At, consumeScopeRetainedOwnerResult as B, attestRuntimeOwnedPendingExecutor as Bi, FileResultBlobStore as Bn, ROUTER_PRICE_SOURCE as Br, createInPlaceCliExecutor as Bt, deriveNodeExecutionIdentity as C, abortError$1 as Ca, AGENT_PROFILE_MATERIALIZATION_AXES as Ci, readPromptOptions as Cn, openSlotGroup as Cr, createContinuationKeeper as Ct, recordScopeOwnerMaterialization as D, providerMessageText as Da, defineProfileMaterializationContract as Di, createAgentEnvironmentProviderRegistry as Dn, runAbortable as Dr, passedItems as Dt, recordScopeOwnerDriverAttempt as E, promptOptionsFromAgentTurnInput as Ea, controlProfileMaterialization as Ei, LEAF_CONTINUATION_TASK as En, linkAbort as Er, failedItems as Et, seatExecutionProfile as F, renderUnsupported as Fi, retainedExecutorSeamKey as Fn, createCodeModeTools as Fr, snapshotExecutorConfig as Ft, scopeRetainedOwnerContext as G, knownExecutionBindingReceipt as Gi, loadSpawnForest as Gn, defaultRedactor as Gr, workerTraceSeamKey as Gt, prepareScopeRetainedOwnerSeatSwitch as H, authoredProfileDigest as Hi, InMemoryResultBlobStore as Hn, mergeTraceEnv as Hr, readWorkerTraceContext as Ht, abandonScopeRetainedOwnerInvocation as I, sandboxActProfileMaterialization as Ii, unavailablePauseMs as In, describeCodeModeTools as Ir, createWorktreeCliExecutor as It, scopeRetainedOwnerResourceReader as J, providerAttemptEvidence as Ji, isNoEntError as Jn, buildLoopOtelSpans as Jr, createActivityLog as Jt, scopeRetainedOwnerJournalRoot as K, knownMaterializationReceipt as Ki, materializeTreeView as Kn, defaultRedactorIdentityMaterial as Kr, taskToPrompt as Kt, beginScopeRetainedOwnerDrive as L, unsupportedProfileDimensions as Li, unavailableSignalOfFailure as Ln, runCodeMode as Lr, DEFAULT_SANDBOX_STEERING_MAX_TURNS as Lt, SeatChain as M, promptOnlyProfileMaterialization as Mi, decodeToolPart as Mn, resolveHarnessTranscriptCapture as Mr, cliWorktreeExecutor as Mt, SeatChainExhaustedError as N, promptResourceProfileMaterialization as Ni, sandboxSessionTraceSource as Nn, retainHarnessTranscript as Nr, createExecutor as Nt, recordScopeOwnerPause as O, fullProfileMaterialization as Oi, providerAsExecutor as On, captureHarnessTranscript as Or, verdictFromJudgeScore as Ot, authoredSeatStages as P, renderProfileMaterializationIssues as Pi, registerRetainedExecutorPreparation as Pn, contentAddress as Pr, createExecutorRegistry as Pt, SPAWN_RESOURCE_PATH_MAX_BYTES as Q, runtimeOwnedExecutorMaterialization as Qi, WORKER_TOOL_TRACE_SCHEMA_VERSION as Qn, createOtelExporter as Qr, DEFAULT_PEER_MAIL_LIMITS as Qt, bindScopeRetainedOwnerEnvironmentId as R, validateProfileMaterialization as Ri, TRACE_ROOT_SCHEMA as Rn, priceTokens as Rr, createSteerableSandboxSession as Rt, createScope as S, decodeHarnessUsage as Sa, terminateProcessTreeAndConfirm as Si, assertBoxlessPromptOptions as Sn, createWorkerSlots as Sr, checkVerdictOf as St, meterRuntimeOwnedProviderAttempt as T, promptFromAgentTurnInput as Ta, assertProfileMaterializes as Ti, runBrainLoop as Tn, abortError as Tr, expandQuestions as Tt, prepareScopeRetainedOwnerTask as U, finalizeRuntimeOwnedPendingExecutor as Ui, InMemorySpawnJournal as Un, readTraceContextFromEnv as Ur, workerTraceEnv as Ut, noteScopeRetainedOwnerCoordination as V, attestRuntimeOwnedScopeOwner as Vi, FileSpawnJournal as Vn, createPropagatingTraceEmitter as Vr, WORKER_TRACE_PROPAGATION as Vt, reconcileScopeRetainedOwnerEnvironment as W, inheritRuntimeOwnedExecutorAttestation as Wi, insideCursorNamespace as Wn, traceContextToEnv as Wr, workerTraceHeaders as Wt, scopeRetainedOwnerResult as X, runtimeOwnedDriveHarnessProviderEvidence as Xi, readCommittedJsonLines as Xn, buildRuntimeEventOtelSpans as Xr, createInbox as Xt, scopeRetainedOwnerRestorePoint as Y, recordRuntimeOwnedDriveHarnessProviderEvidence as Yi, prepareJsonlAppend as Yn, buildLoopSpanNodes as Yr, readWorkerProgress as Yt, scopeRetainedOwnerTurnEnded as Z, runtimeOwnedExecutorExecutionBinding as Zi, writeAllBytes as Zn, createOpenInferenceFileExporter as Zr, AUTHORITY_MARKERS as Zt, isDriverSpec as _, mapSandboxToolEvent as _a, harnessInvocation as _i, runAgentRounds as _n, startRetainedRun as _r, CONTINUATION_FACTS as _t, collectDelivered as a, executableAgentSpecSnapshot as aa, createRuntimeEventCollector as ai, isLiveNodeStatus as an, ReservationWaitRefused as ar, interactiveAdmissionSeamKey as at, assertRecursiveReservationPolicy as b, sandboxProgressEvents as ba, parseCodexTokenUsage as bi, SandboxEvidenceRetentionError as bn, destroyInteractiveEnvironment as br, admitFinding as bt, runTree as c, projectSandboxOutcome as ca, sanitizeKnowledgeReadinessReport as ci, bridgeModelRouteRefusal as cn, meterUsageEvent as cr, reconnectRetainedInteractiveRun as ct, classifyDriverFailure as d, canonicalStreamEventFromSandboxEvent as da, runWorktreeHarness as di, harnessUsageIsEmpty as dn, spendFromUsageTotals as dr, freeSlots as dt, runtimeOwnedPendingExecutorMaterialization as ea, generateSpanId as ei, claimsAuthority as en, isTraceAnalysisStore as er, hostDirectoryReader as et, runDriverWithRetry as f, createSandboxToolPartState as fa, captureWorktreeDiff as fi, readCodexRolloutSession as fn, bridgeRuntimeAttachmentsKey as fr, queueOf as ft, driverExecutorFactory as g, mapSandboxEvent as ga, LOCAL_HARNESSES as gi, isTerminalDecision as gn, recoverRetainedRun as gr, CONTINUATIONS_DIR as gt, driverChild as h, isSandboxTerminalEvent as ha, DEFAULT_LOCAL_HARNESS as hi, defaultSelectWinner as hn, reconnectRetainedRun as hr, mapExecutorResult as ht, bestDelivered as i, executableAgentProfileSnapshot as ia, toOtelAttributes as ii, peerMailVerbNames as in, BudgetReconcileFault as ir, providerVisibleProfile as it, settledToIteration as j, promptModelProfileMaterialization as ji, createPushTraceSource as jn, readHarnessTranscript as jr, cliInPlaceExecutor as jt, restoreScopeOwnerAcceptedExecution as k, profileMaterializationAxes$1 as ki, providerAsSandboxClient as kn, harnessTranscriptArtifact as kr, bindReusableExecutorExecutionId as kt, DriverAttemptsExhaustedError as l, readSandboxOutcome as la, sanitizeRuntimeStreamEvent as li, addHarnessUsage as ln, newUsageTotals as lr, recoverRetainedInteractiveRun as lt, upstreamUnavailableSignal as m, extractLlmCallEvent as ma, removeWorktree as mi, createSandboxForSpec as mn, errMessage as mr, gateOnDeliverable as mt, createRootHandle as n, unknownExecutionBindingReceipt as na, padSpanId as ni, isPeerMailEnvelope as nn, workerTraceAnalysisStore as nr, coordinationMcpAlias as nt, pickBestDelivered as o, detachedFrozen as oa, createRuntimeStreamEventCollector as oi, isTerminalNodeStatus as on, assertValidBudget as or, attachWorker as ot, summarizeDriverAttempts as p, createSandboxUsageLedger as pa, createWorktree as pi, TERMINAL_DECISIONS as pn, bridgeStopSignalKey as pr, rollingDispatch as pt, scopeRetainedOwnerPriorSpend as q, newExecutionAttemptId as qi, replaySpawnTree as qn, resolveRedactor as qr, DEFAULT_STALL_AFTER_MS as qt, createSupervisor as r, unknownMaterializationReceipt as ra, padTraceId as ri, peerMailTools as rn, executorFailure as rr, coordinationProfileToolPrefix as rt, runFinalizer as s, detachedSnapshot as sa, sanitizeAgentRuntimeEvent as si, bridgeAdmissionRefusal as sn, createBudgetPool as sr, readWorkerInteractiveBinding as st, DEFAULT_MAX_DEPTH as t, runtimeOwnedScopeOwnerRuntime as ta, loopEventToOtelSpan as ti, createPeerMailbox as tn, parseWorkerToolTraceArtifact as tr, resolveSpawnResourcePaths as tt, HarnessTurnFailedError as u, assertSandboxServedModel as ua, runSettledCommand as ui, createCodexRolloutStoreReader as un, spendFromUsageEvents as ur, startRetainedInteractiveRun as ut, withDriverExecutor as v, notifySandboxEventObserver as va, harnessSupportsReasoningEffort as vi, createSandboxLineage as vn, startRetainedRunInEnvironment as vr, CheckUnavailableError as vt, meterRuntimeOwnedAccounting as w, awaitAbortable$1 as wa, assertProfileMaterialization as wi, routerBrain as wn, RunCancellationReason as wr, distillFindings as wt, beginScopeOwnerAttempt as x, sumSandboxUsage as xa, CodexExecutionDiagnosticError as xi, captureBeforeDestroy as xn, environmentGone as xr, bestComposite as xt, SUBTREE_RESULT_LIMIT as y, sandboxEventServedBackend as ya, localHarnessExecutable as yi, acquireSandbox as yn, retainedCreateMaterial as yr, admitContinuationPolicy as yt, bindScopeRetainedOwnerProvider as z, worktreeCliProfileMaterialization as zi, TRACE_SUMMARY_SCHEMA as zn, routerTokenPrice as zr, createRouterTranscript as zt };
31353
31538
 
31354
- //# sourceMappingURL=supervisor-bkq2b8k-.js.map
31539
+ //# sourceMappingURL=supervisor-BMMdI4T-.js.map