UNPKG

@tanstack/ai-sandbox

Version:

Provider-agnostic sandbox layer for TanStack AI — run harness adapters inside isolated sandboxes (defineSandbox, defineWorkspace, withSandbox) with a uniform SandboxHandle, workspace bootstrap, policy, and resumable lifecycle.

165 lines (164 loc) • 6.23 kB
import { EventType, sandboxApprovalActivity, withTanstackMetadata } from "@tanstack/ai"; import { evaluateCommand } from "./policy.js"; // src/approvals.ts /** * Shared interactive-approval logic for harness adapters. * * Flow (rides chat()'s existing resume-based approval mechanism): * 1. The agent (inside the sandbox) asks to run a risky action; the harness's * host-side permission callback fires. * 2. `resolveApproval` evaluates the sandbox policy: `allow`/`deny` are final; * `ask` consults the client's approval decisions (threaded via * `TextOptions.approvals`, keyed by a stable `approvalId`). * 3. On `ask` with no decision yet, the adapter emits an `approval-requested` * CUSTOM event (carrying the `approvalId`) and a `sandbox.approval` * activity row with status `pending`, and denies the action this turn. * The client shows UI, then re-runs chat() with the decision in the message; * the engine surfaces it as `approvals`, and the next run allows it. At the * start of that run, the adapter sets the row to `granted` or `denied`. * * `approvalId` is stable for a given (provider, kind, target) so a client grant * matches the same action on the resumed run. */ /** What a harness agent gets for a run that only answers approvals. */ var APPROVAL_CONTINUATION_PROMPT = "The user answered your approval requests. Continue the task."; /** * The messages for the prompt of a harness adapter. `respondToSandboxApproval` * starts a run with no new user message, and a harness prompt needs one. So * when the last message is not from the user and `approvals` has a decision, * this adds a user message that tells the agent to continue. Otherwise it * returns `messages`. */ function withApprovalContinuation(messages, approvals) { if (approvals === void 0 || approvals.size === 0) return messages; if (messages.at(-1)?.role === "user") return messages; return [...messages, { role: "user", content: APPROVAL_CONTINUATION_PROMPT }]; } /** * CUSTOM event name emitted when a harness action needs client approval. * * @deprecated Read the `sandbox.approval` activity row instead * (`buildApprovalActivity`). The event is still sent, and a later breaking * release removes it. */ var APPROVAL_REQUESTED_EVENT = "approval-requested"; /** A stable, opaque approval id for a harness action. */ function approvalId(input) { return `${input.provider}:${input.kind}:${input.target}`; } /** Resolve a harness permission request against policy + client approvals. */ function resolveApproval(input) { const base = input.command !== void 0 ? evaluateCommand(input.command, input.policy, input.scripts) : input.capability !== void 0 ? input.policy?.capabilities?.[input.capability] ?? input.policy?.default ?? "ask" : input.policy?.default ?? "ask"; if (base === "allow") return { decision: "allow", needsApproval: false }; if (base === "deny") return { decision: "deny", needsApproval: false }; const granted = input.approvals?.get(input.id); if (granted === true) return { decision: "allow", needsApproval: false }; if (granted === false) return { decision: "deny", needsApproval: false }; return { decision: "deny", needsApproval: true }; } /** Build the AG-UI `approval-requested` CUSTOM event for a harness action. */ function buildApprovalRequestedEvent(input) { return withTanstackMetadata({ type: EventType.CUSTOM, name: APPROVAL_REQUESTED_EVENT, value: { approvalId: input.approvalId, title: input.title, ...input.detail ?? {} }, timestamp: Date.now() }, { threadId: input.threadId, runId: input.runId }); } /** The id of the `sandbox.approval` activity row of an approval. */ function approvalActivityId(id) { return `sandbox.approval:${id}`; } /** * Emit the pending `sandbox.approval` row and the deprecated * `approval-requested` event on a live bridge channel. Call this from a * permission callback so a crash or takeover still journals the row. */ function emitPendingApproval(channel, input) { channel.emitCustomEvent(APPROVAL_REQUESTED_EVENT, { approvalId: input.approvalId, title: input.title, ...input.detail ?? {} }); channel.emitActivity(sandboxApprovalActivity, approvalActivityId(input.approvalId), { approvalId: input.approvalId, title: input.title, status: "pending", ...input.detail !== void 0 && { detail: input.detail } }); } /** * Build the `sandbox.approval` activity row for a harness action that waits * for a client decision. The status is `pending`. The row id is * `sandbox.approval:<approvalId>`, so a later run updates the same row. * * A harness adapter yields it right after the `approval-requested` event, * with the same input. */ function buildApprovalActivity(input) { return withTanstackMetadata(sandboxApprovalActivity.snapshot(approvalActivityId(input.approvalId), { approvalId: input.approvalId, title: input.title, status: "pending", ...input.detail !== void 0 && { detail: input.detail } }), { threadId: input.threadId, runId: input.runId }); } /** * Build one `ACTIVITY_DELTA` for each client decision of this provider. Each * delta sets the `status` of the `sandbox.approval:<approvalId>` row to * `granted` or `denied`. * * `approvals` holds every approval decision of the run, also the decisions * of normal tool calls. Only the ids that start with `<provider>:` (see * {@link approvalId}) make a delta. A harness adapter yields these right * after its `RUN_STARTED`. */ function approvalDecisionActivities(approvals, meta) { return [...approvals ?? []].filter(([id]) => id.startsWith(`${meta.provider}:`)).map(([id, granted]) => { const delta = { type: EventType.ACTIVITY_DELTA, messageId: approvalActivityId(id), activityType: sandboxApprovalActivity.activityType, patch: [{ op: "replace", path: "/status", value: granted ? "granted" : "denied" }], timestamp: Date.now() }; return withTanstackMetadata(delta, { threadId: meta.threadId, runId: meta.runId }); }); } export { APPROVAL_REQUESTED_EVENT, approvalDecisionActivities, approvalId, buildApprovalActivity, buildApprovalRequestedEvent, emitPendingApproval, resolveApproval, withApprovalContinuation }; //# sourceMappingURL=approvals.js.map