An open-source, faster Devin alternative
TypeScript
Result tool: defineTool({ result: true }) and the compile rule (C1)
Igor Zalutski9a26ac54ede5
diff --git a/agent/package-lock.json b/agent/package-lock.jsonindex 8a38443a..3b9fb2ff 100644--- a/agent/package-lock.json+++ b/agent/package-lock.json@@ -1,12 +1,12 @@{"name": "@opencomputer/agent",- "version": "0.7.2",+ "version": "0.7.3","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@opencomputer/agent",- "version": "0.7.2",+ "version": "0.7.3","dependencies": {"croner": "^9.1.0"},diff --git a/agent/package.json b/agent/package.jsonindex 19788e03..7a46d2d0 100644--- a/agent/package.json+++ b/agent/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/agent",- "version": "0.7.2",+ "version": "0.7.3","description": "Reactive agent authoring API for OpenComputer.","type": "module","main": "./dist/index.js",diff --git a/agent/src/index.test.ts b/agent/src/index.test.tsindex 6215b023..7031237a 100644--- a/agent/src/index.test.ts+++ b/agent/src/index.test.ts@@ -4,6 +4,7 @@ import {bearer,defineConnection,defineMemory,+ defineTool,documentMemory,httpMemory,useInput,@@ -451,3 +452,61 @@ test("useInput narrows a delivered turn outcome to its typed event", () => {delete globals[HOOKS];}});++test("defineTool marks a result tool and pins its output schema", () => {+ const output = {+ type: "object",+ properties: { branch: { type: "string" } },+ required: ["branch"],+ additionalProperties: false,+ };+ const report = defineTool({+ name: "report",+ description: "Report the branch",+ output,+ result: true,+ run: () => ({ branch: "task/1" }),+ });+ assert.equal(report.result, true);+ assert.deepEqual(report.output, output);+ assert.equal(Object.isFrozen(report), true);+ // An ordinary tool carries no result marker at all, so hosts and the+ // compiler test for `result === true` and nothing else.+ const plain = defineTool({+ name: "plain",+ description: "Plain",+ run: () => "ok",+ });+ assert.equal("result" in plain, false);+ const opted = defineTool({+ name: "opted",+ description: "Opted out",+ result: false,+ run: () => "ok",+ });+ assert.equal("result" in opted, false);+});++test("defineTool refuses a result tool without an output schema", () => {+ assert.throws(+ () =>+ defineTool({+ name: "report",+ description: "Report",+ result: true,+ run: () => "ok",+ } as unknown as Parameters<typeof defineTool>[0]),+ /result tools require an output schema/,+ );+ assert.throws(+ () =>+ defineTool({+ name: "report",+ description: "Report",+ output: { type: "object" },+ result: "yes",+ run: () => "ok",+ } as unknown as Parameters<typeof defineTool>[0]),+ /result must be true or false/,+ );+});diff --git a/agent/src/index.ts b/agent/src/index.tsindex 9ee95f92..20b84327 100644--- a/agent/src/index.ts+++ b/agent/src/index.ts@@ -343,9 +343,30 @@ export interface ToolDefinition<readonly description: string;readonly input?: ToolInputSchema;readonly output?: ToolInputSchema;+ /**+ * The agent's result tool: its latest committed output is the session's+ * `result`. At most one tool per agent; `output` is required so the host+ * can validate every value before it is committed.+ */+ readonly result?: true;run(context: ToolExecutionContext): Output | Promise<Output>;}+/**+ * What `defineTool()` accepts. A result tool must declare `output`: the+ * schema is pinned in the deployment and the host rejects a value that does+ * not match it before anything is committed.+ */+export type ToolInput<Output extends DataValue = DataValue> = {+ name: string;+ description: string;+ input?: ToolInputSchema;+ run(context: ToolExecutionContext): Output | Promise<Output>;+} & (+ | { result?: false; output?: ToolInputSchema }+ | { result: true; output: ToolInputSchema }+);+export type {DocumentMemoryInput,DocumentMemoryProvider,@@ -1117,13 +1138,9 @@ export function registerOutbox(});}-export function defineTool<Output extends DataValue = DataValue>(input: {- name: string;- description: string;- input?: ToolInputSchema;- output?: ToolInputSchema;- run(context: ToolExecutionContext): Output | Promise<Output>;-}): ToolDefinition<Output> {+export function defineTool<Output extends DataValue = DataValue>(+ input: ToolInput<Output>,+): ToolDefinition<Output> {const id = identifier(input.name, "defineTool");if (!/^[a-zA-Z0-9_-]+$/.test(id)) {throw new Error(@@ -1139,10 +1156,20 @@ export function defineTool<Output extends DataValue = DataValue>(input: {if (input.output && typeof input.output !== "object") {throw new Error("defineTool output must be a JSON Schema object");}+ if (input.result !== undefined && typeof input.result !== "boolean") {+ throw new Error("defineTool result must be true or false");+ }+ if (input.result === true && !input.output) {+ throw new Error(+ "defineTool result tools require an output schema; the host validates every result against it before committing",+ );+ }+ const { result, ...definition } = input;return Object.freeze({kind: "tool" as const,version: 1 as const,- ...input,+ ...definition,+ ...(result === true ? { result: true as const } : {}),id,name: id,});diff --git a/cli/package-lock.json b/cli/package-lock.jsonindex 3c1e1bc3..7b500249 100644--- a/cli/package-lock.json+++ b/cli/package-lock.json@@ -1,12 +1,12 @@{"name": "@opencomputer/cli",- "version": "0.7.3",+ "version": "0.7.4","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@opencomputer/cli",- "version": "0.7.3",+ "version": "0.7.4","dependencies": {"@opencode-ai/sdk": "1.18.4","ai": "^7.0.45",diff --git a/cli/package.json b/cli/package.jsonindex 091a249c..7c7b39f7 100644--- a/cli/package.json+++ b/cli/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/cli",- "version": "0.7.3",+ "version": "0.7.4","description": "Build, test, deploy, and share OpenComputer agents as code.","type": "module","bin": {diff --git a/cli/src/project.test.ts b/cli/src/project.test.tsindex a0710d36..7c2b2b2d 100644--- a/cli/src/project.test.ts+++ b/cli/src/project.test.ts@@ -899,6 +899,155 @@ export default function Agent() {}});+test("the compiler records the result tool and its pinned output schema", async () => {+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-result-tool-"));+ 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", "report.ts"),+ `import { defineTool } from "@opencomputer/agent";++export const report = defineTool({+ name: "report",+ description: "Report the branch and pull request",+ input: {+ type: "object",+ properties: { branch: { type: "string" } },+ additionalProperties: false,+ },+ output: {+ type: "object",+ properties: {+ branch: { type: "string" },+ pr: { type: "object", properties: { number: { type: "integer" } }, required: ["number"] },+ },+ required: ["branch"],+ additionalProperties: false,+ },+ result: true,+ async run({ input }) {+ return { branch: String(input.branch) };+ },+});++export const lookup = defineTool({+ name: "lookup",+ description: "Look something up",+ result: false,+ async run() {+ return { found: true };+ },+});+`,+ );+ await writeFile(+ resolve(initialized.agentRoot, "agent.ts"),+ `import { useTool } from "@opencomputer/agent";+import { report } from "./tools/report.js";++export default function Agent() {+ useTool(report);+ return "Report when the branch is known.";+}+`,+ );++ const runtime = await prepareAgent(initialized.agentRoot);+ const manifest = JSON.parse(+ await readFile(+ resolve(runtime, ".opencomputer", "reactive.json"),+ "utf8",+ ),+ ) as {+ tools: string[];+ resultTool?: { id: string; output: Record<string, unknown> };+ };+ assert.deepEqual(manifest.tools, ["lookup", "report"]);+ assert.deepEqual(manifest.resultTool, {+ id: "report",+ output: {+ type: "object",+ properties: {+ branch: { type: "string" },+ pr: { type: "object", properties: { number: { type: "integer" } }, required: ["number"] },+ },+ required: ["branch"],+ additionalProperties: false,+ },+ });+ const tools = await import(+ `${pathToFileURL(resolve(runtime, "tools", "report.js")).href}?test=${crypto.randomUUID()}`+ ) as { report: { id: string; result?: boolean }; lookup: { result?: boolean } };+ assert.equal(tools.report.result, true);+ assert.equal("result" in tools.lookup, false);+ } finally {+ await rm(parent, { recursive: true, force: true });+ }+});++test("the compiler rejects a result tool without an output schema", async () => {+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-result-tool-"));+ 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", "report.ts"),+ `import { defineTool } from "@opencomputer/agent";++export const report = defineTool({+ name: "report",+ description: "Report the branch",+ result: true,+ async run() {+ return { branch: "task/1" };+ },+});+`,+ );+ await assert.rejects(+ prepareAgent(initialized.agentRoot),+ /tools\/report\.ts defineTool\("report"\) is the result tool and must declare output/,+ );+ } finally {+ await rm(parent, { recursive: true, force: true });+ }+});++test("the compiler rejects more than one result tool per agent", async () => {+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-result-tool-"));+ const root = resolve(parent, "app");+ try {+ const initialized = await initializeAgentProject(root);+ await mkdir(resolve(initialized.agentRoot, "tools"), { recursive: true });+ for (const name of ["first", "second"]) {+ await writeFile(+ resolve(initialized.agentRoot, "tools", `${name}.ts`),+ `import { defineTool } from "@opencomputer/agent";++export const ${name} = defineTool({+ name: "${name}",+ description: "Report ${name}",+ output: { type: "object" },+ result: true,+ async run() {+ return {};+ },+});+`,+ );+ }+ await assert.rejects(+ prepareAgent(initialized.agentRoot),+ /An agent may declare one result tool; found "first" in tools\/first\.ts and "second" in tools\/second\.ts/,+ );+ } 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.tsindex 668e3c8c..c1864668 100644--- a/cli/src/project.ts+++ b/cli/src/project.ts@@ -2322,6 +2322,59 @@ function definedToolIds(source: string): string[] {.sort();}+interface ResultToolManifest {+ id: string;+ /** The output schema as written, pinned in the deployment for the host to validate against. */+ output: Record<string, unknown>;+}++/**+ * The result tools declared in one tool module: every `defineTool()` whose+ * argument carries the literal `result: true`. The `output` schema is read+ * as static JSON rather than evaluated, so the deployment records exactly+ * the schema the source declares. The one-per-agent rule is applied by the+ * caller across all tool modules.+ */+function definedResultTools(+ source: string,+ path: string,+): ResultToolManifest[] {+ const file = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);+ const declared: ResultToolManifest[] = [];+ 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)) {+ const name = objectProperty(argument, "name");+ const label = `${path} defineTool(${name && ts.isStringLiteralLike(name) ? JSON.stringify(name.text) : ""})`;+ const result = objectProperty(argument, "result");+ if (result && result.kind !== ts.SyntaxKind.TrueKeyword && result.kind !== ts.SyntaxKind.FalseKeyword) {+ throw new Error(`${label} result must be the literal true or false`);+ }+ if (result?.kind === ts.SyntaxKind.TrueKeyword) {+ const output = objectProperty(argument, "output");+ if (!output || !ts.isObjectLiteralExpression(output)) {+ throw new Error(+ `${label} is the result tool and must declare output as an inline JSON Schema object literal`,+ );+ }+ declared.push({+ id: literalStringValue(name, `${label} name`),+ output: staticJsonValue(output, `${label} output`) as Record<string, unknown>,+ });+ }+ }+ }+ ts.forEachChild(node, visit);+ };+ visit(file);+ return declared;+}+function staticModelSelections(source: string,): Array<{ provider: string; model: string }> {@@ -2543,7 +2596,10 @@ 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 });+ if (input.result !== undefined && typeof input.result !== "boolean") throw new Error("defineTool result must be true or false");+ if (input.result === true && !input.output) throw new Error("defineTool result tools require an output schema; the host validates every result against it before committing");+ const { result, ...definition } = input;+ return Object.freeze({ kind: "tool", version: 1, ...definition, ...(result === true ? { result: true } : {}), id: toolId, name: toolId });};export const publishOutbox = async (outbox, input) => {const outboxId = id(typeof outbox === "string" ? outbox : outbox.id, "publishOutbox");@@ -2782,6 +2838,7 @@ the product or support surface presented to users.);const reactiveTools: string[] = [];const toolModules: string[] = [];+ const resultTools: Array<ResultToolManifest & { path: string }> = [];for (const candidate of toolSources) {const ids = definedToolIds(candidate.source);const calls = [@@ -2795,6 +2852,11 @@ the product or support surface presented to users.if (ids.length > 0) {reactiveTools.push(...ids);toolModules.push(`../${compiledModulePath(candidate.path)}`);+ resultTools.push(+ ...definedResultTools(candidate.source, candidate.path).map(+ (tool) => ({ ...tool, path: candidate.path }),+ ),+ );}}const duplicateTool = reactiveTools.find(@@ -2805,6 +2867,19 @@ the product or support surface presented to users.`Tool id ${JSON.stringify(duplicateTool)} is defined more than once`,);}+ // One result per session, so one result tool per agent: a second one+ // would leave the host with two schemas and no rule for which output+ // becomes the session's result.+ if (resultTools.length > 1) {+ throw new Error(+ `An agent may declare one result tool; found ${resultTools+ .map((tool) => `${JSON.stringify(tool.id)} in ${tool.path}`)+ .join(" and ")}`,+ );+ }+ const resultTool: ResultToolManifest | undefined = resultTools[0]+ ? { id: resultTools[0].id, output: resultTools[0].output }+ : undefined;const httpConnections = sourceModules.flatMap((module) =>definedHttpConnections(module.source, module.path),);@@ -2885,6 +2960,9 @@ the product or support surface presented to users.entry: "../agent.js",tools,toolModules: toolModules.sort(),+ // The result tool and the schema the host validates its output+ // against before committing it as the session's result.+ ...(resultTool ? { resultTool } : {}),subagents: literalHookIds(agentSource, "useSubagent"),// Declared HTTP connections AND managed-service grants: the platform// reads one list, and a google grant absent from it makes everydiff --git a/create-start/package.json b/create-start/package.jsonindex 1e1434cd..814ab591 100644--- a/create-start/package.json+++ b/create-start/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/create-start",- "version": "0.7.3",+ "version": "0.7.4","description": "Create a hello-world OpenComputer agent application.","type": "module","bin": {@@ -18,7 +18,7 @@"node": ">=22.0.0"},"dependencies": {- "@opencomputer/cli": "0.7.3"+ "@opencomputer/cli": "0.7.4"},"publishConfig": {"access": "public"diff --git a/docs/agents/api.mdx b/docs/agents/api.mdxindex 30f95856..a2025193 100644--- a/docs/agents/api.mdx+++ b/docs/agents/api.mdx@@ -108,6 +108,7 @@ insufficient_credits`.| `source` | The `source` given at creation || `memory` | Bindings with `resource`, `scope`, `id`, `access` and `writable`; present when the session was created with bindings || `turns` | Every turn: `id`, `input`, `mode`, `status`, `createdAt`, `updatedAt`, and `deliveries` when an [event subscription](#event-subscriptions) selected its outcome |+| `result` | The latest committed output of the agent's [result tool](/agents/tools#the-session-result), or `null`: `{ turnId, callId, reportedAt, data }`. `turnId` and `callId` name the call that reported `data`, so a reader can tell which turn it came from and whether a later turn changed things without reporting. A failed or cancelled turn never clears it. || `createdAt`, `updatedAt` | Timestamps |`GET /sessions` returns `{ sessions }`: the fifty most recently updateddiff --git a/docs/agents/events.mdx b/docs/agents/events.mdxindex 4ea9656d..f51f67f9 100644--- a/docs/agents/events.mdx+++ b/docs/agents/events.mdx@@ -96,7 +96,7 @@ no rule recognizes is `agent_failed`.| --- | --- | --- || `tool.started` | The model called a tool | `tool`: its name; `callId`; `title`; `input` || `tool.progress` | The tool reported progress | runtime-defined |-| `tool.completed` | The tool returned | `tool`, `callId`, `title`, `output` |+| `tool.completed` | The tool returned | `tool`, `callId`, `title`, `output`; `result: true` when the output became the session's result || `tool.failed` | The tool raised an error | `tool`, `callId`, `message` |The exact fields come from the runtime's tool record; read them as optional@@ -104,6 +104,12 @@ and key a tool call on `callId` when it is present. The memory tools(`memory_save`, `memory_read`, `memory_list`) appear here like any othertool; the save itself is reported separately.+A successful call of the agent's [result tool](/agents/tools#the-session-result)+is recorded with `result: true`; its `output` is the validated value as JSON+text, the same value `GET /sessions/<id>` returns parsed as `result.data`.+The session writes this event when it commits the result, before the model+sees the call succeed, and there is one per call.+### Memory| Type | When | `data` |diff --git a/docs/agents/tools.mdx b/docs/agents/tools.mdxindex f228907a..341927b5 100644--- a/docs/agents/tools.mdx+++ b/docs/agents/tools.mdx@@ -58,7 +58,8 @@ the result to the model.| `name` | yes | ID the model calls; letters, numbers, underscores, and hyphens only || `description` | yes | Explains what the tool does and when to use it || `input` | no | JSON Schema for tool arguments |-| `output` | no | JSON Schema describing the result |+| `output` | no | JSON Schema describing the result; required on the result tool |+| `result` | no | `true` marks this tool as the agent's [result tool](#the-session-result); one per agent || `run` | yes | Synchronous or asynchronous implementation |Descriptions are the model's documentation. Include the action, when it is@@ -95,6 +96,73 @@ export const importCatalog = defineTool({Tool results and progress metadata must be JSON-compatible values.+## The session result++An agent may mark one tool as its result tool. Its latest committed output+is the session's `result`: the structured outcome an application reads+instead of parsing the final message.++```tsx+export const report = defineTool({+ name: "report",+ description: "Report the branch and pull request as soon as each is known",+ input: {+ type: "object",+ properties: {+ branch: { type: "string" },+ pr: { type: "object", properties: { number: { type: "integer" }, url: { type: "string" } } },+ },+ required: ["branch"],+ additionalProperties: false,+ },+ output: {+ type: "object",+ properties: {+ branch: { type: "string" },+ pr: {+ type: "object",+ properties: { number: { type: "integer" }, url: { type: "string" } },+ required: ["number", "url"],+ additionalProperties: false,+ },+ },+ required: ["branch"],+ additionalProperties: false,+ },+ result: true,+ async run({ input }) {+ // Verify what the model claims before it becomes the result.+ return { branch: String(input.branch), ...(input.pr ? { pr: input.pr } : {}) };+ },+});+```++The build enforces two rules: an agent declares at most one result tool,+and a result tool declares `output`. The schema is recorded with the+deployment, and every value the tool returns is validated against it.++A call to the result tool succeeds only once its output is committed to+the session:++- The value `run()` returns is validated against `output` and committed+ before the model is told the call succeeded. The session's `result`+ becomes `{ turnId, callId, reportedAt, data }`, and the call's+ `tool.completed` event carries `result: true`+ ([Session events](/agents/events#tools)).+- A value that does not match `output`, or exceeds 8 KB of JSON, fails the+ call; the model sees the reason and can call again. The previous result+ stands.+- A call from a turn that was interrupted or has ended, or from a runtime+ the session no longer runs on, is refused the same way.+- A later call replaces the result. A turn that fails or is cancelled never+ clears it, and the event log keeps every call.++The result says what the agent reported, not that the work succeeded.+Verify claims inside `run()`, where a tool can check that a branch exists+or a pull request is open, and throw to reject them; let the application+check what the result references. Read it from+[`GET /sessions/<id>`](/agents/api#get-and-list).+## Conditional tools`useTool()` may be conditional. This keeps sensitive or specialized actions