Skip to content

An open-source, faster Devin alternative

TypeScript

agents: carry the sender's identity into a channel turn, and add tools whose write waits for a person

Brian Reardondcd863adb8b6
diff --git a/.agents/design/channel-approvals.md b/.agents/design/channel-approvals.md
new file mode 100644
index 00000000..e2f71b0a
--- /dev/null
+++ b/.agents/design/channel-approvals.md
@@ -0,0 +1,287 @@
+# Channel approvals
+
+A human clicks Approve in Slack before an agent's write lands. The click is
+answered by the platform, the write runs once, deterministically, from the
+arguments the human was shown — not from a second pass through the model.
+
+Slack only, in v1. Buttons are the reason.
+
+## Why: nothing a click sends can reach us
+
+Every agent that touches money or production converges on the same shape.
+Autumn's `leaf` is the clearest example in the wild: a Slack billing agent
+whose entire product is "no write without a click." It cannot be built on us
+today, and neither can anything else in that category.
+
+Two separate reasons, and the second is the real one.
+
+Slack posts interactivity to a URL you configure separately from events, as
+`application/x-www-form-urlencoded` carrying a single `payload=` field.
+`receiveSlackWebhook` (`blue/src/edge/index.ts:5235`) reads the body with
+`JSON.parse` on its third line, so a `block_actions` POST throws before
+anything else runs. Past that, `parseSlackEventCallback` returns null for
+everything that is not an `event_callback` and we answer `{ok: true}`.
+
+That part is mechanical. The part that isn't: **a session accepts exactly one
+kind of input.** `enqueueChannelTurn` (`index.ts:4846`) runs the agent and
+delivers what it says. There is no record of a thing the agent proposed and a
+human has not yet decided, so there is nowhere for a click to land even once
+it arrives. Approvals are a new object, not a new event type.
+
+## The proposal is published, not intercepted
+
+The obvious design is to intercept: let the model call the write tool, catch
+the call in the runtime, hold it, and ask. eve does this — `kind:
+"tool-approval"` input requests park a turn mid-flight (`parkedInput.ts`).
+
+We should not, for v1.
+
+Interception needs a runtime round-trip we do not have. `permissionMode` is
+set once at session config (`internal/api/agent_session.go:66`) and never
+answers back. Building that is a change to the agent runtime, the session
+protocol, and the suspend/resume path — a turn parked for eight hours is a
+session we must keep addressable without keeping a microVM warm.
+
+And it buys less than it looks. Autumn runs both mechanisms, and their
+*primary* path is not the parked one. Their gated write records an approval
+and returns to the model:
+
+> "Recorded for approval. The user sees an approval card with the exact change
+> and applies it from there. Do not call this write again, and do not tell the
+> user it has been applied."
+
+The turn then ends normally. Nothing is parked. This is the pattern to build.
+
+So a gated tool publishes a proposal, exactly the way an outbox publishes an
+item: the runtime POSTs to the platform with the token it already holds
+(`OPENCOMPUTER_OUTBOX_URL` / `_TOKEN`, set in
+`blue/src/microvm/supervisor.ts:1138`), and gets back a record id. The
+approvals endpoint is the same shape —
+`/v1/sessions/<sessionId>/approvals`, same `runtimeToken`.
+
+**This is cooperative, not enforced.** A tool that wants to write anyway can:
+`run()` is customer code with its own connections. What the platform
+guarantees is narrower and still worth having — that an approved write runs
+*once*, from the arguments shown on the card, whether or not the proposing
+session still exists. Enforcement would mean the platform holding the
+credential and performing the call, which is the managed-egress story pointed
+at a different problem, and a separate design.
+
+## The SDK surface
+
+A gated tool splits in two: what the human is shown, and what runs after they
+agree.
+
+```ts
+export const attach = defineGatedTool({
+ name: "attach",
+ description: "Move a customer onto a plan.",
+ input: {
+ type: "object",
+ required: ["customerId", "planId"],
+ properties: {
+ customerId: { type: "string" },
+ planId: { type: "string" },
+ },
+ },
+ // What the card says. Pure — no writes, no side effects. It may read.
+ async preview({ input, signal }) {
+ const customer = await billing.fetch(`/customers/${input.customerId}`, { signal });
+ return {
+ title: `Move ${customer.name} to ${input.planId}`,
+ facts: [
+ { label: "Today", value: customer.plan },
+ { label: "After", value: input.planId },
+ { label: "Charged now", value: "$240.00" },
+ ],
+ };
+ },
+ // Runs only after a human approves, from the stored arguments.
+ async apply({ input, decision, signal }) {
+ return billing.fetch(`/subscriptions`, {
+ method: "POST",
+ body: JSON.stringify({ customer: input.customerId, plan: input.planId }),
+ signal,
+ });
+ },
+});
+```
+
+Called by the model, it does not write. It runs `preview`, publishes the
+proposal, and returns the "recorded for approval" sentence — the platform
+supplies that string so every agent tells the same story and nobody has to
+remember to write it.
+
+`apply` runs later, **in a session**, reached by a `tool.apply` frame the
+runtime answers with `tool.applied`. Not a turn: the runtime dispatches
+straight to the tool rather than to the agent prompt, so no model runs and
+nothing can paraphrase the change.
+
+That choice is what makes this cheap. `apply` needs connections, secrets and
+managed egress; all three already work inside a session and nowhere else. The
+proposing session is used when it is still up, woken when suspended, and
+replaced when it is gone — the last of which is the common case, since
+decisions arrive hours later and nothing about `apply` depends on the
+conversation.
+
+**Nothing waits on it.** The dispatch returns as soon as the frame is away, and
+the answer settles the record whenever it arrives. An earlier draft held a
+promise open with a 60-second race; that was wrong twice over — it kept a
+Durable Object request alive for a minute, and a slow-but-successful write got
+reported as a failure. Everything else here that waits is alarm-driven; so is
+this.
+
+## The pending-decision record
+
+On the **account** DO, not the session DO. Approvals outlive sessions —
+sessions suspend after minutes, approvals sit overnight — for the same reason
+`channel_threads` lives there.
+
+```sql
+CREATE TABLE IF NOT EXISTS approvals (
+ id TEXT PRIMARY KEY,
+ agent_id TEXT NOT NULL,
+ alias TEXT NOT NULL,
+ deployment_id TEXT NOT NULL,
+ session_id TEXT, -- who proposed it; may be ended by decision time
+ turn_id TEXT,
+ tool_id TEXT NOT NULL,
+ input_json TEXT NOT NULL, -- the exact arguments. never re-derived
+ preview_json TEXT NOT NULL, -- what the human was shown, kept for the audit trail
+ connection_id TEXT NOT NULL,
+ delivery_ref TEXT NOT NULL, -- adapter-opaque, same contract as channel deliveries
+ external_message_id TEXT, -- the card itself, so the decision can edit it
+ decider_principal TEXT, -- who may decide; NULL means anyone on the connection
+ status TEXT NOT NULL, -- pending|approved|denied|applied|failed|expired
+ decided_by TEXT,
+ decided_at TEXT,
+ applied_at TEXT,
+ result_json TEXT,
+ error TEXT,
+ expires_at TEXT NOT NULL,
+ idempotency_key TEXT NOT NULL,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ UNIQUE (agent_id, alias, idempotency_key)
+);
+CREATE INDEX IF NOT EXISTS approvals_pending ON approvals(status, expires_at);
+```
+
+`input_json` is the whole point. The human approved *those* arguments; the
+write must use *those* arguments. Asking the agent to proceed would let a
+second model pass produce something the card never showed.
+
+There are **two** compare-and-swaps, because there are two moments worth
+protecting. `pending → approved|denied` stops a retried or double-clicked
+decision from being decided twice. `approved → applying` stops the write itself
+from being started twice. Each is a single conditional UPDATE whose `WHERE`
+names the state it moves from, and only the caller that wins it goes on.
+
+`applying_at` also gives the sweep something to find: a write in flight is
+distinguishable from one never started, which is what lets an unanswered write
+be reported honestly rather than guessed at.
+
+`delivery_ref` stays opaque and adapter-owned, exactly as it now does for
+replies (`deliveryTarget`, `session-do.ts` — the fix in blue#55). Do not add
+`channel_id`/`thread_ts` columns here; that is the mistake we just finished
+undoing.
+
+## Where it hooks into blue
+
+**1. A separate interactivity route.**
+`/v1/webhooks/slack/<connectionId>/<token>/interactivity`, alongside the
+events route (`index.ts:5235`). Separate because Slack configures the two URLs
+separately anyway, and because it keeps the form-encoded body away from a
+handler whose contract is JSON. Signature verification is already shared and
+provider-generic (`account.verifyChannelRequest`) and Slack signs interactivity
+with the same HMAC — that part is free.
+
+**2. Two adapter methods.**
+
+```ts
+/** A decision on something we proposed. Null for interactions we do not own. */
+parseDecision?(body: unknown, headers: Headers): InboundDecision | null;
+
+/** Replace a message we sent — the card, after it has been decided. */
+updateMessage?(input: SendInput & { messageId: string }): Promise<void>;
+```
+
+`InboundDecision` carries `approvalId`, `choice`, `externalUserId`,
+`replyTarget`, `messageId`, and a `scope` for `matchesConnection`, mirroring
+`InboundChannelMessage`.
+
+`updateMessage` also fixes something we already owe. Message editing today is
+`account.setSlackStatus` (`session-do.ts:2282`) — Slack-specific, called from
+outside the adapter seam. That is the same shape as the Twilio number missing
+from the Channels tab: a provider-neutral write with a Slack-shaped read still
+attached. Moving edits behind the adapter pays that off and gives cards their
+lifecycle in one change.
+
+**3. Runtime ingress.** `POST /v1/sessions/<id>/approvals`, authed by
+`runtimeToken`, mirroring the outbox endpoint. Body: tool id, input, preview,
+idempotency key. It resolves the current turn's channel delivery for
+`connection_id` and `delivery_ref`, renders the card, sends it, stores
+`external_message_id`.
+
+**4. Decision handling.** Verify, match the connection, load the approval,
+check the decider, CAS to `approved`, CAS to `applying`, dispatch the frame,
+return. The answer arrives later and settles the record from the account DO —
+where the approval's state lives, because the answer can outlive the request
+that triggered it. On denial: CAS to `denied`, edit the card, no session.
+
+**6. The sweep.** The account alarm closes out two things: proposals nobody
+answered before they expired, and writes that never reported back. The second
+settles as **`unknown`**, not `failed` — a write that went quiet may well have
+landed, and "Failed to apply" over a real charge is the worse lie. The card
+says to check before retrying, and `decision.id` is handed to `apply` as an
+idempotency key so that retrying is safe.
+
+**5. Card lifecycle.** After a decision the card must stop being clickable and
+say what happened — "Approved by @brian · applied 14:02" — and a stale click on
+an already-decided approval must be answered gracefully, because Slack will
+send them.
+
+## What the agent learns
+
+The proposing thread should read like a conversation, so a decision posts back
+into it as a normal channel turn: *"@brian approved the plan change; it has
+been applied."* The agent sees it as ordinary input on the session it already
+owns, and can carry on.
+
+That is one line of policy with an outsized effect on how the product feels,
+and it is worth getting into v1.
+
+## Not in v1
+
+- **Parked turns.** Covered above. Revisit only if something real needs a
+ mid-tool pause, and price the suspend/resume work honestly when we do.
+- **Non-Slack cards.** SMS has no buttons; a signed link in an email is a
+ plausible v2 and needs its own thinking about link security.
+- **Quorum and multi-step chains.** Autumn has `approvalSets` and sibling
+ requests; one approver, one decision is enough to learn from.
+- **Dashboard surface.** A pending-approvals list is obvious and can wait.
+
+## Settled since this was written
+
+**Who may decide: only the person the proposal was made to.** The
+`decider_principal` is the external user whose message the agent was answering,
+and a click from anyone else in the thread is ignored. A Slack channel is
+visible to everyone in it, and anyone-in-the-conversation would have let a
+bystander approve somebody else's write. Revisit if a real workflow needs a
+delegate.
+
+**Everything above is built**, on `channels/identity-approvals-apps` in blue and
+`channels/identity-and-approvals` in opencomputer3, along with the app-level
+routing the multi-workspace case needs. What is not covered by tests is the
+shim that acts on a session choice — the choice itself is table-tested through
+`selectApplySession`, but dispatching into a real runtime needs a MicroVM the
+test harness cannot boot.
+
+## Open questions
+
+**Expiry.** Something like 24h, and expired cards should say so rather than
+sit there looking live.
+
+**Preview cost.** `preview` runs during the model's turn and may make network
+calls; it needs the same timeout and error handling as any tool, and a failed
+preview must fail the proposal rather than produce a card with holes in it.
diff --git a/agent/src/index.ts b/agent/src/index.ts
index 841f15da..8bb31d3b 100644
--- a/agent/src/index.ts
+++ b/agent/src/index.ts
@@ -31,6 +31,36 @@ export interface WebhookRequestContext {
readonly receivedAt: string;
}
+/**
+ * Who sent this message, in the provider's own terms.
+ *
+ * An agent serving one Slack workspace never needs this. An agent serving
+ * many — one deployment behind a distributed app — needs it for everything:
+ * which customer's records to read, which credential to use, whether this
+ * person may act at all. Without it the agent is blind to the tenant, and no
+ * amount of prompting recovers what was never sent.
+ *
+ * These are the provider's public identifiers, not ours. `workspaceId` is a
+ * Slack team id or a Twilio account SID; `userId` is a Slack member id or an
+ * E.164 number. They are stable, and they are what an agent can join against
+ * its own customer records.
+ *
+ * Session ownership is keyed separately, by a one-way hash that is deliberately
+ * not derivable from these (see the platform's channel principal). This bag
+ * exists to be used by the agent; that key exists to keep sessions apart.
+ */
+export interface ChannelMessageContext {
+ readonly provider: string;
+ /** The connection this arrived on. Distinct installations, distinct ids. */
+ readonly connectionId: string;
+ /** The provider's tenant: a Slack team, a Twilio account. */
+ readonly workspaceId?: string;
+ /** Where it was said, when the provider names conversations. */
+ readonly conversationId?: string;
+ /** The provider's id for the person who said it. */
+ readonly userId?: string;
+}
+
interface BasicAgentInput {
readonly text?: string;
readonly payload?: DataValue;
@@ -38,7 +68,14 @@ interface BasicAgentInput {
export type AgentInput =
| (BasicAgentInput & {
- readonly source: Exclude<InputSource, "schedule" | "webhook">;
+ readonly source: Exclude<
+ InputSource,
+ "channel" | "schedule" | "webhook"
+ >;
+ })
+ | (BasicAgentInput & {
+ readonly source: "channel";
+ readonly channel: Readonly<ChannelMessageContext>;
})
| (BasicAgentInput & {
readonly source: "schedule";
@@ -305,6 +342,181 @@ export interface ToolDefinition<
run(context: ToolExecutionContext): Output | Promise<Output>;
}
+/** One line on an approval card: what changes, from what, to what. */
+export interface ApprovalFact {
+ readonly label: string;
+ readonly value: string;
+}
+
+/**
+ * What a person is shown before they decide. Built by `preview`, stored
+ * verbatim, and kept after the decision as the record of what was agreed to.
+ */
+export interface ApprovalPreview {
+ readonly title: string;
+ readonly summary?: string;
+ readonly facts?: readonly ApprovalFact[];
+}
+
+export interface ApprovalDecision {
+ /**
+ * This approval, once. Stable, unique, and the same on every attempt to
+ * carry out this one decision.
+ *
+ * Pass it to whatever you call as an idempotency key. Then a write that
+ * cannot be confirmed — the runtime died mid-flight, the answer never came
+ * back — can simply be run again, because the second attempt returns the
+ * first one's result instead of charging anyone twice:
+ *
+ * ```ts
+ * async apply({ input, decision, signal }) {
+ * return billing.fetch("/charges", {
+ * method: "POST",
+ * headers: { "Idempotency-Key": decision.id },
+ * body: JSON.stringify({ customer: input.customerId }),
+ * signal,
+ * });
+ * }
+ * ```
+ *
+ * Without it an unconfirmed write is a dead end: nobody can retry it,
+ * because nobody can tell whether the first attempt landed.
+ */
+ readonly id: string;
+ readonly decidedAt: string;
+ /** Who clicked, in the provider's terms. Absent if the platform decided. */
+ readonly decidedBy?: string;
+}
+
+export interface GatedToolApplyContext extends ToolExecutionContext {
+ readonly decision: Readonly<ApprovalDecision>;
+}
+
+export interface ApprovalPublishResult {
+ readonly id: string;
+ readonly status: "pending" | "approved" | "denied" | "applied";
+ readonly duplicate: boolean;
+ /** What to tell the model. Supplied by the platform so every agent agrees. */
+ readonly message: string;
+}
+
+export interface GatedToolDefinition<
+ Output extends DataValue = DataValue,
+> extends ResourceReference {
+ readonly kind: "gated-tool";
+ readonly version: 1;
+ readonly name: string;
+ readonly description: string;
+ readonly input?: ToolInputSchema;
+ readonly output?: ToolInputSchema;
+ preview(context: ToolExecutionContext): ApprovalPreview | Promise<ApprovalPreview>;
+ apply(context: GatedToolApplyContext): Output | Promise<Output>;
+ /**
+ * What the model calls. It does not write: it builds the preview, records
+ * the proposal, and returns a sentence telling the model to stop. The write
+ * happens later, in `apply`, from the arguments stored here.
+ */
+ run(context: ToolExecutionContext): Promise<string>;
+}
+
+function approvalPreview(value: unknown, toolId: string): ApprovalPreview {
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
+ throw new Error(`Tool ${toolId} preview must return an object`);
+ }
+ const preview = value as ApprovalPreview;
+ if (typeof preview.title !== "string" || !preview.title.trim()) {
+ throw new Error(`Tool ${toolId} preview requires a non-empty title`);
+ }
+ if (preview.summary !== undefined && typeof preview.summary !== "string") {
+ throw new Error(`Tool ${toolId} preview summary must be a string`);
+ }
+ if (preview.facts !== undefined) {
+ if (!Array.isArray(preview.facts)) {
+ throw new Error(`Tool ${toolId} preview facts must be an array`);
+ }
+ if (preview.facts.length > 20) {
+ throw new Error(`Tool ${toolId} preview may carry at most 20 facts`);
+ }
+ for (const fact of preview.facts) {
+ if (
+ !fact ||
+ typeof fact.label !== "string" ||
+ typeof fact.value !== "string"
+ ) {
+ throw new Error(
+ `Tool ${toolId} preview facts must each have a label and a value`,
+ );
+ }
+ }
+ }
+ return preview;
+}
+
+/**
+ * Record a proposal for a human to decide on.
+ *
+ * Reaches the platform the way an outbox item does: over the session's own
+ * runtime token, which is the only credential the agent holds that the
+ * platform trusts.
+ */
+export async function publishApproval(
+ tool: string | ResourceReference,
+ input: {
+ readonly input: DataValue;
+ readonly preview: ApprovalPreview;
+ readonly idempotencyKey: string;
+ },
+): Promise<ApprovalPublishResult> {
+ const id = resourceIdentifier(
+ typeof tool === "string" ? tool : tool.id,
+ "publishApproval",
+ );
+ const idempotencyKey = input.idempotencyKey.trim();
+ if (!idempotencyKey || idempotencyKey.length > 256) {
+ throw new Error("Approval idempotency keys must contain 1 to 256 characters");
+ }
+ const runtime = globalThis as typeof globalThis & {
+ process?: { env?: Record<string, string | undefined> };
+ };
+ const base = runtime.process?.env?.OPENCOMPUTER_APPROVAL_URL;
+ const token = runtime.process?.env?.OPENCOMPUTER_APPROVAL_TOKEN;
+ if (!base || !token) {
+ throw new Error("OpenComputer approvals are unavailable");
+ }
+ const response = await fetch(`${base.replace(/\/$/, "")}`, {
+ method: "POST",
+ headers: {
+ authorization: `Bearer ${token}`,
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ toolId: id,
+ input: input.input,
+ preview: input.preview,
+ idempotencyKey,
+ }),
+ });
+ if (!response.ok) {
+ // Whatever the model is told here, it repeats to a person — and a bare
+ // status code invites it to invent a reason. The platform writes these
+ // sentences so the explanation is true.
+ const detail = await response.text().catch(() => "");
+ let message = "";
+ try {
+ const problem = JSON.parse(detail) as { error?: { message?: unknown } };
+ if (typeof problem.error?.message === "string") {
+ message = problem.error.message;
+ }
+ } catch {
+ /* not a problem document; fall through to the status */
+ }
+ throw new Error(
+ message || `Recording the approval failed with status ${response.status}`,
+ );
+ }
+ return (await response.json()) as ApprovalPublishResult;
+}
+
interface AgentHooks {
useInput(): Readonly<AgentInput>;
useModel(model: ModelSelection): void;
@@ -870,6 +1082,73 @@ export function defineTool<Output extends DataValue = DataValue>(input: {
});
}
+/**
+ * A tool whose write waits for a person.
+ *
+ * The model calls it and nothing is written. `preview` builds what the human
+ * sees, the proposal is recorded against the conversation it came from, and
+ * the model is told to stop. When somebody approves, `apply` runs with the
+ * arguments that were on the card — not with whatever a second pass through
+ * the model would produce.
+ *
+ * This is cooperative. A tool that wants to write in `preview` can; what the
+ * platform guarantees is that `apply` runs once, from the stored arguments,
+ * whether or not this session still exists by then.
+ *
+ * Give `apply` an idempotency key from `decision.id` if whatever you call
+ * accepts one. A write that never reports back is recorded as unconfirmed
+ * rather than failed, and that is only recoverable if running it again is
+ * safe.
+ */
+export function defineGatedTool<Output extends DataValue = DataValue>(input: {
+ name: string;
+ description: string;
+ input?: ToolInputSchema;
+ output?: ToolInputSchema;
+ preview(context: ToolExecutionContext): ApprovalPreview | Promise<ApprovalPreview>;
+ apply(context: GatedToolApplyContext): Output | Promise<Output>;
+}): GatedToolDefinition<Output> {
+ const id = identifier(input.name, "defineGatedTool");
+ if (!/^[a-zA-Z0-9_-]+$/.test(id)) {
+ throw new Error(
+ "Tool IDs may contain only letters, numbers, underscores, and hyphens",
+ );
+ }
+ if (!input.description.trim()) {
+ throw new Error("defineGatedTool requires a non-empty description");
+ }
+ if (input.input && typeof input.input !== "object") {
+ throw new Error("defineGatedTool input must be a JSON Schema object");
+ }
+ if (input.output && typeof input.output !== "object") {
+ throw new Error("defineGatedTool output must be a JSON Schema object");
+ }
+ if (typeof input.preview !== "function") {
+ throw new Error("defineGatedTool requires a preview function");
+ }
+ if (typeof input.apply !== "function") {
+ throw new Error("defineGatedTool requires an apply function");
+ }
+ return Object.freeze({
+ kind: "gated-tool" as const,
+ version: 1 as const,
+ ...input,
+ id,
+ name: id,
+ async run(context: ToolExecutionContext): Promise<string> {
+ const preview = approvalPreview(await input.preview(context), id);
+ // The tool call is the proposal's identity, so the same call recorded
+ // twice — a retry, a resumed turn — is one approval, not two.
+ const result = await publishApproval(id, {
+ input: context.input as DataValue,
+ preview,
+ idempotencyKey: context.messageId,
+ });
+ return result.message;
+ },
+ });
+}
+
export const useInput = (): Readonly<AgentInput> => hooks().useInput();
export const useCurrentInput = useInput;
export const useModel = (model: ModelSelection): void =>
diff --git a/cli/src/project.test.ts b/cli/src/project.test.ts
index 735a93d4..59dadb73 100644
--- a/cli/src/project.test.ts
+++ b/cli/src/project.test.ts
@@ -159,6 +159,7 @@ export default registerOutbox(reviewRequests);
assert.match(built.digest, /^[a-f0-9]{64}$/);
assert.deepEqual(built.manifest, {
version: 1,
+ gatedTools: [],
channels: [
{
id: "team-slack",
@@ -338,6 +339,7 @@ export default function Agent() {
) as {
version: number;
tools: string[];
+ gatedTools: string[];
toolModules: string[];
subagents: string[];
connections: string[];
@@ -354,6 +356,7 @@ export default function Agent() {
version: 2,
entry: "../agent.js",
tools: ["search-docs"],
+ gatedTools: [],
toolModules: [],
subagents: ["researcher"],
connections: [],
@@ -695,6 +698,129 @@ export default function Agent() {
}
});
+test("a gated tool proposes instead of writing, and carries its apply", async () => {
+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-gated-tools-"));
+ const root = resolve(parent, "app");
+ try {
+ const initialized = await initializeAgentProject(root);
+ await mkdir(resolve(initialized.agentRoot, "tools"), { recursive: true });
+ await writeFile(
+ resolve(initialized.agentRoot, "tools", "billing.ts"),
+ `import { defineGatedTool } from "@opencomputer/agent";
+
+export const attach = defineGatedTool({
+ name: "attach",
+ description: "Move a customer onto a plan",
+ input: { type: "object", properties: { plan: { type: "string" } } },
+ preview({ input }) {
+ return { title: \`Move to \${String(input.plan)}\`, facts: [{ label: "Plan", value: String(input.plan) }] };
+ },
+ async apply({ input }) {
+ return { applied: String(input.plan) };
+ },
+});
+`,
+ );
+ await writeFile(
+ resolve(initialized.agentRoot, "agent.ts"),
+ `import { useTool } from "@opencomputer/agent";
+import { attach } from "./tools/billing.js";
+
+export default function Agent() {
+ useTool(attach);
+ return "Change the plan when asked.";
+}
+`,
+ );
+
+ const runtime = await prepareAgent(initialized.agentRoot);
+ const manifest = JSON.parse(
+ await readFile(
+ resolve(runtime, ".opencomputer", "reactive.json"),
+ "utf8",
+ ),
+ ) as { tools: string[]; gatedTools: string[]; toolModules: string[] };
+ // The model sees it as an ordinary tool; the platform is told it is gated.
+ assert.ok(manifest.tools.includes("attach"));
+ assert.deepEqual(manifest.gatedTools, ["attach"]);
+ assert.ok(manifest.toolModules.includes("../tools/billing.js"));
+
+ const built = (await import(
+ `${pathToFileURL(resolve(runtime, "tools", "billing.js")).href}?test=${crypto.randomUUID()}`
+ )) as {
+ attach: {
+ kind: string;
+ run(context: Record<string, unknown>): Promise<string>;
+ apply(context: Record<string, unknown>): Promise<unknown>;
+ };
+ };
+ assert.equal(built.attach.kind, "gated-tool");
+
+ const posted: Array<{ url: string; body: Record<string, unknown> }> = [];
+ const realFetch = globalThis.fetch;
+ process.env.OPENCOMPUTER_APPROVAL_URL = "https://edge.test/v1/sessions/s1/approvals";
+ process.env.OPENCOMPUTER_APPROVAL_TOKEN = "runtime-token";
+ globalThis.fetch = (async (url: string, init: { body: string }) => {
+ posted.push({ url: String(url), body: JSON.parse(init.body) as Record<string, unknown> });
+ return new Response(
+ JSON.stringify({ id: "apr_1", status: "pending", duplicate: false, message: "Recorded for approval." }),
+ { headers: { "content-type": "application/json" } },
+ );
+ }) as unknown as typeof globalThis.fetch;
+ try {
+ // Calling it records a proposal and tells the model to stop. No write.
+ const answer = await built.attach.run({
+ input: { plan: "pro" },
+ messageId: "msg-1",
+ sessionId: "s1",
+ agentId: "a1",
+ });
+ assert.equal(answer, "Recorded for approval.");
+ assert.equal(posted.length, 1);
+ assert.deepEqual(posted[0]!.body.input, { plan: "pro" });
+ assert.deepEqual(posted[0]!.body.preview, {
+ title: "Move to pro",
+ facts: [{ label: "Plan", value: "pro" }],
+ });
+ // The tool call is the proposal's identity, so a retry is one approval.
+ assert.equal(posted[0]!.body.idempotencyKey, "msg-1");
+
+ // A refusal reaches the model, which repeats it to a person. The
+ // platform writes the sentence; a bare status code invites invention.
+ globalThis.fetch = (async () =>
+ new Response(
+ JSON.stringify({
+ error: {
+ code: "approval_needs_a_conversation",
+ message: "This tool can only be used in a conversation where somebody can approve it.",
+ },
+ }),
+ { status: 409, headers: { "content-type": "application/json" } },
+ )) as unknown as typeof globalThis.fetch;
+ await assert.rejects(
+ built.attach.run({
+ input: { plan: "pro" },
+ messageId: "msg-2",
+ sessionId: "s1",
+ agentId: "a1",
+ }),
+ /somebody can approve it/,
+ );
+
+ // The write itself lives in apply, and never ran.
+ assert.deepEqual(await built.attach.apply({ input: { plan: "pro" } }), {
+ applied: "pro",
+ });
+ } finally {
+ globalThis.fetch = realFetch;
+ delete process.env.OPENCOMPUTER_APPROVAL_URL;
+ delete process.env.OPENCOMPUTER_APPROVAL_TOKEN;
+ }
+ } finally {
+ await rm(parent, { recursive: true, force: true });
+ }
+});
+
test("the compiler packages agent source modules outside the tools directory", async () => {
const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-source-modules-"));
const root = resolve(parent, "app");
diff --git a/cli/src/project.ts b/cli/src/project.ts
index 3acdc1da..43beb5d0 100644
--- a/cli/src/project.ts
+++ b/cli/src/project.ts
@@ -97,6 +97,11 @@ export interface ScheduleDefinitionManifest {
};
}
+export interface GatedToolManifest {
+ agentId: string;
+ toolId: string;
+}
+
export interface ProjectResourceManifest {
version: 1;
channels: ChannelDefinitionManifest[];
@@ -104,6 +109,12 @@ export interface ProjectResourceManifest {
outboxes: OutboxDefinitionManifest[];
outboxRegistrations: OutboxRegistrationManifest[];
schedules: ScheduleDefinitionManifest[];
+ /**
+ * Which tools wait for a human. Declared here as well as in the agent's own
+ * manifest because the platform authorizes a proposal before any agent code
+ * is involved.
+ */
+ gatedTools: GatedToolManifest[];
}
export interface BuiltProjectResources {
@@ -1430,7 +1441,13 @@ export async function readProjectResources(
const channelRegistrations: ChannelRegistrationManifest[] = [];
const outboxRegistrations: OutboxRegistrationManifest[] = [];
const schedules: ScheduleDefinitionManifest[] = [];
+ const gatedTools: GatedToolManifest[] = [];
for (const agent of agents) {
+ for (const path of await typescriptFiles(resolve(agent.root, "tools"))) {
+ for (const toolId of definedGatedToolIds(await readFile(path, "utf8"))) {
+ gatedTools.push({ agentId: agent.localId, toolId });
+ }
+ }
for (const path of await typescriptFiles(resolve(agent.root, "channels"))) {
channelRegistrations.push(
channelRegistration(
@@ -1474,6 +1491,11 @@ export async function readProjectResources(
schedules: schedules.sort((left, right) =>
`${left.agentId}:${left.id}`.localeCompare(`${right.agentId}:${right.id}`),
),
+ gatedTools: gatedTools.sort((left, right) =>
+ `${left.agentId}:${left.toolId}`.localeCompare(
+ `${right.agentId}:${right.toolId}`,
+ ),
+ ),
};
const serialized = JSON.stringify(manifest);
return {
@@ -1706,6 +1728,21 @@ function definedToolIds(source: string): string[] {
.sort();
}
+/**
+ * Gated tools are tools: the model sees them and calls them like any other.
+ * They are listed separately as well so the platform knows a call to one is a
+ * proposal, and that the tool has an `apply` to dispatch after a decision.
+ */
+function definedGatedToolIds(source: string): string[] {
+ return [
+ ...source.matchAll(
+ /\bdefineGatedTool(?:<[^>]+>)?\s*\(\s*\{[\s\S]*?\bname\s*:\s*["']([^"']+)["'][\s\S]*?\}\s*\)/g,
+ ),
+ ]
+ .map((match) => match[1]!)
+ .sort();
+}
+
function staticModelSelections(
source: string,
): Array<{ provider: string; model: string }> {
@@ -1833,6 +1870,60 @@ export const defineTool = (input) => {
if (input.output && typeof input.output !== "object") throw new Error("defineTool output must be a JSON Schema object");
return Object.freeze({ kind: "tool", version: 1, ...input, id: toolId, name: toolId });
};
+export const defineGatedTool = (input) => {
+ const toolId = id(input.name, "defineGatedTool");
+ if (!/^[a-zA-Z0-9_-]+$/.test(toolId)) throw new Error("Invalid tool id " + JSON.stringify(toolId));
+ if (!String(input.description).trim()) throw new Error("defineGatedTool requires a non-empty description");
+ if (input.input && typeof input.input !== "object") throw new Error("defineGatedTool input must be a JSON Schema object");
+ if (input.output && typeof input.output !== "object") throw new Error("defineGatedTool output must be a JSON Schema object");
+ if (typeof input.preview !== "function") throw new Error("defineGatedTool requires a preview function");
+ if (typeof input.apply !== "function") throw new Error("defineGatedTool requires an apply function");
+ return Object.freeze({
+ kind: "gated-tool", version: 1, ...input, id: toolId, name: toolId,
+ async run(context) {
+ const preview = approvalPreview(await input.preview(context), toolId);
+ const result = await publishApproval(toolId, {
+ input: context.input,
+ preview,
+ idempotencyKey: context.messageId,
+ });
+ return result.message;
+ },
+ });
+};
+const approvalPreview = (value, toolId) => {
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Tool " + toolId + " preview must return an object");
+ if (typeof value.title !== "string" || !value.title.trim()) throw new Error("Tool " + toolId + " preview requires a non-empty title");
+ if (value.summary !== undefined && typeof value.summary !== "string") throw new Error("Tool " + toolId + " preview summary must be a string");
+ if (value.facts !== undefined) {
+ if (!Array.isArray(value.facts)) throw new Error("Tool " + toolId + " preview facts must be an array");
+ if (value.facts.length > 20) throw new Error("Tool " + toolId + " preview may carry at most 20 facts");
+ for (const fact of value.facts) {
+ if (!fact || typeof fact.label !== "string" || typeof fact.value !== "string") throw new Error("Tool " + toolId + " preview facts must each have a label and a value");
+ }
+ }
+ return value;
+};
+export const publishApproval = async (tool, input) => {
+ const toolId = id(typeof tool === "string" ? tool : tool.id, "publishApproval");
+ const idempotencyKey = String(input.idempotencyKey).trim();
+ if (!idempotencyKey || idempotencyKey.length > 256) throw new Error("Approval idempotency keys must contain 1 to 256 characters");
+ const base = globalThis.process?.env?.OPENCOMPUTER_APPROVAL_URL;
+ const token = globalThis.process?.env?.OPENCOMPUTER_APPROVAL_TOKEN;
+ if (!base || !token) throw new Error("OpenComputer approvals are unavailable");
+ const response = await fetch(base.replace(/\\/$/, ""), {
+ method: "POST",
+ headers: { authorization: "Bearer " + token, "content-type": "application/json" },
+ body: JSON.stringify({ toolId, input: input.input, preview: input.preview, idempotencyKey }),
+ });
+ if (!response.ok) {
+ const detail = await response.text().catch(() => "");
+ let message = "";
+ try { message = JSON.parse(detail)?.error?.message ?? ""; } catch {}
+ throw new Error(message || ("Recording the approval failed with status " + response.status));
+ }
+ return await response.json();
+};
export const publishOutbox = async (outbox, input) => {
const outboxId = id(typeof outbox === "string" ? outbox : outbox.id, "publishOutbox");
const type = String(input.type).trim();
@@ -2010,7 +2101,15 @@ the product or support surface presented to users.
...(config.model === undefined && inferredModel
? { model: inferredModel }
: {}),
- tools: { ...configuredTools, question: !questionDenied },
+ // The skill tool is what loads a packaged skill's body. OpenCode
+ // injects skill names and descriptions either way, so without this
+ // an agent knows its skills exist and can never read one — which is
+ // exactly how nine skills shipped in an artifact and none was used.
+ tools: {
+ use_skill: true,
+ ...configuredTools,
+ question: !questionDenied,
+ },
permission: {
...configuredPermission,
...(configuredPermission.calendar_create_time_off === "ask"
@@ -2060,6 +2159,7 @@ the product or support surface presented to users.
candidate.path.startsWith("tools/"),
);
const reactiveTools: string[] = [];
+ const gatedTools: string[] = [];
const toolModules: string[] = [];
for (const candidate of toolSources) {
const ids = definedToolIds(candidate.source);
@@ -2071,8 +2171,18 @@ the product or support surface presented to users.
`${candidate.path} must give every defineTool() a literal string name`,
);
}
- if (ids.length > 0) {
- reactiveTools.push(...ids);
+ const gatedIds = definedGatedToolIds(candidate.source);
+ const gatedCalls = [
+ ...candidate.source.matchAll(/\bdefineGatedTool(?:<[^>]+>)?\s*\(/g),
+ ].length;
+ if (gatedIds.length !== gatedCalls) {
+ throw new Error(
+ `${candidate.path} must give every defineGatedTool() a literal string name`,
+ );
+ }
+ if (ids.length > 0 || gatedIds.length > 0) {
+ reactiveTools.push(...ids, ...gatedIds);
+ gatedTools.push(...gatedIds);
toolModules.push(`../${compiledModulePath(candidate.path)}`);
}
}
@@ -2140,6 +2250,7 @@ the product or support surface presented to users.
...literalHookIds(agentSource, "useTool"),
]),
].sort(),
+ gatedTools: [...gatedTools].sort(),
toolModules: toolModules.sort(),
subagents: literalHookIds(agentSource, "useSubagent"),
connections: httpConnections.map((connection) => connection.id).sort(),
diff --git a/docs/agents/inputs.mdx b/docs/agents/inputs.mdx
index c4d5e08b..1291640a 100644
--- a/docs/agents/inputs.mdx
+++ b/docs/agents/inputs.mdx
@@ -56,6 +56,54 @@ export default function Agent() {
}
```
+## Know who is speaking
+
+A `channel` input carries the sender's identity in the provider's own terms.
+
+```ts
+interface ChannelMessageContext {
+ readonly provider: string;
+ readonly connectionId: string;
+ readonly workspaceId?: string;
+ readonly conversationId?: string;
+ readonly userId?: string;
+}
+```
+
+| Field | Meaning |
+| --- | --- |
+| `provider` | `slack`, `twilio`, … |
+| `connectionId` | The connection the message arrived on |
+| `workspaceId` | The provider's tenant: a Slack team, a Twilio account |
+| `conversationId` | Where it was said, when the provider names conversations |
+| `userId` | The provider's id for the person who said it |
+
+An agent serving one workspace can ignore all of this. An agent serving many —
+one deployment behind a distributed Slack app — needs it to decide whose
+records to read and which credential to use:
+
+```tsx
+import { useInput } from "@opencomputer/agent";
+
+export default function Agent() {
+ const input = useInput();
+
+ if (input.source === "channel" && input.channel.workspaceId) {
+ return `You are answering for workspace ${input.channel.workspaceId}. ` +
+ `Look up that customer before answering.`;
+ }
+
+ return "Help with the current request.";
+}
+```
+
+These are the provider's public identifiers, not OpenComputer's. They are
+stable, which is what makes them usable as a key into your own records.
+
+Session ownership is keyed separately, by a one-way hash you never see. That
+keeps two people's sessions apart; this tells your agent who it is talking to.
+The two are deliberately different values.
+
## Read structured payloads
Narrow or validate a payload before reading application-specific fields:
diff --git a/docs/agents/skills.mdx b/docs/agents/skills.mdx
index be9b2be3..2468e94e 100644
--- a/docs/agents/skills.mdx
+++ b/docs/agents/skills.mdx
@@ -72,7 +72,11 @@ campaign-brief/
Reference those files from `SKILL.md` so the agent knows when to read them.
Supporting files are deployed with the skill and need no imports from
-`agent.ts`.
+`agent.ts`. Loading a skill lists them, and the agent reads one on request —
+so a long checklist or a set of examples costs nothing until it is needed.
+
+An agent can only read files packaged with the skill it loaded. There is no
+path out of that directory, and no way to reach anything else on the machine.
## Scope skills to an agent
diff --git a/docs/agents/tools.mdx b/docs/agents/tools.mdx
index f228907a..064a67a7 100644
--- a/docs/agents/tools.mdx
+++ b/docs/agents/tools.mdx
@@ -125,8 +125,88 @@ Declare an HTTP connection, store the value as an OpenComputer secret, and
call the connection's `fetch()` method. See
[Secrets and outbound requests](/agents/secrets) for a complete example.
+## Wait for a person before writing
+
+Some writes should not happen because a model decided they should. A gated tool
+proposes instead: the model calls it, nothing is written, and the person the
+agent is talking to sees a card with the exact change and decides.
+
+```tsx
+import { defineGatedTool } from "@opencomputer/agent";
+import { billing } from "./connections/billing";
+
+export const attach = defineGatedTool({
+ name: "attach",
+ description: "Move a customer onto a plan",
+ input: {
+ type: "object",
+ required: ["customerId", "planId"],
+ properties: {
+ customerId: { type: "string" },
+ planId: { type: "string" },
+ },
+ },
+ // What the person sees. It may read; it must not write.
+ async preview({ input, signal }) {
+ const customer = await billing
+ .fetch(`/customers/${String(input.customerId)}`, { signal })
+ .then((response) => response.json());
+ return {
+ title: `Move ${customer.name} to ${String(input.planId)}`,
+ facts: [
+ { label: "Today", value: customer.plan },
+ { label: "After", value: String(input.planId) },
+ { label: "Charged now", value: customer.nextCharge },
+ ],
+ };
+ },
+ // Runs only once somebody approves, from the arguments on the card.
+ async apply({ input, decision, signal }) {
+ return billing.fetch("/subscriptions", {
+ method: "POST",
+ headers: { "Idempotency-Key": decision.id },
+ body: JSON.stringify({
+ customer: input.customerId,
+ plan: input.planId,
+ }),
+ signal,
+ });
+ },
+});
+```
+
+The model calls `attach` like any other tool and is told the change was
+recorded for approval, so it stops rather than reporting the work as done.
+
+`apply` runs later, with the arguments that were on the card — no second pass
+through the model, so what happens is what was agreed to. The proposing session
+is usually gone by then, and that is fine: `apply` needs its arguments, not the
+conversation.
+
+### Always pass `decision.id`
+
+`decision.id` identifies this approval, and it is the same value on every
+attempt to carry it out. Give it to whatever you call as an idempotency key.
+
+If a write never reports back — the runtime died mid-flight, the answer was
+lost — it is recorded as unconfirmed rather than failed, because it may well
+have happened. That is only recoverable if running it again is safe, and this
+is what makes it safe.
+
+### What this does and does not guarantee
+
+A gated tool is a convention your code cooperates with. Nothing stops a tool
+from writing inside `preview`. What the platform guarantees is narrower and
+still worth having: an approved write runs **once**, from the arguments the
+person agreed to, whether or not the session that proposed it still exists.
+
+Gated tools need a conversation to ask in. Called from the playground, a
+schedule or a webhook, there is nobody to ask, and the call fails saying so.
+
## Tools versus skills and MCP
- A tool executes TypeScript you own.
+- A [gated tool](#wait-for-a-person-before-writing) does the same, once a
+ person approves it.
- A [skill](/agents/skills) teaches the agent a reusable procedure.
- An [MCP server](/agents/mcp) supplies a remote collection of tools.