@ai-sdk/harness 1.0.11 → 1.0.13

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/errors/harness-capability-unsupported-error.ts","../../src/errors/harness-error.ts","../../src/agent/harness-agent.ts","../../src/agent/internal/bridge-port-registry.ts","../../src/agent/internal/lifecycle-state-validation.ts","../../src/agent/internal/to-harness-stream.ts","../../src/agent/internal/run-prompt.ts","../../src/agent/internal/harness-stream-text-result.ts","../../src/agent/internal/translate-stream-part.ts","../../src/agent/internal/strip-work-dir.ts","../../src/agent/internal/turn-telemetry.ts","../../src/agent/internal/permission-mode.ts","../../src/agent/harness-agent-session.ts","../../src/agent/harness-agent-tool-approval-continuation.ts","../../src/agent/internal/bootstrap-recipe.ts","../../src/agent/internal/sandbox-bootstrap.ts","../../src/agent/internal/resolve-observability.ts","../../src/agent/prewarm.ts","../../src/agent/prepare-sandbox-for-harness.ts","../../src/agent/observability/file-reporter.ts","../../src/agent/observability/trace-tree-reporter.ts"],"sourcesContent":["import { AISDKError } from '@ai-sdk/provider';\nimport { HarnessError } from './harness-error';\n\nconst name = 'AI_HarnessCapabilityUnsupportedError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Thrown when a caller asks the harness to do something the adapter (or the\n * supplied sandbox) does not support, e.g. requesting manual compaction from\n * an adapter that only auto-compacts, or invoking `getPortUrl` on a sandbox\n * that does not expose one.\n *\n * The caller supplies the full human-readable message. Optional `harnessId`\n * is recorded as structured context for tooling.\n */\nexport class HarnessCapabilityUnsupportedError extends HarnessError {\n private readonly [symbol] = true;\n\n readonly harnessId?: string;\n\n constructor({\n message,\n harnessId,\n cause,\n }: {\n message: string;\n harnessId?: string;\n cause?: unknown;\n }) {\n super({ message, cause });\n Object.defineProperty(this, 'name', { value: name });\n this.harnessId = harnessId;\n }\n\n static isInstance(\n error: unknown,\n ): error is HarnessCapabilityUnsupportedError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_HarnessError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Base error type for failures originating in or signalled by a harness\n * adapter. Specific failure modes (e.g. unsupported capability) extend this\n * class.\n */\nexport class HarnessError extends AISDKError {\n private readonly [symbol] = true;\n\n constructor({ message, cause }: { message: string; cause?: unknown }) {\n super({ name, message, cause });\n }\n\n static isInstance(error: unknown): error is HarnessError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { HarnessCapabilityUnsupportedError } from '../errors/harness-capability-unsupported-error';\nimport type {\n HarnessV1Bootstrap,\n HarnessV1NetworkSandboxSession,\n HarnessV1SandboxProvider,\n} from '../v1';\nimport {\n asSchema,\n generateId,\n type Context,\n type ModelMessage,\n type ToolSet,\n} from '@ai-sdk/provider-utils';\nimport type {\n Agent,\n AgentCallParameters,\n AgentStreamParameters,\n GenerateTextResult,\n ReasoningFileOutput,\n ReasoningOutput,\n StreamTextResult,\n} from 'ai';\nimport type {\n HarnessAgentSandboxConfig,\n HarnessAgentSettings,\n} from './harness-agent-settings';\nimport { HarnessAgentSession } from './harness-agent-session';\nimport type {\n HarnessAgentAdapter,\n HarnessAgentContinueTurnState,\n HarnessAgentPermissionMode,\n HarnessAgentPrompt,\n HarnessAgentResumeSessionState,\n HarnessAgentToolSpec,\n} from './harness-agent-types';\nimport {\n collectHarnessAgentToolApprovalContinuations,\n type HarnessAgentToolApprovalContinuation,\n} from './harness-agent-tool-approval-continuation';\nimport { applyBootstrapRecipe } from './internal/bootstrap-recipe';\nimport {\n acquireBridgePort,\n releaseBridgePort,\n} from './internal/bridge-port-registry';\nimport {\n createSandboxBootstrapPlan,\n ensureSandboxDirectory,\n resolveSessionWorkDir,\n validateSandboxBootstrapSettings,\n type SandboxBootstrapPlan,\n} from './internal/sandbox-bootstrap';\nimport { buildObservability } from './internal/resolve-observability';\nimport { validateLifecycleStateData } from './internal/lifecycle-state-validation';\nimport {\n permissionModeNeedsBuiltinSupport,\n resolvePermissionMode,\n} from './internal/permission-mode';\n\n/** Extract the builtin tool set type from a harness adapter parameter. */\ntype BuiltinToolsOf<H> = H extends HarnessAgentAdapter<infer T> ? T : never;\n\n/**\n * Type-level merge of a harness's builtin tools with user-defined tools.\n * User tools override builtins on key collision.\n */\nexport type HarnessAllTools<\n THarness extends HarnessAgentAdapter<any>,\n TUserTools extends ToolSet,\n> = Omit<BuiltinToolsOf<THarness>, keyof TUserTools> & TUserTools;\n\n/**\n * Required `session` extension on every `HarnessAgent.generate` /\n * `HarnessAgent.stream` call. The agent operates exclusively on the\n * `HarnessAgentSession` the caller passes in — it owns no session\n * state of its own.\n */\nexport interface HarnessAgentCallExtensions {\n /**\n * Active session returned by `agent.createSession(...)`. Drives the\n * underlying harness adapter for this turn.\n */\n session: HarnessAgentSession;\n}\n\n/**\n * AI SDK `Agent` implementation that drives a third-party agent runtime\n * through a harness adapter (Claude Code, Codex, …).\n *\n * Behaviour summary:\n * - **Stateless definition.** Construct once at module scope. The agent\n * holds the harness adapter, the merged tool surface, the sandbox\n * provider and other config — never a live session. Per-call data\n * (prompt, abort signal, the `HarnessAgentSession`) lives on\n * `generate()` / `stream()`.\n * - **Explicit sessions.** Callers spawn sessions with\n * `agent.createSession(...)`, pass the returned\n * `HarnessAgentSession` on every `generate` / `stream`, and end it via\n * `session.detach()`, `session.stop()`, or `session.destroy()`.\n * - **Cross-process resume.** `createSession({ sessionId, resumeFrom })`\n * resumes from state previously returned by `session.detach()` or\n * `session.stop()`. The framework validates `resumeFrom` against the\n * harness's `lifecycleStateSchema` before handing it to the adapter.\n * `createSession({ sessionId, continueFrom })` resumes from state returned\n * by `session.suspendTurn()` before `continueStream()` /\n * `continueGenerate()`.\n * - **Host tool execution.** User tools passed in `settings.tools` are\n * executed on the host whenever the underlying runtime calls them;\n * the result is fed back to the harness via `submitToolResult`.\n * Adapter builtin tools (e.g. Claude Code's `Bash`) pass through\n * untouched.\n * - **Sandbox propagation.** `settings.sandbox` is a sandbox provider.\n * On `createSession`, the agent calls `provider.createSession()` (or\n * `resumeSession()`) and passes the resulting network sandbox session into\n * `doStart`. Its `restricted()` view (a tool-safe\n * `Experimental_SandboxSession`) is handed to user-tool `execute()` calls\n * via `experimental_sandbox`.\n */\nexport class HarnessAgent<\n THarness extends HarnessAgentAdapter<any> = HarnessAgentAdapter,\n TUserTools extends ToolSet = {},\n RUNTIME_CONTEXT extends Context = Context,\n> implements Agent<\n never,\n HarnessAllTools<THarness, TUserTools>,\n RUNTIME_CONTEXT,\n never\n> {\n readonly version = 'agent-v1' as const;\n readonly id: string | undefined;\n\n /**\n * Merged tool set exposed to AI SDK consumers: harness builtins +\n * user-defined tools, with user tools overriding builtins on key\n * collision. Built once at construction time so the typed surface is\n * stable across calls.\n */\n readonly tools: HarnessAllTools<THarness, TUserTools>;\n\n private readonly settings: HarnessAgentSettings<THarness, TUserTools>;\n private readonly sandboxConfig: HarnessAgentSandboxConfig;\n private readonly userTools: TUserTools;\n private readonly permissionMode: HarnessAgentPermissionMode;\n\n constructor(settings: HarnessAgentSettings<THarness, TUserTools>) {\n const sandboxConfig = resolveSandboxConfig(settings);\n validateSandboxBootstrapSettings(sandboxConfig);\n this.settings = settings;\n this.sandboxConfig = sandboxConfig;\n this.id = settings.id;\n this.userTools = settings.tools ?? ({} as TUserTools);\n this.permissionMode = resolvePermissionMode({\n permissionMode: settings.permissionMode,\n });\n if (\n Object.keys(settings.harness.builtinTools).length > 0 &&\n permissionModeNeedsBuiltinSupport({\n permissionMode: this.permissionMode,\n }) &&\n settings.harness.supportsBuiltinToolApprovals !== true\n ) {\n throw new HarnessCapabilityUnsupportedError({\n message: `Harness '${settings.harness.harnessId}' does not support built-in tool approval requests; use permissionMode: 'allow-all'.`,\n harnessId: settings.harness.harnessId,\n });\n }\n this.tools = {\n ...settings.harness.builtinTools,\n ...this.userTools,\n } as HarnessAllTools<THarness, TUserTools>;\n }\n\n /** Identifier of the harness backing this agent. */\n get harnessId(): string {\n return this.settings.harness.harnessId;\n }\n\n /**\n * Start a fresh session, or resume from state previously returned by\n * `session.detach()` or `session.stop()`. The returned\n * `HarnessAgentSession` must be passed to subsequent `generate` / `stream`\n * calls; end it with `session.detach()`, `session.stop()`, or\n * `session.destroy()`.\n */\n async createSession(options?: {\n /**\n * Optional stable identifier for the underlying sandbox/session.\n * When omitted the agent generates one. Supply the original\n * `session.sessionId` together with `resumeFrom` to reattach a\n * previously ended session across processes.\n */\n sessionId?: string;\n /**\n * Resume payload returned by a prior `session.detach()` or\n * `session.stop()`. Must be accompanied by the original `sessionId`; the\n * framework validates it against `harness.lifecycleStateSchema` before\n * handing it to the adapter.\n */\n resumeFrom?: HarnessAgentResumeSessionState;\n /**\n * Continuation payload returned by a prior `session.suspendTurn()`. Must be\n * accompanied by the original `sessionId`; the framework validates it before\n * handing it to the adapter.\n */\n continueFrom?: HarnessAgentContinueTurnState;\n abortSignal?: AbortSignal;\n }): Promise<HarnessAgentSession> {\n const sessionId = options?.sessionId ?? generateId();\n const resumeFrom = options?.resumeFrom;\n const continueFrom = options?.continueFrom;\n const abortSignal = options?.abortSignal;\n const harness = this.settings.harness;\n const sandboxProvider = this.settings.sandbox;\n\n if (resumeFrom != null && continueFrom != null) {\n throw new Error(\n 'HarnessAgent.createSession: pass either `resumeFrom` or `continueFrom`, not both.',\n );\n }\n\n let validatedResumeFrom: HarnessAgentResumeSessionState | undefined;\n if (resumeFrom != null) {\n validatedResumeFrom = await validateLifecycleStateData({\n harness,\n state: resumeFrom,\n expectedType: 'resume-session',\n });\n }\n\n let validatedContinueFrom: HarnessAgentContinueTurnState | undefined;\n if (continueFrom != null) {\n validatedContinueFrom = await validateLifecycleStateData({\n harness,\n state: continueFrom,\n expectedType: 'continue-turn',\n });\n }\n\n const effectiveContinueFrom =\n validatedContinueFrom ?? validatedResumeFrom?.continueFrom;\n const isResumedSession =\n validatedResumeFrom != null || effectiveContinueFrom != null;\n\n let recipe: HarnessV1Bootstrap | undefined;\n if (harness.getBootstrap != null) {\n recipe = await harness.getBootstrap({ abortSignal });\n }\n\n // Defines the hashes based on both harness bootstrap recipe and\n // consumer-defined onBootstrap callback.\n const sandboxBootstrapPlan = await createSandboxBootstrapPlan({\n recipe,\n settings: this.sandboxConfig,\n });\n\n // Acquires the concrete sandbox session, either by starting fresh and then\n // creating a post-bootstrap snapshot, or by reusing a previously created\n // snapshot based on the bootstrap-based hashes.\n const acquiredSandboxSession = await this._acquireSandbox({\n sandboxProvider,\n sessionId,\n isResume: isResumedSession,\n bootstrapPlan: sandboxBootstrapPlan,\n abortSignal,\n });\n\n const leased = applyPortLease({\n provider: sandboxProvider,\n sandboxSession: acquiredSandboxSession,\n sessionId,\n });\n const sandboxSession = leased.sandboxSession;\n const leasedBridgePort = leased.port;\n const sessionWorkDir = resolveSessionWorkDir({\n defaultWorkingDirectory: sandboxSession.defaultWorkingDirectory,\n harnessId: harness.harnessId,\n sessionId,\n workDir: sandboxBootstrapPlan.workDir,\n });\n\n try {\n // In case the sandbox session was created with a custom sandbox, or in\n // case the sandbox provider doesn't respect `onFirstCreate`, we still\n // have to ensure the harness bootstrap recipe has run. In the common\n // scenario, this will be a cheap no-op based on just a marker check.\n if (\n !isResumedSession &&\n sandboxBootstrapPlan.recipe != null &&\n sandboxBootstrapPlan.recipeIdentity != null\n ) {\n await applyBootstrapRecipe(\n sandboxSession.restricted(),\n sandboxBootstrapPlan.recipe,\n sandboxBootstrapPlan.recipeIdentity,\n { abortSignal },\n );\n }\n await ensureSandboxDirectory({\n session: sandboxSession,\n workDir: sessionWorkDir,\n abortSignal,\n });\n if (this.sandboxConfig.onSession != null) {\n await this.sandboxConfig.onSession({\n session: sandboxSession.restricted(),\n sessionWorkDir,\n abortSignal,\n });\n }\n } catch (err) {\n await cleanupAfterStartFailure({\n sandboxProvider,\n sandboxSession,\n sessionId,\n leasedBridgePort,\n });\n throw err;\n }\n\n try {\n const baseStartOptions = {\n sessionId,\n skills: this.settings.skills,\n resumeFrom: validatedResumeFrom,\n continueFrom: effectiveContinueFrom,\n permissionMode: this.permissionMode,\n abortSignal,\n observability: buildObservability({ settings: this.settings }),\n };\n const underlyingSession = await harness.doStart({\n ...baseStartOptions,\n sandboxSession,\n sessionWorkDir,\n });\n return new HarnessAgentSession({\n sessionId,\n harness,\n underlyingSession,\n sandboxSession,\n sandboxProvider,\n leasedBridgePort,\n sessionWorkDir,\n toolApproval: this.settings.toolApproval,\n pendingToolApprovals: effectiveContinueFrom?.pendingToolApprovals,\n turnState:\n effectiveContinueFrom == null\n ? 'idle'\n : effectiveContinueFrom.pendingToolApprovals != null &&\n effectiveContinueFrom.pendingToolApprovals.length > 0\n ? 'awaiting-approval'\n : 'suspended',\n });\n } catch (error) {\n await cleanupAfterStartFailure({\n sandboxProvider,\n sandboxSession,\n sessionId,\n leasedBridgePort,\n });\n throw error;\n }\n }\n\n async generate(\n options: AgentCallParameters<\n never,\n HarnessAllTools<THarness, TUserTools>,\n RUNTIME_CONTEXT\n > &\n HarnessAgentCallExtensions,\n ): Promise<\n GenerateTextResult<\n HarnessAllTools<THarness, TUserTools>,\n RUNTIME_CONTEXT,\n never\n >\n > {\n const turnInput = this._resolveTurnInput(options);\n const runtimeContext = {} as RUNTIME_CONTEXT;\n const { result, done } = this._startTurn({\n session: options.session,\n turnInput,\n runtimeContext,\n abortSignal: options.abortSignal,\n });\n await done;\n return this._toGenerateResult(result);\n }\n\n async stream(\n options: AgentStreamParameters<\n never,\n HarnessAllTools<THarness, TUserTools>,\n RUNTIME_CONTEXT\n > &\n HarnessAgentCallExtensions,\n ): Promise<\n StreamTextResult<\n HarnessAllTools<THarness, TUserTools>,\n RUNTIME_CONTEXT,\n never\n >\n > {\n const turnInput = this._resolveTurnInput(options);\n const runtimeContext = {} as RUNTIME_CONTEXT;\n const { result } = this._startTurn({\n session: options.session,\n turnInput,\n runtimeContext,\n abortSignal: options.abortSignal,\n });\n return result;\n }\n\n /**\n * Continue the in-flight turn **without a new prompt**, draining it like\n * {@link generate}. Used after `createSession({ continueFrom })` to finish\n * consuming a turn that crossed a process boundary.\n */\n async continueGenerate(options: {\n session: HarnessAgentSession;\n toolApprovalContinuations?: readonly HarnessAgentToolApprovalContinuation[];\n abortSignal?: AbortSignal;\n }): Promise<\n GenerateTextResult<\n HarnessAllTools<THarness, TUserTools>,\n RUNTIME_CONTEXT,\n never\n >\n > {\n const runtimeContext = {} as RUNTIME_CONTEXT;\n\n const { result, done } = this._startTurn({\n session: options.session,\n turnInput: {\n mode: 'continue',\n toolApprovalContinuations: options.toolApprovalContinuations ?? [],\n },\n runtimeContext,\n abortSignal: options.abortSignal,\n });\n await done;\n return this._toGenerateResult(result);\n }\n\n /**\n * Continue the in-flight turn **without a new prompt**, streaming its events\n * like {@link stream}. Used to keep consuming a turn that is still running\n * (or finished) in the runtime after a process boundary — the workflow slice\n * loop calls this on every slice after the first. Routes through the adapter's\n * `doContinueTurn`; what it can guarantee (lossless attach vs. lossy rerun)\n * follows from how the adapter resumed the session.\n */\n async continueStream(options: {\n session: HarnessAgentSession;\n toolApprovalContinuations?: readonly HarnessAgentToolApprovalContinuation[];\n abortSignal?: AbortSignal;\n }): Promise<\n StreamTextResult<\n HarnessAllTools<THarness, TUserTools>,\n RUNTIME_CONTEXT,\n never\n >\n > {\n const runtimeContext = {} as RUNTIME_CONTEXT;\n\n const { result } = this._startTurn({\n session: options.session,\n turnInput: {\n mode: 'continue',\n toolApprovalContinuations: options.toolApprovalContinuations ?? [],\n },\n runtimeContext,\n abortSignal: options.abortSignal,\n });\n return result;\n }\n\n // ─── Internals ──────────────────────────────────────────────────────\n\n private _startTurn(input: {\n session: HarnessAgentSession;\n turnInput:\n | { mode: 'prompt'; prompt: HarnessAgentPrompt }\n | {\n mode: 'continue';\n toolApprovalContinuations: readonly HarnessAgentToolApprovalContinuation[];\n };\n runtimeContext: RUNTIME_CONTEXT;\n abortSignal: AbortSignal | undefined;\n }): {\n result: StreamTextResult<\n HarnessAllTools<THarness, TUserTools>,\n RUNTIME_CONTEXT,\n never\n >;\n done: Promise<void>;\n } {\n if (input.turnInput.mode === 'continue') {\n return input.session.continueTurn<\n HarnessAllTools<THarness, TUserTools>,\n RUNTIME_CONTEXT\n >({\n instructions: this.settings.instructions,\n tools: this.tools,\n toolSpecs: this._toToolSpecs(),\n runtimeContext: input.runtimeContext,\n abortSignal: input.abortSignal,\n telemetry: this.settings.telemetry,\n toolApprovalContinuations: input.turnInput.toolApprovalContinuations,\n });\n }\n\n return input.session.promptTurn<\n HarnessAllTools<THarness, TUserTools>,\n RUNTIME_CONTEXT\n >({\n prompt: input.turnInput.prompt,\n instructions: this.settings.instructions,\n tools: this.tools,\n toolSpecs: this._toToolSpecs(),\n runtimeContext: input.runtimeContext,\n abortSignal: input.abortSignal,\n telemetry: this.settings.telemetry,\n });\n }\n\n private async _acquireSandbox(input: {\n sandboxProvider: HarnessV1SandboxProvider;\n sessionId: string;\n isResume: boolean;\n bootstrapPlan: SandboxBootstrapPlan;\n abortSignal: AbortSignal | undefined;\n }): Promise<HarnessV1NetworkSandboxSession> {\n const { sandboxProvider } = input;\n if (input.isResume) {\n if (sandboxProvider.resumeSession == null) {\n throw new HarnessCapabilityUnsupportedError({\n message: `Sandbox provider '${sandboxProvider.providerId}' does not support resume.`,\n harnessId: this.settings.harness.harnessId,\n });\n }\n return sandboxProvider.resumeSession({\n sessionId: input.sessionId,\n abortSignal: input.abortSignal,\n });\n }\n return sandboxProvider.createSession({\n sessionId: input.sessionId,\n abortSignal: input.abortSignal,\n identity: input.bootstrapPlan.identity,\n onFirstCreate: input.bootstrapPlan.onFirstCreate,\n });\n }\n\n /*\n * Reduce AI SDK input to the single user message the harness should run\n * for this turn. The harness session owns prior-turn state (system\n * prompt, assistant turns, tool results) — we never replay it. A bare\n * string is forwarded as-is; a message array is collapsed to its last\n * `role: 'user'` entry. Inputs whose only messages are non-user (system,\n * assistant, tool) have no fresh user input and are rejected.\n */\n private _resolveTurnInput(options: {\n prompt?: string | ModelMessage[];\n messages?: ModelMessage[];\n }):\n | { mode: 'prompt'; prompt: HarnessAgentPrompt }\n | {\n mode: 'continue';\n toolApprovalContinuations: readonly HarnessAgentToolApprovalContinuation[];\n } {\n if (typeof options.prompt === 'string') {\n return { mode: 'prompt', prompt: options.prompt };\n }\n const messages = Array.isArray(options.prompt)\n ? options.prompt\n : options.messages;\n if (Array.isArray(messages)) {\n const toolApprovalContinuations =\n collectHarnessAgentToolApprovalContinuations({ messages });\n if (toolApprovalContinuations.length > 0) {\n return {\n mode: 'continue',\n toolApprovalContinuations,\n };\n }\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (message?.role === 'user')\n return { mode: 'prompt', prompt: message };\n }\n throw new Error(\n 'HarnessAgent: messages must contain at least one `role: \"user\"` entry.',\n );\n }\n throw new Error('HarnessAgent: either `prompt` or `messages` is required.');\n }\n\n /*\n * Wire-format projection of user-defined tools only. Harness builtins are\n * executed by the runtime and the bridge already knows about them — we\n * never re-declare them over the wire.\n */\n private _toToolSpecs(): HarnessAgentToolSpec[] {\n const specs: HarnessAgentToolSpec[] = [];\n for (const [name, tool] of Object.entries(\n this.userTools as Record<string, unknown>,\n )) {\n const t = tool as {\n description?: string;\n inputSchema?: unknown;\n };\n let inputSchema: HarnessAgentToolSpec['inputSchema'];\n if (t.inputSchema != null) {\n try {\n inputSchema = asSchema(\n t.inputSchema as Parameters<typeof asSchema>[0],\n ).jsonSchema as HarnessAgentToolSpec['inputSchema'];\n } catch {\n // tools without a usable schema are still forwarded by name\n }\n }\n specs.push({ name, description: t.description, inputSchema });\n }\n return specs;\n }\n\n private async _toGenerateResult(\n streamResult: StreamTextResult<\n HarnessAllTools<THarness, TUserTools>,\n RUNTIME_CONTEXT,\n never\n >,\n ): Promise<\n GenerateTextResult<\n HarnessAllTools<THarness, TUserTools>,\n RUNTIME_CONTEXT,\n never\n >\n > {\n // The stream is already drained by the time generate() calls this helper\n // (done has resolved). `steps` is the single source of truth the result\n // derives everything else from, mirroring core's `generateText` result.\n const [steps, usage, responseMessages] = await Promise.all([\n streamResult.steps,\n streamResult.usage,\n streamResult.responseMessages,\n ]);\n\n return new HarnessGenerateTextResult<\n HarnessAllTools<THarness, TUserTools>,\n RUNTIME_CONTEXT\n >({ steps, usage, responseMessages });\n }\n}\n\n/*\n * `GenerateTextResult` view over a drained `streamText` run. Non-deprecated\n * members derive from `steps` (the single source of truth), and the deprecated\n * members are exposed as getters that delegate to `finalStep` / `usage`.\n * Implementing the deprecated members as getters — rather than assigning them\n * in an object literal — keeps construction free of deprecated-property usage,\n * matching how core's `generateText` builds its result.\n */\nclass HarnessGenerateTextResult<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context,\n> implements GenerateTextResult<TOOLS, RUNTIME_CONTEXT, never> {\n readonly steps: GenerateTextResult<TOOLS, RUNTIME_CONTEXT, never>['steps'];\n readonly usage: GenerateTextResult<TOOLS, RUNTIME_CONTEXT, never>['usage'];\n readonly responseMessages: GenerateTextResult<\n TOOLS,\n RUNTIME_CONTEXT,\n never\n >['responseMessages'];\n readonly output = undefined as never;\n\n constructor(options: {\n steps: GenerateTextResult<TOOLS, RUNTIME_CONTEXT, never>['steps'];\n usage: GenerateTextResult<TOOLS, RUNTIME_CONTEXT, never>['usage'];\n responseMessages: GenerateTextResult<\n TOOLS,\n RUNTIME_CONTEXT,\n never\n >['responseMessages'];\n }) {\n this.steps = options.steps;\n this.usage = options.usage;\n this.responseMessages = options.responseMessages;\n }\n\n get finalStep() {\n return this.steps.at(-1)!;\n }\n\n get content() {\n return this.steps.flatMap(step => step.content);\n }\n\n get text() {\n return this.finalStep.text;\n }\n\n get files() {\n return this.steps.flatMap(step => step.files);\n }\n\n get sources() {\n return this.steps.flatMap(step => step.sources);\n }\n\n get toolCalls() {\n return this.steps.flatMap(step => step.toolCalls);\n }\n\n get staticToolCalls() {\n return this.steps.flatMap(step => step.staticToolCalls);\n }\n\n get dynamicToolCalls() {\n return this.steps.flatMap(step => step.dynamicToolCalls);\n }\n\n get toolResults() {\n return this.steps.flatMap(step => step.toolResults);\n }\n\n get staticToolResults() {\n return this.steps.flatMap(step => step.staticToolResults);\n }\n\n get dynamicToolResults() {\n return this.steps.flatMap(step => step.dynamicToolResults);\n }\n\n get finishReason() {\n return this.finalStep.finishReason;\n }\n\n get rawFinishReason() {\n return this.finalStep.rawFinishReason;\n }\n\n get warnings() {\n return this.steps.flatMap(step => step.warnings ?? []);\n }\n\n get reasoning() {\n return this.finalStep.content.filter(\n (part): part is ReasoningOutput | ReasoningFileOutput =>\n part.type === 'reasoning' || part.type === 'reasoning-file',\n );\n }\n\n get reasoningText() {\n return this.finalStep.reasoningText;\n }\n\n get totalUsage() {\n return this.usage;\n }\n\n get request() {\n return this.finalStep.request;\n }\n\n get response() {\n return this.finalStep.response;\n }\n\n get providerMetadata() {\n return this.finalStep.providerMetadata;\n }\n}\n\nfunction resolveSandboxConfig(\n settings: Pick<HarnessAgentSettings, 'sandboxConfig' | 'onSandboxSession'>,\n): HarnessAgentSandboxConfig {\n if (settings.onSandboxSession != null) {\n console.warn(\n 'HarnessAgent: `onSandboxSession` is deprecated. Use `sandboxConfig.onSession` instead.',\n );\n }\n\n return {\n ...settings.sandboxConfig,\n ...(settings.sandboxConfig?.onSession == null &&\n settings.onSandboxSession != null\n ? { onSession: settings.onSandboxSession }\n : {}),\n };\n}\n\n/*\n * Bridge-port leasing helper. Returns the port-narrowed network sandbox session\n * plus the leased port (or `undefined` when the provider has no port pool). Kept here\n * rather than on the session so the lease is established as part of session\n * start — the session only needs to release it on close/detach.\n */\nfunction applyPortLease(input: {\n provider: HarnessV1SandboxProvider;\n sandboxSession: HarnessV1NetworkSandboxSession;\n sessionId: string;\n}): {\n sandboxSession: HarnessV1NetworkSandboxSession;\n port: number | undefined;\n} {\n const pool = input.provider.bridgePorts;\n if (pool == null || pool.length === 0) {\n return { sandboxSession: input.sandboxSession, port: undefined };\n }\n const port = acquireBridgePort({\n poolKey: input.provider,\n pool,\n sessionId: input.sessionId,\n });\n return {\n sandboxSession: narrowNetworkSessionPorts(input.sandboxSession, port),\n port,\n };\n}\n\n/*\n * Derive a view of the network sandbox session that reports only the leased\n * port. Implemented as a prototype-delegating overlay so every other member\n * (file I/O, exec, spawn, lifecycle, `restricted`) forwards to the same live\n * instance — only `ports` is shadowed.\n */\nfunction narrowNetworkSessionPorts(\n sandboxSession: HarnessV1NetworkSandboxSession,\n leasedPort: number,\n): HarnessV1NetworkSandboxSession {\n return Object.create(sandboxSession, {\n ports: {\n value: [leasedPort] as ReadonlyArray<number>,\n enumerable: true,\n },\n }) as HarnessV1NetworkSandboxSession;\n}\n\nasync function cleanupAfterStartFailure(input: {\n sandboxProvider: HarnessV1SandboxProvider;\n sandboxSession: HarnessV1NetworkSandboxSession;\n sessionId: string;\n leasedBridgePort: number | undefined;\n}): Promise<void> {\n await Promise.resolve(input.sandboxSession.stop()).catch(() => {});\n if (input.leasedBridgePort != null) {\n releaseBridgePort({\n poolKey: input.sandboxProvider,\n sessionId: input.sessionId,\n });\n }\n}\n","/**\n * Process-wide registry for bridge-port leases. Used when a sandbox provider\n * wraps a caller-provided sandbox with a pre-declared port pool — each\n * concurrent harness session leases one port from the pool, releases on\n * session stop or destroy. Multiple sessions on the same provider instance\n * share the same pool; different provider instances (even wrapping the same\n * underlying sandbox) get independent registries.\n *\n * Sized to the typical case: one provider object passed to N HarnessAgents.\n * Callers that need cross-process coordination must layer that on top.\n */\n\ntype RegistryEntry = {\n readonly pool: ReadonlyArray<number>;\n readonly leases: Map<string, number>;\n};\n\nconst registries = new WeakMap<object, RegistryEntry>();\n\nexport function acquireBridgePort(options: {\n poolKey: object;\n pool: ReadonlyArray<number>;\n sessionId: string;\n}): number {\n let entry = registries.get(options.poolKey);\n if (entry == null) {\n entry = { pool: options.pool, leases: new Map() };\n registries.set(options.poolKey, entry);\n }\n const existing = entry.leases.get(options.sessionId);\n if (existing != null) return existing;\n\n const leased = new Set(entry.leases.values());\n for (const port of entry.pool) {\n if (!leased.has(port)) {\n entry.leases.set(options.sessionId, port);\n return port;\n }\n }\n throw new Error(\n `No available bridge port — pool of ${entry.pool.length} ports is fully leased.`,\n );\n}\n\nexport function releaseBridgePort(options: {\n poolKey: object;\n sessionId: string;\n}): void {\n const entry = registries.get(options.poolKey);\n if (entry == null) return;\n entry.leases.delete(options.sessionId);\n}\n","import { safeValidateTypes } from '@ai-sdk/provider-utils';\nimport { HarnessError } from '../../errors/harness-error';\nimport type { HarnessV1, HarnessV1LifecycleState } from '../../v1';\n\n/**\n * Validate a lifecycle state against the harness's contract:\n * - `type` must match the lifecycle method that will consume it.\n * - `specificationVersion` must be `'harness-v1'`.\n * - `harnessId` must match the harness producing/consuming the payload.\n * - When the harness declares a `lifecycleStateSchema`, `data` is parsed\n * against it.\n *\n * Returns the payload with `data` replaced by the parsed value when a\n * schema is present, so callers downstream see a canonical shape.\n */\nexport async function validateLifecycleStateData<\n STATE extends HarnessV1LifecycleState,\n>(input: {\n harness: HarnessV1;\n state: STATE;\n expectedType: STATE['type'];\n}): Promise<STATE> {\n const { harness, state } = input;\n if (state.type !== input.expectedType) {\n throw new HarnessError({\n message: `Lifecycle state has unexpected type '${state.type}'; expected '${input.expectedType}'.`,\n });\n }\n if (state.specificationVersion !== 'harness-v1') {\n throw new HarnessError({\n message: `Lifecycle state has unexpected specificationVersion '${state.specificationVersion}'; expected 'harness-v1'.`,\n });\n }\n if (state.harnessId !== harness.harnessId) {\n throw new HarnessError({\n message: `Lifecycle state was produced by harness '${state.harnessId}' but this agent uses '${harness.harnessId}'.`,\n });\n }\n if (\n state.type === 'resume-session' &&\n 'pendingToolApprovals' in state &&\n state.pendingToolApprovals !== undefined\n ) {\n throw new HarnessError({\n message:\n 'Resume session state cannot contain pending tool approvals; unfinished turns must be stored as `continueFrom`.',\n });\n }\n\n const data =\n harness.lifecycleStateSchema == null\n ? state.data\n : await (async () => {\n const result = await safeValidateTypes({\n value: state.data,\n schema: harness.lifecycleStateSchema!,\n });\n if (!result.success) {\n throw new HarnessError({\n message: `Lifecycle state failed schema validation for harness '${harness.harnessId}': ${result.error.message}`,\n cause: result.error,\n });\n }\n return result.value as STATE['data'];\n })();\n\n if (state.type === 'resume-session') {\n const continueFrom =\n state.continueFrom == null\n ? undefined\n : await validateLifecycleStateData({\n harness,\n state: state.continueFrom,\n expectedType: 'continue-turn',\n });\n\n return {\n type: state.type,\n harnessId: state.harnessId,\n specificationVersion: state.specificationVersion,\n data,\n ...(continueFrom !== undefined ? { continueFrom } : {}),\n } as STATE;\n }\n\n return {\n type: state.type,\n harnessId: state.harnessId,\n specificationVersion: state.specificationVersion,\n data,\n ...(state.pendingToolApprovals !== undefined\n ? { pendingToolApprovals: state.pendingToolApprovals }\n : {}),\n } as STATE;\n}\n","import type { HarnessV1PromptControl } from '../../v1/harness-v1-prompt-control';\nimport type { HarnessV1StreamPart } from '../../v1/harness-v1-stream-part';\n\n/**\n * Bridge an adapter's emit-based event surface into a pull-based\n * `ReadableStream<HarnessV1StreamPart>`.\n *\n * Adapters implement `doPromptTurn` / `doContinueTurn` against an `emit` callback\n * because that is the natural shape when wrapping an SDK that itself produces\n * events. Consumers (notably `HarnessAgent`) prefer a stream because that is\n * the idiomatic AI SDK shape. This helper converts the former into the latter\n * and is agnostic to which turn entry point produced the control surface — the\n * caller supplies an `invoke` thunk that wires `emit` into either method.\n *\n * Lifetime:\n * 1. Calls `invoke(emit)` immediately (which runs `doPromptTurn`/`doContinueTurn`).\n * 2. Every `emit(part)` becomes a stream chunk.\n * 3. When `control.done` resolves, the stream closes — this includes a\n * graceful `doSuspendTurn`, which resolves `done` cleanly after draining.\n * 4. When `control.done` rejects, an `{ type: 'error', error }` part is\n * enqueued and the stream is then closed normally. The rejection is\n * surfaced to consumers as a discriminated-union event rather than as\n * a stream error so iteration code does not need a separate try/catch\n * around the consumer loop.\n * 5. The supplied `abortSignal` (if any) aborts the underlying turn and\n * closes the stream.\n *\n * The returned `control` is the same object the adapter produced and is\n * intended for use by the consumer to submit tool results / approvals /\n * user messages back into the in-flight turn.\n */\nexport async function toHarnessStream(options: {\n invoke: (\n emit: (event: HarnessV1StreamPart) => void,\n ) => PromiseLike<HarnessV1PromptControl>;\n}): Promise<{\n stream: ReadableStream<HarnessV1StreamPart>;\n control: HarnessV1PromptControl;\n}> {\n let controller!: ReadableStreamDefaultController<HarnessV1StreamPart>;\n let closed = false;\n\n const stream = new ReadableStream<HarnessV1StreamPart>({\n start(c) {\n controller = c;\n },\n });\n\n const safeEnqueue = (part: HarnessV1StreamPart) => {\n if (closed) return;\n controller.enqueue(part);\n };\n\n const safeClose = () => {\n if (closed) return;\n closed = true;\n controller.close();\n };\n\n const control = await options.invoke(safeEnqueue);\n\n Promise.resolve(control.done)\n .then(\n () => safeClose(),\n (err: unknown) => {\n safeEnqueue({ type: 'error', error: err });\n safeClose();\n },\n )\n // Belt-and-suspenders: any throw inside the handlers themselves should\n // not become an unhandled rejection.\n .catch(() => {});\n\n return { stream, control };\n}\n","import type {\n HarnessV1,\n HarnessV1PendingToolApproval,\n HarnessV1Prompt,\n HarnessV1PromptControl,\n HarnessV1Session,\n HarnessV1StreamPart,\n HarnessV1ToolSpec,\n} from '../../v1';\nimport { toHarnessStream } from './to-harness-stream';\nimport {\n executeTool,\n generateId,\n isExecutableTool,\n safeParseJSON,\n type Context,\n type Experimental_SandboxSession as SandboxSession,\n type ToolSet,\n} from '@ai-sdk/provider-utils';\nimport type {\n LanguageModelV4FinishReason,\n LanguageModelV4ToolCall,\n LanguageModelV4Usage,\n} from '@ai-sdk/provider';\nimport { parseToolCall } from 'ai/internal';\nimport type { ContentPart, TelemetryOptions, TextStreamPart } from 'ai';\nimport type { HarnessAgentToolApprovalContinuation } from '../harness-agent-tool-approval-continuation';\nimport type { HarnessAgentToolApprovalConfiguration } from '../harness-agent-settings';\nimport { HarnessStreamTextResult } from './harness-stream-text-result';\nimport { translateStreamPart } from './translate-stream-part';\nimport { stripWorkDir } from './strip-work-dir';\nimport { createTurnTelemetry, type TurnContentPart } from './turn-telemetry';\nimport { resolveCustomToolApproval } from './permission-mode';\n\n/**\n * Drive one prompt turn end-to-end:\n * - call `session.doPromptTurn` via `toHarnessStream`\n * - translate harness events to AI SDK `TextStreamPart`s and push into the\n * result object\n * - execute host-side user tools when their `tool-call` events arrive and\n * submit results back to the harness\n * - close the result when the harness signals `finish` (or on error)\n *\n * Returns the result synchronously after the stream is wired up; callers\n * await its `PromiseLike` accessors to observe completion.\n */\nexport function runPrompt<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context,\n>(input: {\n harness: HarnessV1;\n session: HarnessV1Session;\n /**\n * Turn entry point. `'prompt'` (default) starts a new turn from `prompt`;\n * `'continue'` continues the in-flight turn via `doContinueTurn` and ignores\n * `prompt`/`instructions`.\n */\n mode?: 'prompt' | 'continue';\n /** Required for `mode: 'prompt'`; absent for `mode: 'continue'`. */\n prompt?: HarnessV1Prompt;\n instructions: string | undefined;\n tools: TOOLS;\n toolSpecs: HarnessV1ToolSpec[];\n sandboxSession: SandboxSession;\n sessionWorkDir: string;\n runtimeContext: RUNTIME_CONTEXT;\n abortSignal: AbortSignal | undefined;\n telemetry?: TelemetryOptions | undefined;\n toolApproval?: HarnessAgentToolApprovalConfiguration | undefined;\n pendingToolApprovals?: readonly HarnessV1PendingToolApproval[];\n toolApprovalContinuations?:\n | readonly HarnessAgentToolApprovalContinuation[]\n | undefined;\n onPendingToolApproval?: (approval: HarnessV1PendingToolApproval) => void;\n onToolApprovalSettled?: (approvalId: string) => void;\n onTurnFinished?: () => void;\n}): {\n result: HarnessStreamTextResult<TOOLS, RUNTIME_CONTEXT>;\n done: Promise<void>;\n} {\n const result = new HarnessStreamTextResult<TOOLS, RUNTIME_CONTEXT>({\n tools: input.tools,\n runtimeContext: input.runtimeContext,\n // toolsContext is not configurable for harnesses; pass undefined cast.\n toolsContext: undefined as never,\n harnessId: input.harness.harnessId,\n sessionId: input.session.sessionId,\n });\n const pendingToolApprovals = input.pendingToolApprovals ?? [];\n const onPendingToolApproval = input.onPendingToolApproval ?? (() => {});\n const onToolApprovalSettled = input.onToolApprovalSettled ?? (() => {});\n\n const telemetry = createTurnTelemetry({\n telemetry: input.telemetry,\n harnessId: input.harness.harnessId,\n modelId: input.session.modelId,\n instructions: input.instructions,\n promptText: input.prompt != null ? promptToText(input.prompt) : '',\n runtimeContext: input.runtimeContext,\n });\n\n const done = (async () => {\n let bridge: Awaited<ReturnType<typeof toHarnessStream>>;\n try {\n bridge = await toHarnessStream({\n invoke:\n input.mode === 'continue'\n ? emit =>\n input.session.doContinueTurn({\n tools: input.toolSpecs,\n abortSignal: input.abortSignal,\n emit,\n })\n : emit => {\n if (input.prompt == null) {\n throw new Error(\n 'runPrompt: `prompt` is required for mode \"prompt\".',\n );\n }\n return input.session.doPromptTurn({\n prompt: input.prompt,\n tools: input.toolSpecs,\n instructions: input.instructions,\n abortSignal: input.abortSignal,\n emit,\n });\n },\n });\n } catch (err) {\n telemetry.error(err);\n result.fail(err);\n return;\n }\n\n const { stream, control } = bridge;\n const reader = stream.getReader();\n const toolCallsByToolCallId = new Map<string, ToolCallTextStreamPart>();\n const rawToolCallsByToolCallId = new Map<\n string,\n Extract<HarnessV1StreamPart, { type: 'tool-call' }>\n >();\n const pendingApprovalsByApprovalId = new Map(\n pendingToolApprovals.map(approval => [approval.approvalId, approval]),\n );\n const pendingApprovalsByToolCallId = new Map(\n pendingToolApprovals.map(approval => [approval.toolCallId, approval]),\n );\n const continuationsByApprovalId = new Map(\n (input.toolApprovalContinuations ?? []).map(continuation => [\n continuation.approvalResponse.approvalId,\n continuation,\n ]),\n );\n const settledApprovalToolCallIds = new Set<string>();\n let finalFinish:\n | Extract<HarnessV1StreamPart, { type: 'finish' }>\n | undefined;\n\n // Accumulate the model's output content per step so telemetry can record\n // `gen_ai.output.messages` and reporters can log what was actually said.\n let stepText = '';\n let stepReasoning = '';\n let stepToolCalls: TurnContentPart[] = [];\n const buildStepContent = (): TurnContentPart[] => {\n const parts: TurnContentPart[] = [];\n if (stepText) parts.push({ type: 'text', text: stepText });\n if (stepReasoning) parts.push({ type: 'reasoning', text: stepReasoning });\n parts.push(...stepToolCalls);\n return parts;\n };\n const resetStepContent = (): void => {\n stepText = '';\n stepReasoning = '';\n stepToolCalls = [];\n };\n const zeroUsage: LanguageModelV4Usage = {\n inputTokens: {\n total: undefined,\n noCache: undefined,\n cacheRead: undefined,\n cacheWrite: undefined,\n },\n outputTokens: {\n total: undefined,\n text: undefined,\n reasoning: undefined,\n },\n };\n const toolCallsFinishReason: LanguageModelV4FinishReason = {\n unified: 'tool-calls',\n raw: undefined,\n };\n const finishForToolApprovalPause = async (): Promise<void> => {\n telemetry.stepFinish({\n finishReason: toolCallsFinishReason,\n usage: zeroUsage,\n content: buildStepContent(),\n });\n resetStepContent();\n result.finishStep({\n finishReason: toolCallsFinishReason,\n usage: zeroUsage,\n providerMetadata: undefined,\n warnings: [],\n });\n telemetry.end({\n finishReason: toolCallsFinishReason,\n usage: zeroUsage,\n });\n await result.finish();\n };\n const enqueueApprovalRequest = (approval: {\n approvalId: string;\n toolCall: ToolCallTextStreamPart;\n isAutomatic?: boolean;\n }): void => {\n result.enqueue({\n type: 'tool-approval-request',\n approvalId: approval.approvalId,\n toolCall: approval.toolCall,\n ...(approval.isAutomatic !== undefined\n ? { isAutomatic: approval.isAutomatic }\n : {}),\n } as TextStreamPart<TOOLS>);\n };\n const enqueueAutomaticApprovalResponse = (input: {\n approvalId: string;\n toolCall: ToolCallTextStreamPart;\n approved: boolean;\n reason?: string;\n providerExecuted?: boolean;\n }): void => {\n result.enqueue({\n type: 'tool-approval-response',\n approvalId: input.approvalId,\n toolCall: input.toolCall,\n approved: input.approved,\n ...(input.reason !== undefined ? { reason: input.reason } : {}),\n ...(input.providerExecuted !== undefined\n ? { providerExecuted: input.providerExecuted }\n : {}),\n } as TextStreamPart<TOOLS>);\n };\n const enqueueApprovalResponse = (\n approval: HarnessV1PendingToolApproval,\n continuation: HarnessAgentToolApprovalContinuation,\n ): void => {\n result.enqueue({\n type: 'tool-approval-response',\n approvalId: approval.approvalId,\n toolCall: continuation.toolCall,\n approved: continuation.approvalResponse.approved,\n ...(continuation.approvalResponse.reason !== undefined\n ? { reason: continuation.approvalResponse.reason }\n : {}),\n ...(approval.providerExecuted !== undefined\n ? { providerExecuted: approval.providerExecuted }\n : {}),\n } as TextStreamPart<TOOLS>);\n };\n const processPendingApprovalContinuation = async (\n approval: HarnessV1PendingToolApproval,\n continuation: HarnessAgentToolApprovalContinuation,\n ): Promise<void> => {\n enqueueApprovalResponse(approval, continuation);\n onToolApprovalSettled(approval.approvalId);\n pendingApprovalsByApprovalId.delete(approval.approvalId);\n pendingApprovalsByToolCallId.delete(approval.toolCallId);\n settledApprovalToolCallIds.add(approval.toolCallId);\n\n if (approval.kind === 'builtin') {\n if (control.submitToolApproval == null) {\n throw new Error(\n `Harness '${input.harness.harnessId}' emitted a built-in tool approval request but does not support approval responses.`,\n );\n }\n await control.submitToolApproval({\n approvalId: approval.approvalId,\n approved: continuation.approvalResponse.approved,\n reason: continuation.approvalResponse.reason,\n });\n return;\n }\n\n if (!continuation.approvalResponse.approved) {\n await control.submitToolResult({\n toolCallId: approval.toolCallId,\n output: {\n type: 'execution-denied',\n reason: continuation.approvalResponse.reason,\n },\n });\n return;\n }\n\n const rawToolCall =\n rawToolCallsByToolCallId.get(approval.toolCallId) ??\n ({\n type: 'tool-call',\n toolCallId: approval.toolCallId,\n toolName: approval.toolName,\n input: approval.input,\n } satisfies Extract<HarnessV1StreamPart, { type: 'tool-call' }>);\n\n const outcome = await maybeExecuteHostTool({\n event: rawToolCall,\n tools: input.tools,\n sandboxSession: input.sandboxSession,\n abortSignal: input.abortSignal,\n control,\n onPreliminaryResult: preliminaryOutput => {\n const stripped = stripWorkDir(\n {\n type: 'tool-result',\n toolCallId: rawToolCall.toolCallId,\n toolName: rawToolCall.toolName,\n result: preliminaryOutput as Extract<\n HarnessV1StreamPart,\n { type: 'tool-result' }\n >['result'],\n },\n input.sessionWorkDir,\n ) as Extract<HarnessV1StreamPart, { type: 'tool-result' }>;\n result.enqueue({\n type: 'tool-result',\n toolCallId: rawToolCall.toolCallId,\n toolName: rawToolCall.toolName,\n input: undefined,\n output: stripped.result,\n preliminary: true,\n } as TextStreamPart<TOOLS>);\n },\n });\n telemetry.toolEnd(rawToolCall.toolCallId, outcome);\n };\n\n try {\n for (const approval of pendingToolApprovals) {\n const continuation = continuationsByApprovalId.get(approval.approvalId);\n if (continuation != null) {\n await processPendingApprovalContinuation(approval, continuation);\n }\n }\n\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n if (value == null) continue;\n\n // Begin the operation span on stream-start, using the runtime-resolved\n // model the adapter reports (falling back to the session's model).\n if (value.type === 'stream-start') {\n telemetry.start(value.modelId ?? input.session.modelId);\n }\n\n // Open a step span lazily before the first content of each step.\n if (\n value.type !== 'stream-start' &&\n value.type !== 'finish-step' &&\n value.type !== 'finish' &&\n value.type !== 'error'\n ) {\n telemetry.ensureStepOpen();\n }\n\n /*\n * Strip the session working-directory prefix for everything the\n * consumer sees. The original `value` is kept intact for host tool\n * execution below — the tools need the absolute path to resolve\n * against the sandbox root, so the strip is display-only.\n */\n const displayValue = stripWorkDir(value, input.sessionWorkDir);\n const settledApprovalToolCallReplay =\n displayValue.type === 'tool-call' &&\n !displayValue.providerExecuted &&\n settledApprovalToolCallIds.has(displayValue.toolCallId);\n\n if (settledApprovalToolCallReplay) {\n continue;\n }\n\n // Forward to consumer as soon as possible.\n for (const part of translateStreamPart<TOOLS>(displayValue)) {\n result.enqueue(part);\n }\n\n // Tool-call validation lives here (not in translateStreamPart) because\n // schema parsing is async and needs the merged tool set in scope.\n if (displayValue.type === 'tool-call') {\n const parsed = await validateToolCall<TOOLS>({\n event: displayValue,\n tools: input.tools,\n });\n const parsedToolCall = asToolCallTextStreamPart({ part: parsed });\n rawToolCallsByToolCallId.set(displayValue.toolCallId, displayValue);\n toolCallsByToolCallId.set(displayValue.toolCallId, parsedToolCall);\n result.enqueue(parsed);\n }\n\n // Accumulate output content for telemetry / reporters.\n if (value.type === 'text-delta') {\n stepText += value.delta;\n } else if (value.type === 'reasoning-delta') {\n stepReasoning += value.delta;\n }\n\n // Telemetry: a tool execution begins on its `tool-call`.\n if (value.type === 'tool-call') {\n stepToolCalls.push({\n type: 'tool-call',\n toolCallId: value.toolCallId,\n toolName: value.toolName,\n input: value.input,\n });\n telemetry.toolStart({\n toolCallId: value.toolCallId,\n toolName: value.toolName,\n input: value.input,\n });\n }\n\n // Telemetry: close a tool span when its provider-executed result lands.\n if (value.type === 'tool-result') {\n telemetry.toolEnd(\n value.toolCallId,\n value.isError\n ? { ok: false, error: value.result }\n : { ok: true, output: value.result },\n );\n }\n\n if (value.type === 'tool-approval-request') {\n const toolCall = toolCallsByToolCallId.get(value.toolCallId);\n if (toolCall == null) {\n throw new Error(\n `Harness '${input.harness.harnessId}' emitted approval request '${value.approvalId}' for unknown tool call '${value.toolCallId}'.`,\n );\n }\n\n const rawToolCall = rawToolCallsByToolCallId.get(value.toolCallId);\n const pendingApproval =\n pendingApprovalsByApprovalId.get(value.approvalId) ??\n ({\n approvalId: value.approvalId,\n toolCallId: value.toolCallId,\n toolName: toolCall.toolName,\n input: rawToolCall?.input ?? JSON.stringify(toolCall.input),\n kind: 'builtin',\n providerExecuted: rawToolCall?.providerExecuted ?? true,\n ...(rawToolCall?.nativeName !== undefined\n ? { nativeName: rawToolCall.nativeName }\n : {}),\n } satisfies HarnessV1PendingToolApproval);\n pendingApprovalsByApprovalId.set(\n pendingApproval.approvalId,\n pendingApproval,\n );\n pendingApprovalsByToolCallId.set(\n pendingApproval.toolCallId,\n pendingApproval,\n );\n\n const continuation = continuationsByApprovalId.get(\n pendingApproval.approvalId,\n );\n if (continuation != null) {\n await processPendingApprovalContinuation(\n pendingApproval,\n continuation,\n );\n continue;\n }\n\n onPendingToolApproval(pendingApproval);\n enqueueApprovalRequest({\n approvalId: pendingApproval.approvalId,\n toolCall,\n });\n await finishForToolApprovalPause();\n return;\n }\n\n // Drive step boundaries.\n if (value.type === 'finish-step') {\n telemetry.stepFinish({\n finishReason: value.finishReason,\n usage: value.usage,\n providerMetadata: value.harnessMetadata,\n content: buildStepContent(),\n });\n resetStepContent();\n result.finishStep({\n finishReason: value.finishReason,\n usage: value.usage,\n providerMetadata: value.harnessMetadata,\n warnings: [],\n });\n }\n\n if (value.type === 'finish') {\n finalFinish = value;\n telemetry.end({\n finishReason: value.finishReason,\n usage: value.totalUsage,\n });\n }\n\n // Execute host-side tools when the harness asks for one.\n if (value.type === 'tool-call' && !value.providerExecuted) {\n const toolCall = value;\n const parsedToolCall = toolCallsByToolCallId.get(toolCall.toolCallId);\n if (parsedToolCall == null) {\n throw new Error(\n `Harness '${input.harness.harnessId}' could not find parsed tool call '${toolCall.toolCallId}' for custom tool approval.`,\n );\n }\n const customToolApprovalDecision = resolveCustomToolApproval({\n toolName: toolCall.toolName,\n toolApproval: input.toolApproval,\n });\n if (customToolApprovalDecision.type === 'deny') {\n const approvalId = generateId();\n enqueueApprovalRequest({\n approvalId,\n toolCall: parsedToolCall,\n isAutomatic: true,\n });\n enqueueAutomaticApprovalResponse({\n approvalId,\n toolCall: parsedToolCall,\n approved: false,\n reason: customToolApprovalDecision.reason,\n providerExecuted: false,\n });\n const output = {\n type: 'execution-denied',\n reason: customToolApprovalDecision.reason,\n };\n await control.submitToolResult({\n toolCallId: toolCall.toolCallId,\n output,\n });\n telemetry.toolEnd(toolCall.toolCallId, { ok: true, output });\n continue;\n }\n const pendingApproval =\n pendingApprovalsByToolCallId.get(toolCall.toolCallId) ??\n (customToolApprovalDecision.type === 'request'\n ? ({\n approvalId: generateId(),\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input: toolCall.input,\n kind: 'custom',\n providerExecuted: false,\n ...(toolCall.nativeName !== undefined\n ? { nativeName: toolCall.nativeName }\n : {}),\n } satisfies HarnessV1PendingToolApproval)\n : undefined);\n if (pendingApproval != null) {\n pendingApprovalsByApprovalId.set(\n pendingApproval.approvalId,\n pendingApproval,\n );\n pendingApprovalsByToolCallId.set(\n pendingApproval.toolCallId,\n pendingApproval,\n );\n const continuation = continuationsByApprovalId.get(\n pendingApproval.approvalId,\n );\n if (continuation != null) {\n await processPendingApprovalContinuation(\n pendingApproval,\n continuation,\n );\n continue;\n }\n const pendingParsedToolCall = toolCallsByToolCallId.get(\n pendingApproval.toolCallId,\n );\n if (pendingParsedToolCall == null) {\n throw new Error(\n `Harness '${input.harness.harnessId}' could not find parsed tool call '${pendingApproval.toolCallId}' for approval request '${pendingApproval.approvalId}'.`,\n );\n }\n onPendingToolApproval(pendingApproval);\n enqueueApprovalRequest({\n approvalId: pendingApproval.approvalId,\n toolCall: pendingParsedToolCall,\n });\n await finishForToolApprovalPause();\n return;\n }\n const outcome = await maybeExecuteHostTool({\n event: toolCall,\n tools: input.tools,\n sandboxSession: input.sandboxSession,\n abortSignal: input.abortSignal,\n control,\n onPreliminaryResult: preliminaryOutput => {\n /*\n * Project a `yield`ed value as a preliminary AI SDK\n * `tool-result` part. Unlike the final result — which is\n * submitted to the runtime, echoed back as a `tool-result`\n * event, and stripped on its way through the loop above —\n * preliminary values never reach the runtime, so strip the\n * working directory here to match the final result's projection.\n */\n const stripped = stripWorkDir(\n {\n type: 'tool-result',\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n result: preliminaryOutput as Extract<\n HarnessV1StreamPart,\n { type: 'tool-result' }\n >['result'],\n },\n input.sessionWorkDir,\n ) as Extract<HarnessV1StreamPart, { type: 'tool-result' }>;\n result.enqueue({\n type: 'tool-result',\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input: undefined,\n output: stripped.result,\n preliminary: true,\n } as TextStreamPart<TOOLS>);\n },\n });\n telemetry.toolEnd(toolCall.toolCallId, outcome);\n }\n\n if (value.type === 'error') {\n telemetry.error(value.error);\n result.fail(value.error);\n return;\n }\n }\n input.onTurnFinished?.();\n await result.finish(\n finalFinish\n ? {\n finishReason: finalFinish.finishReason,\n totalUsage: finalFinish.totalUsage,\n providerMetadata: finalFinish.harnessMetadata,\n }\n : undefined,\n );\n } catch (err) {\n telemetry.error(err);\n result.fail(err);\n } finally {\n reader.releaseLock();\n }\n })();\n\n // Swallow the loop's rejection at the top level — failures are observable\n // via the result's `fullStream` `error` part and rejected promise\n // accessors. We do not want the orphan promise to become an unhandled\n // rejection.\n done.catch(() => {});\n\n return { result, done };\n}\n\ntype HostToolOutcome =\n | { ok: true; output: unknown }\n | { ok: false; error: unknown };\n\nfunction asToolCallTextStreamPart<TOOLS extends ToolSet>(input: {\n part: TextStreamPart<TOOLS>;\n}): ToolCallTextStreamPart {\n if (input.part.type !== 'tool-call') {\n throw new Error(\n `Expected parsed tool-call stream part, got '${input.part.type}'.`,\n );\n }\n return input.part as ToolCallTextStreamPart;\n}\n\ntype ToolCallTextStreamPart = {\n readonly type: 'tool-call';\n readonly toolCallId: string;\n readonly toolName: string;\n readonly input: unknown;\n readonly providerExecuted?: boolean;\n readonly providerMetadata?: unknown;\n readonly dynamic?: boolean;\n readonly invalid?: boolean;\n readonly error?: unknown;\n readonly title?: string;\n};\n\nasync function maybeExecuteHostTool<TOOLS extends ToolSet>(input: {\n event: { toolCallId: string; toolName: string; input: string };\n tools: TOOLS;\n sandboxSession: SandboxSession;\n abortSignal: AbortSignal | undefined;\n control: HarnessV1PromptControl;\n /**\n * Called for each value a generator `execute` `yield`s before its last. The\n * caller surfaces these as preliminary `tool-result` parts on the consumer\n * stream. Never called for a plain (non-generator) `execute`.\n */\n onPreliminaryResult: (output: unknown) => void;\n}): Promise<HostToolOutcome> {\n const tool = input.tools[input.event.toolName];\n\n if (!isExecutableTool(tool)) return { ok: true, output: undefined };\n\n const parsed = await safeParseJSON({ text: input.event.input });\n const args = parsed.success ? parsed.value : input.event.input;\n\n try {\n /*\n * Normalize the tool's return value through `executeTool`, the same helper\n * the non-harness AI SDK uses, so generator `execute` functions behave\n * identically here: each `yield`ed value arrives as a `preliminary` part\n * and the last `yield` is re-emitted as the `final` part; a plain value or\n * Promise arrives as a single `final` part. The underlying runtimes accept\n * exactly one tool result per call, so only the final value is submitted\n * back to the model — preliminary values are surfaced to the consumer\n * stream alone, matching how the AI SDK treats `onPreliminaryToolResult`.\n */\n let output: unknown;\n const stream = executeTool({\n tool,\n input: args as never,\n options: {\n toolCallId: input.event.toolCallId,\n messages: [],\n abortSignal: input.abortSignal,\n context: undefined as never,\n experimental_sandbox: input.sandboxSession,\n },\n });\n for await (const part of stream) {\n if (part.type === 'preliminary') {\n input.onPreliminaryResult(part.output);\n } else {\n output = part.output;\n }\n }\n\n await input.control.submitToolResult({\n toolCallId: input.event.toolCallId,\n output,\n });\n return { ok: true, output };\n } catch (err) {\n await input.control.submitToolResult({\n toolCallId: input.event.toolCallId,\n output: { error: String(err) },\n isError: true,\n });\n return { ok: false, error: err };\n }\n}\n\n/*\n * Validate an inbound `tool-call` event against the merged tool set's schema\n * using the AI SDK's canonical `parseToolCall`. Returns an AI SDK `tool-call`\n * stream part with parsed input on success, or a `dynamic + invalid: true`\n * part on failure (unknown tool, schema mismatch, malformed JSON).\n *\n * The harness `tool-call` event is structurally a `LanguageModelV4ToolCall`\n * (plus an optional harness-only `nativeName`). `providerExecuted` already\n * lives on the V4 type — `true` for adapter builtins (Claude Code's `Bash`,\n * Codex's `shell`), false/undefined for host tools — and is passed through\n * to the AI SDK part by `parseToolCall`.\n */\nexport async function validateToolCall<TOOLS extends ToolSet>(args: {\n event: Extract<HarnessV1StreamPart, { type: 'tool-call' }>;\n tools: TOOLS;\n}): Promise<TextStreamPart<TOOLS>> {\n const { event, tools } = args;\n const toolCall: LanguageModelV4ToolCall = {\n type: 'tool-call',\n toolCallId: event.toolCallId,\n toolName: event.toolName,\n input: event.input,\n ...(event.providerExecuted !== undefined\n ? { providerExecuted: event.providerExecuted }\n : {}),\n ...(event.providerMetadata !== undefined\n ? { providerMetadata: event.providerMetadata }\n : {}),\n };\n\n const parsed = await parseToolCall<TOOLS>({\n toolCall,\n tools,\n repairToolCall: undefined,\n refineToolInput: undefined,\n instructions: undefined,\n messages: [],\n });\n\n return parsed as TextStreamPart<TOOLS>;\n}\n\n/** Best-effort plain text of the turn's prompt, for telemetry input messages. */\nfunction promptToText(prompt: HarnessV1Prompt): string {\n if (typeof prompt === 'string') return prompt;\n const content = (prompt as { content?: unknown }).content;\n if (typeof content === 'string') return content;\n if (Array.isArray(content)) {\n return content\n .filter(\n (part): part is { type: 'text'; text: string } =>\n typeof part === 'object' &&\n part != null &&\n (part as { type?: unknown }).type === 'text',\n )\n .map(part => part.text)\n .join('');\n }\n return '';\n}\n\n// keep import bound so unused-but-needed type stays cited\nexport type _ContentPartMarker<T extends ToolSet> = ContentPart<T>;\n","import {\n DelayedPromise,\n generateId,\n type AssistantModelMessage,\n type Context,\n type ToolModelMessage,\n type ToolSet,\n} from '@ai-sdk/provider-utils';\nimport {\n addLanguageModelUsage,\n asLanguageModelUsage,\n createAsyncIterableStream,\n createNullLanguageModelUsage,\n DefaultStepResult,\n toResponseMessages,\n} from 'ai/internal';\nimport type {\n LanguageModelV4FinishReason,\n LanguageModelV4Usage,\n} from '@ai-sdk/provider';\nimport {\n createUIMessageStreamResponse,\n toUIMessageStream as toUIMessageStreamHelper,\n type CallWarning,\n type ContentPart,\n type FinishReason,\n type GenerateTextResult,\n type InferUIMessageChunk,\n type LanguageModelUsage,\n type ProviderMetadata,\n type StepResult,\n type StreamTextResult,\n type TextStreamPart,\n type UIMessage,\n type UIMessageStreamOptions,\n} from 'ai';\n\ntype StreamProp<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context,\n KEY extends keyof StreamTextResult<TOOLS, RUNTIME_CONTEXT, never>,\n> = Awaited<StreamTextResult<TOOLS, RUNTIME_CONTEXT, never>[KEY]>;\n\n/**\n * Concrete `StreamTextResult` implementation backed by a single\n * harness prompt turn.\n *\n * Wraps a `ReadableStream<TextStreamPart<TOOLS>>` that the calling\n * driver pushes events into. Every `PromiseLike` accessor is backed by a\n * `DelayedPromise` so the AI SDK consumer surface stays identical to\n * `streamText`'s — consumers can `await result.text` or iterate\n * `result.fullStream`, in either order.\n *\n * Each `finish-step` boundary in the driver translates to a `StepResult`\n * built via `DefaultStepResult`. Step content is accumulated as\n * `ContentPart[]` and fed straight to `DefaultStepResult`, which derives\n * `text`, `toolCalls`, `toolResults`, `reasoning`, etc. via its getters.\n *\n * The Node.js response helpers (`pipeUIMessageStreamToResponse`,\n * `pipeTextStreamToResponse`, `toTextStreamResponse`) and the\n * output-specification surfaces (`partialOutputStream`/`elementStream`) are not\n * implemented yet — they throw a clear error.\n */\nexport class HarnessStreamTextResult<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context,\n> implements StreamTextResult<TOOLS, RUNTIME_CONTEXT, never> {\n // Delayed promises backing every PromiseLike accessor. Each is typed\n // against the corresponding `StreamTextResult` property so the public\n // surface stays in lockstep with AI SDK's interface as it evolves.\n private readonly _content = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'content'>\n >();\n private readonly _text = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'text'>\n >();\n private readonly _reasoning = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'reasoning'>\n >();\n private readonly _reasoningText = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'reasoningText'>\n >();\n private readonly _files = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'files'>\n >();\n private readonly _sources = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'sources'>\n >();\n private readonly _toolCalls = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'toolCalls'>\n >();\n private readonly _staticToolCalls = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'staticToolCalls'>\n >();\n private readonly _dynamicToolCalls = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'dynamicToolCalls'>\n >();\n private readonly _toolResults = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'toolResults'>\n >();\n private readonly _staticToolResults = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'staticToolResults'>\n >();\n private readonly _dynamicToolResults = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'dynamicToolResults'>\n >();\n private readonly _finishReason = new DelayedPromise<FinishReason>();\n private readonly _rawFinishReason = new DelayedPromise<string | undefined>();\n private readonly _usage = new DelayedPromise<LanguageModelUsage>();\n private readonly _warnings = new DelayedPromise<CallWarning[] | undefined>();\n private readonly _steps = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'steps'>\n >();\n private readonly _finalStep = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'finalStep'>\n >();\n private readonly _request = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'request'>\n >();\n private readonly _response = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'response'>\n >();\n private readonly _responseMessages = new DelayedPromise<\n Array<AssistantModelMessage | ToolModelMessage>\n >();\n private readonly _providerMetadata = new DelayedPromise<\n ProviderMetadata | undefined\n >();\n\n // The driver pushes parts into this controller; consumers read via `stream`.\n private readonly fullStreamController: ReadableStreamDefaultController<\n TextStreamPart<TOOLS>\n >;\n readonly stream: AsyncIterableStream<TextStreamPart<TOOLS>>;\n // `fullStream` is the deprecated alias that AI SDK still exposes on the\n // public interface. Backed by the same underlying stream as `stream`.\n readonly fullStream: AsyncIterableStream<TextStreamPart<TOOLS>>;\n readonly textStream: AsyncIterableStream<string>;\n\n private readonly stepsBuffer: StepResult<TOOLS, RUNTIME_CONTEXT>[] = [];\n private currentStepContent: ContentPart<TOOLS>[] = [];\n private currentStepWarnings: CallWarning[] = [];\n private stepNumber = 0;\n\n private readonly tools: TOOLS;\n private readonly runtimeContext: RUNTIME_CONTEXT;\n private readonly toolsContext: never;\n private readonly providerName: string;\n private readonly modelId: string;\n\n // Accumulators that span the whole turn.\n private accumulatedUsage: LanguageModelUsage = createNullLanguageModelUsage();\n private finalProviderMetadata: ProviderMetadata | undefined = undefined;\n private finalFinishReason: FinishReason = 'other';\n private finalRawFinishReason: string | undefined = undefined;\n private aggregateWarnings: CallWarning[] = [];\n private settled = false;\n\n constructor(options: {\n tools: TOOLS;\n runtimeContext: RUNTIME_CONTEXT;\n toolsContext: never;\n harnessId: string;\n sessionId: string;\n }) {\n this.tools = options.tools;\n this.runtimeContext = options.runtimeContext;\n this.toolsContext = options.toolsContext;\n this.providerName = `harness:${options.harnessId}`;\n this.modelId = options.sessionId;\n\n let controllerRef!: ReadableStreamDefaultController<TextStreamPart<TOOLS>>;\n const baseStream = new ReadableStream<TextStreamPart<TOOLS>>({\n start(c) {\n controllerRef = c;\n },\n });\n this.fullStreamController = controllerRef;\n\n const [forFull, forText] = baseStream.tee();\n this.stream = forFull as AsyncIterableStream<TextStreamPart<TOOLS>>;\n this.fullStream = this.stream;\n this.textStream = forText.pipeThrough(\n new TransformStream<TextStreamPart<TOOLS>, string>({\n transform(part, controller) {\n if (part.type === 'text-delta') {\n controller.enqueue(part.text);\n }\n },\n }),\n ) as AsyncIterableStream<string>;\n }\n\n // ─── Writer-side methods used by the driver ────────────────────────\n\n /**\n * Push a translated `TextStreamPart` into `fullStream` and accumulate it\n * into the current step's content array where applicable.\n */\n enqueue(part: TextStreamPart<TOOLS>): void {\n this.fullStreamController.enqueue(part);\n this.appendToCurrentStepContent(part);\n }\n\n /**\n * Mark the end of a step. Builds a `StepResult` from the accumulated\n * content and records it in the steps array. Accepts the V4-shaped\n * finish reason / usage the harness emits and normalizes to AI SDK's\n * flat shape internally.\n */\n finishStep(input: {\n finishReason: LanguageModelV4FinishReason;\n usage: LanguageModelV4Usage;\n providerMetadata: ProviderMetadata | undefined;\n warnings: CallWarning[];\n }): void {\n const normalizedUsage = asLanguageModelUsage(input.usage);\n const finishReason = input.finishReason.unified;\n const rawFinishReason = input.finishReason.raw;\n\n const step = new DefaultStepResult<TOOLS, RUNTIME_CONTEXT>({\n callId: generateId(),\n stepNumber: this.stepNumber,\n provider: this.providerName,\n modelId: this.modelId,\n runtimeContext: this.runtimeContext,\n toolsContext: this.toolsContext,\n content: this.currentStepContent,\n finishReason,\n rawFinishReason,\n usage: normalizedUsage,\n performance: createEmptyPerformance(),\n warnings: input.warnings.length > 0 ? input.warnings : undefined,\n request: {},\n response: {\n id: generateId(),\n timestamp: new Date(),\n modelId: this.modelId,\n messages: [],\n },\n providerMetadata: input.providerMetadata,\n });\n this.stepsBuffer.push(step);\n\n // Forward an AI SDK finish-step event so consumers reading fullStream\n // see step boundaries.\n this.fullStreamController.enqueue({\n type: 'finish-step',\n finishReason,\n rawFinishReason,\n usage: normalizedUsage,\n providerMetadata: input.providerMetadata,\n response: step.response,\n performance: createEmptyPerformance(),\n } as TextStreamPart<TOOLS>);\n\n this.accumulatedUsage = addLanguageModelUsage(\n this.accumulatedUsage,\n normalizedUsage,\n );\n this.finalFinishReason = finishReason;\n this.finalRawFinishReason = rawFinishReason;\n this.finalProviderMetadata = input.providerMetadata;\n if (input.warnings.length > 0)\n this.aggregateWarnings.push(...input.warnings);\n\n this.stepNumber += 1;\n this.currentStepContent = [];\n this.currentStepWarnings = [];\n }\n\n /**\n * Resolve every delayed promise and close `fullStream`. Idempotent.\n */\n async finish(input?: {\n finishReason: LanguageModelV4FinishReason;\n totalUsage: LanguageModelV4Usage;\n providerMetadata: ProviderMetadata | undefined;\n }): Promise<void> {\n if (this.settled) return;\n this.settled = true;\n\n if (input != null) {\n this.finalFinishReason = input.finishReason.unified;\n this.finalRawFinishReason = input.finishReason.raw;\n this.finalProviderMetadata = input.providerMetadata;\n this.accumulatedUsage = asLanguageModelUsage(input.totalUsage);\n }\n\n // Flush any trailing content not yet captured by a finish-step. We\n // construct the step directly here (the public `finishStep` takes V4\n // shapes; we already have AI SDK shapes at this point).\n if (this.currentStepContent.length > 0) {\n const trailingStep = new DefaultStepResult<TOOLS, RUNTIME_CONTEXT>({\n callId: generateId(),\n stepNumber: this.stepNumber,\n provider: this.providerName,\n modelId: this.modelId,\n runtimeContext: this.runtimeContext,\n toolsContext: this.toolsContext,\n content: this.currentStepContent,\n finishReason: this.finalFinishReason,\n rawFinishReason: this.finalRawFinishReason,\n usage: createNullLanguageModelUsage(),\n performance: createEmptyPerformance(),\n warnings:\n this.currentStepWarnings.length > 0\n ? this.currentStepWarnings\n : undefined,\n request: {},\n response: {\n id: generateId(),\n timestamp: new Date(),\n modelId: this.modelId,\n messages: [],\n },\n providerMetadata: this.finalProviderMetadata,\n });\n this.stepsBuffer.push(trailingStep);\n this.currentStepContent = [];\n this.currentStepWarnings = [];\n }\n\n const finalStep =\n this.stepsBuffer.length > 0\n ? this.stepsBuffer[this.stepsBuffer.length - 1]!\n : new DefaultStepResult<TOOLS, RUNTIME_CONTEXT>({\n callId: generateId(),\n stepNumber: 0,\n provider: this.providerName,\n modelId: this.modelId,\n runtimeContext: this.runtimeContext,\n toolsContext: this.toolsContext,\n content: [],\n finishReason: this.finalFinishReason,\n rawFinishReason: this.finalRawFinishReason,\n usage: createNullLanguageModelUsage(),\n performance: createEmptyPerformance(),\n warnings: undefined,\n request: {},\n response: {\n id: generateId(),\n timestamp: new Date(),\n modelId: this.modelId,\n messages: [],\n },\n providerMetadata: undefined,\n });\n\n const aggregatedContent = this.stepsBuffer.flatMap(s => s.content);\n\n this._content.resolve(\n aggregatedContent as StreamProp<TOOLS, RUNTIME_CONTEXT, 'content'>,\n );\n this._text.resolve(finalStep.text);\n // Reasoning content parts are not yet derived from harness events; the\n // foundation surfaces an empty array. Adapters that emit reasoning\n // deltas can be wired up to produce real reasoning content in a later\n // pass.\n this._reasoning.resolve(\n [] as StreamProp<TOOLS, RUNTIME_CONTEXT, 'reasoning'>,\n );\n this._reasoningText.resolve(undefined);\n this._files.resolve(this.stepsBuffer.flatMap(s => s.files));\n this._sources.resolve(this.stepsBuffer.flatMap(s => s.sources));\n this._toolCalls.resolve(\n this.stepsBuffer.flatMap(s => s.toolCalls) as StreamProp<\n TOOLS,\n RUNTIME_CONTEXT,\n 'toolCalls'\n >,\n );\n this._staticToolCalls.resolve(\n this.stepsBuffer.flatMap(s => s.staticToolCalls) as StreamProp<\n TOOLS,\n RUNTIME_CONTEXT,\n 'staticToolCalls'\n >,\n );\n this._dynamicToolCalls.resolve(\n this.stepsBuffer.flatMap(s => s.dynamicToolCalls) as StreamProp<\n TOOLS,\n RUNTIME_CONTEXT,\n 'dynamicToolCalls'\n >,\n );\n this._toolResults.resolve(\n this.stepsBuffer.flatMap(s => s.toolResults) as StreamProp<\n TOOLS,\n RUNTIME_CONTEXT,\n 'toolResults'\n >,\n );\n this._staticToolResults.resolve(\n this.stepsBuffer.flatMap(s => s.staticToolResults) as StreamProp<\n TOOLS,\n RUNTIME_CONTEXT,\n 'staticToolResults'\n >,\n );\n this._dynamicToolResults.resolve(\n this.stepsBuffer.flatMap(s => s.dynamicToolResults) as StreamProp<\n TOOLS,\n RUNTIME_CONTEXT,\n 'dynamicToolResults'\n >,\n );\n this._finishReason.resolve(this.finalFinishReason);\n this._rawFinishReason.resolve(this.finalRawFinishReason);\n this._usage.resolve(this.accumulatedUsage);\n this._warnings.resolve(\n this.aggregateWarnings.length > 0 ? this.aggregateWarnings : undefined,\n );\n this._steps.resolve(this.stepsBuffer);\n this._finalStep.resolve(finalStep);\n this._request.resolve(finalStep.request);\n this._response.resolve(finalStep.response);\n this._providerMetadata.resolve(this.finalProviderMetadata);\n\n const responseMessages = await toResponseMessages<TOOLS>({\n content: aggregatedContent,\n tools: this.tools,\n });\n this._responseMessages.resolve(responseMessages);\n\n // Forward AI SDK finish event before closing.\n this.fullStreamController.enqueue({\n type: 'finish',\n finishReason: this.finalFinishReason,\n rawFinishReason: this.finalRawFinishReason,\n totalUsage: this.accumulatedUsage,\n providerMetadata: this.finalProviderMetadata,\n } as TextStreamPart<TOOLS>);\n\n this.fullStreamController.close();\n }\n\n /**\n * Surface a fatal error as a stream `error` part + reject every delayed\n * promise so awaiting consumers stop hanging. Idempotent.\n */\n fail(error: unknown): void {\n if (this.settled) return;\n this.settled = true;\n this.fullStreamController.enqueue({\n type: 'error',\n error,\n } as TextStreamPart<TOOLS>);\n this.fullStreamController.close();\n for (const dp of [\n this._content,\n this._text,\n this._reasoning,\n this._reasoningText,\n this._files,\n this._sources,\n this._toolCalls,\n this._staticToolCalls,\n this._dynamicToolCalls,\n this._toolResults,\n this._staticToolResults,\n this._dynamicToolResults,\n this._finishReason,\n this._rawFinishReason,\n this._usage,\n this._warnings,\n this._steps,\n this._finalStep,\n this._request,\n this._response,\n this._responseMessages,\n this._providerMetadata,\n ]) {\n try {\n (dp as DelayedPromise<unknown>).reject(error);\n } catch {\n // ignore double-rejection\n }\n }\n }\n\n // ─── Reader-side public surface (StreamTextResult contract) ────────\n\n get content() {\n return this._content.promise;\n }\n get text() {\n return this._text.promise;\n }\n get reasoning() {\n return this._reasoning.promise;\n }\n get reasoningText() {\n return this._reasoningText.promise;\n }\n get files() {\n return this._files.promise;\n }\n get sources() {\n return this._sources.promise;\n }\n get toolCalls() {\n return this._toolCalls.promise;\n }\n get staticToolCalls() {\n return this._staticToolCalls.promise;\n }\n get dynamicToolCalls() {\n return this._dynamicToolCalls.promise;\n }\n get toolResults() {\n return this._toolResults.promise;\n }\n get staticToolResults() {\n return this._staticToolResults.promise;\n }\n get dynamicToolResults() {\n return this._dynamicToolResults.promise;\n }\n get finishReason() {\n return this._finishReason.promise;\n }\n get rawFinishReason() {\n return this._rawFinishReason.promise;\n }\n get usage() {\n return this._usage.promise;\n }\n get totalUsage() {\n return this._usage.promise;\n }\n get warnings() {\n return this._warnings.promise;\n }\n get steps() {\n return this._steps.promise;\n }\n get finalStep() {\n return this._finalStep.promise;\n }\n get request() {\n return this._request.promise;\n }\n get response() {\n return this._response.promise;\n }\n get responseMessages() {\n return this._responseMessages.promise;\n }\n get providerMetadata() {\n return this._providerMetadata.promise;\n }\n\n // Output-specification surfaces are not yet supported.\n get experimental_partialOutputStream(): never {\n throw notSupportedYet('partial output stream');\n }\n get partialOutputStream(): never {\n throw notSupportedYet('partial output stream');\n }\n get elementStream(): never {\n throw notSupportedYet('element stream');\n }\n get output(): never {\n throw notSupportedYet('structured output');\n }\n\n async consumeStream(): Promise<void> {\n const reader = this.fullStream.getReader();\n try {\n while (true) {\n const { done } = await reader.read();\n if (done) return;\n }\n } finally {\n reader.releaseLock();\n }\n }\n\n toUIMessageStream<UI_MESSAGE extends UIMessage>({\n originalMessages,\n generateMessageId,\n onFinish,\n messageMetadata,\n sendReasoning,\n sendSources,\n sendStart,\n sendFinish,\n onError,\n }: UIMessageStreamOptions<UI_MESSAGE> = {}): AsyncIterableStream<\n InferUIMessageChunk<UI_MESSAGE>\n > {\n return createAsyncIterableStream(\n toUIMessageStreamHelper<TOOLS, UI_MESSAGE>({\n stream: this.stream,\n tools: this.tools,\n originalMessages,\n generateMessageId,\n onFinish,\n messageMetadata,\n sendReasoning,\n sendSources,\n sendStart,\n sendFinish,\n onError,\n }),\n ) as AsyncIterableStream<InferUIMessageChunk<UI_MESSAGE>>;\n }\n\n pipeUIMessageStreamToResponse(): never {\n throw notSupportedYet('pipeUIMessageStreamToResponse');\n }\n\n pipeTextStreamToResponse(): never {\n throw notSupportedYet('pipeTextStreamToResponse');\n }\n\n toUIMessageStreamResponse<UI_MESSAGE extends UIMessage>({\n originalMessages,\n generateMessageId,\n onFinish,\n messageMetadata,\n sendReasoning,\n sendSources,\n sendStart,\n sendFinish,\n onError,\n ...init\n }: ResponseInit & {\n consumeSseStream?: (options: {\n stream: ReadableStream<string>;\n }) => PromiseLike<void> | void;\n } & UIMessageStreamOptions<UI_MESSAGE> = {}): Response {\n return createUIMessageStreamResponse({\n stream: this.toUIMessageStream<UI_MESSAGE>({\n originalMessages,\n generateMessageId,\n onFinish,\n messageMetadata,\n sendReasoning,\n sendSources,\n sendStart,\n sendFinish,\n onError,\n }),\n ...init,\n });\n }\n\n toTextStreamResponse(): never {\n throw notSupportedYet('toTextStreamResponse');\n }\n\n // ─── Helpers ────────────────────────────────────────────────────────\n\n private appendToCurrentStepContent(part: TextStreamPart<TOOLS>): void {\n switch (part.type) {\n case 'text-delta': {\n // Coalesce contiguous text-deltas with the same id into one text part.\n const last =\n this.currentStepContent[this.currentStepContent.length - 1];\n if (last && last.type === 'text') {\n (last as { text: string }).text += part.text;\n } else {\n this.currentStepContent.push({\n type: 'text',\n text: part.text,\n } as ContentPart<TOOLS>);\n }\n return;\n }\n case 'tool-call':\n this.currentStepContent.push({\n ...(part as object),\n } as ContentPart<TOOLS>);\n return;\n case 'tool-approval-request':\n this.currentStepContent.push({\n ...(part as object),\n } as ContentPart<TOOLS>);\n return;\n case 'tool-approval-response':\n this.currentStepContent.push({\n ...(part as object),\n } as ContentPart<TOOLS>);\n return;\n case 'tool-result':\n this.currentStepContent.push({\n ...(part as object),\n } as ContentPart<TOOLS>);\n return;\n default:\n // text-start/end, reasoning-*, raw, error, finish-step, finish are\n // not directly stored as ContentParts. (Reasoning content parts\n // would belong here; we omit them for v0.)\n return;\n }\n }\n}\n\nfunction createEmptyPerformance(): StepResult<ToolSet, Context>['performance'] {\n return {\n effectiveOutputTokensPerSecond: 0,\n outputTokensPerSecond: undefined,\n inputTokensPerSecond: undefined,\n effectiveTotalTokensPerSecond: 0,\n stepTimeMs: 0,\n responseTimeMs: 0,\n toolExecutionMs: {},\n timeToFirstOutputMs: undefined,\n };\n}\n\nfunction notSupportedYet(feature: string): Error {\n return new Error(\n `HarnessAgent: ${feature} is not implemented yet. Track the foundation review for follow-up.`,\n );\n}\n\n// Re-declare `AsyncIterableStream` locally to avoid pulling AI SDK's internal\n// async-iterable-stream helper. ReadableStreams already implement the\n// async-iterator contract in modern runtimes; we expose them under the same\n// nominal type AI SDK does.\ntype AsyncIterableStream<T> = ReadableStream<T> & AsyncIterable<T>;\n\n// `GenerateTextResult` is re-exported only so downstream code can keep this\n// file as the single source of return-shape constants; not otherwise used here.\nexport type _GenerateTextResultMarker<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context,\n> = GenerateTextResult<TOOLS, RUNTIME_CONTEXT, never>;\n","import type { HarnessV1StreamPart } from '../../v1';\nimport type { TextStreamPart } from 'ai';\nimport { generateId, type ToolSet } from '@ai-sdk/provider-utils';\n\n/**\n * Translate one event from the harness wire format to the AI SDK\n * `TextStreamPart` shape consumed by `streamText` callers.\n *\n * Most variants are close to the identity function — V4 primitives\n * (`LanguageModelV4ToolCall`, `LanguageModelV4ToolResult`,\n * `LanguageModelV4ToolApprovalRequest`, `LanguageModelV4FinishReason`,\n * `LanguageModelV4Usage`) flow through unchanged. The adapters are:\n * - `harnessMetadata` → `providerMetadata`\n * - tool-call events are not translated here — validation against the\n * merged tool set is async and handled by `validateToolCall` in\n * `run-prompt.ts`\n * - the harness `raw` part is forwarded as the AI SDK `raw` part\n *\n * Returns an array of zero or more AI SDK parts. Most harness events project\n * to a single AI SDK part; `file-change` fans out into a synthetic\n * dynamic + provider-executed `tool-call` / `tool-result` pair so the event\n * is observable in `streamText`-style flows without a new stream-part type\n * needing first-class AI SDK support. Events with no consumer-facing AI SDK\n * equivalent (`stream-start`, `finish-step`, `finish` — consumed internally)\n * return an empty array.\n */\nexport function translateStreamPart<TOOLS extends ToolSet>(\n event: HarnessV1StreamPart,\n): ReadonlyArray<TextStreamPart<TOOLS>> {\n switch (event.type) {\n case 'stream-start':\n // The agent emits its own `start` part with normalized warnings;\n // the harness-level start signal is consumed internally.\n return [];\n\n case 'text-start':\n return [\n {\n type: 'text-start',\n id: event.id,\n providerMetadata: event.harnessMetadata,\n } as TextStreamPart<TOOLS>,\n ];\n\n case 'text-delta':\n return [\n {\n type: 'text-delta',\n id: event.id,\n text: event.delta,\n providerMetadata: event.harnessMetadata,\n } as TextStreamPart<TOOLS>,\n ];\n\n case 'text-end':\n return [\n {\n type: 'text-end',\n id: event.id,\n providerMetadata: event.harnessMetadata,\n } as TextStreamPart<TOOLS>,\n ];\n\n case 'reasoning-start':\n return [\n {\n type: 'reasoning-start',\n id: event.id,\n providerMetadata: event.harnessMetadata,\n } as TextStreamPart<TOOLS>,\n ];\n\n case 'reasoning-delta':\n return [\n {\n type: 'reasoning-delta',\n id: event.id,\n text: event.delta,\n providerMetadata: event.harnessMetadata,\n } as TextStreamPart<TOOLS>,\n ];\n\n case 'reasoning-end':\n return [\n {\n type: 'reasoning-end',\n id: event.id,\n providerMetadata: event.harnessMetadata,\n } as TextStreamPart<TOOLS>,\n ];\n\n case 'tool-call':\n // Tool-call validation is async (it parses input against the tool's\n // schema) and lives in `run-prompt.ts` where the merged tool set is in\n // scope. The translator returns nothing here — the run-prompt loop\n // handles the emission.\n return [];\n\n case 'tool-approval-request':\n return [];\n\n case 'tool-result':\n return [\n {\n type: 'tool-result',\n toolCallId: event.toolCallId,\n toolName: event.toolName,\n input: undefined,\n output: event.result,\n ...(event.preliminary !== undefined\n ? { preliminary: event.preliminary }\n : {}),\n ...(event.providerMetadata !== undefined\n ? { providerMetadata: event.providerMetadata }\n : {}),\n } as TextStreamPart<TOOLS>,\n ];\n\n case 'file-change': {\n /*\n * `file-change` has no first-class AI SDK stream-part equivalent.\n * Project it as a synthetic dynamic + provider-executed tool-call /\n * tool-result pair under the reserved name `fileChange` so the event\n * is visible to `streamText`-style consumers. `dynamic: true` keeps it\n * out of typed-tool lookups; `providerExecuted: true` signals the\n * runtime already executed it and the host should not dispatch.\n */\n const toolCallId = `harness-file-change-${generateId()}`;\n const payload = { event: event.event, path: event.path };\n return [\n {\n type: 'tool-call',\n toolCallId,\n toolName: 'fileChange',\n input: payload,\n dynamic: true,\n providerExecuted: true,\n ...(event.harnessMetadata !== undefined\n ? { providerMetadata: event.harnessMetadata }\n : {}),\n } as TextStreamPart<TOOLS>,\n {\n type: 'tool-result',\n toolCallId,\n toolName: 'fileChange',\n input: payload,\n output: payload,\n dynamic: true,\n providerExecuted: true,\n ...(event.harnessMetadata !== undefined\n ? { providerMetadata: event.harnessMetadata }\n : {}),\n } as TextStreamPart<TOOLS>,\n ];\n }\n\n case 'compaction': {\n /*\n * Like `file-change`, compaction has no first-class AI SDK stream-part\n * equivalent. Project it as a synthetic dynamic + provider-executed\n * tool-call / tool-result pair under the reserved name `compaction`, so\n * the event is visible to `streamText`-style consumers. Compaction takes\n * no input, so the call input is empty; the metadata rides on the result\n * output. `dynamic: true` keeps it out of typed-tool lookups;\n * `providerExecuted: true` signals the runtime already performed it.\n */\n const toolCallId = `harness-compaction-${generateId()}`;\n const output = {\n trigger: event.trigger,\n summary: event.summary,\n ...(event.tokensBefore !== undefined\n ? { tokensBefore: event.tokensBefore }\n : {}),\n ...(event.tokensAfter !== undefined\n ? { tokensAfter: event.tokensAfter }\n : {}),\n };\n return [\n {\n type: 'tool-call',\n toolCallId,\n toolName: 'compaction',\n input: {},\n dynamic: true,\n providerExecuted: true,\n ...(event.harnessMetadata !== undefined\n ? { providerMetadata: event.harnessMetadata }\n : {}),\n } as TextStreamPart<TOOLS>,\n {\n type: 'tool-result',\n toolCallId,\n toolName: 'compaction',\n input: {},\n output,\n dynamic: true,\n providerExecuted: true,\n ...(event.harnessMetadata !== undefined\n ? { providerMetadata: event.harnessMetadata }\n : {}),\n } as TextStreamPart<TOOLS>,\n ];\n }\n\n case 'error':\n return [{ type: 'error', error: event.error } as TextStreamPart<TOOLS>];\n\n case 'raw':\n return [\n { type: 'raw', rawValue: event.rawValue } as TextStreamPart<TOOLS>,\n ];\n\n case 'finish-step':\n case 'finish':\n // finish-step / finish are consumed by the agent's result builder, not\n // forwarded directly. The agent emits AI SDK `finish-step` / `finish`\n // parts itself once it has assembled the surrounding step / response\n // metadata.\n return [];\n }\n}\n","import type { HarnessV1StreamPart } from '../../v1';\n\n/**\n * Remove the session working-directory prefix from path-bearing fields of a\n * stream event, returning a new event for display to consumers.\n *\n * Harness adapters run the agent in a per-session working directory that is a\n * subdirectory of the sandbox root, and the agent's tools use absolute paths so\n * they resolve against the root regardless of where the runtime process\n * operates. The absolute paths are correct but noisy in a UI, so this strips\n * the prefix for the consumer-facing projection only.\n *\n * Blanket prefix replacement (rather than rewriting known path fields) is used\n * deliberately: `tool-result` results are free-form text — command stdout, grep\n * output — where paths can appear anywhere and field-aware rewriting is\n * impossible. The prefix is long and contains the session id, so it is unique\n * enough that replacing every occurrence is safe.\n */\nexport function stripWorkDir(\n part: HarnessV1StreamPart,\n sessionWorkDir: string,\n): HarnessV1StreamPart {\n if (sessionWorkDir.length === 0) return part;\n\n switch (part.type) {\n case 'tool-call':\n return { ...part, input: stripString(part.input, sessionWorkDir) };\n case 'tool-result':\n return {\n ...part,\n result: stripDeep(part.result, sessionWorkDir) as Extract<\n HarnessV1StreamPart,\n { type: 'tool-result' }\n >['result'],\n };\n case 'file-change':\n return { ...part, path: stripString(part.path, sessionWorkDir) };\n default:\n return part;\n }\n}\n\n/**\n * Replace occurrences of the working directory in a string. A reference to the\n * directory followed by a separator becomes workspace-relative\n * (`/work/dir/src/a.ts` → `src/a.ts`); a bare reference to the directory itself\n * becomes `.`.\n */\nfunction stripString(value: string, workDir: string): string {\n return value.split(`${workDir}/`).join('').split(workDir).join('.');\n}\n\n/**\n * Recursively strip the working directory from every string nested in an\n * arbitrary JSON-like value. Non-string leaves are returned unchanged.\n */\nfunction stripDeep(value: unknown, workDir: string): unknown {\n if (typeof value === 'string') return stripString(value, workDir);\n if (Array.isArray(value)) return value.map(item => stripDeep(item, workDir));\n if (value !== null && typeof value === 'object') {\n const out: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n out[key] = stripDeep(val, workDir);\n }\n return out;\n }\n return value;\n}\n","import { generateId, type ModelMessage } from '@ai-sdk/provider-utils';\nimport { createTelemetryDispatcher } from 'ai/internal';\nimport type { TelemetryOptions } from 'ai';\n\n/*\n * Drives AI SDK's pluggable `Telemetry` lifecycle from a harness turn.\n *\n * A harness turn is not a `streamText` call — it has no language model, prompt\n * standardization, or sampling settings — but the AI SDK telemetry contract is\n * shaped around `generateText`/`streamText` events, and `@ai-sdk/otel` (the\n * main integration) only produces spans when the full lifecycle fires. So we\n * map the turn onto that contract: turn = operation, each `finish-step` = a\n * step boundary, tool-calls = tool executions, `finish` = operation end. The\n * model-call-only event fields the harness has no value for (sampling params,\n * standardized prompt) are left `undefined` / cast; the fields the integrations\n * actually read (`callId`, `operationId`, `provider`, `modelId`, `messages`,\n * `toolCall`, `usage`, `finishReason`) carry real values.\n *\n * Telemetry is opt-in: the framework only drives it when `settings.telemetry`\n * is set (the dispatcher then also honours globally-registered integrations).\n */\n\ntype Dispatcher = ReturnType<typeof createTelemetryDispatcher>;\ntype EventArg<K extends keyof Dispatcher> = Dispatcher[K] extends\n | ((event: infer E) => unknown)\n | undefined\n ? E\n : never;\n\n/**\n * An output content part accumulated over a step — the model's assistant turn.\n * Shaped for the gen_ai output-message conventions `@ai-sdk/otel` reads.\n */\nexport type TurnContentPart =\n | { type: 'text'; text: string }\n | { type: 'reasoning'; text: string }\n | { type: 'tool-call'; toolCallId: string; toolName: string; input: unknown };\n\nexport interface TurnTelemetry {\n /**\n * Begin the operation span. Called on `stream-start`, optionally with the\n * model the runtime resolved to (overriding the session's configured id).\n * Idempotent — the first call wins.\n */\n start(modelId?: string): void;\n /** Open a step span lazily, before the first content of a step. */\n ensureStepOpen(): void;\n /** Close the current step (on a harness `finish-step`). */\n stepFinish(info: {\n finishReason: unknown;\n usage: unknown;\n providerMetadata?: unknown;\n /** The model's output content for this step (text/reasoning/tool-calls). */\n content?: TurnContentPart[];\n }): void;\n /** A tool execution began (on a `tool-call`). */\n toolStart(call: {\n toolCallId: string;\n toolName: string;\n input: unknown;\n }): void;\n /**\n * A tool execution completed (on its `tool-result` or after host execution).\n * Idempotent per `toolCallId` — the first caller wins, so provider-executed\n * and host-executed paths can both call it without double-counting.\n */\n toolEnd(\n toolCallId: string,\n output: { ok: true; output: unknown } | { ok: false; error: unknown },\n ): void;\n /** The turn ended (on a harness `finish`). */\n end(info: { finishReason: unknown; usage: unknown }): void;\n /** The turn failed. */\n error(err: unknown): void;\n}\n\nconst NOOP: TurnTelemetry = {\n start() {},\n ensureStepOpen() {},\n stepFinish() {},\n toolStart() {},\n toolEnd() {},\n end() {},\n error() {},\n};\n\nexport function createTurnTelemetry(opts: {\n telemetry: TelemetryOptions | undefined;\n harnessId: string;\n modelId: string | undefined;\n instructions: string | undefined;\n promptText: string;\n runtimeContext: unknown;\n}): TurnTelemetry {\n // Opt-in: with no telemetry settings we do no work and construct no events.\n if (opts.telemetry == null) return NOOP;\n\n const dispatcher = createTelemetryDispatcher({ telemetry: opts.telemetry });\n\n const callId = generateId();\n const provider = opts.harnessId;\n // The configured session model; `start(modelId)` may override it with the\n // model the runtime actually resolved to.\n let modelId = opts.modelId ?? '';\n const runtimeContext = opts.runtimeContext;\n const inputMessages: ModelMessage[] = [\n { role: 'user', content: opts.promptText },\n ];\n\n let started = false;\n let stepOpen = false;\n let stepNumber = 0;\n let ended = false;\n /** Tool calls started in the current turn and not yet ended. */\n const openTools = new Map<\n string,\n { toolCallId: string; toolName: string; input: unknown }\n >();\n\n const cast = <K extends keyof Dispatcher>(event: unknown): EventArg<K> =>\n event as EventArg<K>;\n\n // onStart — open the operation (root) span. Deferred until `start()` so the\n // runtime-resolved model can be attached to the operation span + trace label.\n const fireStart = (): void => {\n if (started) return;\n started = true;\n dispatcher.onStart?.(\n cast<'onStart'>({\n callId,\n operationId: 'ai.harness',\n provider,\n modelId,\n tools: undefined,\n toolChoice: undefined,\n activeTools: undefined,\n maxRetries: 0,\n timeout: undefined,\n headers: undefined,\n providerOptions: undefined,\n output: undefined,\n toolsContext: undefined,\n runtimeContext,\n instructions: opts.instructions,\n messages: inputMessages,\n }),\n );\n };\n\n const start = (overrideModelId?: string): void => {\n if (started) return;\n if (overrideModelId) modelId = overrideModelId;\n fireStart();\n };\n\n const ensureStepOpen = (): void => {\n if (!started) fireStart();\n if (stepOpen || ended) return;\n stepOpen = true;\n dispatcher.onStepStart?.(\n cast<'onStepStart'>({\n callId,\n provider,\n modelId,\n stepNumber,\n tools: undefined,\n toolChoice: undefined,\n activeTools: undefined,\n steps: new Array(stepNumber),\n providerOptions: undefined,\n output: undefined,\n runtimeContext,\n messages: inputMessages,\n }),\n );\n // Open the inference (language-model call) span — the gen_ai home for the\n // step's input and (on end) output messages.\n dispatcher.onLanguageModelCallStart?.(\n cast<'onLanguageModelCallStart'>({\n callId,\n provider,\n modelId,\n messages: inputMessages,\n tools: undefined,\n }),\n );\n };\n\n /** Close the inference span with the step's output content. */\n const inferenceEnd = (info: {\n finishReason: unknown;\n usage: unknown;\n content: TurnContentPart[];\n }): void => {\n dispatcher.onLanguageModelCallEnd?.(\n cast<'onLanguageModelCallEnd'>({\n callId,\n finishReason: info.finishReason,\n responseId: callId,\n usage: info.usage,\n content: info.content,\n }),\n );\n };\n\n const closeOpenTools = (): void => {\n for (const call of openTools.values()) {\n dispatcher.onToolExecutionEnd?.(\n cast<'onToolExecutionEnd'>({\n callId,\n toolExecutionMs: 0,\n messages: [],\n toolCall: {\n type: 'tool-call',\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n input: call.input,\n dynamic: true,\n },\n toolContext: undefined,\n toolOutput: { type: 'error', error: new Error('tool span unclosed') },\n }),\n );\n }\n openTools.clear();\n };\n\n return {\n start,\n ensureStepOpen,\n\n stepFinish(info) {\n if (!stepOpen) return;\n const content = info.content ?? [];\n closeOpenTools();\n inferenceEnd({\n finishReason: info.finishReason,\n usage: info.usage,\n content,\n });\n dispatcher.onStepEnd?.(\n cast<'onStepEnd'>({\n callId,\n finishReason: info.finishReason,\n usage: info.usage,\n providerMetadata: info.providerMetadata,\n content,\n response: {\n id: callId,\n modelId,\n timestamp: new Date(0),\n messages: [],\n },\n }),\n );\n stepOpen = false;\n stepNumber += 1;\n },\n\n toolStart(call) {\n ensureStepOpen();\n openTools.set(call.toolCallId, call);\n dispatcher.onToolExecutionStart?.(\n cast<'onToolExecutionStart'>({\n callId,\n messages: [],\n toolCall: {\n type: 'tool-call',\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n input: call.input,\n dynamic: true,\n },\n toolContext: undefined,\n }),\n );\n },\n\n toolEnd(toolCallId, output) {\n const call = openTools.get(toolCallId);\n if (call == null) return;\n openTools.delete(toolCallId);\n dispatcher.onToolExecutionEnd?.(\n cast<'onToolExecutionEnd'>({\n callId,\n toolExecutionMs: 0,\n messages: [],\n toolCall: {\n type: 'tool-call',\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n input: call.input,\n dynamic: true,\n },\n toolContext: undefined,\n toolOutput: output.ok\n ? { type: 'tool-result', output: output.output }\n : { type: 'error', error: output.error },\n }),\n );\n },\n\n end(info) {\n if (ended) return;\n if (!started) fireStart();\n if (stepOpen) {\n closeOpenTools();\n inferenceEnd({\n finishReason: info.finishReason,\n usage: info.usage,\n content: [],\n });\n dispatcher.onStepEnd?.(\n cast<'onStepEnd'>({\n callId,\n finishReason: info.finishReason,\n usage: info.usage,\n providerMetadata: undefined,\n content: [],\n response: {\n id: callId,\n modelId,\n timestamp: new Date(0),\n messages: [],\n },\n }),\n );\n stepOpen = false;\n }\n ended = true;\n dispatcher.onEnd?.(\n cast<'onEnd'>({\n callId,\n operationId: 'ai.harness',\n finishReason: info.finishReason,\n usage: info.usage,\n totalUsage: info.usage,\n content: [],\n steps: new Array(stepNumber),\n response: {\n id: callId,\n modelId,\n timestamp: new Date(0),\n messages: [],\n },\n runtimeContext,\n }),\n );\n },\n\n error(err) {\n if (ended) return;\n if (!started) fireStart();\n closeOpenTools();\n ended = true;\n dispatcher.onError?.(err);\n },\n };\n}\n","import type { ToolApprovalStatus } from 'ai';\nimport type { HarnessV1PermissionMode } from '../../v1';\nimport type { HarnessAgentToolApprovalConfiguration } from '../harness-agent-settings';\n\nexport const DEFAULT_PERMISSION_MODE: HarnessV1PermissionMode =\n 'allow-all' as const;\n\nexport function resolvePermissionMode(input: {\n permissionMode: HarnessV1PermissionMode | undefined;\n}): HarnessV1PermissionMode {\n return input.permissionMode ?? DEFAULT_PERMISSION_MODE;\n}\n\nexport function permissionModeNeedsBuiltinSupport(input: {\n permissionMode: HarnessV1PermissionMode;\n}): boolean {\n return input.permissionMode !== 'allow-all';\n}\n\nexport type CustomToolApprovalDecision =\n | { readonly type: 'allow'; readonly reason?: string }\n | { readonly type: 'deny'; readonly reason?: string }\n | { readonly type: 'request' };\n\nexport function resolveCustomToolApproval(input: {\n toolName: string;\n toolApproval: HarnessAgentToolApprovalConfiguration | undefined;\n}): CustomToolApprovalDecision {\n const status = normalizeToolApprovalStatus({\n status: input.toolApproval?.[input.toolName],\n });\n\n switch (status.type) {\n case 'not-applicable':\n case 'approved':\n return { type: 'allow', reason: status.reason };\n case 'denied':\n return { type: 'deny', reason: status.reason };\n case 'user-approval':\n return { type: 'request' };\n }\n}\n\nfunction normalizeToolApprovalStatus(input: {\n status: ToolApprovalStatus | undefined;\n}): Exclude<ToolApprovalStatus, string | undefined> {\n if (input.status === undefined) return { type: 'not-applicable' };\n if (typeof input.status === 'string') return { type: input.status };\n return input.status;\n}\n","import type { Context, ToolSet } from '@ai-sdk/provider-utils';\nimport type { StreamTextResult, TelemetryOptions } from 'ai';\nimport type { HarnessAgentToolApprovalConfiguration } from './harness-agent-settings';\nimport type {\n HarnessV1NetworkSandboxSession,\n HarnessV1SandboxProvider,\n} from '../v1';\nimport type {\n HarnessAgentAdapter,\n HarnessAgentAdapterSession,\n HarnessAgentContinueTurnState,\n HarnessAgentPendingToolApproval,\n HarnessAgentPrompt,\n HarnessAgentResumeSessionState,\n HarnessAgentToolSpec,\n} from './harness-agent-types';\nimport type { HarnessAgentToolApprovalContinuation } from './harness-agent-tool-approval-continuation';\nimport { releaseBridgePort } from './internal/bridge-port-registry';\nimport { validateLifecycleStateData } from './internal/lifecycle-state-validation';\nimport { runPrompt } from './internal/run-prompt';\n\ntype HarnessAgentTurnResult<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context,\n> = {\n result: StreamTextResult<TOOLS, RUNTIME_CONTEXT, never>;\n done: Promise<void>;\n};\n\ntype HarnessAgentSessionState = 'active' | 'detached' | 'stopped' | 'destroyed';\n\ntype HarnessAgentTurnState =\n | 'idle'\n | 'running'\n | 'awaiting-approval'\n | 'suspended';\n\n/**\n * Live harness session held by the caller.\n *\n * Created by {@link import('./harness-agent').HarnessAgent.createSession}.\n * Owns the underlying adapter session, the network sandbox session, and the\n * bridge-port lease (when the provider wraps a caller-provided sandbox with a\n * port pool).\n *\n * Pass the instance back to `agent.generate` / `agent.stream` on every\n * call; end the local handle with `detach()`, `stop()`, or `destroy()`.\n *\n * After any lifecycle method has resolved, the session is unusable — any\n * subsequent `generate`/`stream` call against it throws.\n */\nexport class HarnessAgentSession {\n /**\n * Stable identifier the harness adapter saw in `doStart`. The same\n * string callers persist when they intend to resume the session in a\n * future process.\n */\n readonly sessionId: string;\n\n private readonly harness: HarnessAgentAdapter;\n private readonly sandboxProvider: HarnessV1SandboxProvider;\n private readonly sessionWorkDir: string;\n private underlyingSession: HarnessAgentAdapterSession | undefined;\n private sandboxSession: HarnessV1NetworkSandboxSession | undefined;\n private leasedBridgePort: number | undefined;\n private readonly toolApproval:\n | HarnessAgentToolApprovalConfiguration\n | undefined;\n private readonly pendingToolApprovals = new Map<\n string,\n HarnessAgentPendingToolApproval\n >();\n private sessionState: HarnessAgentSessionState = 'active';\n private turnState: HarnessAgentTurnState;\n private turnSequence = 0;\n private activeTurnSequence = 0;\n\n /**\n * Whether this session was created from `resumeFrom` or `continueFrom`.\n * Captured at construction so it survives lifecycle cleanup.\n */\n readonly isResume: boolean;\n\n constructor(options: {\n sessionId: string;\n harness: HarnessAgentAdapter;\n underlyingSession: HarnessAgentAdapterSession;\n sandboxSession: HarnessV1NetworkSandboxSession;\n sandboxProvider: HarnessV1SandboxProvider;\n leasedBridgePort?: number;\n sessionWorkDir: string;\n toolApproval: HarnessAgentToolApprovalConfiguration | undefined;\n pendingToolApprovals?: readonly HarnessAgentPendingToolApproval[];\n turnState?: HarnessAgentTurnState;\n }) {\n this.sessionId = options.sessionId;\n this.harness = options.harness;\n this.underlyingSession = options.underlyingSession;\n this.sandboxSession = options.sandboxSession;\n this.sandboxProvider = options.sandboxProvider;\n this.leasedBridgePort = options.leasedBridgePort;\n this.sessionWorkDir = options.sessionWorkDir;\n this.toolApproval = options.toolApproval;\n for (const approval of options.pendingToolApprovals ?? []) {\n this.pendingToolApprovals.set(approval.approvalId, approval);\n }\n this.turnState =\n options.turnState ??\n (this.pendingToolApprovals.size > 0 ? 'awaiting-approval' : 'idle');\n this.isResume = options.underlyingSession.isResume;\n }\n\n /**\n * Active network sandbox session.\n *\n * @internal — accessed by session turn and lifecycle drivers.\n */\n getSandboxSession(): HarnessV1NetworkSandboxSession {\n if (this.sessionState !== 'active' || this.sandboxSession == null) {\n throw new Error(\n `Harness session ${this.sessionId} has ended and cannot be reused.`,\n );\n }\n return this.sandboxSession;\n }\n\n /**\n * Working directory the agent runs in for this session. Used to strip the\n * prefix from absolute paths in stream events before they reach consumers.\n *\n * @internal — accessed by session turn drivers.\n */\n getSessionWorkDir(): string {\n return this.sessionWorkDir;\n }\n\n promptTurn<TOOLS extends ToolSet, RUNTIME_CONTEXT extends Context>(options: {\n prompt: HarnessAgentPrompt;\n instructions: string | undefined;\n tools: TOOLS;\n toolSpecs: HarnessAgentToolSpec[];\n runtimeContext: RUNTIME_CONTEXT;\n abortSignal: AbortSignal | undefined;\n telemetry: TelemetryOptions | undefined;\n }): HarnessAgentTurnResult<TOOLS, RUNTIME_CONTEXT> {\n const session = this.requireReusableSession();\n this.requirePromptableTurn();\n const sandboxSession = this.getSandboxSession();\n const turnId = this.startTrackedTurn();\n try {\n const turn = runPrompt<TOOLS, RUNTIME_CONTEXT>({\n harness: this.harness,\n session,\n prompt: options.prompt,\n instructions: options.instructions,\n tools: options.tools,\n toolSpecs: options.toolSpecs,\n sandboxSession: sandboxSession.restricted(),\n sessionWorkDir: this.sessionWorkDir,\n runtimeContext: options.runtimeContext,\n abortSignal: options.abortSignal,\n telemetry: options.telemetry,\n toolApproval: this.toolApproval,\n pendingToolApprovals: this.getPendingToolApprovals(),\n onPendingToolApproval: approval => {\n this.pendingToolApprovals.set(approval.approvalId, approval);\n this.markAwaitingApprovalIfActive();\n },\n onToolApprovalSettled: approvalId => {\n this.pendingToolApprovals.delete(approvalId);\n },\n onTurnFinished: () => {\n this.finishTrackedTurn({ turnId });\n },\n });\n this.trackTurnCompletion({ done: turn.done, turnId });\n return turn;\n } catch (error) {\n this.finishTrackedTurn({ turnId });\n throw error;\n }\n }\n\n continueTurn<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context,\n >(options: {\n instructions: string | undefined;\n tools: TOOLS;\n toolSpecs: HarnessAgentToolSpec[];\n runtimeContext: RUNTIME_CONTEXT;\n abortSignal: AbortSignal | undefined;\n telemetry: TelemetryOptions | undefined;\n toolApprovalContinuations?:\n | readonly HarnessAgentToolApprovalContinuation[]\n | undefined;\n }): HarnessAgentTurnResult<TOOLS, RUNTIME_CONTEXT> {\n const session = this.requireReusableSession();\n this.requireContinuableTurn();\n const sandboxSession = this.getSandboxSession();\n const turnId = this.startTrackedTurn();\n try {\n const turn = runPrompt<TOOLS, RUNTIME_CONTEXT>({\n harness: this.harness,\n session,\n mode: 'continue',\n instructions: options.instructions,\n tools: options.tools,\n toolSpecs: options.toolSpecs,\n sandboxSession: sandboxSession.restricted(),\n sessionWorkDir: this.sessionWorkDir,\n runtimeContext: options.runtimeContext,\n abortSignal: options.abortSignal,\n telemetry: options.telemetry,\n toolApproval: this.toolApproval,\n pendingToolApprovals: this.getPendingToolApprovals(),\n toolApprovalContinuations: options.toolApprovalContinuations,\n onPendingToolApproval: approval => {\n this.pendingToolApprovals.set(approval.approvalId, approval);\n this.markAwaitingApprovalIfActive();\n },\n onToolApprovalSettled: approvalId => {\n this.pendingToolApprovals.delete(approvalId);\n },\n onTurnFinished: () => {\n this.finishTrackedTurn({ turnId });\n },\n });\n this.trackTurnCompletion({ done: turn.done, turnId });\n return turn;\n } catch (error) {\n this.finishTrackedTurn({ turnId });\n throw error;\n }\n }\n\n /**\n * Ask the underlying runtime to compact its context. The runtime performs\n * the compaction itself; when it completes, a `compaction` part appears on\n * the active (or next) turn's stream. Safe to call between turns for\n * runtimes whose compaction is session-scoped (e.g. Pi).\n *\n * Throws `HarnessCapabilityUnsupportedError` for harnesses that cannot\n * trigger compaction manually (e.g. Codex, which still auto-compacts under\n * the hood). Throws if the session has ended.\n */\n async compact(customInstructions?: string): Promise<void> {\n await this.requireReusableSession().doCompact(customInstructions);\n }\n\n /**\n * Park the session, returning a payload the caller can persist and later\n * pass to `agent.createSession({ sessionId, resumeFrom })` to reconnect.\n * The runtime and sandbox keep running; this local session handle becomes\n * unusable.\n */\n async detach(): Promise<HarnessAgentResumeSessionState> {\n if (this.sessionState !== 'active' || this.underlyingSession == null) {\n throw new Error(\n `Harness session ${this.sessionId} is not active and cannot be detached.`,\n );\n }\n const session = this.underlyingSession;\n try {\n if (this.turnState !== 'idle') {\n return this.toResumeStateWithContinuation({\n continueFrom: await this.suspendCurrentTurn({ session }),\n });\n }\n const raw = await session.doDetach();\n const validated = await validateLifecycleStateData({\n harness: this.harness,\n state: raw,\n expectedType: 'resume-session',\n });\n return validated;\n } finally {\n this.endLocalHandle({\n sessionState: 'detached',\n releasePortLease: false,\n });\n }\n }\n\n /**\n * Persist enough state to resume later, then stop the runtime and sandbox.\n * Returns the resume state for a future\n * `agent.createSession({ sessionId, resumeFrom })` call.\n */\n async stop(): Promise<HarnessAgentResumeSessionState> {\n if (this.sessionState !== 'active' || this.underlyingSession == null) {\n throw new Error(\n `Harness session ${this.sessionId} is not active and cannot be stopped.`,\n );\n }\n const session = this.underlyingSession;\n const sandboxSession = this.getSandboxSession();\n try {\n if (this.turnState !== 'idle') {\n return this.toResumeStateWithContinuation({\n continueFrom: await this.suspendCurrentTurn({ session }),\n });\n }\n const raw = await session.doStop();\n const validated = await validateLifecycleStateData({\n harness: this.harness,\n state: raw,\n expectedType: 'resume-session',\n });\n return validated;\n } finally {\n this.endLocalHandle({\n sessionState: 'stopped',\n releasePortLease: true,\n });\n await Promise.resolve(sandboxSession.stop()).catch(() => {});\n }\n }\n\n /**\n * Stop the runtime and discard resumability. The sandbox is destroyed when\n * the provider supports destruction; otherwise it is stopped.\n */\n async destroy(): Promise<void> {\n if (this.sessionState !== 'active') return;\n const session = this.underlyingSession;\n const sandboxSession = this.getSandboxSession();\n this.endLocalHandle({ sessionState: 'destroyed', releasePortLease: true });\n if (session != null) {\n await Promise.resolve(session.doDestroy()).catch(() => {});\n }\n await Promise.resolve(\n sandboxSession.destroy?.() ?? sandboxSession.stop(),\n ).catch(() => {});\n }\n\n /**\n * Gracefully freeze the active turn at the slice boundary and return the\n * continuation payload, **leaving the sandbox/runtime running** so the next\n * process can continue. Resolves once the in-flight `stream()` /\n * `continueStream()` has cleanly wound down at a precise cursor (see\n * `doSuspendTurn`).\n *\n * After this call the session is detached. This in-process handle no\n * longer drives turns; a future slice creates a fresh session from the\n * returned state. The sandbox is **not** stopped and no port lease is\n * released, because bridge-backed adapters may still have a live bridge on\n * that port.\n */\n async suspendTurn(): Promise<HarnessAgentContinueTurnState> {\n if (this.sessionState !== 'active' || this.underlyingSession == null) {\n throw new Error(\n `Harness session ${this.sessionId} is not active and cannot be suspended.`,\n );\n }\n if (this.turnState === 'idle') {\n throw new Error(\n `Harness session ${this.sessionId} has no unfinished turn to suspend.`,\n );\n }\n const session = this.underlyingSession;\n try {\n return await this.suspendCurrentTurn({ session });\n } finally {\n this.endLocalHandle({\n sessionState: 'detached',\n releasePortLease: false,\n });\n }\n }\n\n private getPendingToolApprovals(): readonly HarnessAgentPendingToolApproval[] {\n return Array.from(this.pendingToolApprovals.values());\n }\n\n private addPendingToolApprovals(\n state: HarnessAgentContinueTurnState,\n ): HarnessAgentContinueTurnState {\n const pendingToolApprovals = this.getPendingToolApprovals();\n if (pendingToolApprovals.length === 0) {\n return {\n type: state.type,\n harnessId: state.harnessId,\n specificationVersion: state.specificationVersion,\n data: state.data,\n };\n }\n return {\n ...state,\n pendingToolApprovals,\n };\n }\n\n private async suspendCurrentTurn(options: {\n session: HarnessAgentAdapterSession;\n }): Promise<HarnessAgentContinueTurnState> {\n const raw = await options.session.doSuspendTurn();\n const validated = await validateLifecycleStateData({\n harness: this.harness,\n state: raw,\n expectedType: 'continue-turn',\n });\n this.turnState = 'suspended';\n return this.addPendingToolApprovals(validated);\n }\n\n private toResumeStateWithContinuation(options: {\n continueFrom: HarnessAgentContinueTurnState;\n }): HarnessAgentResumeSessionState {\n const { continueFrom } = options;\n return {\n type: 'resume-session',\n harnessId: continueFrom.harnessId,\n specificationVersion: continueFrom.specificationVersion,\n data: continueFrom.data,\n continueFrom,\n };\n }\n\n private requirePromptableTurn(): void {\n if (this.turnState === 'idle') return;\n if (this.turnState === 'running') {\n throw new Error(\n `Harness session ${this.sessionId} already has a turn in progress.`,\n );\n }\n throw new Error(\n `Harness session ${this.sessionId} has an unfinished turn and must be continued before accepting a new prompt.`,\n );\n }\n\n private requireContinuableTurn(): void {\n if (\n this.turnState === 'awaiting-approval' ||\n this.turnState === 'suspended'\n ) {\n return;\n }\n if (this.turnState === 'running') {\n throw new Error(\n `Harness session ${this.sessionId} already has a turn in progress.`,\n );\n }\n throw new Error(\n `Harness session ${this.sessionId} has no unfinished turn to continue.`,\n );\n }\n\n private markAwaitingApprovalIfActive(): void {\n if (this.sessionState === 'active') {\n this.turnState = 'awaiting-approval';\n }\n }\n\n private startTrackedTurn(): number {\n const turnId = ++this.turnSequence;\n this.activeTurnSequence = turnId;\n this.turnState = 'running';\n return turnId;\n }\n\n private trackTurnCompletion(options: {\n done: Promise<void>;\n turnId: number;\n }): void {\n void Promise.resolve(options.done)\n .finally(() => {\n this.finishTrackedTurn({ turnId: options.turnId });\n })\n .catch(() => {});\n }\n\n private finishTrackedTurn(options: { turnId: number }): void {\n if (this.sessionState !== 'active') return;\n if (this.activeTurnSequence !== options.turnId) return;\n this.turnState =\n this.pendingToolApprovals.size > 0 ? 'awaiting-approval' : 'idle';\n }\n\n private endLocalHandle(options: {\n sessionState: Exclude<HarnessAgentSessionState, 'active'>;\n releasePortLease: boolean;\n }): void {\n this.sessionState = options.sessionState;\n this.underlyingSession = undefined;\n this.sandboxSession = undefined;\n if (options.releasePortLease) {\n this.releasePortLease();\n }\n }\n\n private releasePortLease(): void {\n if (this.leasedBridgePort == null) return;\n releaseBridgePort({\n poolKey: this.sandboxProvider,\n sessionId: this.sessionId,\n });\n this.leasedBridgePort = undefined;\n }\n\n private requireReusableSession(): HarnessAgentAdapterSession {\n if (this.sessionState !== 'active' || this.underlyingSession == null) {\n throw new Error(\n `Harness session ${this.sessionId} has ended and cannot be reused.`,\n );\n }\n return this.underlyingSession;\n }\n}\n","import { HarnessError } from '../errors/harness-error';\nimport type {\n ModelMessage,\n ToolApprovalRequest,\n ToolApprovalResponse,\n} from '@ai-sdk/provider-utils';\n\nexport type HarnessAgentToolApprovalContinuation = {\n readonly approvalResponse: ToolApprovalResponse;\n readonly toolCall: {\n readonly type: 'tool-call';\n readonly toolCallId: string;\n readonly toolName: string;\n readonly input: unknown;\n readonly providerExecuted?: boolean;\n };\n};\n\n/**\n * Extract approval decisions that should continue a suspended harness turn.\n *\n * AI SDK clients send approval decisions as a trailing `role: \"tool\"` message\n * containing `tool-approval-response` parts. The response only carries the\n * approval id, so the harness has to recover the matching approval request\n * locally to find the original tool call before it can resume the paused turn.\n * Responses that already have a tool result are ignored, because those\n * approvals were already consumed by a prior continuation.\n */\nexport function collectHarnessAgentToolApprovalContinuations(input: {\n messages: readonly ModelMessage[];\n}): readonly HarnessAgentToolApprovalContinuation[] {\n const lastMessage = input.messages.at(-1);\n if (lastMessage?.role !== 'tool') return [];\n\n const toolCallsByToolCallId = new Map<\n string,\n HarnessAgentToolApprovalContinuation['toolCall']\n >();\n const approvalRequestsByApprovalId = new Map<string, ToolApprovalRequest>();\n for (const message of input.messages) {\n if (message.role !== 'assistant' || typeof message.content === 'string') {\n continue;\n }\n for (const part of message.content) {\n if (part.type === 'tool-call') {\n toolCallsByToolCallId.set(part.toolCallId, {\n type: 'tool-call',\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: part.input,\n ...(part.providerExecuted !== undefined\n ? { providerExecuted: part.providerExecuted }\n : {}),\n });\n } else if (part.type === 'tool-approval-request') {\n approvalRequestsByApprovalId.set(part.approvalId, part);\n }\n }\n }\n\n const toolResultIds = new Set<string>();\n for (const part of lastMessage.content) {\n if (part.type === 'tool-result') {\n toolResultIds.add(part.toolCallId);\n }\n }\n\n const continuations: HarnessAgentToolApprovalContinuation[] = [];\n for (const part of lastMessage.content) {\n if (part.type !== 'tool-approval-response') continue;\n\n const approvalRequest = approvalRequestsByApprovalId.get(part.approvalId);\n if (approvalRequest == null) {\n throw new HarnessError({\n message: `Tool approval response '${part.approvalId}' does not match a prior tool approval request.`,\n });\n }\n if (toolResultIds.has(approvalRequest.toolCallId)) continue;\n\n const toolCall = toolCallsByToolCallId.get(approvalRequest.toolCallId);\n if (toolCall == null) {\n throw new HarnessError({\n message: `Tool approval request '${approvalRequest.approvalId}' references unknown tool call '${approvalRequest.toolCallId}'.`,\n });\n }\n\n continuations.push({\n approvalResponse: part,\n toolCall,\n });\n }\n\n return continuations;\n}\n","import type { Experimental_SandboxSession as SandboxSession } from '@ai-sdk/provider-utils';\nimport type { HarnessV1Bootstrap } from '../../v1';\n\n/**\n * Version of the bootstrap recipe shape itself. Bump to force every existing\n * snapshot/marker to be invalidated regardless of recipe content.\n */\nexport const BOOTSTRAP_SCHEMA_VERSION = 1;\n\n/**\n * Deterministic 16-char hex identity derived from the recipe's content\n * (harnessId, bootstrapDir, file paths + contents, commands, schema version).\n * Two adapters with equivalent recipes produce the same identity; any\n * content change produces a different identity.\n *\n * Used by sandbox providers as part of the persistent sandbox name so\n * recipe changes automatically invalidate snapshots.\n */\nexport async function hashHarnessBootstrap(\n recipe: HarnessV1Bootstrap,\n): Promise<string> {\n const encoder = new TextEncoder();\n const chunks: Uint8Array[] = [];\n const pushString = (value: string) => {\n chunks.push(encoder.encode(value));\n chunks.push(encoder.encode('\\0'));\n };\n\n pushString(recipe.harnessId);\n pushString(recipe.bootstrapDir);\n\n const sortedFiles = [...recipe.files].sort((a, b) =>\n a.path.localeCompare(b.path),\n );\n for (const file of sortedFiles) {\n pushString(file.path);\n pushString(file.content);\n }\n\n pushString(JSON.stringify(recipe.commands));\n pushString(String(BOOTSTRAP_SCHEMA_VERSION));\n\n const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n const buffer = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n buffer.set(chunk, offset);\n offset += chunk.length;\n }\n\n const digest = await crypto.subtle.digest('SHA-256', buffer);\n const bytes = new Uint8Array(digest);\n let hex = '';\n for (let i = 0; i < 8; i++) {\n hex += bytes[i].toString(16).padStart(2, '0');\n }\n return hex;\n}\n\n/**\n * Absolute path of the marker file the framework writes after a recipe runs\n * successfully. Presence of this path inside the sandbox indicates the\n * recipe with the matching `identity` has already been applied.\n */\nexport function bootstrapMarkerPath(\n recipe: HarnessV1Bootstrap,\n identity: string,\n): string {\n return `${recipe.bootstrapDir}/.bootstrap-${identity}.ok`;\n}\n\n/**\n * Apply a bootstrap recipe to a sandbox session idempotently. Reads the\n * marker file; if it exists, returns immediately. Otherwise writes the\n * recipe's files, runs its commands sequentially, and writes the marker\n * on success.\n *\n * Safe to call multiple times. For sandboxes that already contain the\n * recipe (resumed from snapshot, reused across sessions, or applied by\n * an earlier process) this is a single fast read.\n */\nexport async function applyBootstrapRecipe(\n session: SandboxSession,\n recipe: HarnessV1Bootstrap,\n identity: string,\n options?: { abortSignal?: AbortSignal },\n): Promise<void> {\n const markerPath = bootstrapMarkerPath(recipe, identity);\n\n const existingMarker = await session.readTextFile({\n path: markerPath,\n abortSignal: options?.abortSignal,\n });\n if (existingMarker !== null) {\n return;\n }\n\n for (const file of recipe.files) {\n await session.writeTextFile({\n path: file.path,\n content: file.content,\n abortSignal: options?.abortSignal,\n });\n }\n\n for (const cmd of recipe.commands) {\n const result = await session.run({\n command: cmd.command,\n workingDirectory: cmd.workingDirectory,\n abortSignal: options?.abortSignal,\n });\n if (result.exitCode !== 0) {\n throw new Error(\n `Bootstrap command failed for harness '${recipe.harnessId}' (exit ${result.exitCode}): ${cmd.command}\\n${result.stderr || result.stdout}`,\n );\n }\n }\n\n await session.writeTextFile({\n path: markerPath,\n content: '',\n abortSignal: options?.abortSignal,\n });\n}\n","import { posix } from 'node:path';\nimport type { Experimental_SandboxSession as SandboxSession } from '@ai-sdk/provider-utils';\nimport type { HarnessV1Bootstrap } from '../../v1';\nimport type { HarnessAgentSandboxConfig } from '../harness-agent-settings';\nimport { applyBootstrapRecipe, hashHarnessBootstrap } from './bootstrap-recipe';\n\nconst SANDBOX_BOOTSTRAP_IDENTITY_VERSION = 1;\n\ntype SandboxBootstrapSettings = Omit<HarnessAgentSandboxConfig, 'onSession'>;\n\nexport type SandboxBootstrapPlan = {\n readonly recipe?: HarnessV1Bootstrap;\n readonly recipeIdentity?: string;\n readonly identity?: string;\n readonly workDir?: string;\n readonly onFirstCreate?: (\n session: SandboxSession,\n opts: { abortSignal?: AbortSignal },\n ) => Promise<void>;\n};\n\nexport function validateSandboxBootstrapSettings(\n settings: SandboxBootstrapSettings,\n): void {\n if ((settings.onBootstrap == null) !== (settings.bootstrapHash == null)) {\n throw new Error(\n 'HarnessAgent: `sandboxConfig.onBootstrap` and `sandboxConfig.bootstrapHash` must be provided together.',\n );\n }\n\n if (settings.workDir != null) {\n normalizeSandboxWorkDir(settings.workDir);\n }\n}\n\nexport function normalizeSandboxWorkDir(workDir: string): string {\n if (workDir.length === 0) {\n throw new Error('HarnessAgent: `sandboxConfig.workDir` must not be empty.');\n }\n if (workDir.includes('\\0')) {\n throw new Error(\n 'HarnessAgent: `sandboxConfig.workDir` must not contain NUL.',\n );\n }\n if (workDir.includes('\\\\')) {\n throw new Error(\n 'HarnessAgent: `sandboxConfig.workDir` must use POSIX path separators.',\n );\n }\n if (posix.isAbsolute(workDir)) {\n throw new Error('HarnessAgent: `sandboxConfig.workDir` must be relative.');\n }\n\n const normalized = posix.normalize(workDir);\n if (\n normalized === '.' ||\n normalized === '..' ||\n normalized.startsWith('../')\n ) {\n throw new Error(\n 'HarnessAgent: `sandboxConfig.workDir` must stay inside the sandbox default working directory.',\n );\n }\n return normalized;\n}\n\nexport function resolveSessionWorkDir({\n defaultWorkingDirectory,\n harnessId,\n sessionId,\n workDir,\n}: {\n readonly defaultWorkingDirectory: string;\n readonly harnessId: string;\n readonly sessionId: string;\n readonly workDir?: string;\n}): string {\n return joinSandboxPath({\n base: defaultWorkingDirectory,\n path: workDir ?? `${harnessId}-${sessionId}`,\n });\n}\n\nexport async function createSandboxBootstrapPlan({\n recipe,\n settings,\n}: {\n readonly recipe?: HarnessV1Bootstrap;\n readonly settings: SandboxBootstrapSettings;\n}): Promise<SandboxBootstrapPlan> {\n const workDir =\n settings.workDir == null\n ? undefined\n : normalizeSandboxWorkDir(settings.workDir);\n const recipeIdentity =\n recipe == null ? undefined : await hashHarnessBootstrap(recipe);\n const hasCallerBootstrap = settings.onBootstrap != null;\n const needsCombinedIdentity =\n hasCallerBootstrap || (recipeIdentity != null && workDir != null);\n const identity =\n needsCombinedIdentity && (recipeIdentity != null || hasCallerBootstrap)\n ? await hashSandboxBootstrapIdentity({\n recipeIdentity,\n bootstrapHash: settings.bootstrapHash,\n workDir,\n })\n : recipeIdentity;\n\n return {\n ...(recipe != null ? { recipe } : {}),\n ...(recipeIdentity != null ? { recipeIdentity } : {}),\n ...(identity != null ? { identity } : {}),\n ...(workDir != null ? { workDir } : {}),\n ...(recipe != null || settings.onBootstrap != null\n ? {\n onFirstCreate: (session, opts) =>\n runSandboxBootstrap({\n session,\n recipe,\n recipeIdentity,\n workDir,\n onBootstrap: settings.onBootstrap,\n abortSignal: opts.abortSignal,\n }),\n }\n : {}),\n };\n}\n\nexport async function runSandboxBootstrap({\n session,\n recipe,\n recipeIdentity,\n workDir,\n onBootstrap,\n abortSignal,\n}: {\n readonly session: SandboxSession;\n readonly recipe?: HarnessV1Bootstrap;\n readonly recipeIdentity?: string;\n readonly workDir?: string;\n readonly onBootstrap?: SandboxBootstrapSettings['onBootstrap'];\n readonly abortSignal?: AbortSignal;\n}): Promise<void> {\n if (recipe != null && recipeIdentity != null) {\n await applyBootstrapRecipe(session, recipe, recipeIdentity, {\n abortSignal,\n });\n }\n\n if (onBootstrap == null) return;\n\n const defaultWorkingDirectory = await resolveDefaultWorkingDirectory({\n session,\n abortSignal,\n });\n const bootstrapWorkDir =\n workDir == null\n ? defaultWorkingDirectory\n : joinSandboxPath({\n base: defaultWorkingDirectory,\n path: workDir,\n });\n\n await ensureSandboxDirectory({\n session,\n workDir: bootstrapWorkDir,\n abortSignal,\n });\n await onBootstrap({ session, workDir: bootstrapWorkDir, abortSignal });\n}\n\nexport async function resolveDefaultWorkingDirectory({\n session,\n abortSignal,\n}: {\n readonly session: SandboxSession;\n readonly abortSignal?: AbortSignal;\n}): Promise<string> {\n const result = await session.run({\n command: 'pwd',\n abortSignal,\n });\n if (result.exitCode !== 0) {\n throw new Error(\n `Failed to resolve sandbox default working directory (exit ${result.exitCode}): ${result.stderr || result.stdout}`,\n );\n }\n\n const cwd = result.stdout.trim();\n if (!posix.isAbsolute(cwd)) {\n throw new Error(\n `Failed to resolve sandbox default working directory: expected an absolute path, got ${JSON.stringify(cwd)}.`,\n );\n }\n return cwd === '/' ? cwd : cwd.replace(/\\/+$/, '');\n}\n\nexport async function ensureSandboxDirectory({\n session,\n workDir,\n abortSignal,\n}: {\n readonly session: SandboxSession;\n readonly workDir: string;\n readonly abortSignal?: AbortSignal;\n}): Promise<void> {\n const result = await session.run({\n command: 'mkdir -p \"$WORK_DIR\"',\n env: { WORK_DIR: workDir },\n abortSignal,\n });\n if (result.exitCode !== 0) {\n throw new Error(\n `Failed to create sandbox work directory ${workDir} (exit ${result.exitCode}): ${result.stderr || result.stdout}`,\n );\n }\n}\n\nasync function hashSandboxBootstrapIdentity({\n recipeIdentity,\n bootstrapHash,\n workDir,\n}: {\n readonly recipeIdentity?: string;\n readonly bootstrapHash?: string;\n readonly workDir?: string;\n}): Promise<string> {\n const encoder = new TextEncoder();\n const chunks: Uint8Array[] = [];\n const pushString = (value: string) => {\n chunks.push(encoder.encode(value));\n chunks.push(encoder.encode('\\0'));\n };\n\n pushString(String(SANDBOX_BOOTSTRAP_IDENTITY_VERSION));\n pushString(recipeIdentity ?? '');\n pushString(bootstrapHash ?? '');\n pushString(workDir ?? '');\n\n const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n const buffer = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n buffer.set(chunk, offset);\n offset += chunk.length;\n }\n\n const digest = await crypto.subtle.digest('SHA-256', buffer);\n const bytes = new Uint8Array(digest);\n let hex = '';\n for (let i = 0; i < 8; i++) {\n hex += bytes[i].toString(16).padStart(2, '0');\n }\n return hex;\n}\n\nfunction joinSandboxPath({\n base,\n path,\n}: {\n readonly base: string;\n readonly path: string;\n}): string {\n return posix.join(base, path);\n}\n","import { asArray } from '@ai-sdk/provider-utils';\nimport type { Telemetry } from 'ai';\nimport type { HarnessV1Diagnostic, HarnessV1Observability } from '../../v1';\nimport type {\n HarnessDebugConfig,\n HarnessDebugLevel,\n HarnessDiagnostic,\n HarnessDiagnosticConsumer,\n} from '../observability/types';\nimport type { HarnessAgentSettings } from '../harness-agent-settings';\n\nconst ENV_TRUTHY = new Set(['1', 'true', 'yes', 'on']);\n\nfunction parseList(value: string | undefined): string[] | undefined {\n if (!value) return undefined;\n const items = value\n .split(',')\n .map(item => item.trim())\n .filter(Boolean);\n return items.length > 0 ? items : undefined;\n}\n\n/**\n * Resolve the effective debug config from explicit settings with env-var\n * fallbacks. `HARNESS_DEBUG*` only fill fields the consumer left unset — code is\n * always authoritative.\n */\nexport function resolveDebugConfig(\n debug: HarnessDebugConfig | undefined,\n env: Record<string, string | undefined> = process.env,\n): {\n enabled: boolean;\n level: HarnessDebugLevel;\n subsystems: string[] | undefined;\n} {\n const enabled =\n debug?.enabled ?? ENV_TRUTHY.has((env.HARNESS_DEBUG ?? '').toLowerCase());\n const level =\n debug?.level ??\n (env.HARNESS_DEBUG_LEVEL as HarnessDebugLevel | undefined) ??\n 'debug';\n const subsystems = debug?.subsystems\n ? [...debug.subsystems]\n : parseList(env.HARNESS_DEBUG_SUBSYSTEMS);\n return { enabled, level, subsystems };\n}\n\n/**\n * Map an adapter-emitted `HarnessV1Diagnostic` to the host-facing\n * `HarnessDiagnostic` (the external/telemetry surface). Identity-shaped today,\n * but an explicit boundary so the emission and consumption types can diverge.\n */\nfunction toHarnessDiagnostic(d: HarnessV1Diagnostic): HarnessDiagnostic {\n return {\n level: d.level,\n message: d.message,\n subsystem: d.subsystem,\n kind: d.kind,\n source: d.source,\n stream: d.stream,\n attrs: d.attrs,\n error: d.error,\n sessionId: d.sessionId,\n timestamp: d.timestamp,\n };\n}\n\nfunction formatForStderr(d: HarnessDiagnostic): string {\n const parts = [`[harness:${d.level}]`, d.subsystem, d.message].filter(\n Boolean,\n );\n let line = parts.join(' ');\n if (d.error) {\n line += ` (${d.error.name ?? 'Error'}: ${d.error.message})`;\n }\n return `${line}\\n`;\n}\n\n/**\n * Build the per-session observability handle the framework hands to `doStart`.\n * Returns `undefined` when diagnostics are disabled. When enabled, the `report`\n * sink maps each adapter-emitted `HarnessV1Diagnostic` to the host\n * `HarnessDiagnostic` and fans it out, non-lossy, to: the `HARNESS_DEBUG` stderr\n * default, the consumer's `onLog`, and any telemetry integration that\n * implements `ingestDiagnostic`. Adapters normalize their own source (bridge\n * wire frames, host logs) into `HarnessV1Diagnostic` before calling `report`.\n */\nexport function buildObservability(options: {\n settings: Pick<\n HarnessAgentSettings<any, any>,\n 'debug' | 'onLog' | 'telemetry'\n >;\n}): HarnessV1Observability | undefined {\n const resolved = resolveDebugConfig(options.settings.debug);\n if (!resolved.enabled) return undefined;\n\n const onLog = options.settings.onLog;\n const integrations = options.settings.telemetry?.integrations\n ? asArray(options.settings.telemetry.integrations)\n : [];\n const diagnosticConsumers = integrations.filter(\n (integration): integration is Telemetry & HarnessDiagnosticConsumer =>\n typeof (integration as HarnessDiagnosticConsumer).ingestDiagnostic ===\n 'function',\n );\n\n const report = (emitted: HarnessV1Diagnostic): void => {\n const diagnostic = toHarnessDiagnostic(emitted);\n try {\n process.stderr.write(formatForStderr(diagnostic));\n } catch {\n // Never let the stderr default break the turn.\n }\n onLog?.(diagnostic);\n for (const consumer of diagnosticConsumers) {\n consumer.ingestDiagnostic?.(diagnostic);\n }\n };\n\n return {\n debug: {\n enabled: true,\n level: resolved.level,\n ...(resolved.subsystems ? { subsystems: resolved.subsystems } : {}),\n },\n report,\n };\n}\n","import type { HarnessV1SandboxProvider } from '../v1';\nimport type { HarnessAgentAdapter } from './harness-agent-types';\nimport type { HarnessAgentSandboxConfig } from './harness-agent-settings';\nimport { applyBootstrapRecipe } from './internal/bootstrap-recipe';\nimport {\n createSandboxBootstrapPlan,\n validateSandboxBootstrapSettings,\n} from './internal/sandbox-bootstrap';\n\ntype SandboxBootstrapSettings = Omit<HarnessAgentSandboxConfig, 'onSession'>;\n\n/**\n * Prepare a harness's sandbox template without running an agent. Idempotent: if\n * the template already exists (snapshot present, or marker on a non-snapshot\n * provider), this resolves quickly.\n *\n * Use from a CI/deploy script to amortize the first-session cost so production\n * sessions always resume from snapshot. For adapters without a bootstrap\n * recipe (no `getBootstrap`) this is a no-op.\n *\n * The temporary network sandbox session created during preparation is stopped\n * before the function resolves; the snapshot/template state persists in the\n * provider's native storage (for Vercel: as the `currentSnapshotId` of the\n * named template sandbox).\n */\nexport async function prepareHarnessSandboxTemplate(options: {\n readonly harness: HarnessAgentAdapter;\n readonly sandboxProvider: HarnessV1SandboxProvider;\n readonly sandboxConfig?: SandboxBootstrapSettings;\n readonly abortSignal?: AbortSignal;\n}): Promise<void> {\n const sandboxConfig = options.sandboxConfig ?? {};\n validateSandboxBootstrapSettings(sandboxConfig);\n const recipe = await options.harness.getBootstrap?.({\n abortSignal: options.abortSignal,\n });\n const bootstrapPlan = await createSandboxBootstrapPlan({\n recipe,\n settings: sandboxConfig,\n });\n if (bootstrapPlan.identity == null || bootstrapPlan.onFirstCreate == null) {\n return;\n }\n\n const sandboxSession = await options.sandboxProvider.createSession({\n abortSignal: options.abortSignal,\n identity: bootstrapPlan.identity,\n onFirstCreate: bootstrapPlan.onFirstCreate,\n });\n\n try {\n if (bootstrapPlan.recipe != null && bootstrapPlan.recipeIdentity != null) {\n await applyBootstrapRecipe(\n sandboxSession.restricted(),\n bootstrapPlan.recipe,\n bootstrapPlan.recipeIdentity,\n {\n abortSignal: options.abortSignal,\n },\n );\n }\n } finally {\n await Promise.resolve(sandboxSession.stop()).catch(() => {});\n }\n}\n\n/** @deprecated Use `prepareHarnessSandboxTemplate` instead. */\nexport const prewarmHarness = prepareHarnessSandboxTemplate;\n","import type { Experimental_SandboxSession as SandboxSession } from '@ai-sdk/provider-utils';\nimport type { HarnessAgentSandboxConfig } from './harness-agent-settings';\nimport type { HarnessAgentAdapter } from './harness-agent-types';\nimport {\n applyBootstrapRecipe,\n hashHarnessBootstrap,\n} from './internal/bootstrap-recipe';\nimport {\n normalizeSandboxWorkDir,\n runSandboxBootstrap,\n validateSandboxBootstrapSettings,\n} from './internal/sandbox-bootstrap';\n\nconst PREPARED_SANDBOX_IDENTITY_VERSION = 1;\n\nexport type PrepareSandboxForHarnessResult = {\n readonly identity?: string;\n readonly recipeIdentities: Record<string, string>;\n readonly skippedHarnessIds: ReadonlyArray<string>;\n};\n\nexport async function prepareSandboxForHarness(options: {\n readonly session: SandboxSession;\n readonly harnesses: ReadonlyArray<HarnessAgentAdapter>;\n readonly sandboxConfig?: HarnessAgentSandboxConfig;\n readonly abortSignal?: AbortSignal;\n}): Promise<PrepareSandboxForHarnessResult> {\n const sandboxConfig = options.sandboxConfig ?? {};\n validateSandboxBootstrapSettings(sandboxConfig);\n\n if (options.harnesses.length === 0) {\n throw new Error(\n 'prepareSandboxForHarness: at least one harness must be provided.',\n );\n }\n\n const harnesses = [...options.harnesses].sort((a, b) =>\n a.harnessId.localeCompare(b.harnessId),\n );\n assertUniqueHarnessIds(harnesses);\n\n const workDir =\n sandboxConfig.workDir == null\n ? undefined\n : normalizeSandboxWorkDir(sandboxConfig.workDir);\n const recipeIdentities: Record<string, string> = {};\n const skippedHarnessIds: string[] = [];\n\n for (const harness of harnesses) {\n const recipe = await harness.getBootstrap?.({\n abortSignal: options.abortSignal,\n });\n if (recipe == null) {\n skippedHarnessIds.push(harness.harnessId);\n continue;\n }\n\n const recipeIdentity = await hashHarnessBootstrap(recipe);\n recipeIdentities[harness.harnessId] = recipeIdentity;\n await applyBootstrapRecipe(options.session, recipe, recipeIdentity, {\n abortSignal: options.abortSignal,\n });\n }\n\n if (sandboxConfig.onBootstrap != null) {\n await runSandboxBootstrap({\n session: options.session,\n workDir,\n onBootstrap: sandboxConfig.onBootstrap,\n abortSignal: options.abortSignal,\n });\n }\n\n const identity = await resolvePreparedSandboxIdentity({\n recipeIdentities,\n bootstrapHash: sandboxConfig.bootstrapHash,\n workDir,\n });\n\n return {\n ...(identity != null ? { identity } : {}),\n recipeIdentities,\n skippedHarnessIds,\n };\n}\n\nfunction assertUniqueHarnessIds(\n harnesses: ReadonlyArray<HarnessAgentAdapter>,\n): void {\n const seen = new Set<string>();\n for (const harness of harnesses) {\n if (seen.has(harness.harnessId)) {\n throw new Error(\n `prepareSandboxForHarness: duplicate harness id \"${harness.harnessId}\".`,\n );\n }\n seen.add(harness.harnessId);\n }\n}\n\nasync function resolvePreparedSandboxIdentity({\n recipeIdentities,\n bootstrapHash,\n workDir,\n}: {\n readonly recipeIdentities: Record<string, string>;\n readonly bootstrapHash?: string;\n readonly workDir?: string;\n}): Promise<string | undefined> {\n const entries = Object.entries(recipeIdentities).sort(([a], [b]) =>\n a.localeCompare(b),\n );\n if (entries.length === 0 && bootstrapHash == null) {\n return undefined;\n }\n\n const encoder = new TextEncoder();\n const chunks: Uint8Array[] = [];\n const pushString = (value: string) => {\n chunks.push(encoder.encode(value));\n chunks.push(encoder.encode('\\0'));\n };\n\n pushString(String(PREPARED_SANDBOX_IDENTITY_VERSION));\n pushString(workDir ?? '');\n pushString(bootstrapHash ?? '');\n\n for (const [harnessId, identity] of entries) {\n pushString(harnessId);\n pushString(identity);\n }\n\n const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n const buffer = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n buffer.set(chunk, offset);\n offset += chunk.length;\n }\n\n const digest = await crypto.subtle.digest('SHA-256', buffer);\n const bytes = new Uint8Array(digest);\n let hex = '';\n for (let i = 0; i < 8; i++) {\n hex += bytes[i].toString(16).padStart(2, '0');\n }\n return hex;\n}\n","import { appendFileSync, mkdirSync } from 'node:fs';\nimport type { Telemetry } from 'ai';\nimport type { HarnessDiagnostic, HarnessDiagnosticConsumer } from './types';\n\n/**\n * A harness observability reporter that writes a unified, non-lossy\n * `events.jsonl` containing **both** the telemetry span lifecycle (turn / step\n * / tool) **and** the forwarded bridge diagnostics (console lines + structured\n * events). It is a single object registered in `telemetry.integrations`: the\n * framework drives its `Telemetry` methods for spans and calls\n * `ingestDiagnostic` for diagnostics.\n *\n * No external collector or OTel setup required — this is the AI-SDK-idiomatic\n * replacement for the original SDK's host-side artifact files.\n */\nexport interface FileReporterOptions {\n /** Directory for `events.jsonl` (created if absent). */\n dir: string;\n /**\n * Buffer a turn's records in memory and write them only if the turn produced\n * an error (an `error`-level diagnostic, a failed tool, or an error finish).\n * Default false (write everything).\n */\n failOnly?: boolean;\n /** File name within `dir`. Default `events.jsonl`. */\n fileName?: string;\n}\n\ntype Record_ = { ts: number } & Record<string, unknown>;\n\nexport type FileReporter = Telemetry & HarnessDiagnosticConsumer;\n\nexport function createFileReporter(options: FileReporterOptions): FileReporter {\n const fileName = options.fileName ?? 'events.jsonl';\n const path = `${options.dir}/${fileName}`;\n const failOnly = options.failOnly ?? false;\n\n // Per-turn buffers, keyed by the telemetry callId. Diagnostics (which carry a\n // sessionId, not a callId) attach to the most recently started, open turn.\n const turns = new Map<string, { lines: Record_[]; errored: boolean }>();\n let lastOpenCallId: string | undefined;\n let dirReady = false;\n\n const bucketFor = (callId: string) => {\n let bucket = turns.get(callId);\n if (!bucket) {\n bucket = { lines: [], errored: false };\n turns.set(callId, bucket);\n }\n return bucket;\n };\n\n const record = (callId: string | undefined, rec: Record_): void => {\n const id = callId ?? lastOpenCallId;\n if (id == null) {\n // No active turn — write standalone (best-effort).\n flushLines([rec]);\n return;\n }\n bucketFor(id).lines.push(rec);\n };\n\n const flushLines = (lines: Record_[]): void => {\n if (lines.length === 0) return;\n try {\n if (!dirReady) {\n mkdirSync(options.dir, { recursive: true });\n dirReady = true;\n }\n appendFileSync(path, lines.map(l => JSON.stringify(l)).join('\\n') + '\\n');\n } catch {\n // Best-effort: never let observability break a turn.\n }\n };\n\n const finishTurn = (callId: string): void => {\n const bucket = turns.get(callId);\n if (!bucket) return;\n turns.delete(callId);\n if (lastOpenCallId === callId) lastOpenCallId = undefined;\n if (failOnly && !bucket.errored) return;\n flushLines(bucket.lines);\n };\n\n return {\n onStart(event) {\n const e = event as {\n callId: string;\n operationId?: string;\n modelId?: string;\n provider?: string;\n messages?: unknown;\n instructions?: unknown;\n recordInputs?: boolean;\n };\n lastOpenCallId = e.callId;\n record(e.callId, {\n ts: Date.now(),\n kind: 'turn-start',\n callId: e.callId,\n operationId: e.operationId,\n provider: e.provider,\n modelId: e.modelId,\n // Input prompt, unless the consumer opted out via `recordInputs: false`.\n ...(e.recordInputs === false\n ? {}\n : { input: { messages: e.messages, instructions: e.instructions } }),\n });\n },\n onStepStart(event) {\n const e = event as { callId: string; stepNumber?: number };\n record(e.callId, {\n ts: Date.now(),\n kind: 'step-start',\n callId: e.callId,\n step: e.stepNumber,\n });\n },\n onToolExecutionStart(event) {\n const e = event as {\n callId: string;\n toolCall: { toolName: string; toolCallId: string; input: unknown };\n };\n record(e.callId, {\n ts: Date.now(),\n kind: 'tool-start',\n callId: e.callId,\n toolName: e.toolCall.toolName,\n toolCallId: e.toolCall.toolCallId,\n input: e.toolCall.input,\n });\n },\n onToolExecutionEnd(event) {\n const e = event as {\n callId: string;\n toolCall: { toolCallId: string };\n toolOutput: { type: string; output?: unknown; error?: unknown };\n };\n const isError = e.toolOutput.type === 'error';\n if (isError) bucketFor(e.callId).errored = true;\n record(e.callId, {\n ts: Date.now(),\n kind: 'tool-end',\n callId: e.callId,\n toolCallId: e.toolCall.toolCallId,\n isError,\n output: isError ? e.toolOutput.error : e.toolOutput.output,\n });\n },\n onStepFinish(event) {\n const e = event as {\n callId: string;\n usage?: unknown;\n content?: unknown[];\n recordOutputs?: boolean;\n };\n record(e.callId, {\n ts: Date.now(),\n kind: 'step-finish',\n callId: e.callId,\n usage: e.usage,\n // The model's output content, unless `recordOutputs: false`.\n ...(e.recordOutputs === false || e.content == null\n ? {}\n : { output: e.content }),\n });\n },\n onEnd(event) {\n const e = event as {\n callId: string;\n finishReason?: unknown;\n usage?: unknown;\n totalUsage?: unknown;\n };\n record(e.callId, {\n ts: Date.now(),\n kind: 'turn-finish',\n callId: e.callId,\n finishReason: e.finishReason,\n usage: e.totalUsage ?? e.usage,\n });\n finishTurn(e.callId);\n },\n onError(error) {\n if (lastOpenCallId != null) bucketFor(lastOpenCallId).errored = true;\n record(lastOpenCallId, {\n ts: Date.now(),\n kind: 'error',\n error:\n error instanceof Error\n ? { name: error.name, message: error.message }\n : error,\n });\n },\n ingestDiagnostic(diagnostic: HarnessDiagnostic) {\n if (diagnostic.level === 'error' && lastOpenCallId != null) {\n bucketFor(lastOpenCallId).errored = true;\n }\n record(lastOpenCallId, {\n ts: diagnostic.timestamp,\n kind: 'diagnostic',\n diagnostic,\n });\n },\n };\n}\n","import type { Telemetry } from 'ai';\n\n/**\n * A harness observability reporter that renders an ASCII trace tree of a\n * turn's span lifecycle (turn → steps → tools) to a stream at turn end. It is a\n * `Telemetry` integration — register it in `telemetry.integrations`. Useful for\n * zero-setup local debugging when no OTel collector is wired up; a real OTel\n * backend (via `@ai-sdk/otel`) is a strict superset.\n */\nexport interface TraceTreeReporterOptions {\n /** Where to write the rendered tree. Default `process.stderr.write`. */\n write?: (chunk: string) => void;\n}\n\ntype Node = {\n label: string;\n startMs: number;\n endMs?: number;\n children: Node[];\n};\n\nexport function createTraceTreeReporter(\n options: TraceTreeReporterOptions = {},\n): Telemetry {\n const write =\n options.write ?? ((chunk: string) => void process.stderr.write(chunk));\n\n type TurnState = {\n root: Node;\n step?: Node;\n tools: Map<string, Node>;\n };\n const turns = new Map<string, TurnState>();\n\n const render = (node: Node, depth: number): string => {\n const indent = ' '.repeat(depth);\n const dur =\n node.endMs != null\n ? `${Math.max(0, Math.round(node.endMs - node.startMs))}ms`\n : '(open)';\n let out = `${indent}- ${node.label} ${dur}\\n`;\n for (const child of node.children) out += render(child, depth + 1);\n return out;\n };\n\n return {\n onStart(event) {\n const e = event as {\n callId: string;\n operationId?: string;\n modelId?: string;\n };\n turns.set(e.callId, {\n root: {\n label: `${e.operationId ?? 'turn'}${e.modelId ? ` ${e.modelId}` : ''}`,\n startMs: Date.now(),\n children: [],\n },\n tools: new Map(),\n });\n },\n onStepStart(event) {\n const e = event as { callId: string; stepNumber?: number };\n const turn = turns.get(e.callId);\n if (!turn) return;\n const step: Node = {\n label: `step ${(e.stepNumber ?? turn.root.children.length) + 1}`,\n startMs: Date.now(),\n children: [],\n };\n turn.step = step;\n turn.root.children.push(step);\n },\n onToolExecutionStart(event) {\n const e = event as {\n callId: string;\n toolCall: { toolName: string; toolCallId: string };\n };\n const turn = turns.get(e.callId);\n const parent = turn?.step ?? turn?.root;\n if (!turn || !parent) return;\n const node: Node = {\n label: `tool ${e.toolCall.toolName}`,\n startMs: Date.now(),\n children: [],\n };\n turn.tools.set(e.toolCall.toolCallId, node);\n parent.children.push(node);\n },\n onToolExecutionEnd(event) {\n const e = event as {\n callId: string;\n toolCall: { toolCallId: string };\n toolOutput: { type: string };\n };\n const node = turns.get(e.callId)?.tools.get(e.toolCall.toolCallId);\n if (!node) return;\n node.endMs = Date.now();\n if (e.toolOutput.type === 'error') node.label += ' [error]';\n },\n onStepFinish(event) {\n const e = event as { callId: string };\n const turn = turns.get(e.callId);\n if (turn?.step) {\n turn.step.endMs = Date.now();\n turn.step = undefined;\n }\n },\n onEnd(event) {\n const e = event as { callId: string };\n const turn = turns.get(e.callId);\n if (!turn) return;\n turn.root.endMs = Date.now();\n turns.delete(e.callId);\n try {\n write(`\\n${render(turn.root, 0)}`);\n } catch {\n // Never let rendering break the turn.\n }\n },\n };\n}\n"],"mappings":";AAAA,SAAS,cAAAA,mBAAkB;;;ACA3B,SAAS,kBAAkB;AAE3B,IAAM,OAAO;AACb,IAAM,SAAS,mBAAmB,IAAI;AACtC,IAAM,SAAS,OAAO,IAAI,MAAM;AAJhC;AAWO,IAAM,eAAN,eAA2B,iBACd,aADc,IAAW;AAAA,EAG3C,YAAY,EAAE,SAAS,MAAM,GAAyC;AACpE,UAAM,EAAE,MAAM,SAAS,MAAM,CAAC;AAHhC,SAAkB,MAAU;AAAA,EAI5B;AAAA,EAEA,OAAO,WAAW,OAAuC;AACvD,WAAO,WAAW,UAAU,OAAO,MAAM;AAAA,EAC3C;AACF;;;ADlBA,IAAMC,QAAO;AACb,IAAMC,UAAS,mBAAmBD,KAAI;AACtC,IAAME,UAAS,OAAO,IAAID,OAAM;AALhC,IAAAE,KAAAC;AAgBO,IAAM,oCAAN,eAAgDA,MAAA,cACnCD,MAAAD,SADmCE,KAAa;AAAA,EAKlE,YAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAIG;AACD,UAAM,EAAE,SAAS,MAAM,CAAC;AAb1B,SAAkBD,OAAU;AAc1B,WAAO,eAAe,MAAM,QAAQ,EAAE,OAAOH,MAAK,CAAC;AACnD,SAAK,YAAY;AAAA,EACnB;AAAA,EAEA,OAA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AO;AAzEhC,UAAAA;AA0EM,YAAM,IAAI;AAIV,YAAM,OAAO,MAAM,IAAI,EAAE,MAAM;AAC/B,YAAM,UAASA,MAAA,6BAAM,SAAN,OAAAA,MAAc,6BAAM;AACnC,UAAI,CAAC,QAAQ,CAAC,OAAQ;AACtB,YAAM,OAAa;AAAA,QACjB,OAAO,QAAQ,EAAE,SAAS,QAAQ;AAAA,QAClC,SAAS,KAAK,IAAI;AAAA,QAClB,UAAU,CAAC;AAAA,MACb;AACA,WAAK,MAAM,IAAI,EAAE,SAAS,YAAY,IAAI;AAC1C,aAAO,SAAS,KAAK,IAAI;AAAA,IAC3B;AAAA,IACA,mBAAmB,OAAO;AAzF9B,UAAAA;AA0FM,YAAM,IAAI;AAKV,YAAM,QAAOA,MAAA,MAAM,IAAI,EAAE,MAAM,MAAlB,gBAAAA,IAAqB,MAAM,IAAI,EAAE,SAAS;AACvD,UAAI,CAAC,KAAM;AACX,WAAK,QAAQ,KAAK,IAAI;AACtB,UAAI,EAAE,WAAW,SAAS,QAAS,MAAK,SAAS;AAAA,IACnD;AAAA,IACA,aAAa,OAAO;AAClB,YAAM,IAAI;AACV,YAAM,OAAO,MAAM,IAAI,EAAE,MAAM;AAC/B,UAAI,6BAAM,MAAM;AACd,aAAK,KAAK,QAAQ,KAAK,IAAI;AAC3B,aAAK,OAAO;AAAA,MACd;AAAA,IACF;AAAA,IACA,MAAM,OAAO;AACX,YAAM,IAAI;AACV,YAAM,OAAO,MAAM,IAAI,EAAE,MAAM;AAC/B,UAAI,CAAC,KAAM;AACX,WAAK,KAAK,QAAQ,KAAK,IAAI;AAC3B,YAAM,OAAO,EAAE,MAAM;AACrB,UAAI;AACF,cAAM;AAAA,EAAK,OAAO,KAAK,MAAM,CAAC,CAAC,EAAE;AAAA,MACnC,SAAQC,IAAA;AAAA,MAER;AAAA,IACF;AAAA,EACF;AACF;","names":["AISDKError","name","marker","symbol","_a","_b","AISDKError","generateId","generateId","generateId","generateId","_a","_b","_a","_a","_b","_c","input","done","generateId","_a","_b","_a","_b","_a","generateId","name","_a","_b","_a","_b","_a","_b","_a","e"]}
1
+ {"version":3,"sources":["../../src/errors/harness-capability-unsupported-error.ts","../../src/errors/harness-error.ts","../../src/agent/harness-agent.ts","../../src/agent/internal/bridge-port-registry.ts","../../src/agent/internal/lifecycle-state-validation.ts","../../src/v1/harness-v1-tool-filtering.ts","../../src/agent/internal/to-harness-stream.ts","../../src/agent/internal/run-prompt.ts","../../src/agent/internal/harness-stream-text-result.ts","../../src/agent/internal/translate-stream-part.ts","../../src/agent/internal/strip-work-dir.ts","../../src/agent/internal/turn-telemetry.ts","../../src/agent/internal/permission-mode.ts","../../src/agent/harness-agent-session.ts","../../src/agent/harness-agent-tool-approval-continuation.ts","../../src/agent/internal/bootstrap-recipe.ts","../../src/agent/internal/sandbox-bootstrap.ts","../../src/agent/internal/resolve-observability.ts","../../src/agent/internal/tool-filtering.ts","../../src/agent/prewarm.ts","../../src/agent/prepare-sandbox-for-harness.ts","../../src/agent/observability/file-reporter.ts","../../src/agent/observability/trace-tree-reporter.ts"],"sourcesContent":["import { AISDKError } from '@ai-sdk/provider';\nimport { HarnessError } from './harness-error';\n\nconst name = 'AI_HarnessCapabilityUnsupportedError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Thrown when a caller asks the harness to do something the adapter (or the\n * supplied sandbox) does not support, e.g. requesting manual compaction from\n * an adapter that only auto-compacts, or invoking `getPortUrl` on a sandbox\n * that does not expose one.\n *\n * The caller supplies the full human-readable message. Optional `harnessId`\n * is recorded as structured context for tooling.\n */\nexport class HarnessCapabilityUnsupportedError extends HarnessError {\n private readonly [symbol] = true;\n\n readonly harnessId?: string;\n\n constructor({\n message,\n harnessId,\n cause,\n }: {\n message: string;\n harnessId?: string;\n cause?: unknown;\n }) {\n super({ message, cause });\n Object.defineProperty(this, 'name', { value: name });\n this.harnessId = harnessId;\n }\n\n static isInstance(\n error: unknown,\n ): error is HarnessCapabilityUnsupportedError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_HarnessError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Base error type for failures originating in or signalled by a harness\n * adapter. Specific failure modes (e.g. unsupported capability) extend this\n * class.\n */\nexport class HarnessError extends AISDKError {\n private readonly [symbol] = true;\n\n constructor({ message, cause }: { message: string; cause?: unknown }) {\n super({ name, message, cause });\n }\n\n static isInstance(error: unknown): error is HarnessError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { HarnessCapabilityUnsupportedError } from '../errors/harness-capability-unsupported-error';\nimport type {\n HarnessV1Bootstrap,\n HarnessV1BuiltinToolFiltering,\n HarnessV1NetworkSandboxSession,\n HarnessV1SandboxProvider,\n} from '../v1';\nimport {\n asSchema,\n generateId,\n type Context,\n type ModelMessage,\n type ToolSet,\n} from '@ai-sdk/provider-utils';\nimport type {\n Agent,\n AgentCallParameters,\n AgentStreamParameters,\n GenerateTextResult,\n ReasoningFileOutput,\n ReasoningOutput,\n StreamTextResult,\n} from 'ai';\nimport type {\n HarnessAgentSandboxConfig,\n HarnessAgentSettings,\n} from './harness-agent-settings';\nimport type { HarnessAllTools } from './harness-agent-tool-types';\nimport { HarnessAgentSession } from './harness-agent-session';\nimport type {\n HarnessAgentAdapter,\n HarnessAgentContinueTurnState,\n HarnessAgentPermissionMode,\n HarnessAgentPrompt,\n HarnessAgentResumeSessionState,\n HarnessAgentToolSpec,\n} from './harness-agent-types';\nimport {\n collectHarnessAgentToolApprovalContinuations,\n type HarnessAgentToolApprovalContinuation,\n} from './harness-agent-tool-approval-continuation';\nimport { applyBootstrapRecipe } from './internal/bootstrap-recipe';\nimport {\n acquireBridgePort,\n releaseBridgePort,\n} from './internal/bridge-port-registry';\nimport {\n createSandboxBootstrapPlan,\n ensureSandboxDirectory,\n resolveSessionWorkDir,\n validateSandboxBootstrapSettings,\n type SandboxBootstrapPlan,\n} from './internal/sandbox-bootstrap';\nimport { buildObservability } from './internal/resolve-observability';\nimport { validateLifecycleStateData } from './internal/lifecycle-state-validation';\nimport {\n permissionModeNeedsBuiltinSupport,\n resolvePermissionMode,\n} from './internal/permission-mode';\nimport { resolveHarnessAgentToolFiltering } from './internal/tool-filtering';\n\nexport type { HarnessAllTools } from './harness-agent-tool-types';\n\n/**\n * Required `session` extension on every `HarnessAgent.generate` /\n * `HarnessAgent.stream` call. The agent operates exclusively on the\n * `HarnessAgentSession` the caller passes in — it owns no session\n * state of its own.\n */\nexport interface HarnessAgentCallExtensions {\n /**\n * Active session returned by `agent.createSession(...)`. Drives the\n * underlying harness adapter for this turn.\n */\n session: HarnessAgentSession;\n}\n\n/**\n * AI SDK `Agent` implementation that drives a third-party agent runtime\n * through a harness adapter (Claude Code, Codex, …).\n *\n * Behaviour summary:\n * - **Stateless definition.** Construct once at module scope. The agent\n * holds the harness adapter, the merged tool surface, the sandbox\n * provider and other config — never a live session. Per-call data\n * (prompt, abort signal, the `HarnessAgentSession`) lives on\n * `generate()` / `stream()`.\n * - **Explicit sessions.** Callers spawn sessions with\n * `agent.createSession(...)`, pass the returned\n * `HarnessAgentSession` on every `generate` / `stream`, and end it via\n * `session.detach()`, `session.stop()`, or `session.destroy()`.\n * - **Cross-process resume.** `createSession({ sessionId, resumeFrom })`\n * resumes from state previously returned by `session.detach()` or\n * `session.stop()`. The framework validates `resumeFrom` against the\n * harness's `lifecycleStateSchema` before handing it to the adapter.\n * `createSession({ sessionId, continueFrom })` resumes from state returned\n * by `session.suspendTurn()` before `continueStream()` /\n * `continueGenerate()`.\n * - **Host tool execution.** User tools passed in `settings.tools` are\n * executed on the host whenever the underlying runtime calls them;\n * the result is fed back to the harness via `submitToolResult`.\n * Adapter builtin tools (e.g. Claude Code's `Bash`) pass through\n * untouched.\n * - **Sandbox propagation.** `settings.sandbox` is a sandbox provider.\n * On `createSession`, the agent calls `provider.createSession()` (or\n * `resumeSession()`) and passes the resulting network sandbox session into\n * `doStart`. Its `restricted()` view (a tool-safe\n * `Experimental_SandboxSession`) is handed to user-tool `execute()` calls\n * via `experimental_sandbox`.\n */\nexport class HarnessAgent<\n THarness extends HarnessAgentAdapter<any> = HarnessAgentAdapter,\n TUserTools extends ToolSet = {},\n RUNTIME_CONTEXT extends Context = Context,\n> implements Agent<\n never,\n HarnessAllTools<THarness, TUserTools>,\n RUNTIME_CONTEXT,\n never\n> {\n readonly version = 'agent-v1' as const;\n readonly id: string | undefined;\n\n /**\n * Merged tool set exposed to AI SDK consumers: harness builtins +\n * user-defined tools, with user tools overriding builtins on key\n * collision. Built once at construction time so the typed surface is\n * stable across calls.\n */\n readonly tools: HarnessAllTools<THarness, TUserTools>;\n\n private readonly settings: HarnessAgentSettings<THarness, TUserTools>;\n private readonly sandboxConfig: HarnessAgentSandboxConfig;\n private readonly activeUserTools: TUserTools;\n private readonly builtinToolFiltering:\n | HarnessV1BuiltinToolFiltering\n | undefined;\n private readonly permissionMode: HarnessAgentPermissionMode;\n\n constructor(settings: HarnessAgentSettings<THarness, TUserTools>) {\n const sandboxConfig = resolveSandboxConfig(settings);\n validateSandboxBootstrapSettings(sandboxConfig);\n this.settings = settings;\n this.sandboxConfig = sandboxConfig;\n this.id = settings.id;\n const userTools = settings.tools ?? ({} as TUserTools);\n this.permissionMode = resolvePermissionMode({\n permissionMode: settings.permissionMode,\n });\n const tools = {\n ...settings.harness.builtinTools,\n ...userTools,\n } as HarnessAllTools<THarness, TUserTools>;\n const toolFiltering = resolveHarnessAgentToolFiltering({\n harness: settings.harness,\n userTools,\n allTools: tools,\n activeTools: settings.activeTools,\n inactiveTools: settings.inactiveTools,\n });\n this.activeUserTools = toolFiltering.activeUserTools;\n this.builtinToolFiltering = toolFiltering.builtinToolFiltering;\n if (\n Object.keys(settings.harness.builtinTools).length > 0 &&\n permissionModeNeedsBuiltinSupport({\n permissionMode: this.permissionMode,\n }) &&\n settings.harness.supportsBuiltinToolApprovals !== true\n ) {\n throw new HarnessCapabilityUnsupportedError({\n message: `Harness '${settings.harness.harnessId}' does not support built-in tool approval requests; use permissionMode: 'allow-all'.`,\n harnessId: settings.harness.harnessId,\n });\n }\n this.tools = tools;\n }\n\n /** Identifier of the harness backing this agent. */\n get harnessId(): string {\n return this.settings.harness.harnessId;\n }\n\n /**\n * Start a fresh session, or resume from state previously returned by\n * `session.detach()` or `session.stop()`. The returned\n * `HarnessAgentSession` must be passed to subsequent `generate` / `stream`\n * calls; end it with `session.detach()`, `session.stop()`, or\n * `session.destroy()`.\n */\n async createSession(options?: {\n /**\n * Optional stable identifier for the underlying sandbox/session.\n * When omitted the agent generates one. Supply the original\n * `session.sessionId` together with `resumeFrom` to reattach a\n * previously ended session across processes.\n */\n sessionId?: string;\n /**\n * Resume payload returned by a prior `session.detach()` or\n * `session.stop()`. Must be accompanied by the original `sessionId`; the\n * framework validates it against `harness.lifecycleStateSchema` before\n * handing it to the adapter.\n */\n resumeFrom?: HarnessAgentResumeSessionState;\n /**\n * Continuation payload returned by a prior `session.suspendTurn()`. Must be\n * accompanied by the original `sessionId`; the framework validates it before\n * handing it to the adapter.\n */\n continueFrom?: HarnessAgentContinueTurnState;\n abortSignal?: AbortSignal;\n }): Promise<HarnessAgentSession> {\n const sessionId = options?.sessionId ?? generateId();\n const resumeFrom = options?.resumeFrom;\n const continueFrom = options?.continueFrom;\n const abortSignal = options?.abortSignal;\n const harness = this.settings.harness;\n const sandboxProvider = this.settings.sandbox;\n\n if (resumeFrom != null && continueFrom != null) {\n throw new Error(\n 'HarnessAgent.createSession: pass either `resumeFrom` or `continueFrom`, not both.',\n );\n }\n\n let validatedResumeFrom: HarnessAgentResumeSessionState | undefined;\n if (resumeFrom != null) {\n validatedResumeFrom = await validateLifecycleStateData({\n harness,\n state: resumeFrom,\n expectedType: 'resume-session',\n });\n }\n\n let validatedContinueFrom: HarnessAgentContinueTurnState | undefined;\n if (continueFrom != null) {\n validatedContinueFrom = await validateLifecycleStateData({\n harness,\n state: continueFrom,\n expectedType: 'continue-turn',\n });\n }\n\n const effectiveContinueFrom =\n validatedContinueFrom ?? validatedResumeFrom?.continueFrom;\n const isResumedSession =\n validatedResumeFrom != null || effectiveContinueFrom != null;\n\n let recipe: HarnessV1Bootstrap | undefined;\n if (harness.getBootstrap != null) {\n recipe = await harness.getBootstrap({ abortSignal });\n }\n\n // Defines the hashes based on both harness bootstrap recipe and\n // consumer-defined onBootstrap callback.\n const sandboxBootstrapPlan = await createSandboxBootstrapPlan({\n recipe,\n settings: this.sandboxConfig,\n });\n\n // Acquires the concrete sandbox session, either by starting fresh and then\n // creating a post-bootstrap snapshot, or by reusing a previously created\n // snapshot based on the bootstrap-based hashes.\n const acquiredSandboxSession = await this._acquireSandbox({\n sandboxProvider,\n sessionId,\n isResume: isResumedSession,\n bootstrapPlan: sandboxBootstrapPlan,\n abortSignal,\n });\n\n const leased = applyPortLease({\n provider: sandboxProvider,\n sandboxSession: acquiredSandboxSession,\n sessionId,\n });\n const sandboxSession = leased.sandboxSession;\n const leasedBridgePort = leased.port;\n const sessionWorkDir = resolveSessionWorkDir({\n defaultWorkingDirectory: sandboxSession.defaultWorkingDirectory,\n harnessId: harness.harnessId,\n sessionId,\n workDir: sandboxBootstrapPlan.workDir,\n });\n\n try {\n // In case the sandbox session was created with a custom sandbox, or in\n // case the sandbox provider doesn't respect `onFirstCreate`, we still\n // have to ensure the harness bootstrap recipe has run. In the common\n // scenario, this will be a cheap no-op based on just a marker check.\n if (\n !isResumedSession &&\n sandboxBootstrapPlan.recipe != null &&\n sandboxBootstrapPlan.recipeIdentity != null\n ) {\n await applyBootstrapRecipe(\n sandboxSession.restricted(),\n sandboxBootstrapPlan.recipe,\n sandboxBootstrapPlan.recipeIdentity,\n { abortSignal },\n );\n }\n await ensureSandboxDirectory({\n session: sandboxSession,\n workDir: sessionWorkDir,\n abortSignal,\n });\n if (this.sandboxConfig.onSession != null) {\n await this.sandboxConfig.onSession({\n session: sandboxSession.restricted(),\n sessionWorkDir,\n abortSignal,\n });\n }\n } catch (err) {\n await cleanupAfterStartFailure({\n sandboxProvider,\n sandboxSession,\n sessionId,\n leasedBridgePort,\n });\n throw err;\n }\n\n try {\n const baseStartOptions = {\n sessionId,\n skills: this.settings.skills,\n resumeFrom: validatedResumeFrom,\n continueFrom: effectiveContinueFrom,\n permissionMode: this.permissionMode,\n builtinToolFiltering: this.builtinToolFiltering,\n abortSignal,\n observability: buildObservability({ settings: this.settings }),\n };\n const underlyingSession = await harness.doStart({\n ...baseStartOptions,\n sandboxSession,\n sessionWorkDir,\n });\n return new HarnessAgentSession({\n sessionId,\n harness,\n underlyingSession,\n sandboxSession,\n sandboxProvider,\n leasedBridgePort,\n sessionWorkDir,\n toolApproval: this.settings.toolApproval,\n pendingToolApprovals: effectiveContinueFrom?.pendingToolApprovals,\n turnState:\n effectiveContinueFrom == null\n ? 'idle'\n : effectiveContinueFrom.pendingToolApprovals != null &&\n effectiveContinueFrom.pendingToolApprovals.length > 0\n ? 'awaiting-approval'\n : 'suspended',\n });\n } catch (error) {\n await cleanupAfterStartFailure({\n sandboxProvider,\n sandboxSession,\n sessionId,\n leasedBridgePort,\n });\n throw error;\n }\n }\n\n async generate(\n options: AgentCallParameters<\n never,\n HarnessAllTools<THarness, TUserTools>,\n RUNTIME_CONTEXT\n > &\n HarnessAgentCallExtensions,\n ): Promise<\n GenerateTextResult<\n HarnessAllTools<THarness, TUserTools>,\n RUNTIME_CONTEXT,\n never\n >\n > {\n const turnInput = this._resolveTurnInput(options);\n const runtimeContext = {} as RUNTIME_CONTEXT;\n const { result, done } = this._startTurn({\n session: options.session,\n turnInput,\n runtimeContext,\n abortSignal: options.abortSignal,\n });\n await done;\n return this._toGenerateResult(result);\n }\n\n async stream(\n options: AgentStreamParameters<\n never,\n HarnessAllTools<THarness, TUserTools>,\n RUNTIME_CONTEXT\n > &\n HarnessAgentCallExtensions,\n ): Promise<\n StreamTextResult<\n HarnessAllTools<THarness, TUserTools>,\n RUNTIME_CONTEXT,\n never\n >\n > {\n const turnInput = this._resolveTurnInput(options);\n const runtimeContext = {} as RUNTIME_CONTEXT;\n const { result } = this._startTurn({\n session: options.session,\n turnInput,\n runtimeContext,\n abortSignal: options.abortSignal,\n });\n return result;\n }\n\n /**\n * Continue the in-flight turn **without a new prompt**, draining it like\n * {@link generate}. Used after `createSession({ continueFrom })` to finish\n * consuming a turn that crossed a process boundary.\n */\n async continueGenerate(options: {\n session: HarnessAgentSession;\n toolApprovalContinuations?: readonly HarnessAgentToolApprovalContinuation[];\n abortSignal?: AbortSignal;\n }): Promise<\n GenerateTextResult<\n HarnessAllTools<THarness, TUserTools>,\n RUNTIME_CONTEXT,\n never\n >\n > {\n const runtimeContext = {} as RUNTIME_CONTEXT;\n\n const { result, done } = this._startTurn({\n session: options.session,\n turnInput: {\n mode: 'continue',\n toolApprovalContinuations: options.toolApprovalContinuations ?? [],\n },\n runtimeContext,\n abortSignal: options.abortSignal,\n });\n await done;\n return this._toGenerateResult(result);\n }\n\n /**\n * Continue the in-flight turn **without a new prompt**, streaming its events\n * like {@link stream}. Used to keep consuming a turn that is still running\n * (or finished) in the runtime after a process boundary — the workflow slice\n * loop calls this on every slice after the first. Routes through the adapter's\n * `doContinueTurn`; what it can guarantee (lossless attach vs. lossy rerun)\n * follows from how the adapter resumed the session.\n */\n async continueStream(options: {\n session: HarnessAgentSession;\n toolApprovalContinuations?: readonly HarnessAgentToolApprovalContinuation[];\n abortSignal?: AbortSignal;\n }): Promise<\n StreamTextResult<\n HarnessAllTools<THarness, TUserTools>,\n RUNTIME_CONTEXT,\n never\n >\n > {\n const runtimeContext = {} as RUNTIME_CONTEXT;\n\n const { result } = this._startTurn({\n session: options.session,\n turnInput: {\n mode: 'continue',\n toolApprovalContinuations: options.toolApprovalContinuations ?? [],\n },\n runtimeContext,\n abortSignal: options.abortSignal,\n });\n return result;\n }\n\n // ─── Internals ──────────────────────────────────────────────────────\n\n private _startTurn(input: {\n session: HarnessAgentSession;\n turnInput:\n | { mode: 'prompt'; prompt: HarnessAgentPrompt }\n | {\n mode: 'continue';\n toolApprovalContinuations: readonly HarnessAgentToolApprovalContinuation[];\n };\n runtimeContext: RUNTIME_CONTEXT;\n abortSignal: AbortSignal | undefined;\n }): {\n result: StreamTextResult<\n HarnessAllTools<THarness, TUserTools>,\n RUNTIME_CONTEXT,\n never\n >;\n done: Promise<void>;\n } {\n if (input.turnInput.mode === 'continue') {\n return input.session.continueTurn<\n HarnessAllTools<THarness, TUserTools>,\n RUNTIME_CONTEXT\n >({\n instructions: this.settings.instructions,\n tools: this.tools,\n activeTools: this.activeUserTools,\n toolSpecs: this._toToolSpecs(),\n builtinToolFiltering: this.builtinToolFiltering,\n runtimeContext: input.runtimeContext,\n abortSignal: input.abortSignal,\n telemetry: this.settings.telemetry,\n toolApprovalContinuations: input.turnInput.toolApprovalContinuations,\n });\n }\n\n return input.session.promptTurn<\n HarnessAllTools<THarness, TUserTools>,\n RUNTIME_CONTEXT\n >({\n prompt: input.turnInput.prompt,\n instructions: this.settings.instructions,\n tools: this.tools,\n activeTools: this.activeUserTools,\n toolSpecs: this._toToolSpecs(),\n builtinToolFiltering: this.builtinToolFiltering,\n runtimeContext: input.runtimeContext,\n abortSignal: input.abortSignal,\n telemetry: this.settings.telemetry,\n });\n }\n\n private async _acquireSandbox(input: {\n sandboxProvider: HarnessV1SandboxProvider;\n sessionId: string;\n isResume: boolean;\n bootstrapPlan: SandboxBootstrapPlan;\n abortSignal: AbortSignal | undefined;\n }): Promise<HarnessV1NetworkSandboxSession> {\n const { sandboxProvider } = input;\n if (input.isResume) {\n if (sandboxProvider.resumeSession == null) {\n throw new HarnessCapabilityUnsupportedError({\n message: `Sandbox provider '${sandboxProvider.providerId}' does not support resume.`,\n harnessId: this.settings.harness.harnessId,\n });\n }\n return sandboxProvider.resumeSession({\n sessionId: input.sessionId,\n abortSignal: input.abortSignal,\n });\n }\n return sandboxProvider.createSession({\n sessionId: input.sessionId,\n abortSignal: input.abortSignal,\n identity: input.bootstrapPlan.identity,\n onFirstCreate: input.bootstrapPlan.onFirstCreate,\n });\n }\n\n /*\n * Reduce AI SDK input to the single user message the harness should run\n * for this turn. The harness session owns prior-turn state (system\n * prompt, assistant turns, tool results) — we never replay it. A bare\n * string is forwarded as-is; a message array is collapsed to its last\n * `role: 'user'` entry. Inputs whose only messages are non-user (system,\n * assistant, tool) have no fresh user input and are rejected.\n */\n private _resolveTurnInput(options: {\n prompt?: string | ModelMessage[];\n messages?: ModelMessage[];\n }):\n | { mode: 'prompt'; prompt: HarnessAgentPrompt }\n | {\n mode: 'continue';\n toolApprovalContinuations: readonly HarnessAgentToolApprovalContinuation[];\n } {\n if (typeof options.prompt === 'string') {\n return { mode: 'prompt', prompt: options.prompt };\n }\n const messages = Array.isArray(options.prompt)\n ? options.prompt\n : options.messages;\n if (Array.isArray(messages)) {\n const toolApprovalContinuations =\n collectHarnessAgentToolApprovalContinuations({ messages });\n if (toolApprovalContinuations.length > 0) {\n return {\n mode: 'continue',\n toolApprovalContinuations,\n };\n }\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (message?.role === 'user')\n return { mode: 'prompt', prompt: message };\n }\n throw new Error(\n 'HarnessAgent: messages must contain at least one `role: \"user\"` entry.',\n );\n }\n throw new Error('HarnessAgent: either `prompt` or `messages` is required.');\n }\n\n /*\n * Wire-format projection of user-defined tools only. Harness builtins are\n * executed by the runtime and the bridge already knows about them — we\n * never re-declare them over the wire.\n */\n private _toToolSpecs(): HarnessAgentToolSpec[] {\n const specs: HarnessAgentToolSpec[] = [];\n for (const [name, tool] of Object.entries(\n this.activeUserTools as Record<string, unknown>,\n )) {\n const t = tool as {\n description?: string;\n inputSchema?: unknown;\n };\n let inputSchema: HarnessAgentToolSpec['inputSchema'];\n if (t.inputSchema != null) {\n try {\n inputSchema = asSchema(\n t.inputSchema as Parameters<typeof asSchema>[0],\n ).jsonSchema as HarnessAgentToolSpec['inputSchema'];\n } catch {\n // tools without a usable schema are still forwarded by name\n }\n }\n specs.push({ name, description: t.description, inputSchema });\n }\n return specs;\n }\n\n private async _toGenerateResult(\n streamResult: StreamTextResult<\n HarnessAllTools<THarness, TUserTools>,\n RUNTIME_CONTEXT,\n never\n >,\n ): Promise<\n GenerateTextResult<\n HarnessAllTools<THarness, TUserTools>,\n RUNTIME_CONTEXT,\n never\n >\n > {\n // The stream is already drained by the time generate() calls this helper\n // (done has resolved). `steps` is the single source of truth the result\n // derives everything else from, mirroring core's `generateText` result.\n const [steps, usage, responseMessages] = await Promise.all([\n streamResult.steps,\n streamResult.usage,\n streamResult.responseMessages,\n ]);\n\n return new HarnessGenerateTextResult<\n HarnessAllTools<THarness, TUserTools>,\n RUNTIME_CONTEXT\n >({ steps, usage, responseMessages });\n }\n}\n\n/*\n * `GenerateTextResult` view over a drained `streamText` run. Non-deprecated\n * members derive from `steps` (the single source of truth), and the deprecated\n * members are exposed as getters that delegate to `finalStep` / `usage`.\n * Implementing the deprecated members as getters — rather than assigning them\n * in an object literal — keeps construction free of deprecated-property usage,\n * matching how core's `generateText` builds its result.\n */\nclass HarnessGenerateTextResult<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context,\n> implements GenerateTextResult<TOOLS, RUNTIME_CONTEXT, never> {\n readonly steps: GenerateTextResult<TOOLS, RUNTIME_CONTEXT, never>['steps'];\n readonly usage: GenerateTextResult<TOOLS, RUNTIME_CONTEXT, never>['usage'];\n readonly responseMessages: GenerateTextResult<\n TOOLS,\n RUNTIME_CONTEXT,\n never\n >['responseMessages'];\n readonly output = undefined as never;\n\n constructor(options: {\n steps: GenerateTextResult<TOOLS, RUNTIME_CONTEXT, never>['steps'];\n usage: GenerateTextResult<TOOLS, RUNTIME_CONTEXT, never>['usage'];\n responseMessages: GenerateTextResult<\n TOOLS,\n RUNTIME_CONTEXT,\n never\n >['responseMessages'];\n }) {\n this.steps = options.steps;\n this.usage = options.usage;\n this.responseMessages = options.responseMessages;\n }\n\n get finalStep() {\n return this.steps.at(-1)!;\n }\n\n get content() {\n return this.steps.flatMap(step => step.content);\n }\n\n get text() {\n return this.finalStep.text;\n }\n\n get files() {\n return this.steps.flatMap(step => step.files);\n }\n\n get sources() {\n return this.steps.flatMap(step => step.sources);\n }\n\n get toolCalls() {\n return this.steps.flatMap(step => step.toolCalls);\n }\n\n get staticToolCalls() {\n return this.steps.flatMap(step => step.staticToolCalls);\n }\n\n get dynamicToolCalls() {\n return this.steps.flatMap(step => step.dynamicToolCalls);\n }\n\n get toolResults() {\n return this.steps.flatMap(step => step.toolResults);\n }\n\n get staticToolResults() {\n return this.steps.flatMap(step => step.staticToolResults);\n }\n\n get dynamicToolResults() {\n return this.steps.flatMap(step => step.dynamicToolResults);\n }\n\n get finishReason() {\n return this.finalStep.finishReason;\n }\n\n get rawFinishReason() {\n return this.finalStep.rawFinishReason;\n }\n\n get warnings() {\n return this.steps.flatMap(step => step.warnings ?? []);\n }\n\n get reasoning() {\n return this.finalStep.content.filter(\n (part): part is ReasoningOutput | ReasoningFileOutput =>\n part.type === 'reasoning' || part.type === 'reasoning-file',\n );\n }\n\n get reasoningText() {\n return this.finalStep.reasoningText;\n }\n\n get totalUsage() {\n return this.usage;\n }\n\n get request() {\n return this.finalStep.request;\n }\n\n get response() {\n return this.finalStep.response;\n }\n\n get providerMetadata() {\n return this.finalStep.providerMetadata;\n }\n}\n\nfunction resolveSandboxConfig(\n settings: Pick<HarnessAgentSettings, 'sandboxConfig' | 'onSandboxSession'>,\n): HarnessAgentSandboxConfig {\n if (settings.onSandboxSession != null) {\n console.warn(\n 'HarnessAgent: `onSandboxSession` is deprecated. Use `sandboxConfig.onSession` instead.',\n );\n }\n\n return {\n ...settings.sandboxConfig,\n ...(settings.sandboxConfig?.onSession == null &&\n settings.onSandboxSession != null\n ? { onSession: settings.onSandboxSession }\n : {}),\n };\n}\n\n/*\n * Bridge-port leasing helper. Returns the port-narrowed network sandbox session\n * plus the leased port (or `undefined` when the provider has no port pool). Kept here\n * rather than on the session so the lease is established as part of session\n * start — the session only needs to release it on close/detach.\n */\nfunction applyPortLease(input: {\n provider: HarnessV1SandboxProvider;\n sandboxSession: HarnessV1NetworkSandboxSession;\n sessionId: string;\n}): {\n sandboxSession: HarnessV1NetworkSandboxSession;\n port: number | undefined;\n} {\n const pool = input.provider.bridgePorts;\n if (pool == null || pool.length === 0) {\n return { sandboxSession: input.sandboxSession, port: undefined };\n }\n const port = acquireBridgePort({\n poolKey: input.provider,\n pool,\n sessionId: input.sessionId,\n });\n return {\n sandboxSession: narrowNetworkSessionPorts(input.sandboxSession, port),\n port,\n };\n}\n\n/*\n * Derive a view of the network sandbox session that reports only the leased\n * port. Implemented as a prototype-delegating overlay so every other member\n * (file I/O, exec, spawn, lifecycle, `restricted`) forwards to the same live\n * instance — only `ports` is shadowed.\n */\nfunction narrowNetworkSessionPorts(\n sandboxSession: HarnessV1NetworkSandboxSession,\n leasedPort: number,\n): HarnessV1NetworkSandboxSession {\n return Object.create(sandboxSession, {\n ports: {\n value: [leasedPort] as ReadonlyArray<number>,\n enumerable: true,\n },\n }) as HarnessV1NetworkSandboxSession;\n}\n\nasync function cleanupAfterStartFailure(input: {\n sandboxProvider: HarnessV1SandboxProvider;\n sandboxSession: HarnessV1NetworkSandboxSession;\n sessionId: string;\n leasedBridgePort: number | undefined;\n}): Promise<void> {\n await Promise.resolve(input.sandboxSession.stop()).catch(() => {});\n if (input.leasedBridgePort != null) {\n releaseBridgePort({\n poolKey: input.sandboxProvider,\n sessionId: input.sessionId,\n });\n }\n}\n","/**\n * Process-wide registry for bridge-port leases. Used when a sandbox provider\n * wraps a caller-provided sandbox with a pre-declared port pool — each\n * concurrent harness session leases one port from the pool, releases on\n * session stop or destroy. Multiple sessions on the same provider instance\n * share the same pool; different provider instances (even wrapping the same\n * underlying sandbox) get independent registries.\n *\n * Sized to the typical case: one provider object passed to N HarnessAgents.\n * Callers that need cross-process coordination must layer that on top.\n */\n\ntype RegistryEntry = {\n readonly pool: ReadonlyArray<number>;\n readonly leases: Map<string, number>;\n};\n\nconst registries = new WeakMap<object, RegistryEntry>();\n\nexport function acquireBridgePort(options: {\n poolKey: object;\n pool: ReadonlyArray<number>;\n sessionId: string;\n}): number {\n let entry = registries.get(options.poolKey);\n if (entry == null) {\n entry = { pool: options.pool, leases: new Map() };\n registries.set(options.poolKey, entry);\n }\n const existing = entry.leases.get(options.sessionId);\n if (existing != null) return existing;\n\n const leased = new Set(entry.leases.values());\n for (const port of entry.pool) {\n if (!leased.has(port)) {\n entry.leases.set(options.sessionId, port);\n return port;\n }\n }\n throw new Error(\n `No available bridge port — pool of ${entry.pool.length} ports is fully leased.`,\n );\n}\n\nexport function releaseBridgePort(options: {\n poolKey: object;\n sessionId: string;\n}): void {\n const entry = registries.get(options.poolKey);\n if (entry == null) return;\n entry.leases.delete(options.sessionId);\n}\n","import { safeValidateTypes } from '@ai-sdk/provider-utils';\nimport { HarnessError } from '../../errors/harness-error';\nimport type { HarnessV1, HarnessV1LifecycleState } from '../../v1';\n\n/**\n * Validate a lifecycle state against the harness's contract:\n * - `type` must match the lifecycle method that will consume it.\n * - `specificationVersion` must be `'harness-v1'`.\n * - `harnessId` must match the harness producing/consuming the payload.\n * - When the harness declares a `lifecycleStateSchema`, `data` is parsed\n * against it.\n *\n * Returns the payload with `data` replaced by the parsed value when a\n * schema is present, so callers downstream see a canonical shape.\n */\nexport async function validateLifecycleStateData<\n STATE extends HarnessV1LifecycleState,\n>(input: {\n harness: HarnessV1;\n state: STATE;\n expectedType: STATE['type'];\n}): Promise<STATE> {\n const { harness, state } = input;\n if (state.type !== input.expectedType) {\n throw new HarnessError({\n message: `Lifecycle state has unexpected type '${state.type}'; expected '${input.expectedType}'.`,\n });\n }\n if (state.specificationVersion !== 'harness-v1') {\n throw new HarnessError({\n message: `Lifecycle state has unexpected specificationVersion '${state.specificationVersion}'; expected 'harness-v1'.`,\n });\n }\n if (state.harnessId !== harness.harnessId) {\n throw new HarnessError({\n message: `Lifecycle state was produced by harness '${state.harnessId}' but this agent uses '${harness.harnessId}'.`,\n });\n }\n if (\n state.type === 'resume-session' &&\n 'pendingToolApprovals' in state &&\n state.pendingToolApprovals !== undefined\n ) {\n throw new HarnessError({\n message:\n 'Resume session state cannot contain pending tool approvals; unfinished turns must be stored as `continueFrom`.',\n });\n }\n\n const data =\n harness.lifecycleStateSchema == null\n ? state.data\n : await (async () => {\n const result = await safeValidateTypes({\n value: state.data,\n schema: harness.lifecycleStateSchema!,\n });\n if (!result.success) {\n throw new HarnessError({\n message: `Lifecycle state failed schema validation for harness '${harness.harnessId}': ${result.error.message}`,\n cause: result.error,\n });\n }\n return result.value as STATE['data'];\n })();\n\n if (state.type === 'resume-session') {\n const continueFrom =\n state.continueFrom == null\n ? undefined\n : await validateLifecycleStateData({\n harness,\n state: state.continueFrom,\n expectedType: 'continue-turn',\n });\n\n return {\n type: state.type,\n harnessId: state.harnessId,\n specificationVersion: state.specificationVersion,\n data,\n ...(continueFrom !== undefined ? { continueFrom } : {}),\n } as STATE;\n }\n\n return {\n type: state.type,\n harnessId: state.harnessId,\n specificationVersion: state.specificationVersion,\n data,\n ...(state.pendingToolApprovals !== undefined\n ? { pendingToolApprovals: state.pendingToolApprovals }\n : {}),\n } as STATE;\n}\n","export type HarnessV1BuiltinToolFiltering =\n | {\n mode: 'allow';\n toolNames: string[];\n }\n | {\n mode: 'deny';\n toolNames: string[];\n };\n\nexport function isHarnessV1BuiltinToolIncluded(input: {\n toolName: string;\n toolFiltering: HarnessV1BuiltinToolFiltering | undefined;\n}): boolean {\n if (input.toolFiltering == null) return true;\n return input.toolFiltering.mode === 'allow'\n ? input.toolFiltering.toolNames.includes(input.toolName)\n : !input.toolFiltering.toolNames.includes(input.toolName);\n}\n\nexport function getHarnessV1BuiltinToolFilteringDenialReason(input: {\n toolName: string;\n}): string {\n return `Tool '${input.toolName}' is inactive due to the HarnessAgent tool filtering policy.`;\n}\n","import type { HarnessV1PromptControl } from '../../v1/harness-v1-prompt-control';\nimport type { HarnessV1StreamPart } from '../../v1/harness-v1-stream-part';\n\n/**\n * Bridge an adapter's emit-based event surface into a pull-based\n * `ReadableStream<HarnessV1StreamPart>`.\n *\n * Adapters implement `doPromptTurn` / `doContinueTurn` against an `emit` callback\n * because that is the natural shape when wrapping an SDK that itself produces\n * events. Consumers (notably `HarnessAgent`) prefer a stream because that is\n * the idiomatic AI SDK shape. This helper converts the former into the latter\n * and is agnostic to which turn entry point produced the control surface — the\n * caller supplies an `invoke` thunk that wires `emit` into either method.\n *\n * Lifetime:\n * 1. Calls `invoke(emit)` immediately (which runs `doPromptTurn`/`doContinueTurn`).\n * 2. Every `emit(part)` becomes a stream chunk.\n * 3. When `control.done` resolves, the stream closes — this includes a\n * graceful `doSuspendTurn`, which resolves `done` cleanly after draining.\n * 4. When `control.done` rejects, an `{ type: 'error', error }` part is\n * enqueued and the stream is then closed normally. The rejection is\n * surfaced to consumers as a discriminated-union event rather than as\n * a stream error so iteration code does not need a separate try/catch\n * around the consumer loop.\n * 5. The supplied `abortSignal` (if any) aborts the underlying turn and\n * closes the stream.\n *\n * The returned `control` is the same object the adapter produced and is\n * intended for use by the consumer to submit tool results / approvals /\n * user messages back into the in-flight turn.\n */\nexport async function toHarnessStream(options: {\n invoke: (\n emit: (event: HarnessV1StreamPart) => void,\n ) => PromiseLike<HarnessV1PromptControl>;\n}): Promise<{\n stream: ReadableStream<HarnessV1StreamPart>;\n control: HarnessV1PromptControl;\n}> {\n let controller!: ReadableStreamDefaultController<HarnessV1StreamPart>;\n let closed = false;\n\n const stream = new ReadableStream<HarnessV1StreamPart>({\n start(c) {\n controller = c;\n },\n });\n\n const safeEnqueue = (part: HarnessV1StreamPart) => {\n if (closed) return;\n controller.enqueue(part);\n };\n\n const safeClose = () => {\n if (closed) return;\n closed = true;\n controller.close();\n };\n\n const control = await options.invoke(safeEnqueue);\n\n Promise.resolve(control.done)\n .then(\n () => safeClose(),\n (err: unknown) => {\n safeEnqueue({ type: 'error', error: err });\n safeClose();\n },\n )\n // Belt-and-suspenders: any throw inside the handlers themselves should\n // not become an unhandled rejection.\n .catch(() => {});\n\n return { stream, control };\n}\n","import {\n getHarnessV1BuiltinToolFilteringDenialReason,\n isHarnessV1BuiltinToolIncluded,\n type HarnessV1,\n type HarnessV1BuiltinToolFiltering,\n type HarnessV1PendingToolApproval,\n type HarnessV1Prompt,\n type HarnessV1PromptControl,\n type HarnessV1Session,\n type HarnessV1StreamPart,\n type HarnessV1ToolSpec,\n} from '../../v1';\nimport { toHarnessStream } from './to-harness-stream';\nimport {\n executeTool,\n generateId,\n isExecutableTool,\n safeParseJSON,\n type Context,\n type Experimental_SandboxSession as SandboxSession,\n type ToolSet,\n} from '@ai-sdk/provider-utils';\nimport type {\n LanguageModelV4FinishReason,\n LanguageModelV4ToolCall,\n LanguageModelV4Usage,\n} from '@ai-sdk/provider';\nimport { parseToolCall } from 'ai/internal';\nimport type { ContentPart, TelemetryOptions, TextStreamPart } from 'ai';\nimport type { HarnessAgentToolApprovalContinuation } from '../harness-agent-tool-approval-continuation';\nimport type { HarnessAgentToolApprovalConfiguration } from '../harness-agent-settings';\nimport { HarnessStreamTextResult } from './harness-stream-text-result';\nimport { translateStreamPart } from './translate-stream-part';\nimport { stripWorkDir } from './strip-work-dir';\nimport { createTurnTelemetry, type TurnContentPart } from './turn-telemetry';\nimport { resolveCustomToolApproval } from './permission-mode';\n\n/**\n * Drive one prompt turn end-to-end:\n * - call `session.doPromptTurn` via `toHarnessStream`\n * - translate harness events to AI SDK `TextStreamPart`s and push into the\n * result object\n * - execute host-side user tools when their `tool-call` events arrive and\n * submit results back to the harness\n * - close the result when the harness signals `finish` (or on error)\n *\n * Returns the result synchronously after the stream is wired up; callers\n * await its `PromiseLike` accessors to observe completion.\n */\nexport function runPrompt<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context,\n>(input: {\n harness: HarnessV1;\n session: HarnessV1Session;\n /**\n * Turn entry point. `'prompt'` (default) starts a new turn from `prompt`;\n * `'continue'` continues the in-flight turn via `doContinueTurn` and ignores\n * `prompt`/`instructions`.\n */\n mode?: 'prompt' | 'continue';\n /** Required for `mode: 'prompt'`; absent for `mode: 'continue'`. */\n prompt?: HarnessV1Prompt;\n instructions: string | undefined;\n tools: TOOLS;\n activeTools?: ToolSet;\n toolSpecs: HarnessV1ToolSpec[];\n builtinToolFiltering?: HarnessV1BuiltinToolFiltering | undefined;\n sandboxSession: SandboxSession;\n sessionWorkDir: string;\n runtimeContext: RUNTIME_CONTEXT;\n abortSignal: AbortSignal | undefined;\n telemetry?: TelemetryOptions | undefined;\n toolApproval?: HarnessAgentToolApprovalConfiguration | undefined;\n pendingToolApprovals?: readonly HarnessV1PendingToolApproval[];\n toolApprovalContinuations?:\n | readonly HarnessAgentToolApprovalContinuation[]\n | undefined;\n onPendingToolApproval?: (approval: HarnessV1PendingToolApproval) => void;\n onToolApprovalSettled?: (approvalId: string) => void;\n onTurnFinished?: () => void;\n}): {\n result: HarnessStreamTextResult<TOOLS, RUNTIME_CONTEXT>;\n done: Promise<void>;\n} {\n const result = new HarnessStreamTextResult<TOOLS, RUNTIME_CONTEXT>({\n tools: input.tools,\n runtimeContext: input.runtimeContext,\n // toolsContext is not configurable for harnesses; pass undefined cast.\n toolsContext: undefined as never,\n harnessId: input.harness.harnessId,\n sessionId: input.session.sessionId,\n });\n const pendingToolApprovals = input.pendingToolApprovals ?? [];\n const onPendingToolApproval = input.onPendingToolApproval ?? (() => {});\n const onToolApprovalSettled = input.onToolApprovalSettled ?? (() => {});\n const activeTools = input.activeTools ?? input.tools;\n\n const telemetry = createTurnTelemetry({\n telemetry: input.telemetry,\n harnessId: input.harness.harnessId,\n modelId: input.session.modelId,\n instructions: input.instructions,\n promptText: input.prompt != null ? promptToText(input.prompt) : '',\n runtimeContext: input.runtimeContext,\n });\n\n const done = (async () => {\n let bridge: Awaited<ReturnType<typeof toHarnessStream>>;\n try {\n bridge = await toHarnessStream({\n invoke:\n input.mode === 'continue'\n ? emit =>\n input.session.doContinueTurn({\n tools: input.toolSpecs,\n abortSignal: input.abortSignal,\n emit,\n })\n : emit => {\n if (input.prompt == null) {\n throw new Error(\n 'runPrompt: `prompt` is required for mode \"prompt\".',\n );\n }\n return input.session.doPromptTurn({\n prompt: input.prompt,\n tools: input.toolSpecs,\n instructions: input.instructions,\n abortSignal: input.abortSignal,\n emit,\n });\n },\n });\n } catch (err) {\n telemetry.error(err);\n result.fail(err);\n return;\n }\n\n const { stream, control } = bridge;\n const reader = stream.getReader();\n const toolCallsByToolCallId = new Map<string, ToolCallTextStreamPart>();\n const rawToolCallsByToolCallId = new Map<\n string,\n Extract<HarnessV1StreamPart, { type: 'tool-call' }>\n >();\n const pendingApprovalsByApprovalId = new Map(\n pendingToolApprovals.map(approval => [approval.approvalId, approval]),\n );\n const pendingApprovalsByToolCallId = new Map(\n pendingToolApprovals.map(approval => [approval.toolCallId, approval]),\n );\n const continuationsByApprovalId = new Map(\n (input.toolApprovalContinuations ?? []).map(continuation => [\n continuation.approvalResponse.approvalId,\n continuation,\n ]),\n );\n const settledApprovalToolCallIds = new Set<string>();\n let finalFinish:\n | Extract<HarnessV1StreamPart, { type: 'finish' }>\n | undefined;\n\n // Accumulate the model's output content per step so telemetry can record\n // `gen_ai.output.messages` and reporters can log what was actually said.\n let stepText = '';\n let stepReasoning = '';\n let stepToolCalls: TurnContentPart[] = [];\n const buildStepContent = (): TurnContentPart[] => {\n const parts: TurnContentPart[] = [];\n if (stepText) parts.push({ type: 'text', text: stepText });\n if (stepReasoning) parts.push({ type: 'reasoning', text: stepReasoning });\n parts.push(...stepToolCalls);\n return parts;\n };\n const resetStepContent = (): void => {\n stepText = '';\n stepReasoning = '';\n stepToolCalls = [];\n };\n const zeroUsage: LanguageModelV4Usage = {\n inputTokens: {\n total: undefined,\n noCache: undefined,\n cacheRead: undefined,\n cacheWrite: undefined,\n },\n outputTokens: {\n total: undefined,\n text: undefined,\n reasoning: undefined,\n },\n };\n const toolCallsFinishReason: LanguageModelV4FinishReason = {\n unified: 'tool-calls',\n raw: undefined,\n };\n const finishForToolApprovalPause = async (): Promise<void> => {\n telemetry.stepFinish({\n finishReason: toolCallsFinishReason,\n usage: zeroUsage,\n content: buildStepContent(),\n });\n resetStepContent();\n result.finishStep({\n finishReason: toolCallsFinishReason,\n usage: zeroUsage,\n providerMetadata: undefined,\n warnings: [],\n });\n telemetry.end({\n finishReason: toolCallsFinishReason,\n usage: zeroUsage,\n });\n await result.finish();\n };\n const enqueueApprovalRequest = (approval: {\n approvalId: string;\n toolCall: ToolCallTextStreamPart;\n isAutomatic?: boolean;\n }): void => {\n result.enqueue({\n type: 'tool-approval-request',\n approvalId: approval.approvalId,\n toolCall: approval.toolCall,\n ...(approval.isAutomatic !== undefined\n ? { isAutomatic: approval.isAutomatic }\n : {}),\n } as TextStreamPart<TOOLS>);\n };\n const enqueueAutomaticApprovalResponse = (input: {\n approvalId: string;\n toolCall: ToolCallTextStreamPart;\n approved: boolean;\n reason?: string;\n providerExecuted?: boolean;\n }): void => {\n result.enqueue({\n type: 'tool-approval-response',\n approvalId: input.approvalId,\n toolCall: input.toolCall,\n approved: input.approved,\n ...(input.reason !== undefined ? { reason: input.reason } : {}),\n ...(input.providerExecuted !== undefined\n ? { providerExecuted: input.providerExecuted }\n : {}),\n } as TextStreamPart<TOOLS>);\n };\n const enqueueApprovalResponse = (\n approval: HarnessV1PendingToolApproval,\n continuation: HarnessAgentToolApprovalContinuation,\n ): void => {\n result.enqueue({\n type: 'tool-approval-response',\n approvalId: approval.approvalId,\n toolCall: continuation.toolCall,\n approved: continuation.approvalResponse.approved,\n ...(continuation.approvalResponse.reason !== undefined\n ? { reason: continuation.approvalResponse.reason }\n : {}),\n ...(approval.providerExecuted !== undefined\n ? { providerExecuted: approval.providerExecuted }\n : {}),\n } as TextStreamPart<TOOLS>);\n };\n const processPendingApprovalContinuation = async (\n approval: HarnessV1PendingToolApproval,\n continuation: HarnessAgentToolApprovalContinuation,\n ): Promise<void> => {\n enqueueApprovalResponse(approval, continuation);\n onToolApprovalSettled(approval.approvalId);\n pendingApprovalsByApprovalId.delete(approval.approvalId);\n pendingApprovalsByToolCallId.delete(approval.toolCallId);\n settledApprovalToolCallIds.add(approval.toolCallId);\n\n if (approval.kind === 'builtin') {\n if (control.submitToolApproval == null) {\n throw new Error(\n `Harness '${input.harness.harnessId}' emitted a built-in tool approval request but does not support approval responses.`,\n );\n }\n await control.submitToolApproval({\n approvalId: approval.approvalId,\n approved: continuation.approvalResponse.approved,\n reason: continuation.approvalResponse.reason,\n });\n return;\n }\n\n if (!continuation.approvalResponse.approved) {\n await control.submitToolResult({\n toolCallId: approval.toolCallId,\n output: {\n type: 'execution-denied',\n reason: continuation.approvalResponse.reason,\n },\n });\n return;\n }\n\n const rawToolCall =\n rawToolCallsByToolCallId.get(approval.toolCallId) ??\n ({\n type: 'tool-call',\n toolCallId: approval.toolCallId,\n toolName: approval.toolName,\n input: approval.input,\n } satisfies Extract<HarnessV1StreamPart, { type: 'tool-call' }>);\n\n const outcome = await maybeExecuteHostTool({\n event: rawToolCall,\n tools: activeTools,\n sandboxSession: input.sandboxSession,\n abortSignal: input.abortSignal,\n control,\n onPreliminaryResult: preliminaryOutput => {\n const stripped = stripWorkDir(\n {\n type: 'tool-result',\n toolCallId: rawToolCall.toolCallId,\n toolName: rawToolCall.toolName,\n result: preliminaryOutput as Extract<\n HarnessV1StreamPart,\n { type: 'tool-result' }\n >['result'],\n },\n input.sessionWorkDir,\n ) as Extract<HarnessV1StreamPart, { type: 'tool-result' }>;\n result.enqueue({\n type: 'tool-result',\n toolCallId: rawToolCall.toolCallId,\n toolName: rawToolCall.toolName,\n input: undefined,\n output: stripped.result,\n preliminary: true,\n } as TextStreamPart<TOOLS>);\n },\n });\n telemetry.toolEnd(rawToolCall.toolCallId, outcome);\n };\n\n try {\n for (const approval of pendingToolApprovals) {\n const continuation = continuationsByApprovalId.get(approval.approvalId);\n if (continuation != null) {\n await processPendingApprovalContinuation(approval, continuation);\n }\n }\n\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n if (value == null) continue;\n\n // Begin the operation span on stream-start, using the runtime-resolved\n // model the adapter reports (falling back to the session's model).\n if (value.type === 'stream-start') {\n telemetry.start(value.modelId ?? input.session.modelId);\n }\n\n // Open a step span lazily before the first content of each step.\n if (\n value.type !== 'stream-start' &&\n value.type !== 'finish-step' &&\n value.type !== 'finish' &&\n value.type !== 'error'\n ) {\n telemetry.ensureStepOpen();\n }\n\n /*\n * Strip the session working-directory prefix for everything the\n * consumer sees. The original `value` is kept intact for host tool\n * execution below — the tools need the absolute path to resolve\n * against the sandbox root, so the strip is display-only.\n */\n const displayValue = stripWorkDir(value, input.sessionWorkDir);\n const settledApprovalToolCallReplay =\n displayValue.type === 'tool-call' &&\n !displayValue.providerExecuted &&\n settledApprovalToolCallIds.has(displayValue.toolCallId);\n\n if (settledApprovalToolCallReplay) {\n continue;\n }\n\n if (displayValue.type === 'tool-approval-request') {\n const toolCall = toolCallsByToolCallId.get(displayValue.toolCallId);\n if (toolCall == null) {\n throw new Error(\n `Harness '${input.harness.harnessId}' emitted approval request '${displayValue.approvalId}' for unknown tool call '${displayValue.toolCallId}'.`,\n );\n }\n const rawToolCall = rawToolCallsByToolCallId.get(\n displayValue.toolCallId,\n );\n const toolName = rawToolCall?.toolName ?? toolCall.toolName;\n if (\n !isHarnessV1BuiltinToolIncluded({\n toolName,\n toolFiltering: input.builtinToolFiltering,\n })\n ) {\n if (control.submitToolApproval == null) {\n throw new Error(\n `Harness '${input.harness.harnessId}' emitted a built-in tool approval request but does not support approval responses.`,\n );\n }\n await control.submitToolApproval({\n approvalId: displayValue.approvalId,\n approved: false,\n reason: getHarnessV1BuiltinToolFilteringDenialReason({\n toolName,\n }),\n });\n continue;\n }\n }\n\n // Forward to consumer as soon as possible.\n for (const part of translateStreamPart<TOOLS>(displayValue)) {\n result.enqueue(part);\n }\n\n // Tool-call validation lives here (not in translateStreamPart) because\n // schema parsing is async and needs the merged tool set in scope.\n if (displayValue.type === 'tool-call') {\n const parsed = await validateToolCall<TOOLS>({\n event: displayValue,\n tools: input.tools,\n });\n const parsedToolCall = asToolCallTextStreamPart({ part: parsed });\n rawToolCallsByToolCallId.set(displayValue.toolCallId, displayValue);\n toolCallsByToolCallId.set(displayValue.toolCallId, parsedToolCall);\n result.enqueue(parsed);\n }\n\n // Accumulate output content for telemetry / reporters.\n if (value.type === 'text-delta') {\n stepText += value.delta;\n } else if (value.type === 'reasoning-delta') {\n stepReasoning += value.delta;\n }\n\n // Telemetry: a tool execution begins on its `tool-call`.\n if (value.type === 'tool-call') {\n stepToolCalls.push({\n type: 'tool-call',\n toolCallId: value.toolCallId,\n toolName: value.toolName,\n input: value.input,\n });\n telemetry.toolStart({\n toolCallId: value.toolCallId,\n toolName: value.toolName,\n input: value.input,\n });\n }\n\n // Telemetry: close a tool span when its provider-executed result lands.\n if (value.type === 'tool-result') {\n telemetry.toolEnd(\n value.toolCallId,\n value.isError\n ? { ok: false, error: value.result }\n : { ok: true, output: value.result },\n );\n }\n\n if (value.type === 'tool-approval-request') {\n const toolCall = toolCallsByToolCallId.get(value.toolCallId);\n if (toolCall == null) {\n throw new Error(\n `Harness '${input.harness.harnessId}' emitted approval request '${value.approvalId}' for unknown tool call '${value.toolCallId}'.`,\n );\n }\n\n const rawToolCall = rawToolCallsByToolCallId.get(value.toolCallId);\n const pendingApproval =\n pendingApprovalsByApprovalId.get(value.approvalId) ??\n ({\n approvalId: value.approvalId,\n toolCallId: value.toolCallId,\n toolName: toolCall.toolName,\n input: rawToolCall?.input ?? JSON.stringify(toolCall.input),\n kind: 'builtin',\n providerExecuted: rawToolCall?.providerExecuted ?? true,\n ...(rawToolCall?.nativeName !== undefined\n ? { nativeName: rawToolCall.nativeName }\n : {}),\n } satisfies HarnessV1PendingToolApproval);\n pendingApprovalsByApprovalId.set(\n pendingApproval.approvalId,\n pendingApproval,\n );\n pendingApprovalsByToolCallId.set(\n pendingApproval.toolCallId,\n pendingApproval,\n );\n\n const continuation = continuationsByApprovalId.get(\n pendingApproval.approvalId,\n );\n if (continuation != null) {\n await processPendingApprovalContinuation(\n pendingApproval,\n continuation,\n );\n continue;\n }\n\n onPendingToolApproval(pendingApproval);\n enqueueApprovalRequest({\n approvalId: pendingApproval.approvalId,\n toolCall,\n });\n await finishForToolApprovalPause();\n return;\n }\n\n // Drive step boundaries.\n if (value.type === 'finish-step') {\n telemetry.stepFinish({\n finishReason: value.finishReason,\n usage: value.usage,\n providerMetadata: value.harnessMetadata,\n content: buildStepContent(),\n });\n resetStepContent();\n result.finishStep({\n finishReason: value.finishReason,\n usage: value.usage,\n providerMetadata: value.harnessMetadata,\n warnings: [],\n });\n }\n\n if (value.type === 'finish') {\n finalFinish = value;\n telemetry.end({\n finishReason: value.finishReason,\n usage: value.totalUsage,\n });\n }\n\n // Execute host-side tools when the harness asks for one.\n if (value.type === 'tool-call' && !value.providerExecuted) {\n const toolCall = value;\n const parsedToolCall = toolCallsByToolCallId.get(toolCall.toolCallId);\n if (parsedToolCall == null) {\n throw new Error(\n `Harness '${input.harness.harnessId}' could not find parsed tool call '${toolCall.toolCallId}' for custom tool approval.`,\n );\n }\n if (!hasTool({ tools: activeTools, toolName: toolCall.toolName })) {\n const output = {\n type: 'execution-denied',\n reason: getHarnessV1BuiltinToolFilteringDenialReason({\n toolName: toolCall.toolName,\n }),\n };\n await control.submitToolResult({\n toolCallId: toolCall.toolCallId,\n output,\n });\n telemetry.toolEnd(toolCall.toolCallId, { ok: true, output });\n continue;\n }\n const customToolApprovalDecision = resolveCustomToolApproval({\n toolName: toolCall.toolName,\n toolApproval: input.toolApproval,\n });\n if (customToolApprovalDecision.type === 'deny') {\n const approvalId = generateId();\n enqueueApprovalRequest({\n approvalId,\n toolCall: parsedToolCall,\n isAutomatic: true,\n });\n enqueueAutomaticApprovalResponse({\n approvalId,\n toolCall: parsedToolCall,\n approved: false,\n reason: customToolApprovalDecision.reason,\n providerExecuted: false,\n });\n const output = {\n type: 'execution-denied',\n reason: customToolApprovalDecision.reason,\n };\n await control.submitToolResult({\n toolCallId: toolCall.toolCallId,\n output,\n });\n telemetry.toolEnd(toolCall.toolCallId, { ok: true, output });\n continue;\n }\n const pendingApproval =\n pendingApprovalsByToolCallId.get(toolCall.toolCallId) ??\n (customToolApprovalDecision.type === 'request'\n ? ({\n approvalId: generateId(),\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input: toolCall.input,\n kind: 'custom',\n providerExecuted: false,\n ...(toolCall.nativeName !== undefined\n ? { nativeName: toolCall.nativeName }\n : {}),\n } satisfies HarnessV1PendingToolApproval)\n : undefined);\n if (pendingApproval != null) {\n pendingApprovalsByApprovalId.set(\n pendingApproval.approvalId,\n pendingApproval,\n );\n pendingApprovalsByToolCallId.set(\n pendingApproval.toolCallId,\n pendingApproval,\n );\n const continuation = continuationsByApprovalId.get(\n pendingApproval.approvalId,\n );\n if (continuation != null) {\n await processPendingApprovalContinuation(\n pendingApproval,\n continuation,\n );\n continue;\n }\n const pendingParsedToolCall = toolCallsByToolCallId.get(\n pendingApproval.toolCallId,\n );\n if (pendingParsedToolCall == null) {\n throw new Error(\n `Harness '${input.harness.harnessId}' could not find parsed tool call '${pendingApproval.toolCallId}' for approval request '${pendingApproval.approvalId}'.`,\n );\n }\n onPendingToolApproval(pendingApproval);\n enqueueApprovalRequest({\n approvalId: pendingApproval.approvalId,\n toolCall: pendingParsedToolCall,\n });\n await finishForToolApprovalPause();\n return;\n }\n const outcome = await maybeExecuteHostTool({\n event: toolCall,\n tools: activeTools,\n sandboxSession: input.sandboxSession,\n abortSignal: input.abortSignal,\n control,\n onPreliminaryResult: preliminaryOutput => {\n /*\n * Project a `yield`ed value as a preliminary AI SDK\n * `tool-result` part. Unlike the final result — which is\n * submitted to the runtime, echoed back as a `tool-result`\n * event, and stripped on its way through the loop above —\n * preliminary values never reach the runtime, so strip the\n * working directory here to match the final result's projection.\n */\n const stripped = stripWorkDir(\n {\n type: 'tool-result',\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n result: preliminaryOutput as Extract<\n HarnessV1StreamPart,\n { type: 'tool-result' }\n >['result'],\n },\n input.sessionWorkDir,\n ) as Extract<HarnessV1StreamPart, { type: 'tool-result' }>;\n result.enqueue({\n type: 'tool-result',\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input: undefined,\n output: stripped.result,\n preliminary: true,\n } as TextStreamPart<TOOLS>);\n },\n });\n telemetry.toolEnd(toolCall.toolCallId, outcome);\n }\n\n if (value.type === 'error') {\n telemetry.error(value.error);\n result.fail(value.error);\n return;\n }\n }\n input.onTurnFinished?.();\n await result.finish(\n finalFinish\n ? {\n finishReason: finalFinish.finishReason,\n totalUsage: finalFinish.totalUsage,\n providerMetadata: finalFinish.harnessMetadata,\n }\n : undefined,\n );\n } catch (err) {\n telemetry.error(err);\n result.fail(err);\n } finally {\n reader.releaseLock();\n }\n })();\n\n // Swallow the loop's rejection at the top level — failures are observable\n // via the result's `fullStream` `error` part and rejected promise\n // accessors. We do not want the orphan promise to become an unhandled\n // rejection.\n done.catch(() => {});\n\n return { result, done };\n}\n\ntype HostToolOutcome =\n | { ok: true; output: unknown }\n | { ok: false; error: unknown };\n\nfunction asToolCallTextStreamPart<TOOLS extends ToolSet>(input: {\n part: TextStreamPart<TOOLS>;\n}): ToolCallTextStreamPart {\n if (input.part.type !== 'tool-call') {\n throw new Error(\n `Expected parsed tool-call stream part, got '${input.part.type}'.`,\n );\n }\n return input.part as ToolCallTextStreamPart;\n}\n\ntype ToolCallTextStreamPart = {\n readonly type: 'tool-call';\n readonly toolCallId: string;\n readonly toolName: string;\n readonly input: unknown;\n readonly providerExecuted?: boolean;\n readonly providerMetadata?: unknown;\n readonly dynamic?: boolean;\n readonly invalid?: boolean;\n readonly error?: unknown;\n readonly title?: string;\n};\n\nfunction hasTool(input: { tools: ToolSet; toolName: string }): boolean {\n return Object.prototype.hasOwnProperty.call(input.tools, input.toolName);\n}\n\nasync function maybeExecuteHostTool<TOOLS extends ToolSet>(input: {\n event: { toolCallId: string; toolName: string; input: string };\n tools: TOOLS;\n sandboxSession: SandboxSession;\n abortSignal: AbortSignal | undefined;\n control: HarnessV1PromptControl;\n /**\n * Called for each value a generator `execute` `yield`s before its last. The\n * caller surfaces these as preliminary `tool-result` parts on the consumer\n * stream. Never called for a plain (non-generator) `execute`.\n */\n onPreliminaryResult: (output: unknown) => void;\n}): Promise<HostToolOutcome> {\n const tool = input.tools[input.event.toolName];\n\n if (!isExecutableTool(tool)) return { ok: true, output: undefined };\n\n const parsed = await safeParseJSON({ text: input.event.input });\n const args = parsed.success ? parsed.value : input.event.input;\n\n try {\n /*\n * Normalize the tool's return value through `executeTool`, the same helper\n * the non-harness AI SDK uses, so generator `execute` functions behave\n * identically here: each `yield`ed value arrives as a `preliminary` part\n * and the last `yield` is re-emitted as the `final` part; a plain value or\n * Promise arrives as a single `final` part. The underlying runtimes accept\n * exactly one tool result per call, so only the final value is submitted\n * back to the model — preliminary values are surfaced to the consumer\n * stream alone, matching how the AI SDK treats `onPreliminaryToolResult`.\n */\n let output: unknown;\n const stream = executeTool({\n tool,\n input: args as never,\n options: {\n toolCallId: input.event.toolCallId,\n messages: [],\n abortSignal: input.abortSignal,\n context: undefined as never,\n experimental_sandbox: input.sandboxSession,\n },\n });\n for await (const part of stream) {\n if (part.type === 'preliminary') {\n input.onPreliminaryResult(part.output);\n } else {\n output = part.output;\n }\n }\n\n await input.control.submitToolResult({\n toolCallId: input.event.toolCallId,\n output,\n });\n return { ok: true, output };\n } catch (err) {\n await input.control.submitToolResult({\n toolCallId: input.event.toolCallId,\n output: { error: String(err) },\n isError: true,\n });\n return { ok: false, error: err };\n }\n}\n\n/*\n * Validate an inbound `tool-call` event against the merged tool set's schema\n * using the AI SDK's canonical `parseToolCall`. Returns an AI SDK `tool-call`\n * stream part with parsed input on success, or a `dynamic + invalid: true`\n * part on failure (unknown tool, schema mismatch, malformed JSON).\n *\n * The harness `tool-call` event is structurally a `LanguageModelV4ToolCall`\n * (plus an optional harness-only `nativeName`). `providerExecuted` already\n * lives on the V4 type — `true` for adapter builtins (Claude Code's `Bash`,\n * Codex's `shell`), false/undefined for host tools — and is passed through\n * to the AI SDK part by `parseToolCall`.\n */\nexport async function validateToolCall<TOOLS extends ToolSet>(args: {\n event: Extract<HarnessV1StreamPart, { type: 'tool-call' }>;\n tools: TOOLS;\n}): Promise<TextStreamPart<TOOLS>> {\n const { event, tools } = args;\n const toolCall: LanguageModelV4ToolCall = {\n type: 'tool-call',\n toolCallId: event.toolCallId,\n toolName: event.toolName,\n input: event.input,\n ...(event.providerExecuted !== undefined\n ? { providerExecuted: event.providerExecuted }\n : {}),\n ...(event.providerMetadata !== undefined\n ? { providerMetadata: event.providerMetadata }\n : {}),\n };\n\n const parsed = await parseToolCall<TOOLS>({\n toolCall,\n tools,\n repairToolCall: undefined,\n refineToolInput: undefined,\n instructions: undefined,\n messages: [],\n });\n\n return parsed as TextStreamPart<TOOLS>;\n}\n\n/** Best-effort plain text of the turn's prompt, for telemetry input messages. */\nfunction promptToText(prompt: HarnessV1Prompt): string {\n if (typeof prompt === 'string') return prompt;\n const content = (prompt as { content?: unknown }).content;\n if (typeof content === 'string') return content;\n if (Array.isArray(content)) {\n return content\n .filter(\n (part): part is { type: 'text'; text: string } =>\n typeof part === 'object' &&\n part != null &&\n (part as { type?: unknown }).type === 'text',\n )\n .map(part => part.text)\n .join('');\n }\n return '';\n}\n\n// keep import bound so unused-but-needed type stays cited\nexport type _ContentPartMarker<T extends ToolSet> = ContentPart<T>;\n","import {\n DelayedPromise,\n generateId,\n type AssistantModelMessage,\n type Context,\n type ToolModelMessage,\n type ToolSet,\n} from '@ai-sdk/provider-utils';\nimport {\n addLanguageModelUsage,\n asLanguageModelUsage,\n createAsyncIterableStream,\n createNullLanguageModelUsage,\n DefaultStepResult,\n toResponseMessages,\n} from 'ai/internal';\nimport type {\n LanguageModelV4FinishReason,\n LanguageModelV4Usage,\n} from '@ai-sdk/provider';\nimport {\n createUIMessageStreamResponse,\n toUIMessageStream as toUIMessageStreamHelper,\n type CallWarning,\n type ContentPart,\n type FinishReason,\n type GenerateTextResult,\n type InferUIMessageChunk,\n type LanguageModelUsage,\n type ProviderMetadata,\n type StepResult,\n type StreamTextResult,\n type TextStreamPart,\n type UIMessage,\n type UIMessageStreamOptions,\n} from 'ai';\n\ntype StreamProp<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context,\n KEY extends keyof StreamTextResult<TOOLS, RUNTIME_CONTEXT, never>,\n> = Awaited<StreamTextResult<TOOLS, RUNTIME_CONTEXT, never>[KEY]>;\n\n/**\n * Concrete `StreamTextResult` implementation backed by a single\n * harness prompt turn.\n *\n * Wraps a `ReadableStream<TextStreamPart<TOOLS>>` that the calling\n * driver pushes events into. Every `PromiseLike` accessor is backed by a\n * `DelayedPromise` so the AI SDK consumer surface stays identical to\n * `streamText`'s — consumers can `await result.text` or iterate\n * `result.fullStream`, in either order.\n *\n * Each `finish-step` boundary in the driver translates to a `StepResult`\n * built via `DefaultStepResult`. Step content is accumulated as\n * `ContentPart[]` and fed straight to `DefaultStepResult`, which derives\n * `text`, `toolCalls`, `toolResults`, `reasoning`, etc. via its getters.\n *\n * The Node.js response helpers (`pipeUIMessageStreamToResponse`,\n * `pipeTextStreamToResponse`, `toTextStreamResponse`) and the\n * output-specification surfaces (`partialOutputStream`/`elementStream`) are not\n * implemented yet — they throw a clear error.\n */\nexport class HarnessStreamTextResult<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context,\n> implements StreamTextResult<TOOLS, RUNTIME_CONTEXT, never> {\n // Delayed promises backing every PromiseLike accessor. Each is typed\n // against the corresponding `StreamTextResult` property so the public\n // surface stays in lockstep with AI SDK's interface as it evolves.\n private readonly _content = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'content'>\n >();\n private readonly _text = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'text'>\n >();\n private readonly _reasoning = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'reasoning'>\n >();\n private readonly _reasoningText = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'reasoningText'>\n >();\n private readonly _files = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'files'>\n >();\n private readonly _sources = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'sources'>\n >();\n private readonly _toolCalls = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'toolCalls'>\n >();\n private readonly _staticToolCalls = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'staticToolCalls'>\n >();\n private readonly _dynamicToolCalls = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'dynamicToolCalls'>\n >();\n private readonly _toolResults = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'toolResults'>\n >();\n private readonly _staticToolResults = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'staticToolResults'>\n >();\n private readonly _dynamicToolResults = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'dynamicToolResults'>\n >();\n private readonly _finishReason = new DelayedPromise<FinishReason>();\n private readonly _rawFinishReason = new DelayedPromise<string | undefined>();\n private readonly _usage = new DelayedPromise<LanguageModelUsage>();\n private readonly _warnings = new DelayedPromise<CallWarning[] | undefined>();\n private readonly _steps = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'steps'>\n >();\n private readonly _finalStep = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'finalStep'>\n >();\n private readonly _request = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'request'>\n >();\n private readonly _response = new DelayedPromise<\n StreamProp<TOOLS, RUNTIME_CONTEXT, 'response'>\n >();\n private readonly _responseMessages = new DelayedPromise<\n Array<AssistantModelMessage | ToolModelMessage>\n >();\n private readonly _providerMetadata = new DelayedPromise<\n ProviderMetadata | undefined\n >();\n\n // The driver pushes parts into this controller; consumers read via `stream`.\n private readonly fullStreamController: ReadableStreamDefaultController<\n TextStreamPart<TOOLS>\n >;\n readonly stream: AsyncIterableStream<TextStreamPart<TOOLS>>;\n // `fullStream` is the deprecated alias that AI SDK still exposes on the\n // public interface. Backed by the same underlying stream as `stream`.\n readonly fullStream: AsyncIterableStream<TextStreamPart<TOOLS>>;\n readonly textStream: AsyncIterableStream<string>;\n\n private readonly stepsBuffer: StepResult<TOOLS, RUNTIME_CONTEXT>[] = [];\n private currentStepContent: ContentPart<TOOLS>[] = [];\n private currentStepWarnings: CallWarning[] = [];\n private stepNumber = 0;\n\n private readonly tools: TOOLS;\n private readonly runtimeContext: RUNTIME_CONTEXT;\n private readonly toolsContext: never;\n private readonly providerName: string;\n private readonly modelId: string;\n\n // Accumulators that span the whole turn.\n private accumulatedUsage: LanguageModelUsage = createNullLanguageModelUsage();\n private finalProviderMetadata: ProviderMetadata | undefined = undefined;\n private finalFinishReason: FinishReason = 'other';\n private finalRawFinishReason: string | undefined = undefined;\n private aggregateWarnings: CallWarning[] = [];\n private settled = false;\n\n constructor(options: {\n tools: TOOLS;\n runtimeContext: RUNTIME_CONTEXT;\n toolsContext: never;\n harnessId: string;\n sessionId: string;\n }) {\n this.tools = options.tools;\n this.runtimeContext = options.runtimeContext;\n this.toolsContext = options.toolsContext;\n this.providerName = `harness:${options.harnessId}`;\n this.modelId = options.sessionId;\n\n let controllerRef!: ReadableStreamDefaultController<TextStreamPart<TOOLS>>;\n const baseStream = new ReadableStream<TextStreamPart<TOOLS>>({\n start(c) {\n controllerRef = c;\n },\n });\n this.fullStreamController = controllerRef;\n\n const [forFull, forText] = baseStream.tee();\n this.stream = forFull as AsyncIterableStream<TextStreamPart<TOOLS>>;\n this.fullStream = this.stream;\n this.textStream = forText.pipeThrough(\n new TransformStream<TextStreamPart<TOOLS>, string>({\n transform(part, controller) {\n if (part.type === 'text-delta') {\n controller.enqueue(part.text);\n }\n },\n }),\n ) as AsyncIterableStream<string>;\n }\n\n // ─── Writer-side methods used by the driver ────────────────────────\n\n /**\n * Push a translated `TextStreamPart` into `fullStream` and accumulate it\n * into the current step's content array where applicable.\n */\n enqueue(part: TextStreamPart<TOOLS>): void {\n this.fullStreamController.enqueue(part);\n this.appendToCurrentStepContent(part);\n }\n\n /**\n * Mark the end of a step. Builds a `StepResult` from the accumulated\n * content and records it in the steps array. Accepts the V4-shaped\n * finish reason / usage the harness emits and normalizes to AI SDK's\n * flat shape internally.\n */\n finishStep(input: {\n finishReason: LanguageModelV4FinishReason;\n usage: LanguageModelV4Usage;\n providerMetadata: ProviderMetadata | undefined;\n warnings: CallWarning[];\n }): void {\n const normalizedUsage = asLanguageModelUsage(input.usage);\n const finishReason = input.finishReason.unified;\n const rawFinishReason = input.finishReason.raw;\n\n const step = new DefaultStepResult<TOOLS, RUNTIME_CONTEXT>({\n callId: generateId(),\n stepNumber: this.stepNumber,\n provider: this.providerName,\n modelId: this.modelId,\n runtimeContext: this.runtimeContext,\n toolsContext: this.toolsContext,\n content: this.currentStepContent,\n finishReason,\n rawFinishReason,\n usage: normalizedUsage,\n performance: createEmptyPerformance(),\n warnings: input.warnings.length > 0 ? input.warnings : undefined,\n request: {},\n response: {\n id: generateId(),\n timestamp: new Date(),\n modelId: this.modelId,\n messages: [],\n },\n providerMetadata: input.providerMetadata,\n });\n this.stepsBuffer.push(step);\n\n // Forward an AI SDK finish-step event so consumers reading fullStream\n // see step boundaries.\n this.fullStreamController.enqueue({\n type: 'finish-step',\n finishReason,\n rawFinishReason,\n usage: normalizedUsage,\n providerMetadata: input.providerMetadata,\n response: step.response,\n performance: createEmptyPerformance(),\n } as TextStreamPart<TOOLS>);\n\n this.accumulatedUsage = addLanguageModelUsage(\n this.accumulatedUsage,\n normalizedUsage,\n );\n this.finalFinishReason = finishReason;\n this.finalRawFinishReason = rawFinishReason;\n this.finalProviderMetadata = input.providerMetadata;\n if (input.warnings.length > 0)\n this.aggregateWarnings.push(...input.warnings);\n\n this.stepNumber += 1;\n this.currentStepContent = [];\n this.currentStepWarnings = [];\n }\n\n /**\n * Resolve every delayed promise and close `fullStream`. Idempotent.\n */\n async finish(input?: {\n finishReason: LanguageModelV4FinishReason;\n totalUsage: LanguageModelV4Usage;\n providerMetadata: ProviderMetadata | undefined;\n }): Promise<void> {\n if (this.settled) return;\n this.settled = true;\n\n if (input != null) {\n this.finalFinishReason = input.finishReason.unified;\n this.finalRawFinishReason = input.finishReason.raw;\n this.finalProviderMetadata = input.providerMetadata;\n this.accumulatedUsage = asLanguageModelUsage(input.totalUsage);\n }\n\n // Flush any trailing content not yet captured by a finish-step. We\n // construct the step directly here (the public `finishStep` takes V4\n // shapes; we already have AI SDK shapes at this point).\n if (this.currentStepContent.length > 0) {\n const trailingStep = new DefaultStepResult<TOOLS, RUNTIME_CONTEXT>({\n callId: generateId(),\n stepNumber: this.stepNumber,\n provider: this.providerName,\n modelId: this.modelId,\n runtimeContext: this.runtimeContext,\n toolsContext: this.toolsContext,\n content: this.currentStepContent,\n finishReason: this.finalFinishReason,\n rawFinishReason: this.finalRawFinishReason,\n usage: createNullLanguageModelUsage(),\n performance: createEmptyPerformance(),\n warnings:\n this.currentStepWarnings.length > 0\n ? this.currentStepWarnings\n : undefined,\n request: {},\n response: {\n id: generateId(),\n timestamp: new Date(),\n modelId: this.modelId,\n messages: [],\n },\n providerMetadata: this.finalProviderMetadata,\n });\n this.stepsBuffer.push(trailingStep);\n this.currentStepContent = [];\n this.currentStepWarnings = [];\n }\n\n const finalStep =\n this.stepsBuffer.length > 0\n ? this.stepsBuffer[this.stepsBuffer.length - 1]!\n : new DefaultStepResult<TOOLS, RUNTIME_CONTEXT>({\n callId: generateId(),\n stepNumber: 0,\n provider: this.providerName,\n modelId: this.modelId,\n runtimeContext: this.runtimeContext,\n toolsContext: this.toolsContext,\n content: [],\n finishReason: this.finalFinishReason,\n rawFinishReason: this.finalRawFinishReason,\n usage: createNullLanguageModelUsage(),\n performance: createEmptyPerformance(),\n warnings: undefined,\n request: {},\n response: {\n id: generateId(),\n timestamp: new Date(),\n modelId: this.modelId,\n messages: [],\n },\n providerMetadata: undefined,\n });\n\n const aggregatedContent = this.stepsBuffer.flatMap(s => s.content);\n\n this._content.resolve(\n aggregatedContent as StreamProp<TOOLS, RUNTIME_CONTEXT, 'content'>,\n );\n this._text.resolve(finalStep.text);\n // Reasoning content parts are not yet derived from harness events; the\n // foundation surfaces an empty array. Adapters that emit reasoning\n // deltas can be wired up to produce real reasoning content in a later\n // pass.\n this._reasoning.resolve(\n [] as StreamProp<TOOLS, RUNTIME_CONTEXT, 'reasoning'>,\n );\n this._reasoningText.resolve(undefined);\n this._files.resolve(this.stepsBuffer.flatMap(s => s.files));\n this._sources.resolve(this.stepsBuffer.flatMap(s => s.sources));\n this._toolCalls.resolve(\n this.stepsBuffer.flatMap(s => s.toolCalls) as StreamProp<\n TOOLS,\n RUNTIME_CONTEXT,\n 'toolCalls'\n >,\n );\n this._staticToolCalls.resolve(\n this.stepsBuffer.flatMap(s => s.staticToolCalls) as StreamProp<\n TOOLS,\n RUNTIME_CONTEXT,\n 'staticToolCalls'\n >,\n );\n this._dynamicToolCalls.resolve(\n this.stepsBuffer.flatMap(s => s.dynamicToolCalls) as StreamProp<\n TOOLS,\n RUNTIME_CONTEXT,\n 'dynamicToolCalls'\n >,\n );\n this._toolResults.resolve(\n this.stepsBuffer.flatMap(s => s.toolResults) as StreamProp<\n TOOLS,\n RUNTIME_CONTEXT,\n 'toolResults'\n >,\n );\n this._staticToolResults.resolve(\n this.stepsBuffer.flatMap(s => s.staticToolResults) as StreamProp<\n TOOLS,\n RUNTIME_CONTEXT,\n 'staticToolResults'\n >,\n );\n this._dynamicToolResults.resolve(\n this.stepsBuffer.flatMap(s => s.dynamicToolResults) as StreamProp<\n TOOLS,\n RUNTIME_CONTEXT,\n 'dynamicToolResults'\n >,\n );\n this._finishReason.resolve(this.finalFinishReason);\n this._rawFinishReason.resolve(this.finalRawFinishReason);\n this._usage.resolve(this.accumulatedUsage);\n this._warnings.resolve(\n this.aggregateWarnings.length > 0 ? this.aggregateWarnings : undefined,\n );\n this._steps.resolve(this.stepsBuffer);\n this._finalStep.resolve(finalStep);\n this._request.resolve(finalStep.request);\n this._response.resolve(finalStep.response);\n this._providerMetadata.resolve(this.finalProviderMetadata);\n\n const responseMessages = await toResponseMessages<TOOLS>({\n content: aggregatedContent,\n tools: this.tools,\n });\n this._responseMessages.resolve(responseMessages);\n\n // Forward AI SDK finish event before closing.\n this.fullStreamController.enqueue({\n type: 'finish',\n finishReason: this.finalFinishReason,\n rawFinishReason: this.finalRawFinishReason,\n totalUsage: this.accumulatedUsage,\n providerMetadata: this.finalProviderMetadata,\n } as TextStreamPart<TOOLS>);\n\n this.fullStreamController.close();\n }\n\n /**\n * Surface a fatal error as a stream `error` part + reject every delayed\n * promise so awaiting consumers stop hanging. Idempotent.\n */\n fail(error: unknown): void {\n if (this.settled) return;\n this.settled = true;\n this.fullStreamController.enqueue({\n type: 'error',\n error,\n } as TextStreamPart<TOOLS>);\n this.fullStreamController.close();\n for (const dp of [\n this._content,\n this._text,\n this._reasoning,\n this._reasoningText,\n this._files,\n this._sources,\n this._toolCalls,\n this._staticToolCalls,\n this._dynamicToolCalls,\n this._toolResults,\n this._staticToolResults,\n this._dynamicToolResults,\n this._finishReason,\n this._rawFinishReason,\n this._usage,\n this._warnings,\n this._steps,\n this._finalStep,\n this._request,\n this._response,\n this._responseMessages,\n this._providerMetadata,\n ]) {\n try {\n (dp as DelayedPromise<unknown>).reject(error);\n } catch {\n // ignore double-rejection\n }\n }\n }\n\n // ─── Reader-side public surface (StreamTextResult contract) ────────\n\n get content() {\n return this._content.promise;\n }\n get text() {\n return this._text.promise;\n }\n get reasoning() {\n return this._reasoning.promise;\n }\n get reasoningText() {\n return this._reasoningText.promise;\n }\n get files() {\n return this._files.promise;\n }\n get sources() {\n return this._sources.promise;\n }\n get toolCalls() {\n return this._toolCalls.promise;\n }\n get staticToolCalls() {\n return this._staticToolCalls.promise;\n }\n get dynamicToolCalls() {\n return this._dynamicToolCalls.promise;\n }\n get toolResults() {\n return this._toolResults.promise;\n }\n get staticToolResults() {\n return this._staticToolResults.promise;\n }\n get dynamicToolResults() {\n return this._dynamicToolResults.promise;\n }\n get finishReason() {\n return this._finishReason.promise;\n }\n get rawFinishReason() {\n return this._rawFinishReason.promise;\n }\n get usage() {\n return this._usage.promise;\n }\n get totalUsage() {\n return this._usage.promise;\n }\n get warnings() {\n return this._warnings.promise;\n }\n get steps() {\n return this._steps.promise;\n }\n get finalStep() {\n return this._finalStep.promise;\n }\n get request() {\n return this._request.promise;\n }\n get response() {\n return this._response.promise;\n }\n get responseMessages() {\n return this._responseMessages.promise;\n }\n get providerMetadata() {\n return this._providerMetadata.promise;\n }\n\n // Output-specification surfaces are not yet supported.\n get experimental_partialOutputStream(): never {\n throw notSupportedYet('partial output stream');\n }\n get partialOutputStream(): never {\n throw notSupportedYet('partial output stream');\n }\n get elementStream(): never {\n throw notSupportedYet('element stream');\n }\n get output(): never {\n throw notSupportedYet('structured output');\n }\n\n async consumeStream(): Promise<void> {\n const reader = this.fullStream.getReader();\n try {\n while (true) {\n const { done } = await reader.read();\n if (done) return;\n }\n } finally {\n reader.releaseLock();\n }\n }\n\n toUIMessageStream<UI_MESSAGE extends UIMessage>({\n originalMessages,\n generateMessageId,\n onFinish,\n messageMetadata,\n sendReasoning,\n sendSources,\n sendStart,\n sendFinish,\n onError,\n }: UIMessageStreamOptions<UI_MESSAGE> = {}): AsyncIterableStream<\n InferUIMessageChunk<UI_MESSAGE>\n > {\n return createAsyncIterableStream(\n toUIMessageStreamHelper<TOOLS, UI_MESSAGE>({\n stream: this.stream,\n tools: this.tools,\n originalMessages,\n generateMessageId,\n onFinish,\n messageMetadata,\n sendReasoning,\n sendSources,\n sendStart,\n sendFinish,\n onError,\n }),\n ) as AsyncIterableStream<InferUIMessageChunk<UI_MESSAGE>>;\n }\n\n pipeUIMessageStreamToResponse(): never {\n throw notSupportedYet('pipeUIMessageStreamToResponse');\n }\n\n pipeTextStreamToResponse(): never {\n throw notSupportedYet('pipeTextStreamToResponse');\n }\n\n toUIMessageStreamResponse<UI_MESSAGE extends UIMessage>({\n originalMessages,\n generateMessageId,\n onFinish,\n messageMetadata,\n sendReasoning,\n sendSources,\n sendStart,\n sendFinish,\n onError,\n ...init\n }: ResponseInit & {\n consumeSseStream?: (options: {\n stream: ReadableStream<string>;\n }) => PromiseLike<void> | void;\n } & UIMessageStreamOptions<UI_MESSAGE> = {}): Response {\n return createUIMessageStreamResponse({\n stream: this.toUIMessageStream<UI_MESSAGE>({\n originalMessages,\n generateMessageId,\n onFinish,\n messageMetadata,\n sendReasoning,\n sendSources,\n sendStart,\n sendFinish,\n onError,\n }),\n ...init,\n });\n }\n\n toTextStreamResponse(): never {\n throw notSupportedYet('toTextStreamResponse');\n }\n\n // ─── Helpers ────────────────────────────────────────────────────────\n\n private appendToCurrentStepContent(part: TextStreamPart<TOOLS>): void {\n switch (part.type) {\n case 'text-delta': {\n // Coalesce contiguous text-deltas with the same id into one text part.\n const last =\n this.currentStepContent[this.currentStepContent.length - 1];\n if (last && last.type === 'text') {\n (last as { text: string }).text += part.text;\n } else {\n this.currentStepContent.push({\n type: 'text',\n text: part.text,\n } as ContentPart<TOOLS>);\n }\n return;\n }\n case 'tool-call':\n this.currentStepContent.push({\n ...(part as object),\n } as ContentPart<TOOLS>);\n return;\n case 'tool-approval-request':\n this.currentStepContent.push({\n ...(part as object),\n } as ContentPart<TOOLS>);\n return;\n case 'tool-approval-response':\n this.currentStepContent.push({\n ...(part as object),\n } as ContentPart<TOOLS>);\n return;\n case 'tool-result':\n this.currentStepContent.push({\n ...(part as object),\n } as ContentPart<TOOLS>);\n return;\n default:\n // text-start/end, reasoning-*, raw, error, finish-step, finish are\n // not directly stored as ContentParts. (Reasoning content parts\n // would belong here; we omit them for v0.)\n return;\n }\n }\n}\n\nfunction createEmptyPerformance(): StepResult<ToolSet, Context>['performance'] {\n return {\n effectiveOutputTokensPerSecond: 0,\n outputTokensPerSecond: undefined,\n inputTokensPerSecond: undefined,\n effectiveTotalTokensPerSecond: 0,\n stepTimeMs: 0,\n responseTimeMs: 0,\n toolExecutionMs: {},\n timeToFirstOutputMs: undefined,\n };\n}\n\nfunction notSupportedYet(feature: string): Error {\n return new Error(\n `HarnessAgent: ${feature} is not implemented yet. Track the foundation review for follow-up.`,\n );\n}\n\n// Re-declare `AsyncIterableStream` locally to avoid pulling AI SDK's internal\n// async-iterable-stream helper. ReadableStreams already implement the\n// async-iterator contract in modern runtimes; we expose them under the same\n// nominal type AI SDK does.\ntype AsyncIterableStream<T> = ReadableStream<T> & AsyncIterable<T>;\n\n// `GenerateTextResult` is re-exported only so downstream code can keep this\n// file as the single source of return-shape constants; not otherwise used here.\nexport type _GenerateTextResultMarker<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context,\n> = GenerateTextResult<TOOLS, RUNTIME_CONTEXT, never>;\n","import type { HarnessV1StreamPart } from '../../v1';\nimport type { TextStreamPart } from 'ai';\nimport { generateId, type ToolSet } from '@ai-sdk/provider-utils';\n\n/**\n * Translate one event from the harness wire format to the AI SDK\n * `TextStreamPart` shape consumed by `streamText` callers.\n *\n * Most variants are close to the identity function — V4 primitives\n * (`LanguageModelV4ToolCall`, `LanguageModelV4ToolResult`,\n * `LanguageModelV4ToolApprovalRequest`, `LanguageModelV4FinishReason`,\n * `LanguageModelV4Usage`) flow through unchanged. The adapters are:\n * - `harnessMetadata` → `providerMetadata`\n * - tool-call events are not translated here — validation against the\n * merged tool set is async and handled by `validateToolCall` in\n * `run-prompt.ts`\n * - the harness `raw` part is forwarded as the AI SDK `raw` part\n *\n * Returns an array of zero or more AI SDK parts. Most harness events project\n * to a single AI SDK part; `file-change` fans out into a synthetic\n * dynamic + provider-executed `tool-call` / `tool-result` pair so the event\n * is observable in `streamText`-style flows without a new stream-part type\n * needing first-class AI SDK support. Events with no consumer-facing AI SDK\n * equivalent (`stream-start`, `finish-step`, `finish` — consumed internally)\n * return an empty array.\n */\nexport function translateStreamPart<TOOLS extends ToolSet>(\n event: HarnessV1StreamPart,\n): ReadonlyArray<TextStreamPart<TOOLS>> {\n switch (event.type) {\n case 'stream-start':\n // The agent emits its own `start` part with normalized warnings;\n // the harness-level start signal is consumed internally.\n return [];\n\n case 'text-start':\n return [\n {\n type: 'text-start',\n id: event.id,\n providerMetadata: event.harnessMetadata,\n } as TextStreamPart<TOOLS>,\n ];\n\n case 'text-delta':\n return [\n {\n type: 'text-delta',\n id: event.id,\n text: event.delta,\n providerMetadata: event.harnessMetadata,\n } as TextStreamPart<TOOLS>,\n ];\n\n case 'text-end':\n return [\n {\n type: 'text-end',\n id: event.id,\n providerMetadata: event.harnessMetadata,\n } as TextStreamPart<TOOLS>,\n ];\n\n case 'reasoning-start':\n return [\n {\n type: 'reasoning-start',\n id: event.id,\n providerMetadata: event.harnessMetadata,\n } as TextStreamPart<TOOLS>,\n ];\n\n case 'reasoning-delta':\n return [\n {\n type: 'reasoning-delta',\n id: event.id,\n text: event.delta,\n providerMetadata: event.harnessMetadata,\n } as TextStreamPart<TOOLS>,\n ];\n\n case 'reasoning-end':\n return [\n {\n type: 'reasoning-end',\n id: event.id,\n providerMetadata: event.harnessMetadata,\n } as TextStreamPart<TOOLS>,\n ];\n\n case 'tool-call':\n // Tool-call validation is async (it parses input against the tool's\n // schema) and lives in `run-prompt.ts` where the merged tool set is in\n // scope. The translator returns nothing here — the run-prompt loop\n // handles the emission.\n return [];\n\n case 'tool-approval-request':\n return [];\n\n case 'tool-result':\n return [\n {\n type: 'tool-result',\n toolCallId: event.toolCallId,\n toolName: event.toolName,\n input: undefined,\n output: event.result,\n ...(event.preliminary !== undefined\n ? { preliminary: event.preliminary }\n : {}),\n ...(event.providerMetadata !== undefined\n ? { providerMetadata: event.providerMetadata }\n : {}),\n } as TextStreamPart<TOOLS>,\n ];\n\n case 'file-change': {\n /*\n * `file-change` has no first-class AI SDK stream-part equivalent.\n * Project it as a synthetic dynamic + provider-executed tool-call /\n * tool-result pair under the reserved name `fileChange` so the event\n * is visible to `streamText`-style consumers. `dynamic: true` keeps it\n * out of typed-tool lookups; `providerExecuted: true` signals the\n * runtime already executed it and the host should not dispatch.\n */\n const toolCallId = `harness-file-change-${generateId()}`;\n const payload = { event: event.event, path: event.path };\n return [\n {\n type: 'tool-call',\n toolCallId,\n toolName: 'fileChange',\n input: payload,\n dynamic: true,\n providerExecuted: true,\n ...(event.harnessMetadata !== undefined\n ? { providerMetadata: event.harnessMetadata }\n : {}),\n } as TextStreamPart<TOOLS>,\n {\n type: 'tool-result',\n toolCallId,\n toolName: 'fileChange',\n input: payload,\n output: payload,\n dynamic: true,\n providerExecuted: true,\n ...(event.harnessMetadata !== undefined\n ? { providerMetadata: event.harnessMetadata }\n : {}),\n } as TextStreamPart<TOOLS>,\n ];\n }\n\n case 'compaction': {\n /*\n * Like `file-change`, compaction has no first-class AI SDK stream-part\n * equivalent. Project it as a synthetic dynamic + provider-executed\n * tool-call / tool-result pair under the reserved name `compaction`, so\n * the event is visible to `streamText`-style consumers. Compaction takes\n * no input, so the call input is empty; the metadata rides on the result\n * output. `dynamic: true` keeps it out of typed-tool lookups;\n * `providerExecuted: true` signals the runtime already performed it.\n */\n const toolCallId = `harness-compaction-${generateId()}`;\n const output = {\n trigger: event.trigger,\n summary: event.summary,\n ...(event.tokensBefore !== undefined\n ? { tokensBefore: event.tokensBefore }\n : {}),\n ...(event.tokensAfter !== undefined\n ? { tokensAfter: event.tokensAfter }\n : {}),\n };\n return [\n {\n type: 'tool-call',\n toolCallId,\n toolName: 'compaction',\n input: {},\n dynamic: true,\n providerExecuted: true,\n ...(event.harnessMetadata !== undefined\n ? { providerMetadata: event.harnessMetadata }\n : {}),\n } as TextStreamPart<TOOLS>,\n {\n type: 'tool-result',\n toolCallId,\n toolName: 'compaction',\n input: {},\n output,\n dynamic: true,\n providerExecuted: true,\n ...(event.harnessMetadata !== undefined\n ? { providerMetadata: event.harnessMetadata }\n : {}),\n } as TextStreamPart<TOOLS>,\n ];\n }\n\n case 'error':\n return [{ type: 'error', error: event.error } as TextStreamPart<TOOLS>];\n\n case 'raw':\n return [\n { type: 'raw', rawValue: event.rawValue } as TextStreamPart<TOOLS>,\n ];\n\n case 'finish-step':\n case 'finish':\n // finish-step / finish are consumed by the agent's result builder, not\n // forwarded directly. The agent emits AI SDK `finish-step` / `finish`\n // parts itself once it has assembled the surrounding step / response\n // metadata.\n return [];\n }\n}\n","import type { HarnessV1StreamPart } from '../../v1';\n\n/**\n * Remove the session working-directory prefix from path-bearing fields of a\n * stream event, returning a new event for display to consumers.\n *\n * Harness adapters run the agent in a per-session working directory that is a\n * subdirectory of the sandbox root, and the agent's tools use absolute paths so\n * they resolve against the root regardless of where the runtime process\n * operates. The absolute paths are correct but noisy in a UI, so this strips\n * the prefix for the consumer-facing projection only.\n *\n * Blanket prefix replacement (rather than rewriting known path fields) is used\n * deliberately: `tool-result` results are free-form text — command stdout, grep\n * output — where paths can appear anywhere and field-aware rewriting is\n * impossible. The prefix is long and contains the session id, so it is unique\n * enough that replacing every occurrence is safe.\n */\nexport function stripWorkDir(\n part: HarnessV1StreamPart,\n sessionWorkDir: string,\n): HarnessV1StreamPart {\n if (sessionWorkDir.length === 0) return part;\n\n switch (part.type) {\n case 'tool-call':\n return { ...part, input: stripString(part.input, sessionWorkDir) };\n case 'tool-result':\n return {\n ...part,\n result: stripDeep(part.result, sessionWorkDir) as Extract<\n HarnessV1StreamPart,\n { type: 'tool-result' }\n >['result'],\n };\n case 'file-change':\n return { ...part, path: stripString(part.path, sessionWorkDir) };\n default:\n return part;\n }\n}\n\n/**\n * Replace occurrences of the working directory in a string. A reference to the\n * directory followed by a separator becomes workspace-relative\n * (`/work/dir/src/a.ts` → `src/a.ts`); a bare reference to the directory itself\n * becomes `.`.\n */\nfunction stripString(value: string, workDir: string): string {\n return value.split(`${workDir}/`).join('').split(workDir).join('.');\n}\n\n/**\n * Recursively strip the working directory from every string nested in an\n * arbitrary JSON-like value. Non-string leaves are returned unchanged.\n */\nfunction stripDeep(value: unknown, workDir: string): unknown {\n if (typeof value === 'string') return stripString(value, workDir);\n if (Array.isArray(value)) return value.map(item => stripDeep(item, workDir));\n if (value !== null && typeof value === 'object') {\n const out: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n out[key] = stripDeep(val, workDir);\n }\n return out;\n }\n return value;\n}\n","import { generateId, type ModelMessage } from '@ai-sdk/provider-utils';\nimport { createTelemetryDispatcher } from 'ai/internal';\nimport type { TelemetryOptions } from 'ai';\n\n/*\n * Drives AI SDK's pluggable `Telemetry` lifecycle from a harness turn.\n *\n * A harness turn is not a `streamText` call — it has no language model, prompt\n * standardization, or sampling settings — but the AI SDK telemetry contract is\n * shaped around `generateText`/`streamText` events, and `@ai-sdk/otel` (the\n * main integration) only produces spans when the full lifecycle fires. So we\n * map the turn onto that contract: turn = operation, each `finish-step` = a\n * step boundary, tool-calls = tool executions, `finish` = operation end. The\n * model-call-only event fields the harness has no value for (sampling params,\n * standardized prompt) are left `undefined` / cast; the fields the integrations\n * actually read (`callId`, `operationId`, `provider`, `modelId`, `messages`,\n * `toolCall`, `usage`, `finishReason`) carry real values.\n *\n * Telemetry is opt-in: the framework only drives it when `settings.telemetry`\n * is set (the dispatcher then also honours globally-registered integrations).\n */\n\ntype Dispatcher = ReturnType<typeof createTelemetryDispatcher>;\ntype EventArg<K extends keyof Dispatcher> = Dispatcher[K] extends\n | ((event: infer E) => unknown)\n | undefined\n ? E\n : never;\n\n/**\n * An output content part accumulated over a step — the model's assistant turn.\n * Shaped for the gen_ai output-message conventions `@ai-sdk/otel` reads.\n */\nexport type TurnContentPart =\n | { type: 'text'; text: string }\n | { type: 'reasoning'; text: string }\n | { type: 'tool-call'; toolCallId: string; toolName: string; input: unknown };\n\nexport interface TurnTelemetry {\n /**\n * Begin the operation span. Called on `stream-start`, optionally with the\n * model the runtime resolved to (overriding the session's configured id).\n * Idempotent — the first call wins.\n */\n start(modelId?: string): void;\n /** Open a step span lazily, before the first content of a step. */\n ensureStepOpen(): void;\n /** Close the current step (on a harness `finish-step`). */\n stepFinish(info: {\n finishReason: unknown;\n usage: unknown;\n providerMetadata?: unknown;\n /** The model's output content for this step (text/reasoning/tool-calls). */\n content?: TurnContentPart[];\n }): void;\n /** A tool execution began (on a `tool-call`). */\n toolStart(call: {\n toolCallId: string;\n toolName: string;\n input: unknown;\n }): void;\n /**\n * A tool execution completed (on its `tool-result` or after host execution).\n * Idempotent per `toolCallId` — the first caller wins, so provider-executed\n * and host-executed paths can both call it without double-counting.\n */\n toolEnd(\n toolCallId: string,\n output: { ok: true; output: unknown } | { ok: false; error: unknown },\n ): void;\n /** The turn ended (on a harness `finish`). */\n end(info: { finishReason: unknown; usage: unknown }): void;\n /** The turn failed. */\n error(err: unknown): void;\n}\n\nconst NOOP: TurnTelemetry = {\n start() {},\n ensureStepOpen() {},\n stepFinish() {},\n toolStart() {},\n toolEnd() {},\n end() {},\n error() {},\n};\n\nexport function createTurnTelemetry(opts: {\n telemetry: TelemetryOptions | undefined;\n harnessId: string;\n modelId: string | undefined;\n instructions: string | undefined;\n promptText: string;\n runtimeContext: unknown;\n}): TurnTelemetry {\n // Opt-in: with no telemetry settings we do no work and construct no events.\n if (opts.telemetry == null) return NOOP;\n\n const dispatcher = createTelemetryDispatcher({ telemetry: opts.telemetry });\n\n const callId = generateId();\n const provider = opts.harnessId;\n // The configured session model; `start(modelId)` may override it with the\n // model the runtime actually resolved to.\n let modelId = opts.modelId ?? '';\n const runtimeContext = opts.runtimeContext;\n const inputMessages: ModelMessage[] = [\n { role: 'user', content: opts.promptText },\n ];\n\n let started = false;\n let stepOpen = false;\n let stepNumber = 0;\n let ended = false;\n /** Tool calls started in the current turn and not yet ended. */\n const openTools = new Map<\n string,\n { toolCallId: string; toolName: string; input: unknown }\n >();\n\n const cast = <K extends keyof Dispatcher>(event: unknown): EventArg<K> =>\n event as EventArg<K>;\n\n // onStart — open the operation (root) span. Deferred until `start()` so the\n // runtime-resolved model can be attached to the operation span + trace label.\n const fireStart = (): void => {\n if (started) return;\n started = true;\n dispatcher.onStart?.(\n cast<'onStart'>({\n callId,\n operationId: 'ai.harness',\n provider,\n modelId,\n tools: undefined,\n toolChoice: undefined,\n activeTools: undefined,\n maxRetries: 0,\n timeout: undefined,\n headers: undefined,\n providerOptions: undefined,\n output: undefined,\n toolsContext: undefined,\n runtimeContext,\n instructions: opts.instructions,\n messages: inputMessages,\n }),\n );\n };\n\n const start = (overrideModelId?: string): void => {\n if (started) return;\n if (overrideModelId) modelId = overrideModelId;\n fireStart();\n };\n\n const ensureStepOpen = (): void => {\n if (!started) fireStart();\n if (stepOpen || ended) return;\n stepOpen = true;\n dispatcher.onStepStart?.(\n cast<'onStepStart'>({\n callId,\n provider,\n modelId,\n stepNumber,\n tools: undefined,\n toolChoice: undefined,\n activeTools: undefined,\n steps: new Array(stepNumber),\n providerOptions: undefined,\n output: undefined,\n runtimeContext,\n messages: inputMessages,\n }),\n );\n // Open the inference (language-model call) span — the gen_ai home for the\n // step's input and (on end) output messages.\n dispatcher.onLanguageModelCallStart?.(\n cast<'onLanguageModelCallStart'>({\n callId,\n provider,\n modelId,\n messages: inputMessages,\n tools: undefined,\n }),\n );\n };\n\n /** Close the inference span with the step's output content. */\n const inferenceEnd = (info: {\n finishReason: unknown;\n usage: unknown;\n content: TurnContentPart[];\n }): void => {\n dispatcher.onLanguageModelCallEnd?.(\n cast<'onLanguageModelCallEnd'>({\n callId,\n finishReason: info.finishReason,\n responseId: callId,\n usage: info.usage,\n content: info.content,\n }),\n );\n };\n\n const closeOpenTools = (): void => {\n for (const call of openTools.values()) {\n dispatcher.onToolExecutionEnd?.(\n cast<'onToolExecutionEnd'>({\n callId,\n toolExecutionMs: 0,\n messages: [],\n toolCall: {\n type: 'tool-call',\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n input: call.input,\n dynamic: true,\n },\n toolContext: undefined,\n toolOutput: { type: 'error', error: new Error('tool span unclosed') },\n }),\n );\n }\n openTools.clear();\n };\n\n return {\n start,\n ensureStepOpen,\n\n stepFinish(info) {\n if (!stepOpen) return;\n const content = info.content ?? [];\n closeOpenTools();\n inferenceEnd({\n finishReason: info.finishReason,\n usage: info.usage,\n content,\n });\n dispatcher.onStepEnd?.(\n cast<'onStepEnd'>({\n callId,\n finishReason: info.finishReason,\n usage: info.usage,\n providerMetadata: info.providerMetadata,\n content,\n response: {\n id: callId,\n modelId,\n timestamp: new Date(0),\n messages: [],\n },\n }),\n );\n stepOpen = false;\n stepNumber += 1;\n },\n\n toolStart(call) {\n ensureStepOpen();\n openTools.set(call.toolCallId, call);\n dispatcher.onToolExecutionStart?.(\n cast<'onToolExecutionStart'>({\n callId,\n messages: [],\n toolCall: {\n type: 'tool-call',\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n input: call.input,\n dynamic: true,\n },\n toolContext: undefined,\n }),\n );\n },\n\n toolEnd(toolCallId, output) {\n const call = openTools.get(toolCallId);\n if (call == null) return;\n openTools.delete(toolCallId);\n dispatcher.onToolExecutionEnd?.(\n cast<'onToolExecutionEnd'>({\n callId,\n toolExecutionMs: 0,\n messages: [],\n toolCall: {\n type: 'tool-call',\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n input: call.input,\n dynamic: true,\n },\n toolContext: undefined,\n toolOutput: output.ok\n ? { type: 'tool-result', output: output.output }\n : { type: 'error', error: output.error },\n }),\n );\n },\n\n end(info) {\n if (ended) return;\n if (!started) fireStart();\n if (stepOpen) {\n closeOpenTools();\n inferenceEnd({\n finishReason: info.finishReason,\n usage: info.usage,\n content: [],\n });\n dispatcher.onStepEnd?.(\n cast<'onStepEnd'>({\n callId,\n finishReason: info.finishReason,\n usage: info.usage,\n providerMetadata: undefined,\n content: [],\n response: {\n id: callId,\n modelId,\n timestamp: new Date(0),\n messages: [],\n },\n }),\n );\n stepOpen = false;\n }\n ended = true;\n dispatcher.onEnd?.(\n cast<'onEnd'>({\n callId,\n operationId: 'ai.harness',\n finishReason: info.finishReason,\n usage: info.usage,\n totalUsage: info.usage,\n content: [],\n steps: new Array(stepNumber),\n response: {\n id: callId,\n modelId,\n timestamp: new Date(0),\n messages: [],\n },\n runtimeContext,\n }),\n );\n },\n\n error(err) {\n if (ended) return;\n if (!started) fireStart();\n closeOpenTools();\n ended = true;\n dispatcher.onError?.(err);\n },\n };\n}\n","import type { ToolApprovalStatus } from 'ai';\nimport type { HarnessV1PermissionMode } from '../../v1';\nimport type { HarnessAgentToolApprovalConfiguration } from '../harness-agent-settings';\n\nexport const DEFAULT_PERMISSION_MODE: HarnessV1PermissionMode =\n 'allow-all' as const;\n\nexport function resolvePermissionMode(input: {\n permissionMode: HarnessV1PermissionMode | undefined;\n}): HarnessV1PermissionMode {\n return input.permissionMode ?? DEFAULT_PERMISSION_MODE;\n}\n\nexport function permissionModeNeedsBuiltinSupport(input: {\n permissionMode: HarnessV1PermissionMode;\n}): boolean {\n return input.permissionMode !== 'allow-all';\n}\n\nexport type CustomToolApprovalDecision =\n | { readonly type: 'allow'; readonly reason?: string }\n | { readonly type: 'deny'; readonly reason?: string }\n | { readonly type: 'request' };\n\nexport function resolveCustomToolApproval(input: {\n toolName: string;\n toolApproval: HarnessAgentToolApprovalConfiguration | undefined;\n}): CustomToolApprovalDecision {\n const status = normalizeToolApprovalStatus({\n status: input.toolApproval?.[input.toolName],\n });\n\n switch (status.type) {\n case 'not-applicable':\n case 'approved':\n return { type: 'allow', reason: status.reason };\n case 'denied':\n return { type: 'deny', reason: status.reason };\n case 'user-approval':\n return { type: 'request' };\n }\n}\n\nfunction normalizeToolApprovalStatus(input: {\n status: ToolApprovalStatus | undefined;\n}): Exclude<ToolApprovalStatus, string | undefined> {\n if (input.status === undefined) return { type: 'not-applicable' };\n if (typeof input.status === 'string') return { type: input.status };\n return input.status;\n}\n","import type { Context, ToolSet } from '@ai-sdk/provider-utils';\nimport type { StreamTextResult, TelemetryOptions } from 'ai';\nimport type { HarnessAgentToolApprovalConfiguration } from './harness-agent-settings';\nimport type {\n HarnessV1BuiltinToolFiltering,\n HarnessV1NetworkSandboxSession,\n HarnessV1SandboxProvider,\n} from '../v1';\nimport type {\n HarnessAgentAdapter,\n HarnessAgentAdapterSession,\n HarnessAgentContinueTurnState,\n HarnessAgentPendingToolApproval,\n HarnessAgentPrompt,\n HarnessAgentResumeSessionState,\n HarnessAgentToolSpec,\n} from './harness-agent-types';\nimport type { HarnessAgentToolApprovalContinuation } from './harness-agent-tool-approval-continuation';\nimport { releaseBridgePort } from './internal/bridge-port-registry';\nimport { validateLifecycleStateData } from './internal/lifecycle-state-validation';\nimport { runPrompt } from './internal/run-prompt';\n\ntype HarnessAgentTurnResult<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context,\n> = {\n result: StreamTextResult<TOOLS, RUNTIME_CONTEXT, never>;\n done: Promise<void>;\n};\n\ntype HarnessAgentSessionState = 'active' | 'detached' | 'stopped' | 'destroyed';\n\ntype HarnessAgentTurnState =\n | 'idle'\n | 'running'\n | 'awaiting-approval'\n | 'suspended';\n\n/**\n * Live harness session held by the caller.\n *\n * Created by {@link import('./harness-agent').HarnessAgent.createSession}.\n * Owns the underlying adapter session, the network sandbox session, and the\n * bridge-port lease (when the provider wraps a caller-provided sandbox with a\n * port pool).\n *\n * Pass the instance back to `agent.generate` / `agent.stream` on every\n * call; end the local handle with `detach()`, `stop()`, or `destroy()`.\n *\n * After any lifecycle method has resolved, the session is unusable — any\n * subsequent `generate`/`stream` call against it throws.\n */\nexport class HarnessAgentSession {\n /**\n * Stable identifier the harness adapter saw in `doStart`. The same\n * string callers persist when they intend to resume the session in a\n * future process.\n */\n readonly sessionId: string;\n\n private readonly harness: HarnessAgentAdapter;\n private readonly sandboxProvider: HarnessV1SandboxProvider;\n private readonly sessionWorkDir: string;\n private underlyingSession: HarnessAgentAdapterSession | undefined;\n private sandboxSession: HarnessV1NetworkSandboxSession | undefined;\n private leasedBridgePort: number | undefined;\n private readonly toolApproval:\n | HarnessAgentToolApprovalConfiguration\n | undefined;\n private readonly pendingToolApprovals = new Map<\n string,\n HarnessAgentPendingToolApproval\n >();\n private sessionState: HarnessAgentSessionState = 'active';\n private turnState: HarnessAgentTurnState;\n private turnSequence = 0;\n private activeTurnSequence = 0;\n\n /**\n * Whether this session was created from `resumeFrom` or `continueFrom`.\n * Captured at construction so it survives lifecycle cleanup.\n */\n readonly isResume: boolean;\n\n constructor(options: {\n sessionId: string;\n harness: HarnessAgentAdapter;\n underlyingSession: HarnessAgentAdapterSession;\n sandboxSession: HarnessV1NetworkSandboxSession;\n sandboxProvider: HarnessV1SandboxProvider;\n leasedBridgePort?: number;\n sessionWorkDir: string;\n toolApproval: HarnessAgentToolApprovalConfiguration | undefined;\n pendingToolApprovals?: readonly HarnessAgentPendingToolApproval[];\n turnState?: HarnessAgentTurnState;\n }) {\n this.sessionId = options.sessionId;\n this.harness = options.harness;\n this.underlyingSession = options.underlyingSession;\n this.sandboxSession = options.sandboxSession;\n this.sandboxProvider = options.sandboxProvider;\n this.leasedBridgePort = options.leasedBridgePort;\n this.sessionWorkDir = options.sessionWorkDir;\n this.toolApproval = options.toolApproval;\n for (const approval of options.pendingToolApprovals ?? []) {\n this.pendingToolApprovals.set(approval.approvalId, approval);\n }\n this.turnState =\n options.turnState ??\n (this.pendingToolApprovals.size > 0 ? 'awaiting-approval' : 'idle');\n this.isResume = options.underlyingSession.isResume;\n }\n\n /**\n * Active network sandbox session.\n *\n * @internal — accessed by session turn and lifecycle drivers.\n */\n getSandboxSession(): HarnessV1NetworkSandboxSession {\n if (this.sessionState !== 'active' || this.sandboxSession == null) {\n throw new Error(\n `Harness session ${this.sessionId} has ended and cannot be reused.`,\n );\n }\n return this.sandboxSession;\n }\n\n /**\n * Working directory the agent runs in for this session. Used to strip the\n * prefix from absolute paths in stream events before they reach consumers.\n *\n * @internal — accessed by session turn drivers.\n */\n getSessionWorkDir(): string {\n return this.sessionWorkDir;\n }\n\n promptTurn<TOOLS extends ToolSet, RUNTIME_CONTEXT extends Context>(options: {\n prompt: HarnessAgentPrompt;\n instructions: string | undefined;\n tools: TOOLS;\n activeTools: ToolSet;\n toolSpecs: HarnessAgentToolSpec[];\n builtinToolFiltering: HarnessV1BuiltinToolFiltering | undefined;\n runtimeContext: RUNTIME_CONTEXT;\n abortSignal: AbortSignal | undefined;\n telemetry: TelemetryOptions | undefined;\n }): HarnessAgentTurnResult<TOOLS, RUNTIME_CONTEXT> {\n const session = this.requireReusableSession();\n this.requirePromptableTurn();\n const sandboxSession = this.getSandboxSession();\n const turnId = this.startTrackedTurn();\n try {\n const turn = runPrompt<TOOLS, RUNTIME_CONTEXT>({\n harness: this.harness,\n session,\n prompt: options.prompt,\n instructions: options.instructions,\n tools: options.tools,\n activeTools: options.activeTools,\n toolSpecs: options.toolSpecs,\n builtinToolFiltering: options.builtinToolFiltering,\n sandboxSession: sandboxSession.restricted(),\n sessionWorkDir: this.sessionWorkDir,\n runtimeContext: options.runtimeContext,\n abortSignal: options.abortSignal,\n telemetry: options.telemetry,\n toolApproval: this.toolApproval,\n pendingToolApprovals: this.getPendingToolApprovals(),\n onPendingToolApproval: approval => {\n this.pendingToolApprovals.set(approval.approvalId, approval);\n this.markAwaitingApprovalIfActive();\n },\n onToolApprovalSettled: approvalId => {\n this.pendingToolApprovals.delete(approvalId);\n },\n onTurnFinished: () => {\n this.finishTrackedTurn({ turnId });\n },\n });\n this.trackTurnCompletion({ done: turn.done, turnId });\n return turn;\n } catch (error) {\n this.finishTrackedTurn({ turnId });\n throw error;\n }\n }\n\n continueTurn<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context,\n >(options: {\n instructions: string | undefined;\n tools: TOOLS;\n activeTools: ToolSet;\n toolSpecs: HarnessAgentToolSpec[];\n builtinToolFiltering: HarnessV1BuiltinToolFiltering | undefined;\n runtimeContext: RUNTIME_CONTEXT;\n abortSignal: AbortSignal | undefined;\n telemetry: TelemetryOptions | undefined;\n toolApprovalContinuations?:\n | readonly HarnessAgentToolApprovalContinuation[]\n | undefined;\n }): HarnessAgentTurnResult<TOOLS, RUNTIME_CONTEXT> {\n const session = this.requireReusableSession();\n this.requireContinuableTurn();\n const sandboxSession = this.getSandboxSession();\n const turnId = this.startTrackedTurn();\n try {\n const turn = runPrompt<TOOLS, RUNTIME_CONTEXT>({\n harness: this.harness,\n session,\n mode: 'continue',\n instructions: options.instructions,\n tools: options.tools,\n activeTools: options.activeTools,\n toolSpecs: options.toolSpecs,\n builtinToolFiltering: options.builtinToolFiltering,\n sandboxSession: sandboxSession.restricted(),\n sessionWorkDir: this.sessionWorkDir,\n runtimeContext: options.runtimeContext,\n abortSignal: options.abortSignal,\n telemetry: options.telemetry,\n toolApproval: this.toolApproval,\n pendingToolApprovals: this.getPendingToolApprovals(),\n toolApprovalContinuations: options.toolApprovalContinuations,\n onPendingToolApproval: approval => {\n this.pendingToolApprovals.set(approval.approvalId, approval);\n this.markAwaitingApprovalIfActive();\n },\n onToolApprovalSettled: approvalId => {\n this.pendingToolApprovals.delete(approvalId);\n },\n onTurnFinished: () => {\n this.finishTrackedTurn({ turnId });\n },\n });\n this.trackTurnCompletion({ done: turn.done, turnId });\n return turn;\n } catch (error) {\n this.finishTrackedTurn({ turnId });\n throw error;\n }\n }\n\n /**\n * Ask the underlying runtime to compact its context. The runtime performs\n * the compaction itself; when it completes, a `compaction` part appears on\n * the active (or next) turn's stream. Safe to call between turns for\n * runtimes whose compaction is session-scoped (e.g. Pi).\n *\n * Throws `HarnessCapabilityUnsupportedError` for harnesses that cannot\n * trigger compaction manually (e.g. Codex, which still auto-compacts under\n * the hood). Throws if the session has ended.\n */\n async compact(customInstructions?: string): Promise<void> {\n await this.requireReusableSession().doCompact(customInstructions);\n }\n\n /**\n * Park the session, returning a payload the caller can persist and later\n * pass to `agent.createSession({ sessionId, resumeFrom })` to reconnect.\n * The runtime and sandbox keep running; this local session handle becomes\n * unusable.\n */\n async detach(): Promise<HarnessAgentResumeSessionState> {\n if (this.sessionState !== 'active' || this.underlyingSession == null) {\n throw new Error(\n `Harness session ${this.sessionId} is not active and cannot be detached.`,\n );\n }\n const session = this.underlyingSession;\n try {\n if (this.turnState !== 'idle') {\n return this.toResumeStateWithContinuation({\n continueFrom: await this.suspendCurrentTurn({ session }),\n });\n }\n const raw = await session.doDetach();\n const validated = await validateLifecycleStateData({\n harness: this.harness,\n state: raw,\n expectedType: 'resume-session',\n });\n return validated;\n } finally {\n this.endLocalHandle({\n sessionState: 'detached',\n releasePortLease: false,\n });\n }\n }\n\n /**\n * Persist enough state to resume later, then stop the runtime and sandbox.\n * Returns the resume state for a future\n * `agent.createSession({ sessionId, resumeFrom })` call.\n */\n async stop(): Promise<HarnessAgentResumeSessionState> {\n if (this.sessionState !== 'active' || this.underlyingSession == null) {\n throw new Error(\n `Harness session ${this.sessionId} is not active and cannot be stopped.`,\n );\n }\n const session = this.underlyingSession;\n const sandboxSession = this.getSandboxSession();\n try {\n if (this.turnState !== 'idle') {\n return this.toResumeStateWithContinuation({\n continueFrom: await this.suspendCurrentTurn({ session }),\n });\n }\n const raw = await session.doStop();\n const validated = await validateLifecycleStateData({\n harness: this.harness,\n state: raw,\n expectedType: 'resume-session',\n });\n return validated;\n } finally {\n this.endLocalHandle({\n sessionState: 'stopped',\n releasePortLease: true,\n });\n await Promise.resolve(sandboxSession.stop()).catch(() => {});\n }\n }\n\n /**\n * Stop the runtime and discard resumability. The sandbox is destroyed when\n * the provider supports destruction; otherwise it is stopped.\n */\n async destroy(): Promise<void> {\n if (this.sessionState !== 'active') return;\n const session = this.underlyingSession;\n const sandboxSession = this.getSandboxSession();\n this.endLocalHandle({ sessionState: 'destroyed', releasePortLease: true });\n if (session != null) {\n await Promise.resolve(session.doDestroy()).catch(() => {});\n }\n await Promise.resolve(\n sandboxSession.destroy?.() ?? sandboxSession.stop(),\n ).catch(() => {});\n }\n\n /**\n * Gracefully freeze the active turn at the slice boundary and return the\n * continuation payload, **leaving the sandbox/runtime running** so the next\n * process can continue. Resolves once the in-flight `stream()` /\n * `continueStream()` has cleanly wound down at a precise cursor (see\n * `doSuspendTurn`).\n *\n * After this call the session is detached. This in-process handle no\n * longer drives turns; a future slice creates a fresh session from the\n * returned state. The sandbox is **not** stopped and no port lease is\n * released, because bridge-backed adapters may still have a live bridge on\n * that port.\n */\n async suspendTurn(): Promise<HarnessAgentContinueTurnState> {\n if (this.sessionState !== 'active' || this.underlyingSession == null) {\n throw new Error(\n `Harness session ${this.sessionId} is not active and cannot be suspended.`,\n );\n }\n if (this.turnState === 'idle') {\n throw new Error(\n `Harness session ${this.sessionId} has no unfinished turn to suspend.`,\n );\n }\n const session = this.underlyingSession;\n try {\n return await this.suspendCurrentTurn({ session });\n } finally {\n this.endLocalHandle({\n sessionState: 'detached',\n releasePortLease: false,\n });\n }\n }\n\n private getPendingToolApprovals(): readonly HarnessAgentPendingToolApproval[] {\n return Array.from(this.pendingToolApprovals.values());\n }\n\n private addPendingToolApprovals(\n state: HarnessAgentContinueTurnState,\n ): HarnessAgentContinueTurnState {\n const pendingToolApprovals = this.getPendingToolApprovals();\n if (pendingToolApprovals.length === 0) {\n return {\n type: state.type,\n harnessId: state.harnessId,\n specificationVersion: state.specificationVersion,\n data: state.data,\n };\n }\n return {\n ...state,\n pendingToolApprovals,\n };\n }\n\n private async suspendCurrentTurn(options: {\n session: HarnessAgentAdapterSession;\n }): Promise<HarnessAgentContinueTurnState> {\n const raw = await options.session.doSuspendTurn();\n const validated = await validateLifecycleStateData({\n harness: this.harness,\n state: raw,\n expectedType: 'continue-turn',\n });\n this.turnState = 'suspended';\n return this.addPendingToolApprovals(validated);\n }\n\n private toResumeStateWithContinuation(options: {\n continueFrom: HarnessAgentContinueTurnState;\n }): HarnessAgentResumeSessionState {\n const { continueFrom } = options;\n return {\n type: 'resume-session',\n harnessId: continueFrom.harnessId,\n specificationVersion: continueFrom.specificationVersion,\n data: continueFrom.data,\n continueFrom,\n };\n }\n\n private requirePromptableTurn(): void {\n if (this.turnState === 'idle') return;\n if (this.turnState === 'running') {\n throw new Error(\n `Harness session ${this.sessionId} already has a turn in progress.`,\n );\n }\n throw new Error(\n `Harness session ${this.sessionId} has an unfinished turn and must be continued before accepting a new prompt.`,\n );\n }\n\n private requireContinuableTurn(): void {\n if (\n this.turnState === 'awaiting-approval' ||\n this.turnState === 'suspended'\n ) {\n return;\n }\n if (this.turnState === 'running') {\n throw new Error(\n `Harness session ${this.sessionId} already has a turn in progress.`,\n );\n }\n throw new Error(\n `Harness session ${this.sessionId} has no unfinished turn to continue.`,\n );\n }\n\n private markAwaitingApprovalIfActive(): void {\n if (this.sessionState === 'active') {\n this.turnState = 'awaiting-approval';\n }\n }\n\n private startTrackedTurn(): number {\n const turnId = ++this.turnSequence;\n this.activeTurnSequence = turnId;\n this.turnState = 'running';\n return turnId;\n }\n\n private trackTurnCompletion(options: {\n done: Promise<void>;\n turnId: number;\n }): void {\n void Promise.resolve(options.done)\n .finally(() => {\n this.finishTrackedTurn({ turnId: options.turnId });\n })\n .catch(() => {});\n }\n\n private finishTrackedTurn(options: { turnId: number }): void {\n if (this.sessionState !== 'active') return;\n if (this.activeTurnSequence !== options.turnId) return;\n this.turnState =\n this.pendingToolApprovals.size > 0 ? 'awaiting-approval' : 'idle';\n }\n\n private endLocalHandle(options: {\n sessionState: Exclude<HarnessAgentSessionState, 'active'>;\n releasePortLease: boolean;\n }): void {\n this.sessionState = options.sessionState;\n this.underlyingSession = undefined;\n this.sandboxSession = undefined;\n if (options.releasePortLease) {\n this.releasePortLease();\n }\n }\n\n private releasePortLease(): void {\n if (this.leasedBridgePort == null) return;\n releaseBridgePort({\n poolKey: this.sandboxProvider,\n sessionId: this.sessionId,\n });\n this.leasedBridgePort = undefined;\n }\n\n private requireReusableSession(): HarnessAgentAdapterSession {\n if (this.sessionState !== 'active' || this.underlyingSession == null) {\n throw new Error(\n `Harness session ${this.sessionId} has ended and cannot be reused.`,\n );\n }\n return this.underlyingSession;\n }\n}\n","import { HarnessError } from '../errors/harness-error';\nimport type {\n ModelMessage,\n ToolApprovalRequest,\n ToolApprovalResponse,\n} from '@ai-sdk/provider-utils';\n\nexport type HarnessAgentToolApprovalContinuation = {\n readonly approvalResponse: ToolApprovalResponse;\n readonly toolCall: {\n readonly type: 'tool-call';\n readonly toolCallId: string;\n readonly toolName: string;\n readonly input: unknown;\n readonly providerExecuted?: boolean;\n };\n};\n\n/**\n * Extract approval decisions that should continue a suspended harness turn.\n *\n * AI SDK clients send approval decisions as a trailing `role: \"tool\"` message\n * containing `tool-approval-response` parts. The response only carries the\n * approval id, so the harness has to recover the matching approval request\n * locally to find the original tool call before it can resume the paused turn.\n * Responses that already have a tool result are ignored, because those\n * approvals were already consumed by a prior continuation.\n */\nexport function collectHarnessAgentToolApprovalContinuations(input: {\n messages: readonly ModelMessage[];\n}): readonly HarnessAgentToolApprovalContinuation[] {\n const lastMessage = input.messages.at(-1);\n if (lastMessage?.role !== 'tool') return [];\n\n const toolCallsByToolCallId = new Map<\n string,\n HarnessAgentToolApprovalContinuation['toolCall']\n >();\n const approvalRequestsByApprovalId = new Map<string, ToolApprovalRequest>();\n for (const message of input.messages) {\n if (message.role !== 'assistant' || typeof message.content === 'string') {\n continue;\n }\n for (const part of message.content) {\n if (part.type === 'tool-call') {\n toolCallsByToolCallId.set(part.toolCallId, {\n type: 'tool-call',\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: part.input,\n ...(part.providerExecuted !== undefined\n ? { providerExecuted: part.providerExecuted }\n : {}),\n });\n } else if (part.type === 'tool-approval-request') {\n approvalRequestsByApprovalId.set(part.approvalId, part);\n }\n }\n }\n\n const toolResultIds = new Set<string>();\n for (const part of lastMessage.content) {\n if (part.type === 'tool-result') {\n toolResultIds.add(part.toolCallId);\n }\n }\n\n const continuations: HarnessAgentToolApprovalContinuation[] = [];\n for (const part of lastMessage.content) {\n if (part.type !== 'tool-approval-response') continue;\n\n const approvalRequest = approvalRequestsByApprovalId.get(part.approvalId);\n if (approvalRequest == null) {\n throw new HarnessError({\n message: `Tool approval response '${part.approvalId}' does not match a prior tool approval request.`,\n });\n }\n if (toolResultIds.has(approvalRequest.toolCallId)) continue;\n\n const toolCall = toolCallsByToolCallId.get(approvalRequest.toolCallId);\n if (toolCall == null) {\n throw new HarnessError({\n message: `Tool approval request '${approvalRequest.approvalId}' references unknown tool call '${approvalRequest.toolCallId}'.`,\n });\n }\n\n continuations.push({\n approvalResponse: part,\n toolCall,\n });\n }\n\n return continuations;\n}\n","import type { Experimental_SandboxSession as SandboxSession } from '@ai-sdk/provider-utils';\nimport type { HarnessV1Bootstrap } from '../../v1';\n\n/**\n * Version of the bootstrap recipe shape itself. Bump to force every existing\n * snapshot/marker to be invalidated regardless of recipe content.\n */\nexport const BOOTSTRAP_SCHEMA_VERSION = 1;\n\n/**\n * Deterministic 16-char hex identity derived from the recipe's content\n * (harnessId, bootstrapDir, file paths + contents, commands, schema version).\n * Two adapters with equivalent recipes produce the same identity; any\n * content change produces a different identity.\n *\n * Used by sandbox providers as part of the persistent sandbox name so\n * recipe changes automatically invalidate snapshots.\n */\nexport async function hashHarnessBootstrap(\n recipe: HarnessV1Bootstrap,\n): Promise<string> {\n const encoder = new TextEncoder();\n const chunks: Uint8Array[] = [];\n const pushString = (value: string) => {\n chunks.push(encoder.encode(value));\n chunks.push(encoder.encode('\\0'));\n };\n\n pushString(recipe.harnessId);\n pushString(recipe.bootstrapDir);\n\n const sortedFiles = [...recipe.files].sort((a, b) =>\n a.path.localeCompare(b.path),\n );\n for (const file of sortedFiles) {\n pushString(file.path);\n pushString(file.content);\n }\n\n pushString(JSON.stringify(recipe.commands));\n pushString(String(BOOTSTRAP_SCHEMA_VERSION));\n\n const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n const buffer = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n buffer.set(chunk, offset);\n offset += chunk.length;\n }\n\n const digest = await crypto.subtle.digest('SHA-256', buffer);\n const bytes = new Uint8Array(digest);\n let hex = '';\n for (let i = 0; i < 8; i++) {\n hex += bytes[i].toString(16).padStart(2, '0');\n }\n return hex;\n}\n\n/**\n * Absolute path of the marker file the framework writes after a recipe runs\n * successfully. Presence of this path inside the sandbox indicates the\n * recipe with the matching `identity` has already been applied.\n */\nexport function bootstrapMarkerPath(\n recipe: HarnessV1Bootstrap,\n identity: string,\n): string {\n return `${recipe.bootstrapDir}/.bootstrap-${identity}.ok`;\n}\n\n/**\n * Apply a bootstrap recipe to a sandbox session idempotently. Reads the\n * marker file; if it exists, returns immediately. Otherwise writes the\n * recipe's files, runs its commands sequentially, and writes the marker\n * on success.\n *\n * Safe to call multiple times. For sandboxes that already contain the\n * recipe (resumed from snapshot, reused across sessions, or applied by\n * an earlier process) this is a single fast read.\n */\nexport async function applyBootstrapRecipe(\n session: SandboxSession,\n recipe: HarnessV1Bootstrap,\n identity: string,\n options?: { abortSignal?: AbortSignal },\n): Promise<void> {\n const markerPath = bootstrapMarkerPath(recipe, identity);\n\n const existingMarker = await session.readTextFile({\n path: markerPath,\n abortSignal: options?.abortSignal,\n });\n if (existingMarker !== null) {\n return;\n }\n\n for (const file of recipe.files) {\n await session.writeTextFile({\n path: file.path,\n content: file.content,\n abortSignal: options?.abortSignal,\n });\n }\n\n for (const cmd of recipe.commands) {\n const result = await session.run({\n command: cmd.command,\n workingDirectory: cmd.workingDirectory,\n abortSignal: options?.abortSignal,\n });\n if (result.exitCode !== 0) {\n throw new Error(\n `Bootstrap command failed for harness '${recipe.harnessId}' (exit ${result.exitCode}): ${cmd.command}\\n${result.stderr || result.stdout}`,\n );\n }\n }\n\n await session.writeTextFile({\n path: markerPath,\n content: '',\n abortSignal: options?.abortSignal,\n });\n}\n","import { posix } from 'node:path';\nimport type { Experimental_SandboxSession as SandboxSession } from '@ai-sdk/provider-utils';\nimport type { HarnessV1Bootstrap } from '../../v1';\nimport type { HarnessAgentSandboxConfig } from '../harness-agent-settings';\nimport { applyBootstrapRecipe, hashHarnessBootstrap } from './bootstrap-recipe';\n\nconst SANDBOX_BOOTSTRAP_IDENTITY_VERSION = 1;\n\ntype SandboxBootstrapSettings = Omit<HarnessAgentSandboxConfig, 'onSession'>;\n\nexport type SandboxBootstrapPlan = {\n readonly recipe?: HarnessV1Bootstrap;\n readonly recipeIdentity?: string;\n readonly identity?: string;\n readonly workDir?: string;\n readonly onFirstCreate?: (\n session: SandboxSession,\n opts: { abortSignal?: AbortSignal },\n ) => Promise<void>;\n};\n\nexport function validateSandboxBootstrapSettings(\n settings: SandboxBootstrapSettings,\n): void {\n if ((settings.onBootstrap == null) !== (settings.bootstrapHash == null)) {\n throw new Error(\n 'HarnessAgent: `sandboxConfig.onBootstrap` and `sandboxConfig.bootstrapHash` must be provided together.',\n );\n }\n\n if (settings.workDir != null) {\n normalizeSandboxWorkDir(settings.workDir);\n }\n}\n\nexport function normalizeSandboxWorkDir(workDir: string): string {\n if (workDir.length === 0) {\n throw new Error('HarnessAgent: `sandboxConfig.workDir` must not be empty.');\n }\n if (workDir.includes('\\0')) {\n throw new Error(\n 'HarnessAgent: `sandboxConfig.workDir` must not contain NUL.',\n );\n }\n if (workDir.includes('\\\\')) {\n throw new Error(\n 'HarnessAgent: `sandboxConfig.workDir` must use POSIX path separators.',\n );\n }\n if (posix.isAbsolute(workDir)) {\n throw new Error('HarnessAgent: `sandboxConfig.workDir` must be relative.');\n }\n\n const normalized = posix.normalize(workDir);\n if (\n normalized === '.' ||\n normalized === '..' ||\n normalized.startsWith('../')\n ) {\n throw new Error(\n 'HarnessAgent: `sandboxConfig.workDir` must stay inside the sandbox default working directory.',\n );\n }\n return normalized;\n}\n\nexport function resolveSessionWorkDir({\n defaultWorkingDirectory,\n harnessId,\n sessionId,\n workDir,\n}: {\n readonly defaultWorkingDirectory: string;\n readonly harnessId: string;\n readonly sessionId: string;\n readonly workDir?: string;\n}): string {\n return joinSandboxPath({\n base: defaultWorkingDirectory,\n path: workDir ?? `${harnessId}-${sessionId}`,\n });\n}\n\nexport async function createSandboxBootstrapPlan({\n recipe,\n settings,\n}: {\n readonly recipe?: HarnessV1Bootstrap;\n readonly settings: SandboxBootstrapSettings;\n}): Promise<SandboxBootstrapPlan> {\n const workDir =\n settings.workDir == null\n ? undefined\n : normalizeSandboxWorkDir(settings.workDir);\n const recipeIdentity =\n recipe == null ? undefined : await hashHarnessBootstrap(recipe);\n const hasCallerBootstrap = settings.onBootstrap != null;\n const needsCombinedIdentity =\n hasCallerBootstrap || (recipeIdentity != null && workDir != null);\n const identity =\n needsCombinedIdentity && (recipeIdentity != null || hasCallerBootstrap)\n ? await hashSandboxBootstrapIdentity({\n recipeIdentity,\n bootstrapHash: settings.bootstrapHash,\n workDir,\n })\n : recipeIdentity;\n\n return {\n ...(recipe != null ? { recipe } : {}),\n ...(recipeIdentity != null ? { recipeIdentity } : {}),\n ...(identity != null ? { identity } : {}),\n ...(workDir != null ? { workDir } : {}),\n ...(recipe != null || settings.onBootstrap != null\n ? {\n onFirstCreate: (session, opts) =>\n runSandboxBootstrap({\n session,\n recipe,\n recipeIdentity,\n workDir,\n onBootstrap: settings.onBootstrap,\n abortSignal: opts.abortSignal,\n }),\n }\n : {}),\n };\n}\n\nexport async function runSandboxBootstrap({\n session,\n recipe,\n recipeIdentity,\n workDir,\n onBootstrap,\n abortSignal,\n}: {\n readonly session: SandboxSession;\n readonly recipe?: HarnessV1Bootstrap;\n readonly recipeIdentity?: string;\n readonly workDir?: string;\n readonly onBootstrap?: SandboxBootstrapSettings['onBootstrap'];\n readonly abortSignal?: AbortSignal;\n}): Promise<void> {\n if (recipe != null && recipeIdentity != null) {\n await applyBootstrapRecipe(session, recipe, recipeIdentity, {\n abortSignal,\n });\n }\n\n if (onBootstrap == null) return;\n\n const defaultWorkingDirectory = await resolveDefaultWorkingDirectory({\n session,\n abortSignal,\n });\n const bootstrapWorkDir =\n workDir == null\n ? defaultWorkingDirectory\n : joinSandboxPath({\n base: defaultWorkingDirectory,\n path: workDir,\n });\n\n await ensureSandboxDirectory({\n session,\n workDir: bootstrapWorkDir,\n abortSignal,\n });\n await onBootstrap({ session, workDir: bootstrapWorkDir, abortSignal });\n}\n\nexport async function resolveDefaultWorkingDirectory({\n session,\n abortSignal,\n}: {\n readonly session: SandboxSession;\n readonly abortSignal?: AbortSignal;\n}): Promise<string> {\n const result = await session.run({\n command: 'pwd',\n abortSignal,\n });\n if (result.exitCode !== 0) {\n throw new Error(\n `Failed to resolve sandbox default working directory (exit ${result.exitCode}): ${result.stderr || result.stdout}`,\n );\n }\n\n const cwd = result.stdout.trim();\n if (!posix.isAbsolute(cwd)) {\n throw new Error(\n `Failed to resolve sandbox default working directory: expected an absolute path, got ${JSON.stringify(cwd)}.`,\n );\n }\n return cwd === '/' ? cwd : cwd.replace(/\\/+$/, '');\n}\n\nexport async function ensureSandboxDirectory({\n session,\n workDir,\n abortSignal,\n}: {\n readonly session: SandboxSession;\n readonly workDir: string;\n readonly abortSignal?: AbortSignal;\n}): Promise<void> {\n const result = await session.run({\n command: 'mkdir -p \"$WORK_DIR\"',\n env: { WORK_DIR: workDir },\n abortSignal,\n });\n if (result.exitCode !== 0) {\n throw new Error(\n `Failed to create sandbox work directory ${workDir} (exit ${result.exitCode}): ${result.stderr || result.stdout}`,\n );\n }\n}\n\nasync function hashSandboxBootstrapIdentity({\n recipeIdentity,\n bootstrapHash,\n workDir,\n}: {\n readonly recipeIdentity?: string;\n readonly bootstrapHash?: string;\n readonly workDir?: string;\n}): Promise<string> {\n const encoder = new TextEncoder();\n const chunks: Uint8Array[] = [];\n const pushString = (value: string) => {\n chunks.push(encoder.encode(value));\n chunks.push(encoder.encode('\\0'));\n };\n\n pushString(String(SANDBOX_BOOTSTRAP_IDENTITY_VERSION));\n pushString(recipeIdentity ?? '');\n pushString(bootstrapHash ?? '');\n pushString(workDir ?? '');\n\n const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n const buffer = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n buffer.set(chunk, offset);\n offset += chunk.length;\n }\n\n const digest = await crypto.subtle.digest('SHA-256', buffer);\n const bytes = new Uint8Array(digest);\n let hex = '';\n for (let i = 0; i < 8; i++) {\n hex += bytes[i].toString(16).padStart(2, '0');\n }\n return hex;\n}\n\nfunction joinSandboxPath({\n base,\n path,\n}: {\n readonly base: string;\n readonly path: string;\n}): string {\n return posix.join(base, path);\n}\n","import { asArray } from '@ai-sdk/provider-utils';\nimport type { Telemetry } from 'ai';\nimport type { HarnessV1Diagnostic, HarnessV1Observability } from '../../v1';\nimport type {\n HarnessDebugConfig,\n HarnessDebugLevel,\n HarnessDiagnostic,\n HarnessDiagnosticConsumer,\n} from '../observability/types';\nimport type { HarnessAgentSettings } from '../harness-agent-settings';\n\nconst ENV_TRUTHY = new Set(['1', 'true', 'yes', 'on']);\n\nfunction parseList(value: string | undefined): string[] | undefined {\n if (!value) return undefined;\n const items = value\n .split(',')\n .map(item => item.trim())\n .filter(Boolean);\n return items.length > 0 ? items : undefined;\n}\n\n/**\n * Resolve the effective debug config from explicit settings with env-var\n * fallbacks. `HARNESS_DEBUG*` only fill fields the consumer left unset — code is\n * always authoritative.\n */\nexport function resolveDebugConfig(\n debug: HarnessDebugConfig | undefined,\n env: Record<string, string | undefined> = process.env,\n): {\n enabled: boolean;\n level: HarnessDebugLevel;\n subsystems: string[] | undefined;\n} {\n const enabled =\n debug?.enabled ?? ENV_TRUTHY.has((env.HARNESS_DEBUG ?? '').toLowerCase());\n const level =\n debug?.level ??\n (env.HARNESS_DEBUG_LEVEL as HarnessDebugLevel | undefined) ??\n 'debug';\n const subsystems = debug?.subsystems\n ? [...debug.subsystems]\n : parseList(env.HARNESS_DEBUG_SUBSYSTEMS);\n return { enabled, level, subsystems };\n}\n\n/**\n * Map an adapter-emitted `HarnessV1Diagnostic` to the host-facing\n * `HarnessDiagnostic` (the external/telemetry surface). Identity-shaped today,\n * but an explicit boundary so the emission and consumption types can diverge.\n */\nfunction toHarnessDiagnostic(d: HarnessV1Diagnostic): HarnessDiagnostic {\n return {\n level: d.level,\n message: d.message,\n subsystem: d.subsystem,\n kind: d.kind,\n source: d.source,\n stream: d.stream,\n attrs: d.attrs,\n error: d.error,\n sessionId: d.sessionId,\n timestamp: d.timestamp,\n };\n}\n\nfunction formatForStderr(d: HarnessDiagnostic): string {\n const parts = [`[harness:${d.level}]`, d.subsystem, d.message].filter(\n Boolean,\n );\n let line = parts.join(' ');\n if (d.error) {\n line += ` (${d.error.name ?? 'Error'}: ${d.error.message})`;\n }\n return `${line}\\n`;\n}\n\n/**\n * Build the per-session observability handle the framework hands to `doStart`.\n * Returns `undefined` when diagnostics are disabled. When enabled, the `report`\n * sink maps each adapter-emitted `HarnessV1Diagnostic` to the host\n * `HarnessDiagnostic` and fans it out, non-lossy, to: the `HARNESS_DEBUG` stderr\n * default, the consumer's `onLog`, and any telemetry integration that\n * implements `ingestDiagnostic`. Adapters normalize their own source (bridge\n * wire frames, host logs) into `HarnessV1Diagnostic` before calling `report`.\n */\nexport function buildObservability(options: {\n settings: Pick<\n HarnessAgentSettings<any, any>,\n 'debug' | 'onLog' | 'telemetry'\n >;\n}): HarnessV1Observability | undefined {\n const resolved = resolveDebugConfig(options.settings.debug);\n if (!resolved.enabled) return undefined;\n\n const onLog = options.settings.onLog;\n const integrations = options.settings.telemetry?.integrations\n ? asArray(options.settings.telemetry.integrations)\n : [];\n const diagnosticConsumers = integrations.filter(\n (integration): integration is Telemetry & HarnessDiagnosticConsumer =>\n typeof (integration as HarnessDiagnosticConsumer).ingestDiagnostic ===\n 'function',\n );\n\n const report = (emitted: HarnessV1Diagnostic): void => {\n const diagnostic = toHarnessDiagnostic(emitted);\n try {\n process.stderr.write(formatForStderr(diagnostic));\n } catch {\n // Never let the stderr default break the turn.\n }\n onLog?.(diagnostic);\n for (const consumer of diagnosticConsumers) {\n consumer.ingestDiagnostic?.(diagnostic);\n }\n };\n\n return {\n debug: {\n enabled: true,\n level: resolved.level,\n ...(resolved.subsystems ? { subsystems: resolved.subsystems } : {}),\n },\n report,\n };\n}\n","import { HarnessCapabilityUnsupportedError } from '../../errors/harness-capability-unsupported-error';\nimport type { HarnessV1, HarnessV1BuiltinToolFiltering } from '../../v1';\nimport { NoSuchToolError, type ActiveTools } from 'ai';\nimport type { ToolSet } from '@ai-sdk/provider-utils';\n\nexport type ResolvedHarnessAgentToolFiltering<TUserTools extends ToolSet> = {\n readonly activeUserTools: TUserTools;\n readonly builtinToolFiltering?: HarnessV1BuiltinToolFiltering;\n};\n\nexport function resolveHarnessAgentToolFiltering<\n TAllTools extends ToolSet,\n TUserTools extends ToolSet,\n>(input: {\n harness: HarnessV1;\n userTools: TUserTools;\n allTools: TAllTools;\n activeTools: ActiveTools<TAllTools>;\n inactiveTools: ActiveTools<TAllTools>;\n}): ResolvedHarnessAgentToolFiltering<TUserTools> {\n if (input.activeTools !== undefined && input.inactiveTools !== undefined) {\n throw new Error(\n 'HarnessAgent: pass either `activeTools` or `inactiveTools`, not both.',\n );\n }\n\n const allToolNames = Object.keys(input.allTools);\n const activeTools = dedupeToolNames({ toolNames: input.activeTools });\n const inactiveTools = dedupeToolNames({ toolNames: input.inactiveTools });\n validateToolNames({\n requestedToolNames: activeTools ?? inactiveTools,\n availableToolNames: allToolNames,\n });\n\n const userToolNames = Object.keys(input.userTools);\n const activeUserToolNames =\n activeTools != null\n ? userToolNames.filter(name => activeTools.includes(name))\n : inactiveTools != null\n ? userToolNames.filter(name => !inactiveTools.includes(name))\n : userToolNames;\n\n const builtinToolNames = Object.keys(input.harness.builtinTools);\n const disabledBuiltinToolNames =\n activeTools != null\n ? builtinToolNames.filter(name => !activeTools.includes(name))\n : inactiveTools != null\n ? builtinToolNames.filter(name => inactiveTools.includes(name))\n : [];\n\n const builtinToolFiltering =\n disabledBuiltinToolNames.length > 0\n ? activeTools != null\n ? {\n mode: 'allow' as const,\n toolNames: builtinToolNames.filter(name =>\n activeTools.includes(name),\n ),\n }\n : { mode: 'deny' as const, toolNames: disabledBuiltinToolNames }\n : undefined;\n\n if (\n builtinToolFiltering != null &&\n input.harness.supportsBuiltinToolFiltering !== true &&\n input.harness.supportsBuiltinToolApprovals !== true\n ) {\n throw new HarnessCapabilityUnsupportedError({\n message: `Harness '${input.harness.harnessId}' does not support built-in tool filtering controls.`,\n harnessId: input.harness.harnessId,\n });\n }\n\n return {\n activeUserTools: filterToolSet({\n tools: input.userTools,\n toolNames: activeUserToolNames,\n }),\n ...(builtinToolFiltering != null ? { builtinToolFiltering } : {}),\n };\n}\n\nfunction dedupeToolNames(input: {\n toolNames: ReadonlyArray<string> | undefined;\n}): ReadonlyArray<string> | undefined {\n return input.toolNames == null\n ? undefined\n : Array.from(new Set(input.toolNames));\n}\n\nfunction validateToolNames(input: {\n requestedToolNames: ReadonlyArray<string> | undefined;\n availableToolNames: ReadonlyArray<string>;\n}): void {\n if (input.requestedToolNames == null) return;\n for (const toolName of input.requestedToolNames) {\n if (!input.availableToolNames.includes(toolName)) {\n throw new NoSuchToolError({\n toolName,\n availableTools: [...input.availableToolNames],\n });\n }\n }\n}\n\nfunction filterToolSet<TUserTools extends ToolSet>(input: {\n tools: TUserTools;\n toolNames: ReadonlyArray<string>;\n}): TUserTools {\n const allowed = new Set(input.toolNames);\n return Object.fromEntries(\n Object.entries(input.tools).filter(([name]) => allowed.has(name)),\n ) as TUserTools;\n}\n","import type { HarnessV1SandboxProvider } from '../v1';\nimport type { HarnessAgentAdapter } from './harness-agent-types';\nimport type { HarnessAgentSandboxConfig } from './harness-agent-settings';\nimport { applyBootstrapRecipe } from './internal/bootstrap-recipe';\nimport {\n createSandboxBootstrapPlan,\n validateSandboxBootstrapSettings,\n} from './internal/sandbox-bootstrap';\n\ntype SandboxBootstrapSettings = Omit<HarnessAgentSandboxConfig, 'onSession'>;\n\n/**\n * Prepare a harness's sandbox template without running an agent. Idempotent: if\n * the template already exists (snapshot present, or marker on a non-snapshot\n * provider), this resolves quickly.\n *\n * Use from a CI/deploy script to amortize the first-session cost so production\n * sessions always resume from snapshot. For adapters without a bootstrap\n * recipe (no `getBootstrap`) this is a no-op.\n *\n * The temporary network sandbox session created during preparation is stopped\n * before the function resolves; the snapshot/template state persists in the\n * provider's native storage (for Vercel: as the `currentSnapshotId` of the\n * named template sandbox).\n */\nexport async function prepareHarnessSandboxTemplate(options: {\n readonly harness: HarnessAgentAdapter;\n readonly sandboxProvider: HarnessV1SandboxProvider;\n readonly sandboxConfig?: SandboxBootstrapSettings;\n readonly abortSignal?: AbortSignal;\n}): Promise<void> {\n const sandboxConfig = options.sandboxConfig ?? {};\n validateSandboxBootstrapSettings(sandboxConfig);\n const recipe = await options.harness.getBootstrap?.({\n abortSignal: options.abortSignal,\n });\n const bootstrapPlan = await createSandboxBootstrapPlan({\n recipe,\n settings: sandboxConfig,\n });\n if (bootstrapPlan.identity == null || bootstrapPlan.onFirstCreate == null) {\n return;\n }\n\n const sandboxSession = await options.sandboxProvider.createSession({\n abortSignal: options.abortSignal,\n identity: bootstrapPlan.identity,\n onFirstCreate: bootstrapPlan.onFirstCreate,\n });\n\n try {\n if (bootstrapPlan.recipe != null && bootstrapPlan.recipeIdentity != null) {\n await applyBootstrapRecipe(\n sandboxSession.restricted(),\n bootstrapPlan.recipe,\n bootstrapPlan.recipeIdentity,\n {\n abortSignal: options.abortSignal,\n },\n );\n }\n } finally {\n await Promise.resolve(sandboxSession.stop()).catch(() => {});\n }\n}\n\n/** @deprecated Use `prepareHarnessSandboxTemplate` instead. */\nexport const prewarmHarness = prepareHarnessSandboxTemplate;\n","import type { Experimental_SandboxSession as SandboxSession } from '@ai-sdk/provider-utils';\nimport type { HarnessAgentSandboxConfig } from './harness-agent-settings';\nimport type { HarnessAgentAdapter } from './harness-agent-types';\nimport {\n applyBootstrapRecipe,\n hashHarnessBootstrap,\n} from './internal/bootstrap-recipe';\nimport {\n normalizeSandboxWorkDir,\n runSandboxBootstrap,\n validateSandboxBootstrapSettings,\n} from './internal/sandbox-bootstrap';\n\nconst PREPARED_SANDBOX_IDENTITY_VERSION = 1;\n\nexport type PrepareSandboxForHarnessResult = {\n readonly identity?: string;\n readonly recipeIdentities: Record<string, string>;\n readonly skippedHarnessIds: ReadonlyArray<string>;\n};\n\nexport async function prepareSandboxForHarness(options: {\n readonly session: SandboxSession;\n readonly harnesses: ReadonlyArray<HarnessAgentAdapter>;\n readonly sandboxConfig?: HarnessAgentSandboxConfig;\n readonly abortSignal?: AbortSignal;\n}): Promise<PrepareSandboxForHarnessResult> {\n const sandboxConfig = options.sandboxConfig ?? {};\n validateSandboxBootstrapSettings(sandboxConfig);\n\n if (options.harnesses.length === 0) {\n throw new Error(\n 'prepareSandboxForHarness: at least one harness must be provided.',\n );\n }\n\n const harnesses = [...options.harnesses].sort((a, b) =>\n a.harnessId.localeCompare(b.harnessId),\n );\n assertUniqueHarnessIds(harnesses);\n\n const workDir =\n sandboxConfig.workDir == null\n ? undefined\n : normalizeSandboxWorkDir(sandboxConfig.workDir);\n const recipeIdentities: Record<string, string> = {};\n const skippedHarnessIds: string[] = [];\n\n for (const harness of harnesses) {\n const recipe = await harness.getBootstrap?.({\n abortSignal: options.abortSignal,\n });\n if (recipe == null) {\n skippedHarnessIds.push(harness.harnessId);\n continue;\n }\n\n const recipeIdentity = await hashHarnessBootstrap(recipe);\n recipeIdentities[harness.harnessId] = recipeIdentity;\n await applyBootstrapRecipe(options.session, recipe, recipeIdentity, {\n abortSignal: options.abortSignal,\n });\n }\n\n if (sandboxConfig.onBootstrap != null) {\n await runSandboxBootstrap({\n session: options.session,\n workDir,\n onBootstrap: sandboxConfig.onBootstrap,\n abortSignal: options.abortSignal,\n });\n }\n\n const identity = await resolvePreparedSandboxIdentity({\n recipeIdentities,\n bootstrapHash: sandboxConfig.bootstrapHash,\n workDir,\n });\n\n return {\n ...(identity != null ? { identity } : {}),\n recipeIdentities,\n skippedHarnessIds,\n };\n}\n\nfunction assertUniqueHarnessIds(\n harnesses: ReadonlyArray<HarnessAgentAdapter>,\n): void {\n const seen = new Set<string>();\n for (const harness of harnesses) {\n if (seen.has(harness.harnessId)) {\n throw new Error(\n `prepareSandboxForHarness: duplicate harness id \"${harness.harnessId}\".`,\n );\n }\n seen.add(harness.harnessId);\n }\n}\n\nasync function resolvePreparedSandboxIdentity({\n recipeIdentities,\n bootstrapHash,\n workDir,\n}: {\n readonly recipeIdentities: Record<string, string>;\n readonly bootstrapHash?: string;\n readonly workDir?: string;\n}): Promise<string | undefined> {\n const entries = Object.entries(recipeIdentities).sort(([a], [b]) =>\n a.localeCompare(b),\n );\n if (entries.length === 0 && bootstrapHash == null) {\n return undefined;\n }\n\n const encoder = new TextEncoder();\n const chunks: Uint8Array[] = [];\n const pushString = (value: string) => {\n chunks.push(encoder.encode(value));\n chunks.push(encoder.encode('\\0'));\n };\n\n pushString(String(PREPARED_SANDBOX_IDENTITY_VERSION));\n pushString(workDir ?? '');\n pushString(bootstrapHash ?? '');\n\n for (const [harnessId, identity] of entries) {\n pushString(harnessId);\n pushString(identity);\n }\n\n const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n const buffer = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n buffer.set(chunk, offset);\n offset += chunk.length;\n }\n\n const digest = await crypto.subtle.digest('SHA-256', buffer);\n const bytes = new Uint8Array(digest);\n let hex = '';\n for (let i = 0; i < 8; i++) {\n hex += bytes[i].toString(16).padStart(2, '0');\n }\n return hex;\n}\n","import { appendFileSync, mkdirSync } from 'node:fs';\nimport type { Telemetry } from 'ai';\nimport type { HarnessDiagnostic, HarnessDiagnosticConsumer } from './types';\n\n/**\n * A harness observability reporter that writes a unified, non-lossy\n * `events.jsonl` containing **both** the telemetry span lifecycle (turn / step\n * / tool) **and** the forwarded bridge diagnostics (console lines + structured\n * events). It is a single object registered in `telemetry.integrations`: the\n * framework drives its `Telemetry` methods for spans and calls\n * `ingestDiagnostic` for diagnostics.\n *\n * No external collector or OTel setup required — this is the AI-SDK-idiomatic\n * replacement for the original SDK's host-side artifact files.\n */\nexport interface FileReporterOptions {\n /** Directory for `events.jsonl` (created if absent). */\n dir: string;\n /**\n * Buffer a turn's records in memory and write them only if the turn produced\n * an error (an `error`-level diagnostic, a failed tool, or an error finish).\n * Default false (write everything).\n */\n failOnly?: boolean;\n /** File name within `dir`. Default `events.jsonl`. */\n fileName?: string;\n}\n\ntype Record_ = { ts: number } & Record<string, unknown>;\n\nexport type FileReporter = Telemetry & HarnessDiagnosticConsumer;\n\nexport function createFileReporter(options: FileReporterOptions): FileReporter {\n const fileName = options.fileName ?? 'events.jsonl';\n const path = `${options.dir}/${fileName}`;\n const failOnly = options.failOnly ?? false;\n\n // Per-turn buffers, keyed by the telemetry callId. Diagnostics (which carry a\n // sessionId, not a callId) attach to the most recently started, open turn.\n const turns = new Map<string, { lines: Record_[]; errored: boolean }>();\n let lastOpenCallId: string | undefined;\n let dirReady = false;\n\n const bucketFor = (callId: string) => {\n let bucket = turns.get(callId);\n if (!bucket) {\n bucket = { lines: [], errored: false };\n turns.set(callId, bucket);\n }\n return bucket;\n };\n\n const record = (callId: string | undefined, rec: Record_): void => {\n const id = callId ?? lastOpenCallId;\n if (id == null) {\n // No active turn — write standalone (best-effort).\n flushLines([rec]);\n return;\n }\n bucketFor(id).lines.push(rec);\n };\n\n const flushLines = (lines: Record_[]): void => {\n if (lines.length === 0) return;\n try {\n if (!dirReady) {\n mkdirSync(options.dir, { recursive: true });\n dirReady = true;\n }\n appendFileSync(path, lines.map(l => JSON.stringify(l)).join('\\n') + '\\n');\n } catch {\n // Best-effort: never let observability break a turn.\n }\n };\n\n const finishTurn = (callId: string): void => {\n const bucket = turns.get(callId);\n if (!bucket) return;\n turns.delete(callId);\n if (lastOpenCallId === callId) lastOpenCallId = undefined;\n if (failOnly && !bucket.errored) return;\n flushLines(bucket.lines);\n };\n\n return {\n onStart(event) {\n const e = event as {\n callId: string;\n operationId?: string;\n modelId?: string;\n provider?: string;\n messages?: unknown;\n instructions?: unknown;\n recordInputs?: boolean;\n };\n lastOpenCallId = e.callId;\n record(e.callId, {\n ts: Date.now(),\n kind: 'turn-start',\n callId: e.callId,\n operationId: e.operationId,\n provider: e.provider,\n modelId: e.modelId,\n // Input prompt, unless the consumer opted out via `recordInputs: false`.\n ...(e.recordInputs === false\n ? {}\n : { input: { messages: e.messages, instructions: e.instructions } }),\n });\n },\n onStepStart(event) {\n const e = event as { callId: string; stepNumber?: number };\n record(e.callId, {\n ts: Date.now(),\n kind: 'step-start',\n callId: e.callId,\n step: e.stepNumber,\n });\n },\n onToolExecutionStart(event) {\n const e = event as {\n callId: string;\n toolCall: { toolName: string; toolCallId: string; input: unknown };\n };\n record(e.callId, {\n ts: Date.now(),\n kind: 'tool-start',\n callId: e.callId,\n toolName: e.toolCall.toolName,\n toolCallId: e.toolCall.toolCallId,\n input: e.toolCall.input,\n });\n },\n onToolExecutionEnd(event) {\n const e = event as {\n callId: string;\n toolCall: { toolCallId: string };\n toolOutput: { type: string; output?: unknown; error?: unknown };\n };\n const isError = e.toolOutput.type === 'error';\n if (isError) bucketFor(e.callId).errored = true;\n record(e.callId, {\n ts: Date.now(),\n kind: 'tool-end',\n callId: e.callId,\n toolCallId: e.toolCall.toolCallId,\n isError,\n output: isError ? e.toolOutput.error : e.toolOutput.output,\n });\n },\n onStepFinish(event) {\n const e = event as {\n callId: string;\n usage?: unknown;\n content?: unknown[];\n recordOutputs?: boolean;\n };\n record(e.callId, {\n ts: Date.now(),\n kind: 'step-finish',\n callId: e.callId,\n usage: e.usage,\n // The model's output content, unless `recordOutputs: false`.\n ...(e.recordOutputs === false || e.content == null\n ? {}\n : { output: e.content }),\n });\n },\n onEnd(event) {\n const e = event as {\n callId: string;\n finishReason?: unknown;\n usage?: unknown;\n totalUsage?: unknown;\n };\n record(e.callId, {\n ts: Date.now(),\n kind: 'turn-finish',\n callId: e.callId,\n finishReason: e.finishReason,\n usage: e.totalUsage ?? e.usage,\n });\n finishTurn(e.callId);\n },\n onError(error) {\n if (lastOpenCallId != null) bucketFor(lastOpenCallId).errored = true;\n record(lastOpenCallId, {\n ts: Date.now(),\n kind: 'error',\n error:\n error instanceof Error\n ? { name: error.name, message: error.message }\n : error,\n });\n },\n ingestDiagnostic(diagnostic: HarnessDiagnostic) {\n if (diagnostic.level === 'error' && lastOpenCallId != null) {\n bucketFor(lastOpenCallId).errored = true;\n }\n record(lastOpenCallId, {\n ts: diagnostic.timestamp,\n kind: 'diagnostic',\n diagnostic,\n });\n },\n };\n}\n","import type { Telemetry } from 'ai';\n\n/**\n * A harness observability reporter that renders an ASCII trace tree of a\n * turn's span lifecycle (turn → steps → tools) to a stream at turn end. It is a\n * `Telemetry` integration — register it in `telemetry.integrations`. Useful for\n * zero-setup local debugging when no OTel collector is wired up; a real OTel\n * backend (via `@ai-sdk/otel`) is a strict superset.\n */\nexport interface TraceTreeReporterOptions {\n /** Where to write the rendered tree. Default `process.stderr.write`. */\n write?: (chunk: string) => void;\n}\n\ntype Node = {\n label: string;\n startMs: number;\n endMs?: number;\n children: Node[];\n};\n\nexport function createTraceTreeReporter(\n options: TraceTreeReporterOptions = {},\n): Telemetry {\n const write =\n options.write ?? ((chunk: string) => void process.stderr.write(chunk));\n\n type TurnState = {\n root: Node;\n step?: Node;\n tools: Map<string, Node>;\n };\n const turns = new Map<string, TurnState>();\n\n const render = (node: Node, depth: number): string => {\n const indent = ' '.repeat(depth);\n const dur =\n node.endMs != null\n ? `${Math.max(0, Math.round(node.endMs - node.startMs))}ms`\n : '(open)';\n let out = `${indent}- ${node.label} ${dur}\\n`;\n for (const child of node.children) out += render(child, depth + 1);\n return out;\n };\n\n return {\n onStart(event) {\n const e = event as {\n callId: string;\n operationId?: string;\n modelId?: string;\n };\n turns.set(e.callId, {\n root: {\n label: `${e.operationId ?? 'turn'}${e.modelId ? ` ${e.modelId}` : ''}`,\n startMs: Date.now(),\n children: [],\n },\n tools: new Map(),\n });\n },\n onStepStart(event) {\n const e = event as { callId: string; stepNumber?: number };\n const turn = turns.get(e.callId);\n if (!turn) return;\n const step: Node = {\n label: `step ${(e.stepNumber ?? turn.root.children.length) + 1}`,\n startMs: Date.now(),\n children: [],\n };\n turn.step = step;\n turn.root.children.push(step);\n },\n onToolExecutionStart(event) {\n const e = event as {\n callId: string;\n toolCall: { toolName: string; toolCallId: string };\n };\n const turn = turns.get(e.callId);\n const parent = turn?.step ?? turn?.root;\n if (!turn || !parent) return;\n const node: Node = {\n label: `tool ${e.toolCall.toolName}`,\n startMs: Date.now(),\n children: [],\n };\n turn.tools.set(e.toolCall.toolCallId, node);\n parent.children.push(node);\n },\n onToolExecutionEnd(event) {\n const e = event as {\n callId: string;\n toolCall: { toolCallId: string };\n toolOutput: { type: string };\n };\n const node = turns.get(e.callId)?.tools.get(e.toolCall.toolCallId);\n if (!node) return;\n node.endMs = Date.now();\n if (e.toolOutput.type === 'error') node.label += ' [error]';\n },\n onStepFinish(event) {\n const e = event as { callId: string };\n const turn = turns.get(e.callId);\n if (turn?.step) {\n turn.step.endMs = Date.now();\n turn.step = undefined;\n }\n },\n onEnd(event) {\n const e = event as { callId: string };\n const turn = turns.get(e.callId);\n if (!turn) return;\n turn.root.endMs = Date.now();\n turns.delete(e.callId);\n try {\n write(`\\n${render(turn.root, 0)}`);\n } catch {\n // Never let rendering break the turn.\n }\n },\n };\n}\n"],"mappings":";AAAA,SAAS,cAAAA,mBAAkB;;;ACA3B,SAAS,kBAAkB;AAE3B,IAAM,OAAO;AACb,IAAM,SAAS,mBAAmB,IAAI;AACtC,IAAM,SAAS,OAAO,IAAI,MAAM;AAJhC;AAWO,IAAM,eAAN,eAA2B,iBACd,aADc,IAAW;AAAA,EAG3C,YAAY,EAAE,SAAS,MAAM,GAAyC;AACpE,UAAM,EAAE,MAAM,SAAS,MAAM,CAAC;AAHhC,SAAkB,MAAU;AAAA,EAI5B;AAAA,EAEA,OAAO,WAAW,OAAuC;AACvD,WAAO,WAAW,UAAU,OAAO,MAAM;AAAA,EAC3C;AACF;;;ADlBA,IAAMC,QAAO;AACb,IAAMC,UAAS,mBAAmBD,KAAI;AACtC,IAAME,UAAS,OAAO,IAAID,OAAM;AALhC,IAAAE,KAAAC;AAgBO,IAAM,oCAAN,eAAgDA,MAAA,cACnCD,MAAAD,SADmCE,KAAa;AAAA,EAKlE,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Q,KAAK,IAAI;AAC3B,aAAK,OAAO;AAAA,MACd;AAAA,IACF;AAAA,IACA,MAAM,OAAO;AACX,YAAM,IAAI;AACV,YAAM,OAAO,MAAM,IAAI,EAAE,MAAM;AAC/B,UAAI,CAAC,KAAM;AACX,WAAK,KAAK,QAAQ,KAAK,IAAI;AAC3B,YAAM,OAAO,EAAE,MAAM;AACrB,UAAI;AACF,cAAM;AAAA,EAAK,OAAO,KAAK,MAAM,CAAC,CAAC,EAAE;AAAA,MACnC,SAAQC,IAAA;AAAA,MAER;AAAA,IACF;AAAA,EACF;AACF;","names":["AISDKError","name","marker","symbol","_a","_b","AISDKError","generateId","generateId","generateId","generateId","_a","_b","_a","_a","_b","_c","_d","input","done","generateId","_a","_b","_a","_b","name","_a","generateId","name","_a","_b","_a","_b","_a","_b","_a","e"]}