An open-source, faster Devin alternative
TypeScript
sdk: approval is an option on defineTool rather than a second primitive — a gated tool was always a tool whose run() we write for you, so defineGatedTool duplicated a name for what is really a property of one; supplying preview() and apply() instead of run() now makes the model's call a proposal, useTool is unchanged, and the compiler reads gating from the syntax tree because it is no longer visible in the callee's name and a textual match would read a JSON Schema property called preview as a gate
Brian Reardon9e3d65b9186d
diff --git a/agent/src/index.ts b/agent/src/index.tsindex 367d480f..d0815bb2 100644--- a/agent/src/index.ts+++ b/agent/src/index.ts@@ -1153,92 +1153,111 @@ export function registerOutbox(});}-export function defineTool<Output extends DataValue = DataValue>(input: {+export interface ToolInput<Output extends DataValue = DataValue> {name: string;description: string;input?: ToolInputSchema;output?: ToolInputSchema;run(context: ToolExecutionContext): Output | Promise<Output>;-}): ToolDefinition<Output> {- const id = identifier(input.name, "defineTool");- 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("defineTool requires a non-empty description");- }- if (input.input && typeof input.input !== "object") {- throw new Error("defineTool input must be a JSON Schema object");- }- if (input.output && typeof input.output !== "object") {- throw new Error("defineTool output must be a JSON Schema object");- }- return Object.freeze({- kind: "tool" as const,- version: 1 as const,- ...input,- id,- name: id,- });}-/**- * 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: {+export interface GatedToolInput<Output extends DataValue = DataValue> {name: string;description: string;input?: ToolInputSchema;output?: ToolInputSchema;+ /**+ * Runs when the model calls the tool. Reads; never writes. What this returns+ * is what a person sees and agrees to.+ */preview(context: ToolExecutionContext): ApprovalPreview | Promise<ApprovalPreview>;+ /** Runs only after somebody approves, from the arguments previewed above. */apply(context: GatedToolApplyContext): Output | Promise<Output>;-}): GatedToolDefinition<Output> {- const id = identifier(input.name, "defineGatedTool");+}++/**+ * Define a tool.+ *+ * A tool that writes can wait for a person: supply `preview` and `apply`+ * instead of `run`, and the model's call becomes a proposal rather than the+ * write. `run` is then written for you — it builds the preview, records the+ * proposal under the calling message's id so a retry is one approval rather+ * than two, and returns a sentence telling the model to stop.+ *+ * Waiting for approval is a property of a tool, not a different kind of thing:+ * the model sees it, and `useTool` selects it, exactly as for any other. What+ * changes is only whether the tool's body runs now or after a decision.+ */+export function defineTool<Output extends DataValue = DataValue>(+ input: ToolInput<Output>,+): ToolDefinition<Output>;+export function defineTool<Output extends DataValue = DataValue>(+ input: GatedToolInput<Output>,+): GatedToolDefinition<Output>;+export function defineTool<Output extends DataValue = DataValue>(+ input: ToolInput<Output> | GatedToolInput<Output>,+): ToolDefinition<Output> | GatedToolDefinition<Output> {+ const id = identifier(input.name, "defineTool");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");+ throw new Error("defineTool requires a non-empty description");}if (input.input && typeof input.input !== "object") {- throw new Error("defineGatedTool input must be a JSON Schema object");+ throw new Error("defineTool 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");+ throw new Error("defineTool output must be a JSON Schema object");+ }++ const candidate = input as Partial<ToolInput<Output>> &+ Partial<GatedToolInput<Output>>;+ const gated =+ typeof candidate.preview === "function" ||+ typeof candidate.apply === "function";++ if (!gated) {+ if (typeof candidate.run !== "function") {+ throw new Error(+ "defineTool requires run(), or preview() and apply() for a tool that waits for approval",+ );+ }+ return Object.freeze({+ kind: "tool" as const,+ version: 1 as const,+ ...(input as ToolInput<Output>),+ id,+ name: id,+ });}- if (typeof input.preview !== "function") {- throw new Error("defineGatedTool requires a preview function");++ // Half a gate is the dangerous shape: a preview with no apply asks for a+ // decision nothing acts on, and an apply with no preview asks a person to+ // approve something they were never shown.+ if (typeof candidate.preview !== "function") {+ throw new Error("A tool with apply() also requires preview()");}- if (typeof input.apply !== "function") {- throw new Error("defineGatedTool requires an apply function");+ if (typeof candidate.apply !== "function") {+ throw new Error("A tool with preview() also requires apply()");}+ if (typeof candidate.run === "function") {+ throw new Error(+ "A tool has either run(), or preview() and apply() — not both; run() is written for you when the tool waits for approval",+ );+ }++ const definition = input as GatedToolInput<Output>;return Object.freeze({kind: "gated-tool" as const,version: 1 as const,- ...input,+ ...definition,id,name: id,async run(context: ToolExecutionContext): Promise<string> {- const preview = approvalPreview(await input.preview(context), id);+ const preview = approvalPreview(await definition.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, {@@ -1251,12 +1270,6 @@ export function defineGatedTool<Output extends DataValue = DataValue>(input: {});}-/**- * The projection the host recalled for this session's binding of `memory`.- * It never fetches: a session without that binding fails the render here,- * before inference. Calling it also selects the binding's permitted tools for- * this model request; omitting it exposes none of them.- */export function useMemory(memory: string | ResourceReference): MemoryProjection {const id = memoryId(typeof memory === "string" ? memory : memory.id,diff --git a/cli/src/project.test.ts b/cli/src/project.test.tsindex eb548bf6..82904916 100644--- a/cli/src/project.test.ts+++ b/cli/src/project.test.ts@@ -427,6 +427,108 @@ export default function Agent() {}});+test("a tool is gated by having preview and apply, not by the words appearing in it", async () => {+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-gated-shape-"));+ try {+ const initialized = await initializeAgentProject(resolve(parent, "app"));+ await mkdir(resolve(initialized.agentRoot, "tools"), { recursive: true });+ // An ordinary tool whose SCHEMA happens to describe fields called preview+ // and apply. Gating used to be visible in the function's name; now it is+ // the shape of the object, and a textual match would read this as gated+ // and make the runtime refuse to render it.+ await writeFile(+ resolve(initialized.agentRoot, "tools", "drafts.ts"),+ `import { defineTool } from "@opencomputer/agent";++export const draft = defineTool({+ name: "draft",+ description: "Render a draft",+ input: {+ type: "object",+ properties: {+ preview: { type: "boolean", description: "Return a preview only" },+ apply: { type: "boolean", description: "Apply the template" },+ },+ },+ run({ input }) {+ return { preview: Boolean(input.preview) };+ },+});+`,+ );+ await writeFile(+ resolve(initialized.agentRoot, "agent.ts"),+ `import { useTool } from "@opencomputer/agent";+import { draft } from "./tools/drafts.js";++export default function Agent() {+ useTool(draft);+ return "Draft 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[] };+ assert.deepEqual(manifest.tools, ["draft"]);+ assert.deepEqual(manifest.gatedTools, []);+ } finally {+ await rm(parent, { recursive: true, force: true });+ }+});++test("a tool cannot be half gated", async () => {+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-half-gate-"));+ try {+ const initialized = await initializeAgentProject(resolve(parent, "app"));+ await mkdir(resolve(initialized.agentRoot, "tools"), { recursive: true });+ await writeFile(+ resolve(initialized.agentRoot, "tools", "billing.ts"),+ `import { defineTool } from "@opencomputer/agent";++// apply() with no preview(): a person would be asked to approve something+// they were never shown.+export const cancel = defineTool({+ name: "cancel",+ description: "Cancel a subscription",+ async apply() {+ return { cancelled: true };+ },+});+`,+ );+ await writeFile(+ resolve(initialized.agentRoot, "agent.ts"),+ `import { useTool } from "@opencomputer/agent";+import { cancel } from "./tools/billing.js";++export default function Agent() {+ useTool(cancel);+ return "Cancel when asked.";+}+`,+ );++ // The compiler still records it as gated — either half means it intends to+ // wait — so the module load is where the incomplete pair is caught.+ const runtime = await prepareAgent(initialized.agentRoot);+ const manifest = JSON.parse(+ await readFile(resolve(runtime, ".opencomputer", "reactive.json"), "utf8"),+ ) as { gatedTools: string[] };+ assert.deepEqual(manifest.gatedTools, ["cancel"]);+ await assert.rejects(+ import(+ `${pathToFileURL(resolve(runtime, "tools", "billing.js")).href}?test=${crypto.randomUUID()}`+ ),+ /A tool with apply\(\) also requires preview\(\)/,+ );+ } finally {+ await rm(parent, { recursive: true, force: true });+ }+});+test("the compiler records secret-backed HTTP connections without secret values", async () => {const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-egress-"));const root = resolve(parent, "app");@@ -708,9 +810,9 @@ test("a gated tool proposes instead of writing, and carries its apply", async ()await mkdir(resolve(initialized.agentRoot, "tools"), { recursive: true });await writeFile(resolve(initialized.agentRoot, "tools", "billing.ts"),- `import { defineGatedTool } from "@opencomputer/agent";+ `import { defineTool } from "@opencomputer/agent";-export const attach = defineGatedTool({+export const attach = defineTool({name: "attach",description: "Move a customer onto a plan",input: { type: "object", properties: { plan: { type: "string" } } },diff --git a/cli/src/project.ts b/cli/src/project.tsindex 30540892..4920b6d0 100644--- a/cli/src/project.ts+++ b/cli/src/project.ts@@ -2035,8 +2035,10 @@ export async function readProjectResources(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 tool of definedTools(await readFile(path, "utf8"), path)) {+ if (tool.gated) {+ gatedTools.push({ agentId: agent.localId, toolId: tool.id });+ }}}for (const path of await typescriptFiles(resolve(agent.root, "channels"))) {@@ -2332,29 +2334,70 @@ function definedHttpConnections(return definitions;}-function definedToolIds(source: string): string[] {- return [- ...source.matchAll(- /\bdefineTool(?:<[^>]+>)?\s*\(\s*\{[\s\S]*?\bname\s*:\s*["']([^"']+)["'][\s\S]*?\}\s*\)/g,- ),- ]- .map((match) => match[1]!)- .sort();+interface DefinedTool {+ readonly id: string;+ /** Has preview() and apply(), so the model's call is a proposal. */+ readonly gated: boolean;+}++/** Matches `preview: fn`, `preview(ctx) {}` and `async preview(ctx) {}` alike. */+function hasMember(object: ts.ObjectLiteralExpression, name: string): boolean {+ return object.properties.some((property) => {+ if (+ !ts.isPropertyAssignment(property) &&+ !ts.isMethodDeclaration(property) &&+ !ts.isShorthandPropertyAssignment(property)+ ) {+ return false;+ }+ const key = property.name;+ return (+ (!!key && ts.isIdentifier(key) && key.text === name) ||+ (!!key && ts.isStringLiteral(key) && key.text === name)+ );+ });}/**- * 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.+ * Every tool a module defines, and whether it waits for approval.+ *+ * Read from the syntax tree rather than by regex, because gated-ness is no+ * longer visible in the function's name — it is the presence of `preview` and+ * `apply` on the object literal. A textual match would see those words inside+ * a nested JSON Schema (a tool whose input has a property called `preview` is+ * perfectly legal) and declare an ordinary tool gated, which the runtime then+ * refuses to render at all.*/-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 definedTools(source: string, path: string): DefinedTool[] {+ const file = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);+ const tools: DefinedTool[] = [];+ const visit = (node: ts.Node): void => {+ if (+ ts.isCallExpression(node) &&+ ts.isIdentifier(node.expression) &&+ node.expression.text === "defineTool"+ ) {+ const argument = node.arguments[0];+ if (!argument || !ts.isObjectLiteralExpression(argument)) {+ throw new Error(`${path} defineTool() requires an object literal`);+ }+ const id = literalStringValue(+ objectProperty(argument, "name"),+ `${path} tool name`,+ );+ tools.push({+ id,+ // Either half marks it gated; defineTool() rejects a lone one at run+ // time. Treating a half-gate as ordinary here would let a tool that+ // means to wait be registered as one that does not.+ gated:+ hasMember(argument, "preview") || hasMember(argument, "apply"),+ });+ }+ ts.forEachChild(node, visit);+ };+ visit(file);+ return tools.sort((left, right) => left.id.localeCompare(right.id));}function staticModelSelections(@@ -2494,16 +2537,14 @@ export const defineTool = (input) => {if (!String(input.description).trim()) throw new Error("defineTool requires a non-empty description");if (input.input && typeof input.input !== "object") throw new Error("defineTool input must be a JSON Schema object");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");+ const gated = typeof input.preview === "function" || typeof input.apply === "function";+ if (!gated) {+ if (typeof input.run !== "function") throw new Error("defineTool requires run(), or preview() and apply() for a tool that waits for approval");+ return Object.freeze({ kind: "tool", version: 1, ...input, id: toolId, name: toolId });+ }+ if (typeof input.preview !== "function") throw new Error("A tool with apply() also requires preview()");+ if (typeof input.apply !== "function") throw new Error("A tool with preview() also requires apply()");+ if (typeof input.run === "function") throw new Error("A tool has either run(), or preview() and apply() - not both; run() is written for you when the tool waits for approval");return Object.freeze({kind: "gated-tool", version: 1, ...input, id: toolId, name: toolId,async run(context) {@@ -2796,27 +2837,14 @@ the product or support surface presented to users.const gatedTools: string[] = [];const toolModules: string[] = [];for (const candidate of toolSources) {- const ids = definedToolIds(candidate.source);- const calls = [- ...candidate.source.matchAll(/\bdefineTool(?:<[^>]+>)?\s*\(/g),- ].length;- if (ids.length !== calls) {- throw new Error(- `${candidate.path} must give every defineTool() a literal string name`,+ // literalStringValue throws on a computed name, which is what used to be+ // caught by counting calls against extracted ids.+ const defined = definedTools(candidate.source, candidate.path);+ if (defined.length > 0) {+ reactiveTools.push(...defined.map((tool) => tool.id));+ gatedTools.push(+ ...defined.filter((tool) => tool.gated).map((tool) => tool.id),);- }- 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)}`);}}