An open-source, faster Devin alternative
TypeScript
Merge feat/typed-session-result (#742): defineTool({ result: true }), compile rule, docs
Igor Zalutski68df8adfd74b
diff --cc agent/src/index.test.tsindex 820c37f3,7031237a..958732be--- a/agent/src/index.test.ts+++ b/agent/src/index.test.ts@@@ -4,10 -4,9 +4,11 @@@ importbearer,defineConnection,defineMemory,+ defineTool,documentMemory,+ githubApp,httpMemory,+ useConnection,useInput,useMemory,useSecret,@@@ -525,3 -452,61 +526,76 @@@ test("useInput narrows a delivered turdelete 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/,+ );+ });++++test("defineTool refuses a result tool that waits for approval", () => {++ assert.throws(++ () =>++ defineTool({++ name: "report",++ description: "Report",++ output: { type: "object" },++ result: true,++ preview: () => ({ title: "Report" }),++ apply: () => ({}),++ } as unknown as Parameters<typeof defineTool>[0]),++ /waits for approval cannot be the result tool/,++ );++});diff --cc agent/src/index.tsindex e8ce5512,20b84327..6176f2a0--- a/agent/src/index.ts+++ b/agent/src/index.ts@@@ -1447,50 -1138,9 +1453,59 @@@ export function registerOutbox});}- export interface ToolInput<Output extends DataValue = DataValue> {++/**++ * 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. A tool that waits for a person++ * (`preview` and `apply`) is a `GatedToolInput` and cannot be the result++ * tool: the model's call records a proposal, not the output.++ */++export type ToolInput<Output extends DataValue = DataValue> = {+ name: string;+ description: string;+ input?: ToolInputSchema;- output?: ToolInputSchema;+ run(context: ToolExecutionContext): Output | Promise<Output>;- }++} & (++ | { result?: false; output?: ToolInputSchema }++ | { result: true; output: ToolInputSchema }++);++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>;+}++/**+ * 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> {+): 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(@@@ -1506,61 -1156,22 +1521,79 @@@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");++ 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",+ );+ }++ const tool = input as ToolInput<Output>;++ if (tool.result !== undefined && typeof tool.result !== "boolean") {++ throw new Error("defineTool result must be true or false");++ }++ if (tool.result === true && !tool.output) {++ throw new Error(++ "defineTool result tools require an output schema; the host validates every result against it before committing",++ );++ }++ const { result, ...definition } = tool;+ return Object.freeze({+ kind: "tool" as const,+ version: 1 as const,- ...(input as ToolInput<Output>),++ ...definition,++ ...(result === true ? { result: true as const } : {}),+ id,+ name: id,+ });+ }+++ // The result tool's committed output is what its run() returns; a gated++ // tool's run() is written here and returns the platform's sentence, so the++ // two cannot be one tool.++ if ("result" in candidate) {++ throw new Error("A tool that waits for approval cannot be the result tool");++ }+++ // 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 candidate.apply !== "function") {+ throw new Error("A tool with preview() also requires apply()");}- if (input.result === true && !input.output) {+ if (typeof candidate.run === "function") {throw new Error(- "defineTool result tools require an output schema; the host validates every result against it before committing",+ "A tool has either run(), or preview() and apply() — not both; run() is written for you when the tool waits for approval",);}- const { result, ...definition } = input;++ const definition = input as GatedToolInput<Output>;return Object.freeze({- kind: "tool" as const,+ kind: "gated-tool" as const,version: 1 as const,...definition,- ...(result === true ? { result: true as const } : {}),id,name: id,+ async run(context: ToolExecutionContext): Promise<string> {+ 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, {+ input: context.input as DataValue,+ preview,+ idempotencyKey: context.messageId,+ });+ return result.message;+ },});}diff --cc cli/src/project.test.tsindex 1d60e625,7c2b2b2d..a28e5ae3--- a/cli/src/project.test.ts+++ b/cli/src/project.test.ts@@@ -1122,129 -899,155 +1122,311 @@@ 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 { defineTool } from "@opencomputer/agent";++export const attach = defineTool({+ 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 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 rejects a result tool that waits for approval", 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",++ output: { type: "object" },++ result: true,++ preview() {++ return { title: "Report" };++ },++ async apply() {++ return {};++ },++});++`,++ );++ await assert.rejects(++ prepareAgent(initialized.agentRoot),++ /tools\/report\.ts defineTool\("report"\) waits for approval and cannot be the result tool/,++ );++ } 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 --cc cli/src/project.tsindex a81eec39,c1864668..7c1a833d--- a/cli/src/project.ts+++ b/cli/src/project.ts@@@ -2465,214 -2312,69 +2465,267 @@@ function definedHttpConnectionsreturn 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();+const GITHUB_APP_PERMISSION_KEYS = new Set([+ "actions",+ "checks",+ "contents",+ "issues",+ "metadata",+ "pull_requests",+]);++function definedGitHubConnections(+ source: string,+ path: string,+): GitHubConnectionManifest[] {+ const file = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);+ const definitions: GitHubConnectionManifest[] = [];+ const visit = (node: ts.Node): void => {+ if (+ ts.isCallExpression(node) &&+ ts.isIdentifier(node.expression) &&+ node.expression.text === "defineConnection"+ ) {+ const input = node.arguments[0];+ if (!input || !ts.isObjectLiteralExpression(input)) {+ throw new Error("defineConnection() requires an object literal");+ }+ const providerExpression = objectProperty(input, "provider");+ if (!providerExpression) {+ ts.forEachChild(node, visit);+ return;+ }+ const id = literalStringValue(+ objectProperty(input, "id"),+ "connection id",+ );+ for (const property of input.properties) {+ if (!ts.isPropertyAssignment(property)) {+ throw new Error(+ `Connection ${id} cannot use spreads or shorthand properties`,+ );+ }+ const name = staticPropertyName(property.name, `Connection ${id}`);+ if (name !== "id" && name !== "provider") {+ throw new Error(+ `GitHub connection ${id} does not support the ${name} option`,+ );+ }+ }+ if (+ !ts.isCallExpression(providerExpression) ||+ !ts.isIdentifier(providerExpression.expression) ||+ providerExpression.expression.text !== "githubApp"+ ) {+ throw new Error(+ `Connection ${id} provider must be an inline githubApp() call`,+ );+ }+ const options = literalCallArgument(+ providerExpression,+ `Connection ${id} githubApp()`,+ );+ if (!options) {+ throw new Error(`Connection ${id} githubApp() requires permissions`);+ }+ for (const property of options.properties) {+ if (!ts.isPropertyAssignment(property)) {+ throw new Error(+ `Connection ${id} githubApp() options must be static`,+ );+ }+ if (+ staticPropertyName(property.name, `Connection ${id} githubApp()`) !==+ "permissions"+ ) {+ throw new Error(+ `Connection ${id} githubApp() only supports permissions`,+ );+ }+ }+ const permissionsExpression = objectProperty(options, "permissions");+ if (+ !permissionsExpression ||+ !ts.isObjectLiteralExpression(permissionsExpression)+ ) {+ throw new Error(+ `Connection ${id} githubApp() permissions must be an inline object literal`,+ );+ }+ const permissions: Record<string, GitHubAppPermission> = {};+ for (const property of permissionsExpression.properties) {+ if (!ts.isPropertyAssignment(property)) {+ throw new Error(+ `Connection ${id} githubApp() permissions must use literal properties`,+ );+ }+ const name = staticPropertyName(+ property.name,+ `Connection ${id} githubApp() permissions`,+ );+ if (!GITHUB_APP_PERMISSION_KEYS.has(name)) {+ throw new Error(+ `Connection ${id} githubApp() does not support the ${name} permission`,+ );+ }+ const level = literalStringValue(+ property.initializer,+ `Connection ${id} githubApp() permission ${name}`,+ );+ if (level !== "read" && level !== "write") {+ throw new Error(+ `Connection ${id} githubApp() permission ${name} must be "read" or "write"`,+ );+ }+ if (name === "metadata" && level !== "read") {+ throw new Error(+ `Connection ${id} githubApp() permission metadata must be "read"`,+ );+ }+ permissions[name] = level;+ }+ if (Object.keys(permissions).length === 0) {+ throw new Error(+ `Connection ${id} githubApp() requires at least one permission`,+ );+ }+ definitions.push({+ id,+ provider: {+ kind: "github-app",+ permissions: Object.fromEntries(+ Object.entries(permissions).sort(([left], [right]) =>+ left.localeCompare(right),+ ),+ ),+ },+ });+ }+ ts.forEachChild(node, visit);+ };+ visit(file);+ return definitions;+}++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)+ );+ });+}++/**+ * 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 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));}+ 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 }> {@@@ -2914,59 -2596,10 +2967,63 @@@ 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");- 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 });+ 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 (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 });+ }++ if ("result" in input) throw new Error("A tool that waits for approval cannot be the result tool");+ 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) {+ 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");@@@ -3213,18 -2837,26 +3270,24 @@@ the product or support surface presentecandidate.path.startsWith("tools/"),);const reactiveTools: string[] = [];+ const gatedTools: string[] = [];const toolModules: string[] = [];+ const resultTools: Array<ResultToolManifest & { path: 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),);- }- 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(@@@ -3235,6 -2867,19 +3298,27 @@@`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 ")}`,+ );+ }++ // A gated tool's run() is written by the platform and returns its sentence;++ // there is no output of its own to commit as the session's result.++ const gatedResultTool = resultTools.find((tool) => gatedTools.includes(tool.id));++ if (gatedResultTool) {++ throw new Error(++ `${gatedResultTool.path} defineTool(${JSON.stringify(gatedResultTool.id)}) waits for approval and cannot be the result tool`,++ );++ }+ 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),);@@@ -3318,11 -2959,13 +3402,14 @@@version: 2,entry: "../agent.js",tools,+ gatedTools: [...gatedTools].sort(),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 every+ // reads one list, and a provider grant absent from it makes every// connected mailbox invisible to listServices().connections: [...new Set([diff --cc docs/agents/api.mdxindex 7d2775e0,a2025193..194247f1--- a/docs/agents/api.mdx+++ b/docs/agents/api.mdx@@@ -110,71 -106,14 +110,71 @@@ insufficient_credits`| `environment` | `development` or `production`, when the request named one || `status` | `new`, `connecting`, `idle`, `running`, `waiting_runtime`, `suspending`, `suspended`, `resuming`, `failed` or `ended` || `source` | The `source` given at creation |+| `labels`, `labelsUpdatedAt` | Your metadata, and when it last changed; see [Labels](#labels) || `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, `{ turnId, callId, reportedAt, data }`, or `null` when no turn has reported one |+ | `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. |+| `revision` | A counter that increases with every change to the session's status, turns, labels or result || `createdAt`, `updatedAt` | Timestamps |-`GET /sessions` returns `{ sessions }`: the fifty most recently updated-sessions of the organization, newest first, in the same shape. There are no-filters or paging parameters; keep your own index of session IDs.+`GET /sessions` returns one page of rows, `{ sessions, nextCursor }`, filtered+by the query:++```bash+curl 'https://app.opencomputer.dev/api/managed-agents/sessions?project=<project-id>&environment=development&label.topic=workshop&limit=50' \+ -H 'x-api-key: <api-key>'+```++| Parameter | Meaning |+| --- | --- |+| `project` | A project id or slug |+| `environment` | `development` or `production` |+| `agent` | An agent id |+| `status` | One session status |+| `label.<key>=<value>` | Sessions whose label `<key>` equals `<value>` exactly; at most three |+| `limit` | Rows per page, 1 to 100; default 50 |+| `cursor` | The `nextCursor` of the previous page |++Any other parameter is `400 invalid_query`, as is a malformed value. A+project-scoped key lists its own project; naming another is+`403 project_scope_violation`.++A row is `id`, `projectId`, `agentId`, `deploymentId`, `environment` (`null`+when the session has none), `source`, `status`, `labels`, `createdAt`,+`updatedAt`, `revision`, `activity` and `result`. `activity` is+`{ activeTurnId, queued, lastSettledTurn }`: the running turn's id or `null`,+how many turns wait behind it, and the most recently finished turn as+`{ id, status, at }` or `null`. Rows carry no `turns` and no `memory`; read+`GET /sessions/<id>` for those.++Rows are ordered by `createdAt`, newest first, then by `id`, and the order+never changes: a session that is updated does not move, so a traversal with+`cursor` sees every row exactly once even while sessions are running. To show+recent activity first, sort the page you hold by `updatedAt`. `nextCursor` is+`null` on the last page. A session appears in the list as soon as its create+call has returned.++### Labels++Labels are your own metadata on a session: at most 16 keys, each matching+`^[a-z][a-z0-9_.-]{0,63}$`, each value at most 256 characters, 4 KB in all.+They filter the list and appear on the session and its row. They are not+permissions, are not searched beyond equality, and are never shown to the+agent; give the agent its context in the turn input.++`PATCH /sessions/<id>/labels` changes them and returns the session:++```bash+curl -X PATCH 'https://app.opencomputer.dev/api/managed-agents/sessions/<session-id>/labels' \+ -H 'x-api-key: <api-key>' \+ -H 'Content-Type: application/json' \+ -d '{ "set": { "outcome": "merged" }, "unset": ["requested_by"] }'+```++`unset` removes keys, then `set` writes keys; each key takes the last write.+The session's `labelsUpdatedAt` records the change. A patch that would exceed+the bounds, or a key or value that does not fit them, is `400 invalid_labels`+and changes nothing. Labels can be changed on an ended session.### End and interruptdiff --cc docs/agents/tools.mdxindex 37e3db59,341927b5..440e2983--- a/docs/agents/tools.mdx+++ b/docs/agents/tools.mdx@@@ -58,12 -58,9 +58,13 @@@ 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 |++| `result` | no | `true` marks this tool as the agent's [result tool](#the-session-result); one per agent, and it must have `run` |+| `run` | yes* | Synchronous or asynchronous implementation |+| `preview` / `apply` | no | Supply these *instead of* `run` to [wait for a person](#wait-for-a-person-before-writing) |++\* A tool has either `run`, or `preview` and `apply` — never both, and never+just one of the pair.Descriptions are the model's documentation. Include the action, when it isappropriate, and any important precondition.@@@ -99,6 -96,73 +100,75 @@@ export const importCatalog = defineToolTool 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.++The build enforces three rules: an agent declares at most one result tool,++a result tool declares `output`, and it runs with `run()` rather than++[waiting for a person](#wait-for-a-person-before-writing). 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