@tangle-network/agent-runtime 0.225.0 → 0.225.3
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/dist/{activation-CKlpXoDU.js → activation-C7i-w3kS.js} +2 -2
- package/dist/{activation-CKlpXoDU.js.map → activation-C7i-w3kS.js.map} +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +2 -2
- package/dist/{coordination-driver-GFI-HzJX.js → coordination-driver-DcwOMS5C.js} +2 -2
- package/dist/{coordination-driver-GFI-HzJX.js.map → coordination-driver-DcwOMS5C.js.map} +1 -1
- package/dist/{delegate-DiH4-45Z.js → delegate-C9B_prgp.js} +2 -2
- package/dist/{delegate-DiH4-45Z.js.map → delegate-C9B_prgp.js.map} +1 -1
- package/dist/durable.d.ts +1 -1
- package/dist/durable.js +2 -2
- package/dist/{graph-CiGsa580.js → graph-B_6SZzlE.js} +4 -4
- package/dist/{graph-CiGsa580.js.map → graph-B_6SZzlE.js.map} +1 -1
- package/dist/{improvement-cycle-BFdb4lCd.js → improvement-cycle-DmuqSX6_.js} +4 -4
- package/dist/{improvement-cycle-BFdb4lCd.js.map → improvement-cycle-DmuqSX6_.js.map} +1 -1
- package/dist/{index-C2T1Z3jZ.d.ts → index-ClXIBpKe.d.ts} +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +8 -8
- package/dist/intelligence.js +3 -3
- package/dist/kernel.d.ts +1 -1
- package/dist/kernel.js +9 -9
- package/dist/{loop-runner-bin-BMCpT2i0.d.ts → loop-runner-bin-BRfsk-9d.d.ts} +2 -2
- package/dist/{loop-runner-bin-3ERWSHxx.js → loop-runner-bin-Jxq-BUGo.js} +3 -3
- package/dist/{loop-runner-bin-3ERWSHxx.js.map → loop-runner-bin-Jxq-BUGo.js.map} +1 -1
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +1 -1
- package/dist/mcp/index.js +5 -5
- package/dist/{model-policy-DKDyr-fc.js → model-policy-BbSCSak0.js} +4 -4
- package/dist/model-policy-BbSCSak0.js.map +1 -0
- package/dist/profiles.js +1 -1
- package/dist/{provision-supervisor-DD9Xc1as.js → provision-supervisor-ChEnL5xX.js} +8 -35
- package/dist/provision-supervisor-ChEnL5xX.js.map +1 -0
- package/dist/{runtime-CL6nVSEt.js → runtime-BVV9PbmE.js} +24 -24
- package/dist/runtime-BVV9PbmE.js.map +1 -0
- package/dist/{server-BWDo2UNM.js → server-Cf0_J9nZ.js} +3 -3
- package/dist/{server-BWDo2UNM.js.map → server-Cf0_J9nZ.js.map} +1 -1
- package/dist/{structural-rollout-Bs6IfZ8d.js → structural-rollout-C_tpSY6Y.js} +6 -7
- package/dist/structural-rollout-C_tpSY6Y.js.map +1 -0
- package/dist/{supervise-DYZVP44H.js → supervise-Ah7kMn2p.js} +9 -15
- package/dist/supervise-Ah7kMn2p.js.map +1 -0
- package/dist/{supervisor-DBzsb6Qt.js → supervisor-0ksHf44Z.js} +230 -172
- package/dist/supervisor-0ksHf44Z.js.map +1 -0
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +12 -12
- package/dist/tui/index.d.ts +1 -1
- package/dist/tui/index.js +1 -1
- package/package.json +1 -1
- package/dist/model-policy-DKDyr-fc.js.map +0 -1
- package/dist/provision-supervisor-DD9Xc1as.js.map +0 -1
- package/dist/runtime-CL6nVSEt.js.map +0 -1
- package/dist/structural-rollout-Bs6IfZ8d.js.map +0 -1
- package/dist/supervise-DYZVP44H.js.map +0 -1
- package/dist/supervisor-DBzsb6Qt.js.map +0 -1
package/dist/mcp/index.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Ai as sleep, Hn as mergeTraceEnv, Mi as throwAbort, Ni as throwIfAborted, Ti as deleteBoxSafe, Un as readTraceContextFromEnv, Vn as createPropagatingTraceEmitter, Wn as traceContextToEnv, _r as localHarnessExecutable, an as createSandboxForSpec, cn as runAgentRounds, dr as captureWorktreeDiff, fn as assertBoxlessPromptOptions, fr as createWorktree, gr as harnessSupportsReasoningEffort, hr as LOCAL_HARNESSES, mr as DEFAULT_LOCAL_HARNESS, pr as removeWorktree, ur as runWorktreeHarness, vr as parseCodexTokenUsage, yr as CodexExecutionDiagnosticError } from "../supervisor-0ksHf44Z.js";
|
|
2
2
|
import { i as ConfigError, m as ValidationError } from "../errors-DodWX-cb.js";
|
|
3
|
-
import { t as assertExecutableAgentProfile } from "../model-policy-
|
|
4
|
-
import { E as runCoderChecks, ot as selectValidWinner } from "../runtime-
|
|
3
|
+
import { t as assertExecutableAgentProfile } from "../model-policy-BbSCSak0.js";
|
|
4
|
+
import { E as runCoderChecks, ot as selectValidWinner } from "../runtime-BVV9PbmE.js";
|
|
5
5
|
import { t as createStdioToolServer } from "../tool-server-BJbCPhoW.js";
|
|
6
|
-
import { C as ANALYST_DEFINITION_BOUNDS, M as questionEscalationTargets, O as createCoordinationTools, T as analystToolGroupNames, j as parseAuthoredAnalystDefinition, k as downMessageRefusalReasons, w as DEFAULT_AWAIT_EVENT_TIMEOUT_MS } from "../coordination-driver-
|
|
6
|
+
import { C as ANALYST_DEFINITION_BOUNDS, M as questionEscalationTargets, O as createCoordinationTools, T as analystToolGroupNames, j as parseAuthoredAnalystDefinition, k as downMessageRefusalReasons, w as DEFAULT_AWAIT_EVENT_TIMEOUT_MS } from "../coordination-driver-DcwOMS5C.js";
|
|
7
7
|
import { t as createKbGate } from "../kb-gate-DpaSwXVx.js";
|
|
8
8
|
import { _ as InMemoryFeedbackStore, a as validateDelegationStatusArgs, c as DELEGATION_HISTORY_TOOL_NAME, d as delegationProfiles, f as DELEGATE_FEEDBACK_DESCRIPTION, g as validateDelegateFeedbackArgs, h as createDelegateFeedbackHandler, i as createDelegationStatusHandler, l as createDelegationHistoryHandler, m as DELEGATE_FEEDBACK_TOOL_NAME, n as DELEGATION_STATUS_INPUT_SCHEMA, o as DELEGATION_HISTORY_DESCRIPTION, p as DELEGATE_FEEDBACK_INPUT_SCHEMA, r as DELEGATION_STATUS_TOOL_NAME, s as DELEGATION_HISTORY_INPUT_SCHEMA, t as DELEGATION_STATUS_DESCRIPTION, u as validateDelegationHistoryArgs, v as eventToSnapshot } from "../delegation-status-CF4D0NZ_.js";
|
|
9
9
|
import { n as mcpToolsForRuntimeMcpSubset, t as mcpToolsForRuntimeMcp } from "../openai-tools-DoQ32vpe.js";
|
|
10
10
|
import { t as coderTaskToPrompt } from "../coder-yhVWbdWc.js";
|
|
11
|
-
import { C as composeLoopTraceEmitters, S as capDelegationTrace, _ as FileDelegationStore, a as DELEGATE_UI_AUDIT_TOOL_NAME, b as DELEGATION_TRACE_MAX_SPANS, c as DELEGATE_DESCRIPTION, d as createDelegateHandler, f as validateDelegateArgs, g as DelegationStateCorruptError, h as DelegationPersistenceError, i as DELEGATE_UI_AUDIT_INPUT_SCHEMA, l as DELEGATE_INPUT_SCHEMA, m as hashIdempotencyInput, n as createMcpServer, o as createDelegateUiAuditHandler, p as DelegationTaskQueue, r as DELEGATE_UI_AUDIT_DESCRIPTION, s as validateDelegateUiAuditArgs, t as createInProcessTransport, u as DELEGATE_TOOL_NAME, v as InMemoryDelegationStore, w as createDelegationTraceCollector, x as buildDelegationTraceSpans, y as DELEGATION_TRACE_MAX_BYTES } from "../server-
|
|
11
|
+
import { C as composeLoopTraceEmitters, S as capDelegationTrace, _ as FileDelegationStore, a as DELEGATE_UI_AUDIT_TOOL_NAME, b as DELEGATION_TRACE_MAX_SPANS, c as DELEGATE_DESCRIPTION, d as createDelegateHandler, f as validateDelegateArgs, g as DelegationStateCorruptError, h as DelegationPersistenceError, i as DELEGATE_UI_AUDIT_INPUT_SCHEMA, l as DELEGATE_INPUT_SCHEMA, m as hashIdempotencyInput, n as createMcpServer, o as createDelegateUiAuditHandler, p as DelegationTaskQueue, r as DELEGATE_UI_AUDIT_DESCRIPTION, s as validateDelegateUiAuditArgs, t as createInProcessTransport, u as DELEGATE_TOOL_NAME, v as InMemoryDelegationStore, w as createDelegationTraceCollector, x as buildDelegationTraceSpans, y as DELEGATION_TRACE_MAX_BYTES } from "../server-Cf0_J9nZ.js";
|
|
12
12
|
import { a as createMemoryToolServer, c as resolveMemoryFromEnv, i as MEMORY_NAME_ENV, n as MEMORY_ITEMS_ENV, o as parseMemoryItems, r as MEMORY_LOG_ENV, s as readMemoryItemsFile, t as MEMORY_FILE_ENV } from "../memory-server-BR310Weg.js";
|
|
13
13
|
import { agentProfileSchema } from "@tangle-network/agent-interface";
|
|
14
14
|
import { randomUUID } from "node:crypto";
|
|
@@ -53,7 +53,7 @@ function resolveRouterRetryPolicy(input, context) {
|
|
|
53
53
|
const maxAttempts = positiveInteger$1(policy.maxAttempts, 5, `${context}.maxAttempts`);
|
|
54
54
|
const initialBackoffMs = timerInteger(policy.initialBackoffMs, 1e3, `${context}.initialBackoffMs`);
|
|
55
55
|
const maxBackoffMs = timerInteger(policy.maxBackoffMs, 3e4, `${context}.maxBackoffMs`);
|
|
56
|
-
const requestTimeoutMs = timerInteger(policy.requestTimeoutMs, 0, `${context}.requestTimeoutMs
|
|
56
|
+
const requestTimeoutMs = timerInteger(policy.requestTimeoutMs, 0, `${context}.requestTimeoutMs`, Number.MAX_SAFE_INTEGER - Date.now());
|
|
57
57
|
const jitter = policy.jitter ?? .25;
|
|
58
58
|
if (typeof jitter !== "number" || !Number.isFinite(jitter) || jitter < 0 || jitter > 1) throw new ValidationError(`${context}.jitter must be a finite number from 0 through 1`);
|
|
59
59
|
const retryStatuses = parseRetryStatuses(policy.retryStatuses, context);
|
|
@@ -84,9 +84,9 @@ function positiveInteger$1(value, fallback, context) {
|
|
|
84
84
|
if (typeof parsed !== "number" || !Number.isSafeInteger(parsed) || parsed < 1) throw new ValidationError(`${context} must be a positive safe integer`);
|
|
85
85
|
return parsed;
|
|
86
86
|
}
|
|
87
|
-
function timerInteger(value, fallback, context) {
|
|
87
|
+
function timerInteger(value, fallback, context, maximum = maximumTimerMs) {
|
|
88
88
|
const parsed = value ?? fallback;
|
|
89
|
-
if (typeof parsed !== "number" || !Number.isSafeInteger(parsed) || parsed < 0 || parsed >
|
|
89
|
+
if (typeof parsed !== "number" || !Number.isSafeInteger(parsed) || parsed < 0 || parsed > maximum) throw new ValidationError(`${context} must be a nonnegative safe integer no greater than ${maximum}`);
|
|
90
90
|
return parsed;
|
|
91
91
|
}
|
|
92
92
|
//#endregion
|
|
@@ -300,4 +300,4 @@ function assertProfileModelsAllowed(profile, allowed) {
|
|
|
300
300
|
//#endregion
|
|
301
301
|
export { concreteProfileModel as a, profileModelExecutionSettings as c, agentHarness as d, harnessRunsAgent as f, concreteModelId as i, profileProviderModel as l, assertModelAllowed as n, enforceTokenLimits as o, assertProfileModelsAllowed as r, profileBridgeWireModel as s, assertExecutableAgentProfile as t, resolveRouterRetryPolicy as u };
|
|
302
302
|
|
|
303
|
-
//# sourceMappingURL=model-policy-
|
|
303
|
+
//# sourceMappingURL=model-policy-BbSCSak0.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"model-policy-BbSCSak0.js","names":["positiveInteger"],"sources":["../src/runtime/harness-role.ts","../src/runtime/router-retry-policy.ts","../src/runtime/supervise/model-policy.ts"],"sourcesContent":["/**\n * Which `HarnessType` values name a real coding-agent runtime, and which name a MODE that has no\n * agent behind it.\n *\n * `cli-base` is the router-backed mode — a plain multi-turn router call with no coding-agent\n * harness (`@tangle-network/agent-interface`'s `HarnessType` doc, and the same table's\n * `harnessReasoningCeiling['cli-base'] = 'none'` commented \"cli-base has no agent\"). The\n * distinction is REAL; what was accidental is that three call sites each spelled the test\n * themselves, so a second no-agent mode would have to be remembered in three places.\n *\n * SHOULD UPSTREAM: this belongs next to `harnessHonorsEffort` in agent-interface's\n * `harness-capabilities.ts`, which already encodes the fact but exports no predicate for it.\n * Until it does, this is the one local copy — extend the set here, never re-test the name.\n */\n\nimport type { HarnessType } from '@tangle-network/agent-interface'\n\n/**\n * Harness ids that select a router/no-agent mode rather than a coding-agent runtime.\n *\n * `nanoclaw` is deliberately ABSENT: the shared capability table clamps its reasoning ceiling the\n * same way it clamps `cli-base`, but nanoclaw does run an agent (a socket-bridge runner to the\n * NanoClaw daemon) and every caller here treats it as a full harness. Add a row only with the\n * behavior change stated, never to make the two clamps look symmetric.\n */\nconst NO_AGENT_HARNESSES: ReadonlySet<string> = new Set<string>(['cli-base' satisfies HarnessType])\n\n/** Whether this profile harness selects a real coding-agent runtime (vs. the router/no-agent mode\n * or no preference at all). Accepts the looser `string` some local profile shapes declare, and\n * preserves the caller's own harness type when it is narrower. */\nexport function harnessRunsAgent<T extends string>(harness: T | null | undefined): harness is T {\n return harness != null && !NO_AGENT_HARNESSES.has(harness)\n}\n\n/** The coding-agent harness this profile selects, or `undefined` when it selects none — the shape\n * callers want when a no-agent mode must fall through to the router arm. */\nexport function agentHarness<T extends string>(harness: T | null | undefined): T | undefined {\n return harnessRunsAgent(harness) ? harness : undefined\n}\n","import { ValidationError } from '../errors'\n\n/** Exact retry controls accepted at `AgentProfile.model.metadata.retry`. */\nexport interface RouterRetryPolicy {\n /** Total attempts, including the first request. */\n readonly maxAttempts?: number\n /** Delay before the second attempt. Later delays grow exponentially. */\n readonly initialBackoffMs?: number\n /** Maximum delay between attempts. */\n readonly maxBackoffMs?: number\n /** Symmetric random variation around each delay, from 0 through 1. */\n readonly jitter?: number\n /** HTTP statuses that may be retried. */\n readonly retryStatuses?: ReadonlyArray<number>\n /** Deadline for receiving one attempt's response headers. Zero disables it. */\n readonly requestTimeoutMs?: number\n}\n\nexport interface ResolvedRouterRetryPolicy {\n readonly maxAttempts: number\n readonly initialBackoffMs: number\n readonly maxBackoffMs: number\n readonly jitter: number\n readonly retryStatuses: ReadonlyArray<number>\n readonly requestTimeoutMs: number\n}\n\nconst maximumTimerMs = 2_147_483_647\nconst defaultRetryStatuses = Object.freeze([408, 425, 429, 500, 502, 503, 504, 520, 522, 524])\nconst retryPolicyKeys = new Set([\n 'initialBackoffMs',\n 'jitter',\n 'maxAttempts',\n 'maxBackoffMs',\n 'requestTimeoutMs',\n 'retryStatuses',\n])\n\n/** Parse untrusted profile/config data once and return an immutable complete policy. */\nexport function resolveRouterRetryPolicy(\n input: unknown,\n context: string,\n): ResolvedRouterRetryPolicy {\n if (\n input !== undefined &&\n (typeof input !== 'object' || input === null || Array.isArray(input))\n ) {\n throw new ValidationError(`${context} must be an object`)\n }\n const policy = input === undefined ? {} : Object.fromEntries(Object.entries(input))\n const unknown = Object.keys(policy).filter((key) => !retryPolicyKeys.has(key))\n if (unknown.length > 0) {\n throw new ValidationError(`${context} has unsupported fields: ${unknown.join(', ')}`)\n }\n const maxAttempts = positiveInteger(policy.maxAttempts, 5, `${context}.maxAttempts`)\n const initialBackoffMs = timerInteger(\n policy.initialBackoffMs,\n 1_000,\n `${context}.initialBackoffMs`,\n )\n const maxBackoffMs = timerInteger(policy.maxBackoffMs, 30_000, `${context}.maxBackoffMs`)\n const requestTimeoutMs = timerInteger(\n policy.requestTimeoutMs,\n 0,\n `${context}.requestTimeoutMs`,\n Number.MAX_SAFE_INTEGER - Date.now(),\n )\n const jitter = policy.jitter ?? 0.25\n if (typeof jitter !== 'number' || !Number.isFinite(jitter) || jitter < 0 || jitter > 1) {\n throw new ValidationError(`${context}.jitter must be a finite number from 0 through 1`)\n }\n const retryStatuses = parseRetryStatuses(policy.retryStatuses, context)\n return Object.freeze({\n maxAttempts,\n initialBackoffMs,\n maxBackoffMs,\n jitter,\n retryStatuses,\n requestTimeoutMs,\n })\n}\n\nfunction parseRetryStatuses(value: unknown, context: string): ReadonlyArray<number> {\n if (value === undefined) return defaultRetryStatuses\n if (!Array.isArray(value)) {\n throw new ValidationError(`${context}.retryStatuses must be an array of HTTP statuses`)\n }\n const statuses: number[] = []\n const seen = new Set<number>()\n for (const status of value) {\n if (!Number.isSafeInteger(status) || status < 100 || status > 599) {\n throw new ValidationError(\n `${context}.retryStatuses must contain integer HTTP statuses from 100 through 599`,\n )\n }\n if (seen.has(status)) {\n throw new ValidationError(`${context}.retryStatuses must not contain duplicates`)\n }\n seen.add(status)\n statuses.push(status)\n }\n return Object.freeze(statuses)\n}\n\nfunction positiveInteger(value: unknown, fallback: number, context: string): number {\n const parsed = value ?? fallback\n if (typeof parsed !== 'number' || !Number.isSafeInteger(parsed) || parsed < 1) {\n throw new ValidationError(`${context} must be a positive safe integer`)\n }\n return parsed\n}\n\nfunction timerInteger(\n value: unknown,\n fallback: number,\n context: string,\n maximum = maximumTimerMs,\n): number {\n const parsed = value ?? fallback\n if (\n typeof parsed !== 'number' ||\n !Number.isSafeInteger(parsed) ||\n parsed < 0 ||\n parsed > maximum\n ) {\n throw new ValidationError(\n `${context} must be a nonnegative safe integer no greater than ${maximum}`,\n )\n }\n return parsed\n}\n","/**\n * `assertModelAllowed` — a fail-loud guard that restricts a run to a chosen subset of\n * models. The two front doors (`supervise()` / `improve()`) call it once per configured\n * model at resolve time, so a run that names a model outside the allowed set throws before\n * any compute is spent — never silently swapped or silently allowed.\n */\nimport { HARNESS_NATIVE_MODEL } from '@tangle-network/agent-eval'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { ConfigError } from '../../errors'\nimport { agentHarness } from '../harness-role'\nimport { type ResolvedRouterRetryPolicy, resolveRouterRetryPolicy } from '../router-retry-policy'\n\n/**\n * Return the model id an executor may send to a provider.\n *\n * Eval stamps {@link HARNESS_NATIVE_MODEL} into a profile when model selection is deliberately\n * delegated to the configured runtime. That marker belongs in experiment identity and cost\n * admission; it is not a provider model id.\n */\nexport function concreteModelId(model: string | undefined): string | undefined {\n if (model === undefined) return undefined\n const id = model.trim()\n return id.length > 0 && !isHarnessNativeModel(id) ? id : undefined\n}\n\n/** Whether a model value delegates selection to the chosen execution system. */\nexport function isHarnessNativeModel(model: string | undefined): boolean {\n return model?.trim() === HARNESS_NATIVE_MODEL\n}\n\n/** Return a profile's explicitly selected provider model, if it has one. */\nexport function concreteProfileModel(profile: Pick<AgentProfile, 'model'>): string | undefined {\n return concreteModelId(profile.model?.default)\n}\n\n/**\n * Return the model id for a direct provider request.\n *\n * A portable profile can qualify its model with the selected provider. The direct endpoint already\n * selects that provider, so remove only the exact matching prefix. Preserve every other prefix\n * because it can identify a provider-owned nested route, such as `anthropic/claude-sonnet`.\n */\nexport function profileProviderModel(profile: Pick<AgentProfile, 'model'>): string | undefined {\n const model = concreteProfileModel(profile)\n const provider = profile.model?.provider?.trim()\n if (!model || !provider || !model.startsWith(`${provider}/`)) return model\n return concreteModelId(model.slice(provider.length + 1))\n}\n\n/** The full cli-bridge wire id declared by a profile: harness/provider/model. */\nexport function profileBridgeWireModel(\n profile: Pick<AgentProfile, 'harness' | 'model'>,\n): string | undefined {\n const model = concreteProfileModel(profile)\n const provider = profile.model?.provider\n const harness = agentHarness(profile.harness)\n const modelWithoutHarness =\n model && harness && model.startsWith(`${harness}/`) ? model.slice(harness.length + 1) : model\n const providerModel = modelWithoutHarness\n ? provider && !modelWithoutHarness.startsWith(`${provider}/`)\n ? `${provider}/${modelWithoutHarness}`\n : modelWithoutHarness\n : undefined\n if (!harness) return providerModel\n if (!providerModel) return harness\n return providerModel.startsWith(`${harness}/`) ? providerModel : `${harness}/${providerModel}`\n}\n\n/**\n * Refuse an incomplete execution identity before any backend may fill it from ambient config.\n * `AgentProfile` is the sole behavioral authority: harness, provider, and concrete model all\n * participate in its digest. Eval's runtime-selected marker is a matrix-planning value, never an\n * executable model.\n */\nexport function assertExecutableAgentProfile(profile: AgentProfile, context: string): void {\n if (profile.harness === undefined) {\n throw new ConfigError(`${context}: AgentProfile.harness must be explicit before execution`)\n }\n const declared = profile.model?.default\n const model = concreteModelId(declared)\n if (!model) {\n const reason = isHarnessNativeModel(declared) ? 'runtime-selected' : 'missing'\n throw new ConfigError(\n `${context}: AgentProfile.model.default is ${reason}; execution requires a concrete model`,\n )\n }\n if (!profile.model?.provider?.trim()) {\n throw new ConfigError(\n `${context}: AgentProfile.model.provider must be explicit before execution`,\n )\n }\n}\n\n/**\n * Separate completion ceilings an exact profile may request.\n *\n * They are distinct because providers do not share one meaning for a single number: measured\n * through the Tangle Router on 2026-08-10, `glm-5.2` accepted `max_tokens: 8` and still billed 135\n * completion tokens — 132 reasoning, 3 visible — while `max_completion_tokens: 256` bounded the\n * total. A path that cannot enforce a requested ceiling refuses the run instead of sending a\n * number that means something else there.\n */\nexport interface ProfileTokenLimits {\n /** Visible answer tokens, from `AgentProfile.model.maxVisibleOutputTokens`. */\n readonly visible?: number\n /** Hidden reasoning tokens, from `AgentProfile.model.maxReasoningTokens`. */\n readonly reasoning?: number\n /** Visible and reasoning tokens together, from `AgentProfile.model.maxTotalOutputTokens`. */\n readonly total?: number\n}\n\n/** The ceilings one execution path actually sends, in the request fields it sends them as. */\nexport interface AppliedTokenLimits {\n /** Sent as `max_tokens`. */\n readonly maxTokens?: number\n /** Sent as `max_completion_tokens`. */\n readonly maxCompletionTokens?: number\n}\n\n/** What a path was asked to enforce and what it sent, for the execution receipt. */\nexport interface TokenLimitDecision {\n readonly requested: ProfileTokenLimits\n readonly applied: AppliedTokenLimits\n}\n\n/** The execution paths that lower a profile into a provider request. */\nexport type ModelExecutionPath = 'router' | 'bridge' | 'sandbox' | 'provider'\n\n/** Generation and loop controls that may affect one model execution. */\nexport interface ProfileModelExecutionSettings {\n readonly temperature?: number\n /** Completion ceilings the profile requested. Empty when it requested none. */\n readonly tokenLimits: ProfileTokenLimits\n readonly retry?: ResolvedRouterRetryPolicy\n readonly seed?: number\n readonly toolChoice?: 'auto' | 'required' | 'none'\n readonly extraBody?: Readonly<Record<string, unknown>>\n /** Zero means no turn-count cap; conserved budgets and deadlines still apply. */\n readonly maxTurns?: number\n readonly stream?: boolean\n}\n\nconst PROFILE_MODEL_METADATA_KEYS = new Set([\n 'extraBody',\n 'maxTurns',\n 'retry',\n 'seed',\n 'stream',\n 'temperature',\n 'toolChoice',\n])\n\n/**\n * Read every Router-affecting control from the exact profile and reject unknown controls.\n * Backends receive endpoint/auth and executable ports only; they cannot silently alter behavior.\n */\nexport function profileModelExecutionSettings(\n profile: Pick<AgentProfile, 'model'>,\n context: string,\n): ProfileModelExecutionSettings {\n const metadata = profile.model?.metadata ?? {}\n if (metadata.maxTokens !== undefined) {\n throw new ConfigError(\n `${context}: AgentProfile.model.metadata.maxTokens is ambiguous across providers; declare AgentProfile.model.maxVisibleOutputTokens, maxReasoningTokens, or maxTotalOutputTokens instead`,\n )\n }\n const unknown = Object.keys(metadata).filter((key) => !PROFILE_MODEL_METADATA_KEYS.has(key))\n if (unknown.length > 0) {\n throw new ConfigError(\n `${context}: unsupported AgentProfile.model.metadata fields: ${unknown.join(', ')}`,\n )\n }\n const temperature = finiteNumber(metadata.temperature, `${context}: temperature`)\n const tokenLimits = profileTokenLimits(profile, context)\n const retryInput = metadata.retry\n const retry =\n retryInput === undefined\n ? undefined\n : resolveRouterRetryPolicy(retryInput, `${context}: AgentProfile.model.metadata.retry`)\n const seed = safeInteger(metadata.seed, `${context}: seed`)\n const maxTurns = nonnegativeInteger(metadata.maxTurns, `${context}: maxTurns`)\n const stream = optionalBoolean(metadata.stream, `${context}: stream`)\n const toolChoice = metadata.toolChoice\n if (\n toolChoice !== undefined &&\n toolChoice !== 'auto' &&\n toolChoice !== 'required' &&\n toolChoice !== 'none'\n ) {\n throw new ConfigError(`${context}: toolChoice must be auto, required, or none`)\n }\n const extraBody = metadata.extraBody\n if (\n extraBody !== undefined &&\n (typeof extraBody !== 'object' || extraBody === null || Array.isArray(extraBody))\n ) {\n throw new ConfigError(`${context}: extraBody must be an object`)\n }\n return {\n ...(temperature !== undefined ? { temperature } : {}),\n tokenLimits,\n ...(retry !== undefined ? { retry } : {}),\n ...(seed !== undefined ? { seed } : {}),\n ...(toolChoice !== undefined ? { toolChoice } : {}),\n ...(extraBody !== undefined\n ? { extraBody: Object.freeze({ ...(extraBody as Record<string, unknown>) }) }\n : {}),\n ...(maxTurns !== undefined ? { maxTurns } : {}),\n ...(stream !== undefined ? { stream } : {}),\n }\n}\n\n/**\n * Read the completion ceilings an exact profile declares. The Interface schema already refines\n * these fields, but a profile can reach an executor without a parse, so the same rules are\n * enforced here: positive integers, and no single ceiling above the total.\n */\nexport function profileTokenLimits(\n profile: Pick<AgentProfile, 'model'>,\n context: string,\n): ProfileTokenLimits {\n const model = profile.model\n const visible = positiveInteger(\n model?.maxVisibleOutputTokens,\n `${context}: maxVisibleOutputTokens`,\n )\n const reasoning = positiveInteger(model?.maxReasoningTokens, `${context}: maxReasoningTokens`)\n const total = positiveInteger(model?.maxTotalOutputTokens, `${context}: maxTotalOutputTokens`)\n if (total !== undefined) {\n for (const [name, value] of [\n ['maxVisibleOutputTokens', visible],\n ['maxReasoningTokens', reasoning],\n ] as const) {\n if (value !== undefined && value > total) {\n throw new ConfigError(\n `${context}: AgentProfile.model.${name} (${value}) exceeds maxTotalOutputTokens (${total})`,\n )\n }\n }\n }\n return {\n ...(visible !== undefined ? { visible } : {}),\n ...(reasoning !== undefined ? { reasoning } : {}),\n ...(total !== undefined ? { total } : {}),\n }\n}\n\n/**\n * Lower the requested ceilings onto one execution path, or refuse the run before any paid\n * transport.\n *\n * - Router and OpenAI-compatible routes send the visible ceiling as `max_tokens` and the total as\n * `max_completion_tokens`.\n * - The CLI Bridge lowers ONE completion cap into the run's model catalog, so it carries the total\n * as `max_tokens` and cannot bound the visible half on its own.\n * - The Sandbox and environment-provider paths expose no completion cap at all.\n * - No route publishes a reasoning-token budget, so a reasoning ceiling is refused everywhere.\n * `AgentProfile.model.reasoningEffort` is an intensity dial, not a token bound.\n */\nexport function enforceTokenLimits(\n limits: ProfileTokenLimits,\n path: ModelExecutionPath,\n context: string,\n): TokenLimitDecision {\n const refuse = (field: string, reason: string): never => {\n throw new ConfigError(\n `${context}: AgentProfile.model.${field} cannot be enforced on the ${path} path (${reason}); remove the ceiling or select a path that enforces it`,\n )\n }\n if (limits.reasoning !== undefined) {\n refuse('maxReasoningTokens', 'no route exposes a reasoning-token budget')\n }\n if (path === 'router') {\n return {\n requested: limits,\n applied: {\n ...(limits.visible !== undefined ? { maxTokens: limits.visible } : {}),\n ...(limits.total !== undefined ? { maxCompletionTokens: limits.total } : {}),\n },\n }\n }\n if (path === 'bridge') {\n if (limits.visible !== undefined) {\n refuse('maxVisibleOutputTokens', 'the bridge lowers one completion cap covering both halves')\n }\n return {\n requested: limits,\n applied: {\n ...(limits.total !== undefined ? { maxTokens: limits.total } : {}),\n },\n }\n }\n if (limits.visible !== undefined) refuse('maxVisibleOutputTokens', 'the backend accepts no cap')\n if (limits.total !== undefined) refuse('maxTotalOutputTokens', 'the backend accepts no cap')\n return { requested: limits, applied: {} }\n}\n\n/** The receipt form of one path's ceilings: what was asked for, and what was sent. */\nexport function tokenLimitReceipt(decision: TokenLimitDecision): {\n readonly requested: ProfileTokenLimits\n readonly applied: AppliedTokenLimits\n} {\n return { requested: decision.requested, applied: decision.applied }\n}\n\nfunction finiteNumber(value: unknown, context: string): number | undefined {\n if (value === undefined) return undefined\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new ConfigError(`${context} must be a finite number`)\n }\n return value\n}\n\nfunction safeInteger(value: unknown, context: string): number | undefined {\n if (value === undefined) return undefined\n if (!Number.isSafeInteger(value)) throw new ConfigError(`${context} must be a safe integer`)\n return value as number\n}\n\nfunction positiveInteger(value: unknown, context: string): number | undefined {\n const parsed = safeInteger(value, context)\n if (parsed !== undefined && parsed < 1) {\n throw new ConfigError(`${context} must be positive`)\n }\n return parsed\n}\n\nfunction nonnegativeInteger(value: unknown, context: string): number | undefined {\n const parsed = safeInteger(value, context)\n if (parsed !== undefined && parsed < 0) {\n throw new ConfigError(`${context} must be nonnegative`)\n }\n return parsed\n}\n\nfunction optionalBoolean(value: unknown, context: string): boolean | undefined {\n if (value === undefined) return undefined\n if (typeof value !== 'boolean') throw new ConfigError(`${context} must be boolean`)\n return value\n}\n\n/**\n * Throw a `ConfigError` when `allowed` is set, `model` is defined, and `model` is not a\n * member of `allowed`. No-op when `allowed` is unset (the unrestricted default) or when\n * `model` is undefined (nothing was configured to check).\n */\nexport function assertModelAllowed(\n model: string | undefined,\n allowed: readonly string[] | undefined,\n): void {\n if (!allowed || model === undefined) return\n if (!allowed.includes(model)) {\n throw new ConfigError(\n `model ${JSON.stringify(model)} is not in the allowed set ${JSON.stringify([...allowed])}`,\n )\n }\n}\n\n/** Check every canonical model-bearing field in a complete profile, including the models a\n * backend may select for cheap work, named subagents, or modes.\n *\n * Every compared value is a bare model id. The composed `harness/provider/model` wire id\n * (`profileBridgeWireModel`) is neither built nor compared here, so this admits any route that\n * declares an allowed id, and a qualified entry in `allowed` matches nothing. Route pinning\n * belongs to `SuperviseOptions.authorizeSpawn`. */\nexport function assertProfileModelsAllowed(\n profile: AgentProfile,\n allowed: readonly string[] | undefined,\n): void {\n assertModelAllowed(profile.model?.default, allowed)\n assertModelAllowed(profile.model?.small, allowed)\n for (const subagent of Object.values(profile.subagents ?? {})) {\n assertModelAllowed(subagent.model, allowed)\n }\n for (const mode of Object.values(profile.modes ?? {})) {\n assertModelAllowed(mode.model, allowed)\n }\n}\n"],"mappings":";;;;;;;;;;;AAyBA,MAAM,qCAA0C,IAAI,IAAY,CAAC,UAAgC,CAAC;;;;AAKlG,SAAgB,iBAAmC,SAA6C;CAC9F,OAAO,WAAW,QAAQ,CAAC,mBAAmB,IAAI,OAAO;AAC3D;;;AAIA,SAAgB,aAA+B,SAA8C;CAC3F,OAAO,iBAAiB,OAAO,IAAI,UAAU,KAAA;AAC/C;;;ACXA,MAAM,iBAAiB;AACvB,MAAM,uBAAuB,OAAO,OAAO;CAAC;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;AAAG,CAAC;AAC7F,MAAM,kCAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,SAAgB,yBACd,OACA,SAC2B;CAC3B,IACE,UAAU,KAAA,MACT,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,IAEnE,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C,GACzF;AAEJ;;;;;;;;AASA,SAAgB,2BACd,SACA,SACM;CACN,mBAAmB,QAAQ,OAAO,SAAS,OAAO;CAClD,mBAAmB,QAAQ,OAAO,OAAO,OAAO;CAChD,KAAK,MAAM,YAAY,OAAO,OAAO,QAAQ,aAAa,CAAC,CAAC,GAC1D,mBAAmB,SAAS,OAAO,OAAO;CAE5C,KAAK,MAAM,QAAQ,OAAO,OAAO,QAAQ,SAAS,CAAC,CAAC,GAClD,mBAAmB,KAAK,OAAO,OAAO;AAE1C"}
|
package/dist/profiles.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { i as ConfigError } from "./errors-DodWX-cb.js";
|
|
2
|
-
import { t as assertExecutableAgentProfile } from "./model-policy-
|
|
2
|
+
import { t as assertExecutableAgentProfile } from "./model-policy-BbSCSak0.js";
|
|
3
3
|
import { n as UI_LENSES, t as UI_FINDING_SEVERITIES } from "./substrate-B0TYNrXn.js";
|
|
4
4
|
import { t as coderTaskToPrompt } from "./coder-yhVWbdWc.js";
|
|
5
5
|
import { agentProfileSchema } from "@tangle-network/agent-interface";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { B as readWorkerInteractiveBinding,
|
|
2
|
-
import { a as concreteProfileModel } from "./model-policy-
|
|
1
|
+
import { Ai as sleep, An as abortError$1, B as readWorkerInteractiveBinding, Br as attestRuntimeOwnedPendingExecutor, Cn as sandboxClientAsProvider, Ft as taskToPrompt, G as startRetainedInteractiveRun, I as interactiveAdmissionSeamKey, K as destroyInteractiveEnvironment, Ln as retainedCreateMaterial, St as contentAddress, Ur as finalizeRuntimeOwnedPendingExecutor, Vi as abortError, Wi as armDeadlineTimer, ii as executableAgentProfileSnapshot, jn as linkAbort, n as createSupervisor, qr as newExecutionAttemptId, si as detachedSnapshot, t as createRootHandle, zt as createInbox } from "./supervisor-0ksHf44Z.js";
|
|
2
|
+
import { a as concreteProfileModel } from "./model-policy-BbSCSak0.js";
|
|
3
3
|
import { i as writeAtomicDurableFile } from "./durable-file-D24y9zg7.js";
|
|
4
|
-
import { O as createCoordinationTools, n as createSteerAcknowledger, t as createCancelAcknowledger, v as createFileRunContext } from "./coordination-driver-
|
|
4
|
+
import { O as createCoordinationTools, n as createSteerAcknowledger, t as createCancelAcknowledger, v as createFileRunContext } from "./coordination-driver-DcwOMS5C.js";
|
|
5
5
|
import { h as supervisorRunDir } from "./run-layout-hZREkcfu.js";
|
|
6
6
|
import { agentInteractiveSessionControlClaimRequestDigest, agentInteractiveSessionPromptRequestDigest, agentInteractiveSessionStopRequestDigest, agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest } from "@tangle-network/agent-interface";
|
|
7
7
|
import { randomUUID } from "node:crypto";
|
|
@@ -562,29 +562,6 @@ async function safeStatus(handle) {
|
|
|
562
562
|
if (timer !== void 0) clearTimeout(timer);
|
|
563
563
|
}
|
|
564
564
|
}
|
|
565
|
-
async function sleep(ms, signal) {
|
|
566
|
-
await new Promise((resolve) => {
|
|
567
|
-
if (signal?.aborted) {
|
|
568
|
-
resolve();
|
|
569
|
-
return;
|
|
570
|
-
}
|
|
571
|
-
let settled = false;
|
|
572
|
-
const onAbort = () => {
|
|
573
|
-
if (settled) return;
|
|
574
|
-
settled = true;
|
|
575
|
-
clearTimeout(timer);
|
|
576
|
-
signal?.removeEventListener("abort", onAbort);
|
|
577
|
-
resolve();
|
|
578
|
-
};
|
|
579
|
-
const timer = setTimeout(() => {
|
|
580
|
-
if (settled) return;
|
|
581
|
-
settled = true;
|
|
582
|
-
signal?.removeEventListener("abort", onAbort);
|
|
583
|
-
resolve();
|
|
584
|
-
}, Math.max(0, ms));
|
|
585
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
586
|
-
});
|
|
587
|
-
}
|
|
588
565
|
//#endregion
|
|
589
566
|
//#region src/runtime/supervise/provision-supervisor.ts
|
|
590
567
|
/**
|
|
@@ -956,22 +933,18 @@ async function pollUntil(read, run, pollMs) {
|
|
|
956
933
|
}
|
|
957
934
|
async function withTimeout(promise, timeoutMs, label) {
|
|
958
935
|
if (timeoutMs === void 0) return await promise;
|
|
959
|
-
let
|
|
936
|
+
let clearTimer;
|
|
960
937
|
const timeout = new Promise((_resolve, reject) => {
|
|
961
|
-
|
|
962
|
-
if (typeof timer.unref === "function") timer.unref();
|
|
938
|
+
clearTimer = armDeadlineTimer(timeoutMs, () => reject(unavailable(`Runtime supervisor timed out waiting for ${label}`)));
|
|
963
939
|
});
|
|
964
940
|
try {
|
|
965
941
|
return await Promise.race([promise, timeout]);
|
|
966
942
|
} finally {
|
|
967
|
-
|
|
943
|
+
clearTimer?.();
|
|
968
944
|
}
|
|
969
945
|
}
|
|
970
946
|
function delay(ms, keepAlive = false) {
|
|
971
|
-
return
|
|
972
|
-
const timer = setTimeout(resolveDelay, ms);
|
|
973
|
-
if (!keepAlive && typeof timer.unref === "function") timer.unref();
|
|
974
|
-
});
|
|
947
|
+
return sleep(ms, void 0, keepAlive);
|
|
975
948
|
}
|
|
976
949
|
function updateStateFromResult(state, result) {
|
|
977
950
|
state.status = result.kind === "winner" ? "done" : result.reason === "cancelled" ? "cancelled" : "down";
|
|
@@ -1035,4 +1008,4 @@ function writeState(path, state) {
|
|
|
1035
1008
|
//#endregion
|
|
1036
1009
|
export { workerFromInteractiveProvider as n, claimRetainedInteractiveControl as r, provisionSupervisor as t };
|
|
1037
1010
|
|
|
1038
|
-
//# sourceMappingURL=provision-supervisor-
|
|
1011
|
+
//# sourceMappingURL=provision-supervisor-ChEnL5xX.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provision-supervisor-ChEnL5xX.js","names":["abortError"],"sources":["../src/runtime/retained-interactive-control.ts","../src/runtime/supervise/interactive-worker.ts","../src/runtime/supervise/provision-supervisor.ts"],"sourcesContent":["import type { AgentInteractiveSessionControlClaim } from '@tangle-network/agent-interface'\nimport {\n agentInteractiveSessionControlClaimRequestDigest,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport type { RetainedInteractiveRunHandle } from './retained-interactive-types'\nimport { abortError } from './retained-run-binding'\n\nconst MAX_GENERATION_CONFLICTS = 8\n\n/** Input for acquiring write authority over one exact interactive process. @stable */\nexport interface ClaimRetainedInteractiveControlOptions {\n readonly handle: RetainedInteractiveRunHandle\n readonly holderId: string\n /** Last known provider generation. Zero discovers the current generation safely. */\n readonly expectedGeneration?: number\n readonly signal?: AbortSignal\n}\n\n/**\n * Acquire provider-issued write authority without reading authority from status.\n *\n * A new coordinator starts at generation zero. If another claim already exists,\n * the provider returns its public generation and this helper retries one new\n * compare-and-swap operation. Every generation has a deterministic operation\n * identifier, so retrying after an ambiguous response cannot create two claims.\n * @stable\n */\nexport async function claimRetainedInteractiveControl(\n options: ClaimRetainedInteractiveControlOptions,\n): Promise<AgentInteractiveSessionControlClaim> {\n const expected = options.expectedGeneration ?? 0\n if (!Number.isSafeInteger(expected) || expected < 0) {\n throw new Error('interactive control expectedGeneration must be a non-negative integer')\n }\n\n let generation = expected\n for (let conflict = 0; conflict <= MAX_GENERATION_CONFLICTS; conflict += 1) {\n if (options.signal?.aborted) throw abortError(options.signal.reason)\n const material = {\n operationId: controlClaimOperationId(options.handle, options.holderId, generation),\n ref: options.handle.ref,\n holderId: options.holderId,\n expectedGeneration: generation,\n }\n const acknowledgement = await options.handle.claimControl(\n {\n ...material,\n requestDigest: agentInteractiveSessionControlClaimRequestDigest(material),\n },\n options.signal === undefined ? undefined : { signal: options.signal },\n )\n if (acknowledgement.status === 'accepted' || acknowledgement.status === 'replayed') {\n const control = acknowledgement.control\n if (control === undefined) {\n throw new Error('provider accepted interactive control without returning its claim')\n }\n if (Date.parse(control.expiresAt) <= Date.now()) {\n throw new Error('provider returned an expired interactive control claim')\n }\n return control\n }\n if (\n acknowledgement.status !== 'conflict' ||\n acknowledgement.conflictReason !== 'generation_mismatch'\n ) {\n throw new Error(\n acknowledgement.status === 'unknown'\n ? 'interactive control claim outcome is unknown; retry the same acquisition'\n : 'interactive control claim operation conflicts with different request material',\n )\n }\n const current = acknowledgement.currentGeneration\n if (current === undefined || current <= generation) {\n throw new Error('provider returned a non-advancing interactive control generation')\n }\n generation = current\n }\n throw new Error('interactive control changed too often to acquire safely')\n}\n\nfunction controlClaimOperationId(\n handle: RetainedInteractiveRunHandle,\n holderId: string,\n expectedGeneration: number,\n): string {\n const digest = canonicalCandidateDigest({\n kind: 'retained-interactive-control-claim.v1',\n ref: handle.ref,\n holderId,\n expectedGeneration,\n })\n return `interactive-claim-${digest.slice('sha256:'.length, 'sha256:'.length + 40)}`\n}\n","/**\n * Runtime-owned worker seam for a provider's native interactive coding-agent process.\n *\n * This adapter composes the retained-interactive lifecycle. It does not create a second stream,\n * replay buffer, session id, or cancellation protocol. The provider owns process state; Scope owns\n * the supervised worker, journal, budget, and local control inbox.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport {\n type AgentInteractiveSessionPromptCommand,\n type AgentInteractiveSessionRef,\n type AgentInteractiveSessionStatus,\n type AgentInteractiveSessionStopAcknowledgement,\n type AgentInteractiveSessionStopCommand,\n type AgentProfile,\n agentInteractiveSessionPromptRequestDigest,\n agentInteractiveSessionStopRequestDigest,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironment,\n AgentEnvironmentProvider,\n CreateAgentEnvironmentInput,\n} from '@tangle-network/agent-interface/environment-provider'\nimport { contentAddress } from '../../durable/spawn-journal'\nimport type { MakeWorkerAgent, WorkerSpawnContext } from '../../mcp/tools/coordination'\nimport { destroyInteractiveEnvironment } from '../retained-interactive-lifecycle'\nimport type { RetainedInteractiveRunHandle } from '../retained-interactive-types'\nimport { claimRetainedInteractiveControl, startRetainedInteractiveRun } from '../retained-run'\nimport { retainedCreateMaterial } from '../retained-run-intent'\nimport type { RetainedInteractiveAdmission } from '../retained-run-types'\nimport { sleep } from '../util'\nimport { abortError, linkAbort } from './abortable'\nimport { executableAgentProfileSnapshot } from './executable-spec'\nimport { createInbox } from './inbox'\nimport {\n type InteractiveAdmissionWriter,\n interactiveAdmissionSeamKey,\n} from './interactive-admission'\nimport {\n attestRuntimeOwnedPendingExecutor,\n finalizeRuntimeOwnedPendingExecutor,\n newExecutionAttemptId,\n} from './materialization'\nimport { concreteProfileModel } from './model-policy'\nimport { detachedSnapshot } from './snapshot'\nimport { taskToPrompt } from './task-prompt'\nimport type {\n Agent,\n AgentSpec,\n Executor,\n ExecutorCancellation,\n ExecutorContext,\n ExecutorResult,\n Runtime,\n Spend,\n UsageEvent,\n WorkerInteractiveSession,\n} from './types'\n\n/** Environment fields supplied to every interactive worker after Runtime adds the exact profile. */\nexport type InteractiveWorkerEnvironment = Omit<\n CreateAgentEnvironmentInput,\n 'profile' | 'idempotencyKey' | 'signal'\n>\n\n/** Native interactive worker output. Provider usage is intentionally not fabricated. */\nexport interface InteractiveWorkerResult {\n readonly provider: string\n readonly environmentId: string\n readonly sessionId: string\n readonly executionId: string\n readonly state: 'exited' | 'unknown'\n readonly ref: AgentInteractiveSessionRef\n readonly reason?: string\n readonly exitCode?: number\n readonly exitSignal?: string\n}\n\n/** Configuration shared by every worker produced by `workerFromInteractiveProvider`. */\nexport interface InteractiveWorkerOptions {\n /** Provider create fields. Runtime supplies `profile`, the two idempotency keys, and `signal`. */\n readonly environment?: InteractiveWorkerEnvironment\n /** Stable environment identity override. Defaults to a digest of the exact worker assignment. */\n readonly environmentIdempotencyKey?: (input: InteractiveWorkerKeyInput) => string\n /** Stable interactive-session identity override. Defaults to a digest of assignment and task. */\n readonly interactiveIdempotencyKey?: (input: InteractiveWorkerKeyInput) => string\n /** Provider holder id used only while the worker sends a steer or stop command. */\n readonly holderId?: string | ((input: InteractiveWorkerKeyInput) => string)\n /** Initial prompt override. The exact worker task is the default prompt. */\n readonly initialPrompt?: string | ((task: unknown, input: InteractiveWorkerKeyInput) => string)\n readonly cwd?: string\n readonly cols?: number\n readonly rows?: number\n /** Runtime tag written into tree snapshots. Defaults to the provider name. */\n readonly runtime?: Runtime\n /** Poll delay used while waiting for the provider's native process to exit. */\n readonly pollIntervalMs?: number\n /** Destroy the provider environment after the process is terminal. Defaults to true. */\n readonly destroyEnvironmentOnTeardown?: boolean\n}\n\nconst INTERACTIVE_TEARDOWN_TIMEOUT_MS = 30_000\n\n/** Stable input available to key and holder functions. */\nexport interface InteractiveWorkerKeyInput {\n readonly provider: string\n readonly profile: AgentProfile\n readonly context?: WorkerSpawnContext\n readonly task?: unknown\n readonly nodeId?: string\n}\n\n/**\n * Build a `MakeWorkerAgent` that starts one exact provider-owned native TUI per worker.\n *\n * A Scope supplies the durable admission hook and kernel-minted node attempt. The returned worker\n * exposes `interactiveReady`, so Scope writes the exact provider reference before the worker can be\n * attached by a different process. `attachWorker` then reconnects that same reference through the\n * provider's public `get`/interactive contract.\n */\nexport function workerFromInteractiveProvider(\n provider: AgentEnvironmentProvider,\n options: InteractiveWorkerOptions = {},\n): MakeWorkerAgent {\n if (!provider.name.trim())\n throw new Error('workerFromInteractiveProvider: provider.name required')\n if (!provider.get) {\n throw new Error(\n `workerFromInteractiveProvider(${provider.name}): provider.get is required for reconnect`,\n )\n }\n const capturedEnvironment = options.environment\n ? (structuredClone(options.environment) as InteractiveWorkerEnvironment)\n : undefined\n const unscopedNamespace = randomUUID()\n let unscopedOrdinal = 0\n const runtime = options.runtime ?? (provider.name as Runtime)\n\n return (rawProfile, spawnContext) => {\n const profile = executableAgentProfileSnapshot(\n rawProfile,\n `workerFromInteractiveProvider(${provider.name})`,\n )\n const input: InteractiveWorkerKeyInput = {\n provider: provider.name,\n profile,\n ...(spawnContext === undefined ? {} : { context: spawnContext }),\n }\n const assignmentId =\n spawnContext?.assignmentId ?? `unscoped:${unscopedNamespace}:${unscopedOrdinal++}`\n const baseInput = { ...input, nodeId: spawnContext?.parentNodeId }\n const environmentKey = stableKey(\n options.environmentIdempotencyKey?.({ ...baseInput }) ??\n derivedKey('supervised-interactive-environment', {\n provider: provider.name,\n assignmentId,\n parentNodeId: spawnContext?.parentNodeId,\n profile,\n }),\n 'environment idempotency key',\n )\n const name = profile.name ?? 'interactive-worker'\n\n const executorFactory = (\n spec: AgentSpec,\n ctx: ExecutorContext,\n ): Executor<InteractiveWorkerResult> =>\n interactiveExecutor({\n provider,\n profile: spec.profile,\n context: spawnContext,\n environment: capturedEnvironment,\n environmentKey,\n interactiveKey: (task: unknown) =>\n stableKey(\n options.interactiveIdempotencyKey?.({\n ...baseInput,\n task,\n }) ??\n derivedKey('supervised-interactive-session', {\n provider: provider.name,\n assignmentId,\n parentNodeId: spawnContext?.parentNodeId,\n profile: spec.profile,\n task,\n }),\n 'interactive idempotency key',\n ),\n holderId: (task: unknown) => {\n const selected =\n typeof options.holderId === 'function'\n ? options.holderId({ ...baseInput, task })\n : options.holderId\n return stableKey(\n selected ??\n `runtime-interactive-worker:${canonicalCandidateDigest({\n provider: provider.name,\n assignmentId,\n })}`,\n 'interactive holder id',\n )\n },\n initialPrompt: options.initialPrompt,\n cwd: options.cwd,\n cols: options.cols,\n rows: options.rows,\n runtime,\n pollIntervalMs: options.pollIntervalMs,\n destroyEnvironmentOnTeardown: options.destroyEnvironmentOnTeardown,\n executionAttemptId: ctx.node?.attemptId,\n nodeId: ctx.node?.nodeId,\n admission: admissionWriter(ctx, provider.name, ctx.node?.nodeId),\n })\n\n const spec: AgentSpec = {\n profile,\n harness: null,\n executorFactory,\n ...(spawnContext?.execution ? { execution: spawnContext.execution } : {}),\n }\n return {\n name,\n act: async () => {\n throw new Error(\n 'workerFromInteractiveProvider: interactive workers execute through executorSpec',\n )\n },\n executorSpec: spec,\n } as Agent<unknown, InteractiveWorkerResult> & { executorSpec: AgentSpec }\n }\n}\n\ninterface InteractiveExecutorInput {\n readonly provider: AgentEnvironmentProvider\n readonly profile: AgentProfile\n readonly context?: WorkerSpawnContext\n readonly environment?: InteractiveWorkerEnvironment\n readonly environmentKey: string\n readonly interactiveKey: (task: unknown) => string\n readonly holderId: (task: unknown) => string\n readonly initialPrompt?: InteractiveWorkerOptions['initialPrompt']\n readonly cwd?: string\n readonly cols?: number\n readonly rows?: number\n readonly runtime: Runtime\n readonly pollIntervalMs?: number\n readonly destroyEnvironmentOnTeardown?: boolean\n readonly executionAttemptId?: string\n readonly nodeId?: string\n readonly admission: InteractiveAdmissionWriter\n}\n\nfunction interactiveExecutor(input: InteractiveExecutorInput): Executor<InteractiveWorkerResult> {\n const attemptId =\n input.executionAttemptId ?? newExecutionAttemptId(input.nodeId ?? input.environmentKey)\n const localController = new AbortController()\n const inbox = createInbox()\n let handle: RetainedInteractiveRunHandle | undefined\n let createdEnvironment: AgentEnvironment | undefined\n let environmentId: string | undefined\n let artifact: ExecutorResult<InteractiveWorkerResult> | undefined\n let activeLink: ReturnType<typeof linkAbort> | undefined\n let startPromise: Promise<RetainedInteractiveRunHandle> | undefined\n let executeStarted = false\n let readyResolve!: (session: WorkerInteractiveSession) => void\n const ready = new Promise<WorkerInteractiveSession>((resolve) => {\n readyResolve = resolve\n })\n const stopOperations = new Map<string, Promise<ExecutorCancellation>>()\n const memoryAdmissions = new Map<string, RetainedInteractiveAdmission>()\n let teardownComplete = false\n let teardownPromise: Promise<{ destroyed: boolean }> | undefined\n let flushChain: Promise<void> = Promise.resolve()\n let controlError: unknown\n\n const executor: Executor<InteractiveWorkerResult> = {\n runtime: input.runtime,\n teardownTimeoutMs: INTERACTIVE_TEARDOWN_TIMEOUT_MS,\n execute(task, signal): AsyncIterable<UsageEvent> {\n if (executeStarted || teardownComplete || teardownPromise !== undefined) {\n throw new Error('workerFromInteractiveProvider: execute() may only be called once')\n }\n executeStarted = true\n startPromise = startInteractive(task, signal)\n return runInteractive(signal)\n },\n deliver(message: unknown): boolean {\n if (teardownComplete || teardownPromise !== undefined) return false\n const accepted = inbox.deliver(message)\n if (accepted) void flushInbox()\n return accepted\n },\n interactive(): WorkerInteractiveSession {\n return handle\n ? { status: 'available', handle }\n : { status: 'unavailable', reason: 'interactive-session-not-started' }\n },\n interactiveReady(): Promise<WorkerInteractiveSession> {\n return ready\n },\n async cancel(request): Promise<ExecutorCancellation> {\n const existing = stopOperations.get(request.operationId)\n if (existing) return existing\n const operation = stopInteractive(request.operationId, request.reason, request.signal)\n const tracked = operation.then((result) => {\n if (result.status === 'unknown' && stopOperations.get(request.operationId) === tracked) {\n stopOperations.delete(request.operationId)\n }\n return result\n })\n stopOperations.set(request.operationId, tracked)\n return tracked\n },\n teardown(grace): Promise<{ destroyed: boolean }> {\n void grace\n if (teardownComplete) return Promise.resolve({ destroyed: true })\n if (teardownPromise !== undefined) return teardownPromise\n const pending = teardownInteractive()\n teardownPromise = pending.then(\n (result) => {\n teardownComplete = true\n return result\n },\n (error) => {\n teardownPromise = undefined\n throw error\n },\n )\n return teardownPromise\n },\n resultArtifact(): ExecutorResult<InteractiveWorkerResult> {\n if (!artifact) {\n throw new Error(\n 'workerFromInteractiveProvider: resultArtifact() read before execution settled',\n )\n }\n return artifact\n },\n }\n\n const declaredEnvironment = input.environment\n ? retainedCreateMaterial({\n ...input.environment,\n profile: input.profile,\n idempotencyKey: input.environmentKey,\n })\n : null\n const profileModel = concreteProfileModel(input.profile)\n const plannedDeclaration = {\n effectiveProfile: input.profile,\n backend: input.provider.name,\n model: profileModel\n ? { status: 'known' as const, id: profileModel }\n : { status: 'unknown' as const, reason: 'provider selected the model' },\n execution: { kind: 'interactive-session', id: input.nodeId ?? input.environmentKey },\n materializer: 'retained-interactive-provider',\n plan: {\n kind: 'retained-interactive-provider',\n provider: input.provider.name,\n environment: declaredEnvironment,\n environmentIdempotencyKey: input.environmentKey,\n destroyEnvironmentOnTeardown: input.destroyEnvironmentOnTeardown !== false,\n },\n }\n attestRuntimeOwnedPendingExecutor(executor, input.runtime, plannedDeclaration, {\n attemptId,\n binding: {\n provider: input.provider.name,\n environmentIdempotencyKey: input.environmentKey,\n nodeId: input.nodeId ?? null,\n },\n descriptor: {\n kind: 'interactive-session',\n provider: input.provider.name,\n transport: 'agent-environment',\n },\n })\n\n async function startInteractive(\n task: unknown,\n signal: AbortSignal,\n ): Promise<RetainedInteractiveRunHandle> {\n try {\n activeLink = linkAbort(signal, localController.signal)\n const initialPrompt =\n typeof input.initialPrompt === 'function'\n ? input.initialPrompt(task, {\n provider: input.provider.name,\n profile: input.profile,\n ...(input.context === undefined ? {} : { context: input.context }),\n task,\n ...(input.nodeId === undefined ? {} : { nodeId: input.nodeId }),\n })\n : (input.initialPrompt ?? taskToPrompt(task))\n if (typeof initialPrompt !== 'string') {\n throw new Error('workerFromInteractiveProvider: initialPrompt must return a string')\n }\n const interactiveIdempotencyKey = input.interactiveKey(task)\n const started = await startRetainedInteractiveRun({\n provider: {\n ...input.provider,\n async create(environmentInput): Promise<AgentEnvironment> {\n const environment = await input.provider.create!(environmentInput)\n createdEnvironment = environment\n return environment\n },\n },\n environment: {\n ...(input.environment ?? {}),\n profile: input.profile,\n idempotencyKey: input.environmentKey,\n },\n interactiveIdempotencyKey,\n ...(initialPrompt.length === 0 ? {} : { initialPrompt }),\n ...(input.cwd === undefined ? {} : { cwd: input.cwd }),\n ...(input.cols === undefined ? {} : { cols: input.cols }),\n ...(input.rows === undefined ? {} : { rows: input.rows }),\n onAdmission: async (admission) => {\n environmentId =\n admission.phase === 'interactive_environment' ? admission.environmentId : environmentId\n const existing = memoryAdmissions.get(admission.phase)\n if (existing !== undefined) {\n if (canonicalCandidateDigest(existing) !== canonicalCandidateDigest(admission)) {\n throw new Error(\n `interactive admission phase '${admission.phase}' changed across retry`,\n )\n }\n } else {\n memoryAdmissions.set(\n admission.phase,\n detachedSnapshot(admission, 'interactive admission'),\n )\n }\n await input.admission(admission)\n },\n signal: activeLink.signal,\n })\n finalizeRuntimeOwnedPendingExecutor(\n executor,\n {\n ...plannedDeclaration,\n execution: { kind: 'interactive-session', id: started.ref.run.executionId },\n plan: {\n ...plannedDeclaration.plan,\n environmentId: started.ref.run.environmentId,\n interactiveIdempotencyKey,\n },\n },\n {\n attemptId,\n binding: {\n provider: input.provider.name,\n ref: started.ref,\n environmentId: started.ref.run.environmentId,\n },\n descriptor: {\n kind: 'interactive-session',\n provider: input.provider.name,\n transport: 'agent-environment',\n },\n },\n )\n handle = started\n readyResolve({ status: 'available', handle: started })\n void flushInbox()\n return started\n } catch (error) {\n readyResolve({ status: 'unavailable', reason: unavailableReason(error) })\n activeLink?.release()\n throw error\n }\n }\n\n async function* runInteractive(signal: AbortSignal): AsyncIterable<UsageEvent> {\n const startedAt = Date.now()\n try {\n const current = await startPromise\n if (current === undefined) {\n throw new Error('workerFromInteractiveProvider: interactive start did not begin')\n }\n yield { kind: 'iteration' }\n // Native TUI sessions do not expose a complete turn receipt. These zero counters are an\n // observed floor and the explicit false markers keep the run's accounting honest.\n yield { kind: 'tokens', input: 0, output: 0, tokensKnown: false }\n yield { kind: 'cost', usd: 0, usdKnown: false, provenance: 'uncaptured' }\n let status: AgentInteractiveSessionStatus | undefined\n for (;;) {\n if (signal.aborted || localController.signal.aborted) {\n throw abortError(\n signal.aborted ? signal : localController.signal,\n 'interactive execution aborted',\n )\n }\n status = await current.status({ signal: activeLink?.signal })\n await flushChain\n if (controlError !== undefined) throw controlErrorValue(controlError)\n if (status.state !== 'running') break\n await sleep(input.pollIntervalMs ?? 100, activeLink?.signal)\n }\n const finished = status\n const output: InteractiveWorkerResult = {\n provider: input.provider.name,\n environmentId: current.ref.run.environmentId,\n sessionId: current.ref.run.sessionId,\n executionId: current.ref.run.executionId,\n state: finished?.state === 'exited' ? 'exited' : 'unknown',\n ref: current.ref,\n ...(finished?.state === 'exited' && finished.reason ? { reason: finished.reason } : {}),\n ...(finished?.state === 'exited' && finished.exitCode !== undefined\n ? { exitCode: finished.exitCode }\n : {}),\n ...(finished?.state === 'exited' && finished.exitSignal !== undefined\n ? { exitSignal: finished.exitSignal }\n : {}),\n }\n const spent: Spend = {\n iterations: 1,\n tokens: { input: 0, output: 0 },\n tokensKnown: false,\n usd: 0,\n usdKnown: false,\n ms: Date.now() - startedAt,\n }\n artifact = {\n outRef: contentAddress(output),\n out: output,\n spent,\n }\n } finally {\n activeLink?.release()\n }\n }\n\n async function flushInbox(): Promise<void> {\n flushChain = flushChain.then(async () => {\n try {\n if (!handle) return\n const messages = inbox.drain()\n if (messages.length === 0) return\n const prompt = inbox.fold(messages)\n const operationId = `interactive-prompt-${canonicalCandidateDigest({\n ref: handle.ref,\n prompt,\n }).slice('sha256:'.length)}`\n const control = await claimRetainedInteractiveControl({\n handle,\n holderId: input.holderId(undefined),\n })\n const material = {\n operationId,\n ref: handle.ref,\n control,\n prompt,\n }\n const command: AgentInteractiveSessionPromptCommand = {\n ...material,\n requestDigest: agentInteractiveSessionPromptRequestDigest(material),\n }\n await handle.sendPrompt(command)\n } catch (error) {\n controlError ??= error\n }\n })\n await flushChain\n }\n\n async function stopInteractive(\n operationId: string,\n reason?: string,\n signal?: AbortSignal,\n ): Promise<ExecutorCancellation> {\n const observedAt = new Date().toISOString()\n if (!handle) {\n localController.abort(reason ?? 'interactive cancellation requested')\n return {\n status: 'unknown',\n effect: 'cancel_requested',\n observedAt,\n detail: 'interactive process has not published a provider reference',\n }\n }\n try {\n const control = await claimRetainedInteractiveControl({\n handle,\n holderId: input.holderId(undefined),\n signal,\n })\n const material = { operationId, ref: handle.ref, control }\n const command: AgentInteractiveSessionStopCommand = {\n ...material,\n requestDigest: agentInteractiveSessionStopRequestDigest(material),\n }\n const acknowledgement = await handle.stop(\n command,\n signal === undefined ? undefined : { signal },\n )\n localController.abort(reason ?? 'interactive cancellation requested')\n return cancellationFromAcknowledgement(acknowledgement, observedAt)\n } catch (error) {\n localController.abort(reason ?? 'interactive cancellation requested')\n return {\n status: 'unknown',\n effect: 'cancel_requested',\n observedAt,\n detail: error instanceof Error ? error.message : String(error),\n evidence: { operationId },\n }\n }\n }\n\n async function teardownInteractive(): Promise<{ destroyed: boolean }> {\n localController.abort('interactive worker teardown')\n activeLink?.release()\n await startPromise?.catch(() => undefined)\n if (handle) {\n const status = await safeStatus(handle)\n if (status?.state === 'running') {\n const operationId = `interactive-teardown-${canonicalCandidateDigest(handle.ref).slice(\n 'sha256:'.length,\n )}`\n const cancellation = await stopInteractive(operationId, 'interactive worker teardown')\n if (cancellation.status === 'rejected' || cancellation.status === 'unknown') {\n throw new Error(cancellation.detail ?? 'interactive teardown was not acknowledged')\n }\n }\n }\n await destroyEnvironment()\n return { destroyed: true }\n }\n\n async function destroyEnvironment(): Promise<void> {\n if (input.destroyEnvironmentOnTeardown === false) return\n if (createdEnvironment !== undefined) {\n await destroyInteractiveEnvironment(createdEnvironment)\n return\n }\n if (!input.provider.get) return\n // The exact provider reference is durable and remains available even when the admission\n // callback was interrupted after the environment was created. Use it as the cleanup identity\n // so an aborted provider signal cannot turn a real environment into an unconfirmed leak.\n const cleanupEnvironmentId = environmentId ?? handle?.ref.run.environmentId\n if (!cleanupEnvironmentId) return\n const environment = await input.provider.get(cleanupEnvironmentId)\n if (environment !== undefined && environment !== null) {\n await destroyInteractiveEnvironment(environment)\n }\n }\n\n return executor\n}\n\nfunction admissionWriter(\n ctx: ExecutorContext,\n provider: string,\n workerId: string | undefined,\n): InteractiveAdmissionWriter {\n const candidate = ctx.seams[interactiveAdmissionSeamKey]\n if (typeof candidate === 'function') {\n return async (admission) => {\n await (candidate as (value: RetainedInteractiveAdmission) => Promise<void>)(admission)\n }\n }\n // In-memory runs still need a real hook because retained-start refuses an omitted hook. The\n // durable Scope path always supplies the Runtime-owned writer above; this fallback is explicit\n // and process-local, never mistaken for restart evidence.\n const records = new Map<string, RetainedInteractiveAdmission>()\n return async (admission) => {\n const prior = records.get(admission.phase)\n if (prior && canonicalCandidateDigest(prior) !== canonicalCandidateDigest(admission)) {\n throw new Error(\n `worker ${workerId ?? '(unscoped)'} provider ${provider} admission changed in memory`,\n )\n }\n records.set(admission.phase, detachedSnapshot(admission, 'interactive admission'))\n }\n}\n\nfunction derivedKey(kind: string, value: unknown): string {\n return `${kind}-${canonicalCandidateDigest(value).slice('sha256:'.length)}`\n}\n\nfunction stableKey(value: string, label: string): string {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new Error(`${label} must be a non-empty string`)\n }\n const key = value.trim()\n if (key.length > 256) throw new Error(`${label} must not exceed 256 bytes`)\n return key\n}\n\nfunction unavailableReason(\n error: unknown,\n): 'provider-has-no-interactive-contract' | 'interactive-binding-stale' {\n const message = error instanceof Error ? error.message : String(error)\n return message.includes('interactive') || message.includes('Interactive')\n ? 'provider-has-no-interactive-contract'\n : 'interactive-binding-stale'\n}\n\nfunction cancellationFromAcknowledgement(\n acknowledgement: AgentInteractiveSessionStopAcknowledgement,\n observedAt: string,\n): ExecutorCancellation {\n const status =\n acknowledgement.status === 'accepted' || acknowledgement.status === 'replayed'\n ? 'accepted'\n : acknowledgement.status === 'conflict'\n ? 'rejected'\n : 'unknown'\n const effect =\n acknowledgement.effect === 'stopped'\n ? 'cancelled'\n : acknowledgement.effect === 'not_live'\n ? 'not_live'\n : acknowledgement.effect === 'stop_requested'\n ? 'cancel_requested'\n : 'unknown'\n return {\n status,\n effect,\n observedAt,\n ...(acknowledgement.message === undefined ? {} : { detail: acknowledgement.message }),\n evidence: {\n operationId: acknowledgement.operationId,\n requestDigest: acknowledgement.requestDigest,\n providerStatus: acknowledgement.status,\n providerEffect: acknowledgement.effect,\n },\n }\n}\n\nfunction controlErrorValue(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error))\n}\n\nasync function safeStatus(\n handle: RetainedInteractiveRunHandle,\n): Promise<AgentInteractiveSessionStatus | undefined> {\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<undefined>((resolve) => {\n timer = setTimeout(() => resolve(undefined), 100)\n timer.unref?.()\n })\n try {\n // A provider environment created with the worker's abort signal may reject or hang all\n // subsequent calls after the scope begins teardown. Keep status best-effort and let the fresh\n // environment lookup below prove release without spending the teardown acknowledgement window\n // on a stale connection.\n return await Promise.race([handle.status(), timeout])\n } catch {\n return undefined\n } finally {\n if (timer !== undefined) clearTimeout(timer)\n }\n}\n","/**\n * Public one-call composition for a durable Runtime supervisor proof run.\n *\n * This is intentionally a thin owner of existing Runtime primitives. The supervisor owns the\n * root abort channel and join barrier, Scope owns worker admission and lifecycle, and the provider\n * owns the environment and interactive process. External clients receive identifiers and opaque\n * handles; they do not receive a second supervisor protocol or a copy of provider state.\n *\n * @experimental\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { mkdirSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { dirname, join, resolve } from 'node:path'\nimport {\n type AgentProfile,\n agentProfileSchema,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironmentCapabilities,\n AgentEnvironmentProvider,\n} from '@tangle-network/agent-interface/environment-provider'\nimport type { McpToolDescriptor } from '../../mcp/server'\nimport { createCoordinationTools } from '../../mcp/tools/coordination'\nimport { sandboxClientAsProvider } from '../environment-provider'\nimport type { SandboxClient } from '../types'\nimport { sleep } from '../util'\nimport { createCancelAcknowledger, createSteerAcknowledger } from './coordination-driver'\nimport { armDeadlineTimer } from './deadline'\nimport { writeAtomicDurableFile } from './durable-file'\nimport {\n type InteractiveWorkerEnvironment,\n workerFromInteractiveProvider,\n} from './interactive-worker'\nimport { createFileRunContext } from './run-context'\nimport { supervisorRunDir } from './run-layout'\nimport { createRootHandle, createSupervisor } from './supervisor'\nimport type { Agent, Budget, Scope, SpawnEvent, SupervisedResult } from './types'\nimport { readWorkerInteractiveBinding } from './worker-interactive'\n\nconst DEFAULT_POLL_MS = 25\nconst ROOT_MAX_ITERATIONS = 100\nconst ROOT_MAX_TOKENS = 100_000\nconst WORKER_MAX_ITERATIONS = 25\nconst WORKER_MAX_TOKENS = 25_000\n\n/** Caller-supplied provider or Sandbox SDK connection for one supervisor run. */\nexport interface ProvisionSupervisorConnection {\n /** A fully constructed provider. This is the preferred programmatic seam and is testable. */\n readonly provider?: AgentEnvironmentProvider\n /** A Sandbox SDK-compatible client. Runtime adapts it to the public provider contract. */\n readonly client?: SandboxClient\n /** Alias for `client`, accepted so callers can pass their existing connection object. */\n readonly sandboxClient?: SandboxClient\n /** Sandbox API endpoint used only when Runtime constructs the SDK client. */\n readonly endpoint?: string\n /** Transient Sandbox API key used only when Runtime constructs the SDK client. */\n readonly apiKey?: string\n /** Connection kind is descriptive only and does not select a hidden implementation. */\n readonly kind?: string\n}\n\n/** Input to the public Runtime supervisor provisioner. */\nexport interface ProvisionSupervisorRequest {\n readonly invocationId: string\n /** Caller-owned task assigned to the first interactive worker. */\n readonly task: string\n /** Canonical profile assigned to the first interactive worker. */\n readonly profile: AgentProfile\n /** Generic provider create fields forwarded to the interactive worker. */\n readonly workerEnvironment?: InteractiveWorkerEnvironment\n /** Root directory for Runtime-owned `.agent/supervisor` state. */\n readonly workspaceDir?: string\n /** Maximum wall-clock time for the complete supervisor lifecycle, including cleanup. Omit for no lifecycle deadline. */\n readonly timeoutMs?: number\n /** Poll cadence for lifecycle/control readiness. */\n readonly pollMs?: number\n /** Explicit provider, client, or endpoint and API key for one provider connection. */\n readonly connection: ProvisionSupervisorConnection\n}\n\n/** Exact owner-scoped cleanup receipt returned after Runtime releases the run resources. */\nexport interface SupervisorCleanupReceipt {\n readonly status: 'completed'\n readonly rootDir: string\n readonly supervisorId: string\n readonly workerId: string\n readonly supervisorStatus: string\n readonly workerStatus: 'running' | 'done' | 'down' | 'cancelled'\n readonly resourcesReleased: true\n readonly remainingResources: readonly []\n}\n\n/** Handles for one Runtime-owned supervisor and its first interactive worker. */\nexport interface ProvisionedSupervisor {\n readonly rootDir: string\n readonly supervisorId: string\n readonly workerId: string\n /** Provider source for `attachWorker`; omitted only when resolution did not produce one. */\n readonly providers?: AgentEnvironmentProvider\n /** Capability-derived terminal takeover requirement. */\n readonly terminalTakeover: 'required' | 'unsupported' | 'unspecified'\n cleanup(): Promise<SupervisorCleanupReceipt>\n}\n\nclass SupervisorProvisionUnavailableError extends Error {\n readonly unavailable = true as const\n\n constructor(message: string, cause?: unknown) {\n super(message, cause === undefined ? undefined : { cause })\n this.name = 'SupervisorProvisionUnavailableError'\n }\n}\n\ninterface MutableState {\n readonly id: string\n status: string\n readonly task: string\n readonly workspaceDir: string\n readonly budget: number\n readonly workerModel?: string\n readonly startedAt: string\n completedAt?: string\n}\n\ninterface Deferred<T> {\n readonly promise: Promise<T>\n resolve(value: T): void\n reject(error: unknown): void\n readonly settled: () => boolean\n}\n\n/**\n * Provision one real provider-backed worker and keep its owning manager alive for controls.\n *\n * The root manager does not use a model. It runs the same coordination tools used by a driver in a\n * small deterministic loop, so durable steer and cancel requests are acknowledged by the owning\n * Runtime turn loop and never by a test-only shortcut. The caller owns profile, task, and provider\n * connection selection; Runtime does not infer them from process environment variables.\n */\nexport async function provisionSupervisor(\n request: ProvisionSupervisorRequest,\n): Promise<ProvisionedSupervisor> {\n const input = normalizeRequest(request)\n const provider = await resolveProvider(input)\n const capabilities = await readCapabilities(provider)\n const terminalTakeover = terminalCapability(capabilities)\n const profile = input.profile\n const rootDir = resolve(input.workspaceDir ?? makeWorkspaceDir())\n mkdirSync(rootDir, { recursive: true })\n const supervisorId = supervisorIdFor(input.invocationId)\n const eventDir = supervisorRunDir(rootDir, supervisorId)\n const statePath = join(eventDir, 'state.json')\n mkdirSync(dirname(eventDir), { recursive: true })\n try {\n // The run directory is the cross-process invocation lock. A non-recursive mkdir closes the\n // duplicate-start race before any journal or provider resource is created.\n mkdirSync(eventDir)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'EEXIST') {\n throw unavailable(\n `Runtime supervisor '${supervisorId}' already exists at '${eventDir}'; use a new invocationId`,\n )\n }\n throw error\n }\n\n const context = createFileRunContext(eventDir)\n const startedAtMs = Date.now()\n const state: MutableState = {\n id: supervisorId,\n status: 'running',\n task: input.task,\n workspaceDir: rootDir,\n budget: ROOT_MAX_TOKENS,\n ...(profile.model?.default === undefined ? {} : { workerModel: profile.model.default }),\n startedAt: new Date(startedAtMs).toISOString(),\n }\n writeState(statePath, state)\n\n const rootHandle = createRootHandle<unknown>()\n const supervisor = createSupervisor<unknown, unknown>()\n supervisor.attach(rootHandle)\n const workerSpawned = deferred<string>()\n const workerRunning = deferred<void>()\n const workerProfile = profile\n const workerEnvironment = {\n ...(input.workerEnvironment ?? {}),\n metadata: {\n ...(input.workerEnvironment?.metadata ?? {}),\n runtime: 'agent-runtime',\n invocationId: input.invocationId,\n },\n name: input.workerEnvironment?.name ?? `runtime-${supervisorId}`,\n }\n const makeWorkerAgent = workerFromInteractiveProvider(provider, {\n environment: workerEnvironment,\n pollIntervalMs: input.pollMs,\n destroyEnvironmentOnTeardown: true,\n })\n\n const rootAgent: Agent<unknown, unknown> = {\n name: 'runtime-supervisor-root',\n async act(_task: unknown, scope: Scope<unknown>): Promise<unknown> {\n const coord = createCoordinationTools({\n scope,\n blobs: context.blobs,\n makeWorkerAgent,\n perWorker: workerBudget(),\n // Keep each supervisor turn bounded so control requests are observed while the remote\n // worker is running. The coordination tool keeps one settlement drain in flight, so a\n // timeout only ends this turn; it cannot lose the eventual worker event.\n awaitTimeoutMs: input.pollMs,\n })\n await coord.ready()\n const spawn = findTool(coord.tools, 'spawn_worker')\n const awaitEvent = findTool(coord.tools, 'await_event')\n const result = await spawn.handler({\n profile: workerProfile,\n task: input.task,\n label: 'interactive-worker',\n })\n const childId = workerIdFromSpawn(result)\n workerSpawned.resolve(childId)\n\n for (;;) {\n const child = scope.view.nodes.find((node) => node.id === childId)\n if (child?.status === 'running') break\n if (\n child === undefined ||\n child.status === 'done' ||\n child.status === 'failed' ||\n child.status === 'cancelled'\n ) {\n throw new Error(`Runtime supervisor worker '${childId}' ended before becoming live`)\n }\n await delay(input.pollMs)\n }\n workerRunning.resolve()\n\n const steerAcknowledger = createSteerAcknowledger({\n dir: eventDir,\n coord,\n now: Date.now,\n ownerId: scope.view.root,\n })\n const cancelAcknowledger = createCancelAcknowledger({\n dir: eventDir,\n coord,\n scope,\n now: Date.now,\n ownerId: scope.view.root,\n controlScope: 'run',\n })\n try {\n while (true) {\n await steerAcknowledger.pass('turn')\n cancelAcknowledger.pass('turn')\n // `await_event` owns the single scope cursor drain. Calling `scope.next()` directly here\n // would bypass the coordination ledger and make a real cancellation look unknown.\n const event = await awaitEvent.handler({ kinds: ['settled'] })\n if (isSettledEvent(event)) {\n await steerAcknowledger.pass('final')\n cancelAcknowledger.pass('final')\n return undefined\n }\n if (isIdleEvent(event)) {\n throw new Error(`Runtime supervisor worker '${childId}' ended without a settlement`)\n }\n if (!isPendingEvent(event)) {\n throw new Error(`Runtime supervisor returned an invalid settlement response`)\n }\n }\n } finally {\n // The final pass closes requests that landed after the last turn. It is idempotent with the\n // normal path and prevents an admitted operation from remaining open after root teardown.\n await steerAcknowledger.pass('final')\n cancelAcknowledger.pass('final')\n cancelAcknowledger.finish()\n }\n },\n }\n const runBudget = rootBudget(input.timeoutMs)\n let runResult: SupervisedResult<unknown> | undefined\n let runError: unknown\n let runSettled = false\n const runPromise = supervisor\n .run(rootAgent, input.task, {\n budget: runBudget,\n rootIdentity: {\n profileDigest: canonicalAgentProfileDigest(profile),\n taskDigest: canonicalCandidateDigest(input.task),\n },\n runId: supervisorId,\n ...context,\n interactiveBindingDir: eventDir,\n maxDepth: 1,\n maxLiveWorkers: 1,\n })\n .then(\n (result) => {\n runResult = result\n runSettled = true\n updateStateFromResult(state, result)\n writeState(statePath, state)\n return result\n },\n (error) => {\n runError = error\n runSettled = true\n state.status = 'down'\n state.completedAt = new Date().toISOString()\n writeState(statePath, state)\n throw error\n },\n )\n void runPromise.catch(() => undefined)\n\n let workerId: string\n try {\n workerId = await waitForWorkerSpawn(workerSpawned.promise, runPromise, input.timeoutMs)\n await waitForWorkerRunning(workerRunning.promise, runPromise, input.timeoutMs)\n if (terminalTakeover === 'required') {\n await waitForInteractiveBinding(eventDir, workerId, runPromise, input.timeoutMs, input.pollMs)\n }\n } catch (error) {\n if (!runSettled) {\n try {\n rootHandle.abort('supervisor provisioning failed')\n } catch {\n // The supervisor may have released the handle between the state read and this abort.\n }\n }\n await runPromise.catch(() => undefined)\n throw error\n }\n\n let cleanupPromise: Promise<SupervisorCleanupReceipt> | undefined\n const cleanup = async (): Promise<SupervisorCleanupReceipt> => {\n cleanupPromise ??= (async () => {\n if (!runSettled) {\n try {\n rootHandle.abort('supervisor cleanup')\n } catch {\n // A concurrent run completion already released the handle.\n }\n }\n const result = await runPromise.catch((error) => {\n runError = error\n return undefined\n })\n if (result !== undefined) runResult = result\n if (runError !== undefined) throw runError\n const finalEvents = await waitForWorkerTerminal(\n context.journal,\n supervisorId,\n workerId,\n input.timeoutMs,\n input.pollMs,\n )\n const workerStatus = workerStatusFromEvents(finalEvents, workerId)\n if (workerStatus === 'running') {\n throw new Error(`Runtime supervisor worker '${workerId}' did not reach a terminal state`)\n }\n if (runResult?.teardownUnconfirmed?.length) {\n throw new Error(\n `Runtime supervisor cleanup could not confirm ${runResult.teardownUnconfirmed.length} resource(s) released`,\n )\n }\n const supervisorStatus = state.status\n state.completedAt ??= new Date().toISOString()\n writeState(statePath, state)\n return Object.freeze({\n status: 'completed' as const,\n rootDir,\n supervisorId,\n workerId,\n supervisorStatus,\n workerStatus,\n resourcesReleased: true as const,\n remainingResources: Object.freeze([]) as readonly [],\n })\n })()\n return cleanupPromise\n }\n\n return Object.freeze({\n rootDir,\n supervisorId,\n workerId,\n providers: provider,\n terminalTakeover,\n cleanup,\n })\n}\n\nfunction normalizeRequest(request: ProvisionSupervisorRequest): ProvisionSupervisorRequest & {\n readonly invocationId: string\n readonly task: string\n readonly timeoutMs: number | undefined\n readonly pollMs: number\n readonly profile: AgentProfile\n readonly connection: ProvisionSupervisorConnection\n} {\n const invocationId = request.invocationId.trim()\n if (!invocationId) throw new SupervisorProvisionUnavailableError('invocationId is required')\n const task = request.task.trim()\n if (!task) throw new SupervisorProvisionUnavailableError('task is required')\n const profile = resolveProfile(request.profile)\n if (request.connection === undefined) {\n throw new SupervisorProvisionUnavailableError('provider connection is required')\n }\n const timeoutMs =\n request.timeoutMs === undefined ? undefined : positiveNumber(request.timeoutMs, 'timeoutMs')\n const pollMs = positiveNumber(request.pollMs ?? DEFAULT_POLL_MS, 'pollMs')\n return { ...request, invocationId, task, timeoutMs, pollMs, profile }\n}\n\nfunction positiveNumber(value: number, name: string): number {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new SupervisorProvisionUnavailableError(`${name} must be a positive safe integer`)\n }\n return value\n}\n\nfunction makeWorkspaceDir(): string {\n return join(tmpdir(), `agent-runtime-supervisor-${randomUUID()}`)\n}\n\nfunction supervisorIdFor(invocationId: string): string {\n const digest = canonicalCandidateDigest({ kind: 'runtime-supervisor', invocationId })\n return `runtime-supervisor-${digest.slice('sha256:'.length)}`\n}\n\n/** A caller-supplied deadline covers the complete supervisor lifecycle from run start through cleanup. */\nfunction rootBudget(timeoutMs: number | undefined): Budget {\n return {\n maxIterations: ROOT_MAX_ITERATIONS,\n maxTokens: ROOT_MAX_TOKENS,\n ...(timeoutMs === undefined ? {} : { deadlineMs: timeoutMs }),\n }\n}\n\nfunction workerBudget(): Budget {\n return {\n maxIterations: WORKER_MAX_ITERATIONS,\n maxTokens: WORKER_MAX_TOKENS,\n }\n}\n\nfunction resolveProfile(profile: AgentProfile): AgentProfile {\n const parsed = agentProfileSchema.safeParse(profile)\n if (!parsed.success) {\n throw unavailable(\n `Runtime supervisor profile is invalid: ${parsed.error.issues\n .map((issue) => `${issue.path.join('.')}: ${issue.message}`)\n .join('; ')}`,\n )\n }\n return parsed.data\n}\n\nasync function resolveProvider(\n request: ProvisionSupervisorRequest,\n): Promise<AgentEnvironmentProvider> {\n const connection = request.connection\n if (connection === undefined) {\n throw unavailable('Runtime supervisor provider connection is required')\n }\n if (connection?.provider !== undefined) return requireReconnectProvider(connection.provider)\n const client = connection?.client ?? connection?.sandboxClient\n if (client !== undefined) {\n return requireReconnectProvider(sandboxClientAsProvider(client))\n }\n const apiKey = connection.apiKey?.trim()\n const endpoint = connection.endpoint?.trim()\n if (!apiKey || !endpoint) {\n throw unavailable(\n 'Runtime supervisor needs a provider/client or both connection.endpoint and connection.apiKey',\n )\n }\n let module: typeof import('@tangle-network/sandbox')\n try {\n module = await import('@tangle-network/sandbox')\n } catch (error) {\n throw unavailable('Runtime supervisor could not load the Sandbox SDK peer dependency', error)\n }\n const SandboxCtor = (module as { Sandbox?: new (config: unknown) => SandboxClient }).Sandbox\n if (SandboxCtor === undefined) throw unavailable('Sandbox SDK does not export a Sandbox client')\n const provider = sandboxClientAsProvider(new SandboxCtor({ apiKey, baseUrl: endpoint }))\n return requireReconnectProvider(provider)\n}\n\nfunction requireReconnectProvider(provider: AgentEnvironmentProvider): AgentEnvironmentProvider {\n if (!provider.name.trim()) throw unavailable('Runtime supervisor provider has no name')\n if (typeof provider.get !== 'function') {\n throw unavailable(\n `Runtime supervisor provider '${provider.name}' cannot reconnect environments`,\n )\n }\n return provider\n}\n\nasync function readCapabilities(\n provider: AgentEnvironmentProvider,\n): Promise<AgentEnvironmentCapabilities> {\n try {\n return await provider.capabilities()\n } catch (error) {\n throw unavailable(`Runtime supervisor could not read '${provider.name}' capabilities`, error)\n }\n}\n\nfunction terminalCapability(\n capabilities: AgentEnvironmentCapabilities,\n): 'required' | 'unsupported' | 'unspecified' {\n const interactive = capabilities.interactiveAgent\n if (interactive === undefined) return 'unsupported'\n const complete = [\n interactive.start,\n interactive.control,\n interactive.status,\n interactive.attach,\n interactive.reattach,\n interactive.sendPrompt,\n interactive.input,\n interactive.resize,\n interactive.stop,\n ].every((value) => value === true)\n return complete ? 'required' : 'unsupported'\n}\n\nfunction findTool(tools: readonly McpToolDescriptor[], name: string): McpToolDescriptor {\n const tool = tools.find((candidate) => candidate.name === name)\n if (tool === undefined)\n throw new Error(`Runtime supervisor coordination tool '${name}' is missing`)\n return tool\n}\n\nfunction workerIdFromSpawn(value: unknown): string {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('Runtime supervisor spawn did not return a worker id')\n }\n const workerId = (value as { workerId?: unknown }).workerId\n if (typeof workerId !== 'string' || !workerId.trim()) {\n throw new Error('Runtime supervisor spawn did not return a worker id')\n }\n return workerId\n}\n\nfunction isSettledEvent(value: unknown): boolean {\n return isObject(value) && value.type === 'settled'\n}\n\nfunction isIdleEvent(value: unknown): boolean {\n return isObject(value) && value.idle === true\n}\n\nfunction isPendingEvent(value: unknown): boolean {\n return isObject(value) && value.pending === true\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n\nasync function waitForWorkerSpawn(\n worker: Promise<string>,\n run: Promise<SupervisedResult<unknown>>,\n timeoutMs: number | undefined,\n): Promise<string> {\n return await withTimeout(\n Promise.race([\n worker,\n run.then(() => {\n throw new Error('Runtime supervisor ended before it spawned a worker')\n }),\n ]),\n timeoutMs,\n 'worker spawn',\n )\n}\n\nasync function waitForWorkerRunning(\n running: Promise<void>,\n run: Promise<SupervisedResult<unknown>>,\n timeoutMs: number | undefined,\n): Promise<void> {\n await withTimeout(\n Promise.race([\n running,\n run.then(() => {\n throw new Error('Runtime supervisor ended before the worker became live')\n }),\n ]),\n timeoutMs,\n 'worker readiness',\n )\n}\n\nasync function waitForInteractiveBinding(\n eventDir: string,\n workerId: string,\n run: Promise<SupervisedResult<unknown>>,\n timeoutMs: number | undefined,\n pollMs: number,\n): Promise<void> {\n await withTimeout(\n pollUntil(\n async () => {\n const binding = readWorkerInteractiveBinding(eventDir, workerId)\n if (binding?.status === 'available') return true\n if (binding?.status === 'unavailable') {\n throw unavailable(`Runtime worker '${workerId}' could not publish an interactive binding`)\n }\n return false\n },\n run,\n pollMs,\n ),\n timeoutMs,\n 'interactive terminal binding',\n )\n}\n\nasync function pollUntil(\n read: () => Promise<boolean> | boolean,\n run: Promise<SupervisedResult<unknown>>,\n pollMs: number,\n): Promise<void> {\n for (;;) {\n if (await read()) return\n await Promise.race([\n delay(pollMs),\n run.then(() => {\n throw new Error('Runtime supervisor ended before readiness was observed')\n }),\n ])\n }\n}\n\nasync function withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number | undefined,\n label: string,\n): Promise<T> {\n if (timeoutMs === undefined) return await promise\n let clearTimer: (() => void) | undefined\n const timeout = new Promise<never>((_resolve, reject) => {\n clearTimer = armDeadlineTimer(timeoutMs, () =>\n reject(unavailable(`Runtime supervisor timed out waiting for ${label}`)),\n )\n })\n try {\n return await Promise.race([promise, timeout])\n } finally {\n clearTimer?.()\n }\n}\n\nfunction delay(ms: number, keepAlive = false): Promise<void> {\n return sleep(ms, undefined, keepAlive)\n}\n\nfunction updateStateFromResult(state: MutableState, result: SupervisedResult<unknown>): void {\n state.status =\n result.kind === 'winner' ? 'done' : result.reason === 'cancelled' ? 'cancelled' : 'down'\n state.completedAt = new Date().toISOString()\n}\n\nfunction workerStatusFromEvents(\n events: readonly SpawnEvent[],\n workerId: string,\n): SupervisorCleanupReceipt['workerStatus'] {\n let status: SupervisorCleanupReceipt['workerStatus'] = 'running'\n let terminal = false\n for (const event of events) {\n if (event.id !== workerId) continue\n if (terminal) continue\n if (event.kind === 'spawned' || event.kind === 'progress') status = 'running'\n else if (event.kind === 'settled') {\n status = event.status === 'done' ? 'done' : 'down'\n terminal = true\n } else if (event.kind === 'cancelled') {\n status = 'cancelled'\n terminal = true\n }\n }\n return status\n}\n\nasync function waitForWorkerTerminal(\n journal: import('./types').SpawnJournal,\n root: string,\n workerId: string,\n timeoutMs: number | undefined,\n pollMs: number,\n): Promise<SpawnEvent[]> {\n const deadline = timeoutMs === undefined ? undefined : Date.now() + timeoutMs\n for (;;) {\n const events = await journal.loadTree(root)\n if (events !== undefined && workerStatusFromEvents(events, workerId) !== 'running') {\n return events\n }\n if (deadline !== undefined && Date.now() >= deadline) {\n throw unavailable(`Runtime supervisor timed out waiting for worker '${workerId}' to settle`)\n }\n // Cleanup is an explicit lifecycle operation. Keep this bounded poll referenced so a caller\n // awaiting cleanup cannot have Node exit while the provider is still committing the terminal\n // worker event.\n await delay(pollMs, true)\n }\n}\n\nfunction deferred<T>(): Deferred<T> {\n let done = false\n let resolveValue!: (value: T) => void\n let rejectValue!: (error: unknown) => void\n const promise = new Promise<T>((resolvePromise, rejectPromise) => {\n resolveValue = (value) => {\n if (done) return\n done = true\n resolvePromise(value)\n }\n rejectValue = (error) => {\n if (done) return\n done = true\n rejectPromise(error)\n }\n })\n return {\n promise,\n resolve: resolveValue,\n reject: rejectValue,\n settled: () => done,\n }\n}\n\nfunction unavailable(message: string, cause?: unknown): SupervisorProvisionUnavailableError {\n return new SupervisorProvisionUnavailableError(message, cause)\n}\n\nfunction writeState(path: string, state: MutableState): void {\n mkdirSync(dirname(path), { recursive: true })\n writeAtomicDurableFile(path, `${JSON.stringify(state)}\\n`, { mode: 0o600 })\n}\n"],"mappings":";;;;;;;;;;;AAQA,MAAM,2BAA2B;;;;;;;;;;AAoBjC,eAAsB,gCACpB,SAC8C;CAC9C,MAAM,WAAW,QAAQ,sBAAsB;CAC/C,IAAI,CAAC,OAAO,cAAc,QAAQ,KAAK,WAAW,GAChD,MAAM,IAAI,MAAM,uEAAuE;CAGzF,IAAI,aAAa;CACjB,KAAK,IAAI,WAAW,GAAG,YAAY,0BAA0B,YAAY,GAAG;EAC1E,IAAI,QAAQ,QAAQ,SAAS,MAAM,WAAW,QAAQ,OAAO,MAAM;EACnE,MAAM,WAAW;GACf,aAAa,wBAAwB,QAAQ,QAAQ,QAAQ,UAAU,UAAU;GACjF,KAAK,QAAQ,OAAO;GACpB,UAAU,QAAQ;GAClB,oBAAoB;EACtB;EACA,MAAM,kBAAkB,MAAM,QAAQ,OAAO,aAC3C;GACE,GAAG;GACH,eAAe,iDAAiD,QAAQ;EAC1E,GACA,QAAQ,WAAW,KAAA,IAAY,KAAA,IAAY,EAAE,QAAQ,QAAQ,OAAO,CACtE;EACA,IAAI,gBAAgB,WAAW,cAAc,gBAAgB,WAAW,YAAY;GAClF,MAAM,UAAU,gBAAgB;GAChC,IAAI,YAAY,KAAA,GACd,MAAM,IAAI,MAAM,mEAAmE;GAErF,IAAI,KAAK,MAAM,QAAQ,SAAS,KAAK,KAAK,IAAI,GAC5C,MAAM,IAAI,MAAM,wDAAwD;GAE1E,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eAAe,KAAK;GACtB;GACA,eAAe,UAAU;IACvB,IAAI,MAAM;IACV,OAAO;IACP,cAAc,KAAK;GACrB;EACF,CAEQ;EACN,SAAS;EACT,QAAQ;EACR,eAAe;CACjB;AACF;AAEA,SAAS,YAAY,SAAiB,OAAsD;CAC1F,OAAO,IAAI,oCAAoC,SAAS,KAAK;AAC/D;AAEA,SAAS,WAAW,MAAc,OAA2B;CAC3D,UAAU,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;CAC5C,uBAAuB,MAAM,GAAG,KAAK,UAAU,KAAK,EAAE,KAAK,EAAE,MAAM,IAAM,CAAC;AAC5E"}
|
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Ai as sleep, Ci as chargedTokens, Di as isAbortError, Ei as hasCompleteCacheBreakdown, Ii as zeroSpend, Ir as isNoEntError, Lr as parseCommittedJsonLines, Rr as prepareJsonlAppend, Si as addSpend, St as contentAddress, Wi as armDeadlineTimer, X as rollingDispatch, ai as executableAgentSpecSnapshot, cn as runAgentRounds, dt as InMemorySpawnJournal, fn as assertBoxlessPromptOptions, ft as insideCursorNamespace, gn as canonicalObservedModelParts, h as withDriverExecutor, hn as runBrainLoop, ii as executableAgentProfileSnapshot, it as createWorktreeCliExecutor, ji as stringifySafe, ki as randomSuffix, ln as createSandboxLineage, mn as routerBrain, n as createSupervisor, nt as createExecutorRegistry, oi as detachedFrozen, on as defaultSelectWinner, pn as readPromptOptions, tt as createExecutor, un as probeSandboxCapabilities, ut as InMemoryResultBlobStore, vi as notifySandboxEventObserver, w as settledToIteration, wi as cloneSpend, wn as createPushTraceSource, yt as isTraceAnalysisStore, zr as writeAllBytes } from "./supervisor-0ksHf44Z.js";
|
|
2
2
|
import { m as ValidationError, n as AnalystError, s as PlannerError } from "./errors-DodWX-cb.js";
|
|
3
|
-
import { E as profileChatClient, S as ObservationError, T as renderReport, b as sample, k as strategyAuthorMethod, v as refine, w as observe, x as sampleThenRefine, y as runAgentic } from "./structural-rollout-
|
|
4
|
-
import { c as profileModelExecutionSettings, i as concreteModelId, l as profileProviderModel, o as enforceTokenLimits, t as assertExecutableAgentProfile } from "./model-policy-
|
|
3
|
+
import { E as profileChatClient, S as ObservationError, T as renderReport, b as sample, k as strategyAuthorMethod, v as refine, w as observe, x as sampleThenRefine, y as runAgentic } from "./structural-rollout-C_tpSY6Y.js";
|
|
4
|
+
import { c as profileModelExecutionSettings, i as concreteModelId, l as profileProviderModel, o as enforceTokenLimits, t as assertExecutableAgentProfile } from "./model-policy-BbSCSak0.js";
|
|
5
5
|
import { i as notifyRuntimeHookEvent } from "./runtime-hooks-tXpAarhW.js";
|
|
6
6
|
import { f as sha256Bytes, i as redactProtectedValue, o as canonicalCandidateDigest$1, r as redactProtectedReason, u as immutableCandidateValue } from "./protected-redaction-wGo44k2K.js";
|
|
7
|
-
import { _ as mapExecutorResult, g as gateOnDeliverable, n as supervise } from "./supervise-
|
|
8
|
-
import "./coordination-driver-
|
|
7
|
+
import { _ as mapExecutorResult, g as gateOnDeliverable, n as supervise } from "./supervise-Ah7kMn2p.js";
|
|
8
|
+
import "./coordination-driver-DcwOMS5C.js";
|
|
9
9
|
import "./run-layout-hZREkcfu.js";
|
|
10
|
-
import "./provision-supervisor-
|
|
11
|
-
import "./delegate-
|
|
12
|
-
import "./graph-
|
|
10
|
+
import "./provision-supervisor-ChEnL5xX.js";
|
|
11
|
+
import "./delegate-C9B_prgp.js";
|
|
12
|
+
import "./graph-B_6SZzlE.js";
|
|
13
13
|
import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, validateAgentProfileSecurity } from "@tangle-network/agent-interface";
|
|
14
14
|
import { CODING_HARNESSES, DEFAULT_TRACE_ANALYST_KINDS, InMemoryTraceStore, OUTPUT_VALUE, benjaminiHochberg, buildTrajectory, computeFindingId as computeFindingId$1, confidenceInterval, createTraceAnalyst, expandProfileAxes, makeFinding as makeFinding$1, pairedBootstrap, paretoFrontier, wilcoxonSignedRank, wilson } from "@tangle-network/agent-eval";
|
|
15
15
|
import { createAgentRunOutcomeTracker } from "@tangle-network/sandbox/runtime";
|
|
@@ -666,7 +666,7 @@ async function connectStdioMcp(spec) {
|
|
|
666
666
|
const pending = /* @__PURE__ */ new Map();
|
|
667
667
|
const failAllPending = (err) => {
|
|
668
668
|
for (const p of pending.values()) {
|
|
669
|
-
|
|
669
|
+
p.clearTimer();
|
|
670
670
|
p.reject(err);
|
|
671
671
|
}
|
|
672
672
|
pending.clear();
|
|
@@ -693,7 +693,7 @@ async function connectStdioMcp(spec) {
|
|
|
693
693
|
const p = pending.get(msg.id);
|
|
694
694
|
if (!p) return;
|
|
695
695
|
pending.delete(msg.id);
|
|
696
|
-
|
|
696
|
+
p.clearTimer();
|
|
697
697
|
p.resolve(msg);
|
|
698
698
|
});
|
|
699
699
|
const send = (msg) => {
|
|
@@ -703,14 +703,14 @@ async function connectStdioMcp(spec) {
|
|
|
703
703
|
if (spawnFault) return reject(spawnFault);
|
|
704
704
|
if (closed) return reject(/* @__PURE__ */ new Error("MCP connection closed"));
|
|
705
705
|
const id = nextId++;
|
|
706
|
-
const
|
|
706
|
+
const clearTimer = armDeadlineTimer(timeoutMs, () => {
|
|
707
707
|
pending.delete(id);
|
|
708
708
|
reject(new Error(redactReason(`${timeoutMessage}${stderrTail()}`)));
|
|
709
|
-
},
|
|
709
|
+
}, true);
|
|
710
710
|
pending.set(id, {
|
|
711
711
|
resolve,
|
|
712
712
|
reject,
|
|
713
|
-
|
|
713
|
+
clearTimer
|
|
714
714
|
});
|
|
715
715
|
try {
|
|
716
716
|
send({
|
|
@@ -721,7 +721,7 @@ async function connectStdioMcp(spec) {
|
|
|
721
721
|
});
|
|
722
722
|
} catch (err) {
|
|
723
723
|
pending.delete(id);
|
|
724
|
-
|
|
724
|
+
clearTimer();
|
|
725
725
|
reject(new Error(redactReason(`writing to MCP server stdin failed: ${err instanceof Error ? err.message : String(err)}${stderrTail()}`)));
|
|
726
726
|
}
|
|
727
727
|
});
|
|
@@ -2576,7 +2576,7 @@ function execute(args, timeoutMs, limit, signal) {
|
|
|
2576
2576
|
if (error.code !== "ESRCH") child.kill("SIGKILL");
|
|
2577
2577
|
}
|
|
2578
2578
|
};
|
|
2579
|
-
const
|
|
2579
|
+
const clearTimer = armDeadlineTimer(timeoutMs, () => stop("timeout"), true);
|
|
2580
2580
|
const cancel = () => stop("cancelled");
|
|
2581
2581
|
signal?.addEventListener("abort", cancel, { once: true });
|
|
2582
2582
|
if (signal?.aborted) cancel();
|
|
@@ -2600,7 +2600,7 @@ function execute(args, timeoutMs, limit, signal) {
|
|
|
2600
2600
|
spawnError = error;
|
|
2601
2601
|
});
|
|
2602
2602
|
child.on("close", (code) => {
|
|
2603
|
-
|
|
2603
|
+
clearTimer();
|
|
2604
2604
|
signal?.removeEventListener("abort", cancel);
|
|
2605
2605
|
const out = Buffer.concat(stdout).toString();
|
|
2606
2606
|
const err = Buffer.concat(stderr).toString();
|
|
@@ -4271,21 +4271,21 @@ async function preflightModels(cfg) {
|
|
|
4271
4271
|
const failures = (await Promise.allSettled(models.map(async (model) => {
|
|
4272
4272
|
const controller = new AbortController();
|
|
4273
4273
|
let timeoutError;
|
|
4274
|
-
let
|
|
4274
|
+
let clearTimer;
|
|
4275
4275
|
try {
|
|
4276
4276
|
await Promise.race([check(model, cfg.worker, controller.signal), new Promise((_, reject) => {
|
|
4277
|
-
|
|
4277
|
+
clearTimer = armDeadlineTimer(timeoutMs, () => {
|
|
4278
4278
|
timeoutError = /* @__PURE__ */ new Error(`timed out after ${timeoutMs} ms`);
|
|
4279
4279
|
controller.abort(timeoutError);
|
|
4280
4280
|
reject(timeoutError);
|
|
4281
|
-
},
|
|
4281
|
+
}, true);
|
|
4282
4282
|
})]);
|
|
4283
4283
|
} catch (cause) {
|
|
4284
4284
|
const reported = timeoutError ?? cause;
|
|
4285
4285
|
const message = reported instanceof Error ? reported.message : String(reported);
|
|
4286
4286
|
throw new Error(`Benchmark model "${model}" preflight failed: ${message}`, { cause: reported });
|
|
4287
4287
|
} finally {
|
|
4288
|
-
|
|
4288
|
+
clearTimer?.();
|
|
4289
4289
|
}
|
|
4290
4290
|
}))).flatMap((result) => result.status === "rejected" ? [result.reason] : []);
|
|
4291
4291
|
if (failures.length === 1) throw failures[0];
|
|
@@ -5727,12 +5727,12 @@ function codeModeSupervisorTools(runner, options = {}) {
|
|
|
5727
5727
|
const execution = new AbortController();
|
|
5728
5728
|
let timedOut = false;
|
|
5729
5729
|
const onScopeAbort = () => execution.abort(abortReason(context.signal));
|
|
5730
|
-
const
|
|
5730
|
+
const clearTimer = timeoutMs === null ? void 0 : armDeadlineTimer(timeoutMs, () => {
|
|
5731
5731
|
if (!execution.signal.aborted) {
|
|
5732
5732
|
timedOut = true;
|
|
5733
5733
|
execution.abort(new ValidationError(`code mode: program timed out after ${timeoutMs}ms`));
|
|
5734
5734
|
}
|
|
5735
|
-
},
|
|
5735
|
+
}, true);
|
|
5736
5736
|
if (context.signal.aborted) execution.abort(abortReason(context.signal));
|
|
5737
5737
|
else context.signal.addEventListener("abort", onScopeAbort, { once: true });
|
|
5738
5738
|
const bindings = {};
|
|
@@ -5754,7 +5754,7 @@ function codeModeSupervisorTools(runner, options = {}) {
|
|
|
5754
5754
|
signal: execution.signal
|
|
5755
5755
|
});
|
|
5756
5756
|
} finally {
|
|
5757
|
-
|
|
5757
|
+
clearTimer?.();
|
|
5758
5758
|
context.signal.removeEventListener("abort", onScopeAbort);
|
|
5759
5759
|
}
|
|
5760
5760
|
}
|
|
@@ -7171,4 +7171,4 @@ function tail(s) {
|
|
|
7171
7171
|
//#endregion
|
|
7172
7172
|
export { InMemoryCorpus as $, chatWorkerSeam as A, pairwiseSignificance as At, SandboxRunAbortError as B, createMcpEnvironment as Bt, withUntrackedArtifacts as C, loopDispatch as Ct, codeModeSupervisorTools as D, sentinelCompletion as Dt, runCoderChecks as E, deterministicCompletion as Et, selectChampion as F, auditIntent as Ft, equalKOnCost as G, resolveSecretEnv as Gt, printBenchmarkReport as H, envKeyProvider as Ht, assertStrategyContract as I, defaultAuditorInstruction as It, runPersonified as J, trajectoryReport as K, secretEnvOfMcpServer as Kt, authorStrategy as L, McpSpawnFault as Lt, discriminatingMeans as M, renderLeaderboardMarkdown as Mt, pickChampion as N, renderLeaderboardSvg as Nt, unsafeInProcessRunner as O, stopSentinel as Ot, runStrategyEvolution as P, renderPairwiseMarkdown as Pt, FileCorpus as Q, strategyAuthorContract as R, connectStdioMcp as Rt, copyUntrackedIntoClone as S, loopCampaignDispatch as St, patchDelivered as T, completionAuthorizes as Tt, runBenchmark as U, mcpSecretEnvMetadataKey as Ut, openSandboxRun as V, sanitizeMcpToolSchema as Vt, promotionGate as W, resolveMcpServerLaunch as Wt, createShapeRegistry as X, builtinShapes as Y, registerShape as Z, NOTE_MAX_CHARS as _, harvestCorpus as _t, localShell as a, pipeline as at, composeWorkerEvidence as b, localSandboxClient as bt, createVerifierEnvironment as c, widen as ct, harvestSurfaceDiffs as d, createScopeAnalyst as dt, renderCorpusToInstructions as et, analystsFromRegistry as f, registryScopeAnalyst as ft, EVIDENCE_MAX_CHARS as g, HarvestError as gt, worktreeFanout as h, inProcessSandboxClient as ht, jjWorkspace as i, panel as it, createChatSessionStore as j, renderLeaderboardHtml as jt, chatTransportExecutor as k, leaderboard as kt, boxSurfaceReader as l, assertTraceDerivedFindings as lt, superviseSurface as m, runIsolatedCheck as mt, makeFinding$1 as n, flatWidenGate as nt, runInWorkspace as o, selectValidWinner as ot, failuresAnalyst as p, observationFromRegistry as pt, definePersona as q, createTangleSandboxExactProcessProvider as qt, gitWorkspace as r, loopUntil as rt, createWaterfallCollector as s, verify as st, computeFindingId$1 as t, fanout as tt, fsSurfaceReader as u, buildSteerContext as ut, VERIFY_TAIL_CHARS as v, defineLeaderboard as vt, analyzeTrace as w, superviseDispatch as wt, settledWorkerOut as x, inlineSandboxClient as xt, closingWorkerNote as y, resolveSandboxClient as yt, strategyAuthorSystemPrompt as z, materializeLocalMcp as zt };
|
|
7173
7173
|
|
|
7174
|
-
//# sourceMappingURL=runtime-
|
|
7174
|
+
//# sourceMappingURL=runtime-BVV9PbmE.js.map
|