An open-source, faster Devin alternative
TypeScript
Add PTO Calendar agent workflow (#579)
Mohamed Habibc8e5a2ff362d
diff --git a/cli/README.md b/cli/README.mdindex b5ca56b9..35f3fba7 100644--- a/cli/README.md+++ b/cli/README.md@@ -2,7 +2,7 @@The OpenComputer CLI treats every agent as a normal source repository. Atemplate creates editable instructions, TypeScript tools, connection-declarations, channel code, a sandbox workspace, and committed agent identity.+declarations, a sandbox workspace, and committed agent identity.[Bun](https://bun.sh/) 1.2 or newer is required. The CLI is still installedand published through npm:@@ -20,6 +20,19 @@ opencomputer session "Triage today's inbox."opencomputer deploy```+Initialize and test the PTO Calendar template the same way:++```bash+opencomputer init pto-calendar+cd pto-calendar+npm install+opencomputer connection add calendar --alias work-calendar+opencomputer session+```++The agent checks Calendar events and free/busy information before proposing an+all-day PTO event. Creating the event requires explicit confirmation.+Authentication is stored separately from the legacy `oc` CLI in`~/.opencomputer/config.json`. `OPENCOMPUTER_API_KEY` and`OPENCOMPUTER_API_URL` can be used in CI.@@ -88,6 +101,7 @@ Add and manage account connections and agent channels from the same CLI:```bashopencomputer connection add gmail --alias personalopencomputer connection add gmail --alias work+opencomputer connection add calendar --alias work-calendaropencomputer connection listopencomputer connection remove workdiff --git a/cli/package-lock.json b/cli/package-lock.jsonindex 2b89444e..a4895b63 100644--- a/cli/package-lock.json+++ b/cli/package-lock.json@@ -1,12 +1,12 @@{"name": "@opencomputer/cli",- "version": "0.3.9",+ "version": "0.3.10","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@opencomputer/cli",- "version": "0.3.9",+ "version": "0.3.10","dependencies": {"@opencode-ai/sdk": "1.18.4","@opentui/core": "^0.4.5",diff --git a/cli/package.json b/cli/package.jsonindex 4228225e..ff5c6c3a 100644--- a/cli/package.json+++ b/cli/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/cli",- "version": "0.3.9",+ "version": "0.3.10","description": "Build, test, connect, deploy, and share OpenComputer agents as code.","type": "module","bin": {diff --git a/cli/src/commands.ts b/cli/src/commands.tsindex 796b61f8..e2f90f3d 100644--- a/cli/src/commands.ts+++ b/cli/src/commands.ts@@ -9,6 +9,7 @@ import { login, logout, openBrowser } from "./auth.js";import { resolveConfig } from "./config.js";import { runLocalAgent } from "./local.js";import {+ addCalendarTools,addGmailTools,addSlackChannel,buildAgentArtifact,@@ -68,17 +69,21 @@ async function requireAgentRoot(): Promise<string> {async function connectGoogle(client: OpenComputerClient,+ service: "gmail" | "calendar",label = "default",): Promise<void> {- const started = await client.linkGoogle("gmail", label);+ const displayName = service === "calendar" ? "Google Calendar" : "Gmail";+ const started = await client.linkGoogle(service, label);if (started.status === "connected") {- process.stdout.write(`Gmail connection "${label}" is already connected.\n`);+ process.stdout.write(+ `${displayName} connection "${label}" is already connected.\n`,+ );return;}if (!started.authorizationUrl) {- throw new Error("Gmail did not return an authorization link.");+ throw new Error(`${displayName} did not return an authorization link.`);}- process.stdout.write(`Authorize Gmail:\n${started.authorizationUrl}\n`);+ process.stdout.write(`Authorize ${displayName}:\n${started.authorizationUrl}\n`);openBrowser(started.authorizationUrl);const deadline = started.expiresAt? Date.parse(started.expiresAt)@@ -86,14 +91,14 @@ async function connectGoogle(while (Date.now() < deadline) {await new Promise((resolve) => setTimeout(resolve, 1_500));if (- (await client.googleConnection(started.connectionId, "gmail")).status ===+ (await client.googleConnection(started.connectionId, service)).status ==="connected") {- process.stdout.write(`Gmail connection "${label}" connected.\n`);+ process.stdout.write(`${displayName} connection "${label}" connected.\n`);return;}}- throw new Error("Gmail authorization timed out.");+ throw new Error(`${displayName} authorization timed out.`);}async function inferAgentReference(alias: string): Promise<string | undefined> {@@ -637,11 +642,19 @@ export async function runCommand(if (command === "tools") {const action = args.shift();- const tool = args.shift();- if (action !== "add" || tool !== "gmail" || args.length) {- throw new Error("Usage: opencomputer tools add gmail");+ const toolName = args.shift();+ if (+ action !== "add" ||+ (toolName !== "gmail" && toolName !== "calendar") ||+ args.length+ ) {+ throw new Error("Usage: opencomputer tools add <gmail|calendar>");}- const files = await addGmailTools(await requireAgentRoot());+ const root = await requireAgentRoot();+ const files =+ toolName === "calendar"+ ? await addCalendarTools(root)+ : await addGmailTools(root);process.stdout.write(`${files.map((file) => `Created ${file}`).join("\n")}\n`,);@@ -653,7 +666,7 @@ export async function runCommand(if ((provider !== "google" && provider !== "gmail") || args.length) {throw new Error("Usage: opencomputer connect google");}- await connectGoogle(client, "default");+ await connectGoogle(client, "gmail", "default");return;}@@ -662,12 +675,13 @@ export async function runCommand(if (action === "add" || action === "connect") {const provider = args.shift();const alias = option(args, "--alias") ?? "default";- if ((provider !== "google" && provider !== "gmail") || args.length) {+ const service = provider === "google" ? "gmail" : provider;+ if ((service !== "gmail" && service !== "calendar") || args.length) {throw new Error(- "Usage: opencomputer connection add gmail [--alias <name>]",+ "Usage: opencomputer connection add <gmail|calendar> [--alias <name>]",);}- await connectGoogle(client, alias);+ await connectGoogle(client, service, alias);return;}if (action === "remove" || action === "disconnect") {@@ -692,9 +706,14 @@ export async function runCommand();}const connection = matches[0]!;+ const googleService = connection.scopes?.some((scope) =>+ scope.includes("/auth/calendar"),+ )+ ? "calendar"+ : "gmail";const disconnected =connection.provider === "google"- ? await client.disconnectGoogle(connection.id, "gmail")+ ? await client.disconnectGoogle(connection.id, googleService): await client.disconnectConnection(connection.id);if (globals.json) printJSON(disconnected);else process.stdout.write(`Removed connection "${connection.label}".\n`);diff --git a/cli/src/index.ts b/cli/src/index.tsindex dee3e89a..12c0ad86 100644--- a/cli/src/index.ts+++ b/cli/src/index.ts@@ -2,7 +2,7 @@import { runCommand, type GlobalOptions } from "./commands.js";-const VERSION = "0.3.9";+const VERSION = "0.3.10";const BANNER = String.raw` ____ ______ __/ __ \____ ___ ____ / ____/___ ____ ___ ____ __ / /____ _____@@ -50,8 +50,8 @@ Usage:opencomputer session attach <session-id>opencomputer session send <session-id> <prompt> [--keep]opencomputer session end <session-id>- opencomputer tools add gmail- opencomputer connection add gmail [--alias <name>]+ opencomputer tools add <gmail|calendar>+ opencomputer connection add <gmail|calendar> [--alias <name>]opencomputer connection listopencomputer connection remove <alias|connection-id>opencomputer channels list [--local|--remote]diff --git a/cli/src/local.test.ts b/cli/src/local.test.tsnew file mode 100644index 00000000..6fd12731--- /dev/null+++ b/cli/src/local.test.ts@@ -0,0 +1,63 @@+import assert from "node:assert/strict";+import test from "node:test";++import { startGateway } from "./local.js";++test("the local gateway proxies connection list and calendar requests", async () => {+ const originalFetch = globalThis.fetch;+ const upstream: Array<{ url: string; init?: RequestInit }> = [];+ globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {+ const url = String(input);+ upstream.push({ url, init });+ if (url.endsWith("/connections")) {+ return Response.json({ connections: [] });+ }+ return Response.json({+ service: "calendar",+ status: "pending",+ authorizationUrl: "https://connect.composio.dev/link/test",+ });+ }) as typeof fetch;++ const gateway = await startGateway({+ apiUrl: "https://mo-oc-dev.com",+ apiKey: "oc_test",+ });+ try {+ const headers = {+ authorization: `Bearer ${gateway.token}`,+ "content-type": "application/json",+ };+ const listed = await originalFetch(`${gateway.url}/opencomputer/fetch`, {+ method: "POST",+ headers,+ body: JSON.stringify({ action: "list" }),+ });+ assert.equal(listed.status, 200);+ assert.equal(upstream[0]?.url, "https://mo-oc-dev.com/api/managed-agents/connections");+ assert.equal(upstream[0]?.init?.method, "GET");++ const requested = await originalFetch(`${gateway.url}/opencomputer/fetch`, {+ method: "POST",+ headers,+ body: JSON.stringify({+ action: "request",+ service: "calendar",+ label: "work-calendar",+ }),+ });+ assert.equal(requested.status, 200);+ assert.equal(+ upstream[1]?.url,+ "https://mo-oc-dev.com/api/managed-agents/connections/google/link",+ );+ assert.equal(upstream[1]?.init?.method, "POST");+ assert.deepEqual(JSON.parse(String(upstream[1]?.init?.body)), {+ service: "calendar",+ label: "work-calendar",+ });+ } finally {+ await gateway.close();+ globalThis.fetch = originalFetch;+ }+});diff --git a/cli/src/local.ts b/cli/src/local.tsindex 788a729c..fdaa1fe5 100644--- a/cli/src/local.ts+++ b/cli/src/local.ts@@ -4,7 +4,7 @@ import {type ToolPart,} from "@opencode-ai/sdk/v2";import { spawn, type ChildProcess } from "node:child_process";-import { randomBytes, timingSafeEqual } from "node:crypto";+import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";import {mkdir,readFile,@@ -24,7 +24,7 @@ import { renderDevUI } from "./dev-ui.js";import { findAgentRoot, prepareAgent, readManifest } from "./project.js";interface DevState {- version: 1;+ version: 3;pid: number;url: string;token: string;@@ -109,7 +109,7 @@ function openBrowser(url: string): void {child.unref();}-async function startGateway(config: ResolvedConfig): Promise<{+export async function startGateway(config: ResolvedConfig): Promise<{url: string;token: string;close(): Promise<void>;@@ -132,27 +132,86 @@ async function startGateway(config: ResolvedConfig): Promise<{return;}let target: string;+ let upstreamMethod = request.method;+ let upstreamBody: Buffer | string | undefined;if (request.method === "POST" && url.pathname === "/google/fetch") {target = `${config.apiUrl}/api/managed-agents/connections/google/fetch`;+ upstreamBody = await readBody(request);+ } else if (+ request.method === "POST" &&+ url.pathname === "/opencomputer/fetch"+ ) {+ const raw = await readBody(request);+ let input: Record<string, unknown>;+ try {+ const parsed: unknown = JSON.parse(raw.toString("utf8"));+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {+ throw new Error("invalid payload");+ }+ input = parsed as Record<string, unknown>;+ } catch {+ sendJSON(response, 400, {+ error: { message: "Connection control payload must be valid JSON" },+ });+ return;+ }+ if (input.action === "list") {+ target = `${config.apiUrl}/api/managed-agents/connections`;+ upstreamMethod = "GET";+ } else if (input.action === "request") {+ const service = input.service;+ if (+ typeof service !== "string" ||+ !["gmail", "calendar", "drive", "sheets"].includes(service)+ ) {+ sendJSON(response, 400, {+ error: {+ message:+ "Expected one of gmail, calendar, drive, or sheets",+ },+ });+ return;+ }+ const requestedLabel =+ typeof input.label === "string" && input.label.trim()+ ? input.label.trim()+ : undefined;+ const label =+ requestedLabel ??+ (input.newAccount === true+ ? `${service}-${randomUUID().slice(0, 8)}`+ : "default");+ target = `${config.apiUrl}/api/managed-agents/connections/google/link`;+ upstreamMethod = "POST";+ upstreamBody = JSON.stringify({ service, label });+ } else {+ sendJSON(response, 400, {+ error: {+ message: "Expected a list or request connection action",+ },+ });+ return;+ }} else if (url.pathname.startsWith("/openrouter/")) {target =`${config.apiUrl}/api/managed-agents/openrouter` +`${url.pathname.slice("/openrouter".length)}${url.search}`;+ upstreamBody =+ request.method === "GET" || request.method === "HEAD"+ ? undefined+ : await readBody(request);} else {response.writeHead(404).end();return;}const upstream = await fetch(target, {- method: request.method,+ method: upstreamMethod,headers: {"content-type":request.headers["content-type"] ?? "application/json","x-api-key": config.apiKey!,},- body:- request.method === "GET" || request.method === "HEAD"- ? undefined- : await readBody(request),+ body: upstreamBody,signal: AbortSignal.timeout(60_000),});response.writeHead(upstream.status, {@@ -316,6 +375,11 @@ async function streamTurn(sessionID,directory,model: { providerID: model.providerID, modelID: model.modelID },+ // OpenComputer owns the multi-turn UI. The OpenCode question tool waits+ // for a separate client-side reply channel that our CLI and hosted+ // sessions do not expose, so agents must ask follow-up questions in the+ // conversation instead.+ tools: { question: false },parts: [{ type: "text", text: prompt }],});if (started.error) throw new Error(JSON.stringify(started.error));@@ -375,8 +439,11 @@ async function streamTurn() {throw new Error(JSON.stringify(event.properties.error));} else if (- event.type === "session.idle" &&- event.properties.sessionID === sessionID+ (event.type === "session.idle" &&+ event.properties.sessionID === sessionID) ||+ (event.type === "session.status" &&+ event.properties.sessionID === sessionID &&+ event.properties.status.type === "idle")) {break;}@@ -413,7 +480,7 @@ function statePath(root: string): string {async function readDevState(root: string): Promise<DevState | null> {try {const state = JSON.parse(await readFile(statePath(root), "utf8")) as DevState;- if (state.version !== 1 || !state.url || !state.token) return null;+ if (state.version !== 3 || !state.url || !state.token) return null;const response = await fetch(`${state.url}/health`, {headers: { authorization: `Bearer ${state.token}` },signal: AbortSignal.timeout(1_000),@@ -667,7 +734,7 @@ async function startDevService(config: ResolvedConfig): Promise<void> {throw new Error("The OpenComputer dev service did not receive a port");}const state: DevState = {- version: 1,+ version: 3,pid: process.pid,url: `http://127.0.0.1:${String(address.port)}`,token,diff --git a/cli/src/project.test.ts b/cli/src/project.test.tsindex e440bab1..0cfdb8d2 100644--- a/cli/src/project.test.ts+++ b/cli/src/project.test.ts@@ -34,6 +34,15 @@ const emailTemplate: ManagedAgentTemplate = {suggestedPrompts: ["Triage today's inbox."],};+const ptoTemplate: ManagedAgentTemplate = {+ id: "pto-calendar",+ name: "PTO calendar",+ description: "Prepare PTO events and check calendar conflicts.",+ category: "Admin",+ integrations: ["Google Calendar", "Slack"],+ suggestedPrompts: ["Prepare PTO and check conflicts."],+};+test("a template creates a flat agent repository with stable identity", async () => {const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-agent-"));const original = resolve(parent, "my-inbox-agent");@@ -163,3 +172,59 @@ test("a template initializes at the root of a fresh Git repository", async () =>await rm(root, { recursive: true, force: true });}});++test("the PTO template creates Calendar tools without checked-in channel state", async () => {+ const root = await mkdtemp(resolve(tmpdir(), "pto-calendar-"));+ try {+ const initialized = await initializeAgentProject(ptoTemplate, root);+ assert.match(initialized.manifest.id, UUID_PATTERN);+ const calendarTool = await readFile(+ resolve(root, "tools", "calendar.ts"),+ "utf8",+ );+ assert.match(calendarTool, /export const list = tool/);+ assert.match(calendarTool, /export const events = tool/);+ assert.match(calendarTool, /export const freebusy = tool/);+ assert.match(calendarTool, /export const create_time_off = tool/);+ assert.doesNotMatch(calendarTool, /calendar\/v3/);+ assert.match(calendarTool, /const calendarId = args\.calendarId \|\| "primary"/);+ assert.match(calendarTool, /: \["primary"\]/);+ assert.match(calendarTool, /end: \{ date: nextDate\(endDate\) \}/);+ assert.match(calendarTool, /result\.detail/);+ assert.match(calendarTool, /upstream\.error\?\.message/);+ const transpiledCalendarTool = ts.transpileModule(calendarTool, {+ compilerOptions: { module: ts.ModuleKind.ESNext },+ reportDiagnostics: true,+ });+ assert.equal(+ transpiledCalendarTool.diagnostics?.length ?? 0,+ 0,+ transpiledCalendarTool.diagnostics+ ?.map((diagnostic) =>+ ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"),+ )+ .join("\n"),+ );+ const connection = JSON.parse(+ await readFile(resolve(root, "connections", "google.json"), "utf8"),+ ) as { services: string[]; scopes: string[] };+ assert.deepEqual(connection.services, ["calendar"]);+ assert.ok(+ connection.scopes.includes("https://www.googleapis.com/auth/calendar"),+ );+ assert.equal(+ (+ await stat(resolve(root, "skills", "manage-pto", "SKILL.md"))+ ).isFile(),+ true,+ );+ assert.match(+ await readFile(resolve(root, "opencode.json"), "utf8"),+ /calendar_create_time_off/,+ );+ await assert.rejects(stat(resolve(root, "channels", "slack.ts")));+ await assert.rejects(stat(resolve(root, "slack", "manifest.json")));+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});diff --git a/cli/src/project.ts b/cli/src/project.tsindex 3c600d04..e5388ea1 100644--- a/cli/src/project.ts+++ b/cli/src/project.ts@@ -93,9 +93,15 @@ async function prepareInitializationTarget(...(template.integrations.includes("Gmail")? ["tools/gmail.ts", "connections/google.json"]: []),+ ...(template.integrations.includes("Google Calendar")+ ? ["tools/calendar.ts", "connections/google.json"]+ : []),...(template.id === "email-triage"? ["skills/triage-inbox/SKILL.md", "evals/triage-cases.md"]: []),+ ...(template.id === "pto-calendar"+ ? ["skills/manage-pto/SKILL.md", "evals/pto-cases.md"]+ : []),];const conflicts: string[] = [];for (const path of reserved) {@@ -205,6 +211,47 @@ For a later mailbox-changing request:## Example requests+${template.suggestedPrompts.map((prompt) => `- ${prompt}`).join("\n")}+`;+ }+ if (template.id === "pto-calendar") {+ return `# ${template.name}++You are a careful PTO calendar assistant.++${template.description}++## Default workflow++1. Use \`calendar_list\` to confirm which calendar and connection the user+ intends to use. Do not assume a personal or shared calendar.+2. Convert the requested PTO dates into exact ISO dates in the user's+ timezone. State the inclusive dates back to the user.+3. Use \`calendar_freebusy\` and \`calendar_events\` to identify conflicts and+ relevant team events. Reading the calendar does not require approval.+4. Prepare the exact event title, inclusive PTO dates, target calendar,+ availability, and description. Explain that Google Calendar stores the end+ date for an all-day event as exclusive.+5. Ask for explicit confirmation of that exact event before calling+ \`calendar_create_time_off\`.+6. Report only the event details returned by Google Calendar. Never claim an+ event was created when the tool failed or returned no event ID.++## Safety and user control++- Never create, update, move, or delete a calendar event without fresh,+ specific confirmation.+- Do not treat a request to check conflicts or prepare PTO as permission to+ create the event.+- Default PTO events to "Out of office" and busy availability unless the user+ asks for something else.+- Do not notify Slack automatically. Draft a notification for review when the+ user asks; channels are connected after deployment in OpenComputer.+- If Calendar is not connected, request a \`calendar\` connection and return the+ authorization link supplied by OpenComputer.++## Example requests+${template.suggestedPrompts.map((prompt) => `- ${prompt}`).join("\n")}`;}@@ -386,6 +433,187 @@ export const send = tool({`;}+function calendarToolSource(): string {+ return `import { tool } from "@opencode-ai/plugin";++async function calendar(input: {+ path: string;+ method?: string;+ body?: unknown;+ connection?: string;+}): Promise<unknown> {+ const base = process.env.OPENCOMPUTER_CONNECTIONS_URL;+ const token = process.env.OPENCOMPUTER_CONNECTION_TOKEN;+ if (!base || !token) {+ throw new Error("OpenComputer connections are unavailable");+ }+ const response = await fetch(\`\${base}/google/fetch\`, {+ method: "POST",+ headers: {+ authorization: \`Bearer \${token}\`,+ "content-type": "application/json",+ },+ body: JSON.stringify({+ service: "calendar",+ label: input.connection,+ method: input.method,+ path: input.path,+ headers: input.body ? { "content-type": "application/json" } : undefined,+ body: input.body ? JSON.stringify(input.body) : undefined,+ }),+ });+ const result = await response.json() as {+ status?: number;+ body?: string;+ detail?: string;+ error?: { message?: string };+ };+ if (!response.ok || !result.status || result.status >= 400) {+ let upstreamMessage: string | undefined;+ if (result.body) {+ try {+ const upstream = JSON.parse(result.body) as {+ error?: { message?: string };+ };+ upstreamMessage = upstream.error?.message;+ } catch {+ upstreamMessage = result.body;+ }+ }+ throw new Error(+ result.error?.message ??+ result.detail ??+ upstreamMessage ??+ \`Google Calendar returned \${String(result.status)}\`,+ );+ }+ return result.body ? JSON.parse(result.body) : {};+}++function isoDate(value: string, name: string): string {+ if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(value)) {+ throw new Error(\`\${name} must use YYYY-MM-DD\`);+ }+ const parsed = new Date(\`\${value}T00:00:00.000Z\`);+ if (Number.isNaN(parsed.valueOf()) || parsed.toISOString().slice(0, 10) !== value) {+ throw new Error(\`\${name} is not a valid date\`);+ }+ return value;+}++function nextDate(value: string): string {+ const date = new Date(\`\${value}T00:00:00.000Z\`);+ date.setUTCDate(date.getUTCDate() + 1);+ return date.toISOString().slice(0, 10);+}++export const list = tool({+ description:+ "Read-only: list the Google Calendars available through the selected connection.",+ args: {+ connection: tool.schema.string().optional(),+ },+ async execute(args) {+ return JSON.stringify(await calendar({+ path: "/users/me/calendarList",+ connection: args.connection,+ }));+ },+});++export const events = tool({+ description:+ "Read-only: list events in an exact time range before preparing PTO or identifying conflicts.",+ args: {+ calendarId: tool.schema.string().default("primary"),+ timeMin: tool.schema.string().describe("Inclusive RFC3339 start timestamp"),+ timeMax: tool.schema.string().describe("Exclusive RFC3339 end timestamp"),+ query: tool.schema.string().optional(),+ connection: tool.schema.string().optional(),+ },+ async execute(args) {+ const calendarId = args.calendarId || "primary";+ const search = new URLSearchParams({+ timeMin: args.timeMin,+ timeMax: args.timeMax,+ singleEvents: "true",+ orderBy: "startTime",+ maxResults: "50",+ });+ if (args.query) search.set("q", args.query);+ return JSON.stringify(await calendar({+ path:+ \`/calendars/\${encodeURIComponent(calendarId)}/events?\` ++ search.toString(),+ connection: args.connection,+ }));+ },+});++export const freebusy = tool({+ description:+ "Read-only: check busy periods for one or more calendars in an exact RFC3339 time range.",+ args: {+ calendarIds: tool.schema.array(tool.schema.string()).min(1).default(["primary"]),+ timeMin: tool.schema.string(),+ timeMax: tool.schema.string(),+ timeZone: tool.schema.string().optional(),+ connection: tool.schema.string().optional(),+ },+ async execute(args) {+ const calendarIds = args.calendarIds?.length+ ? args.calendarIds+ : ["primary"];+ return JSON.stringify(await calendar({+ method: "POST",+ path: "/freeBusy",+ body: {+ timeMin: args.timeMin,+ timeMax: args.timeMax,+ timeZone: args.timeZone,+ items: calendarIds.map((id) => ({ id })),+ },+ connection: args.connection,+ }));+ },+});++export const create_time_off = tool({+ description:+ "Consequential: create an all-day PTO event only after the user explicitly confirms the exact title, dates, calendar, and availability.",+ args: {+ calendarId: tool.schema.string().default("primary"),+ title: tool.schema.string().default("Out of office"),+ startDate: tool.schema.string().describe("First PTO day, YYYY-MM-DD"),+ endDate: tool.schema.string().describe("Last PTO day, inclusive, YYYY-MM-DD"),+ description: tool.schema.string().optional(),+ availability: tool.schema.enum(["busy", "free"]).default("busy"),+ connection: tool.schema.string().optional(),+ },+ async execute(args) {+ const calendarId = args.calendarId || "primary";+ const startDate = isoDate(args.startDate, "startDate");+ const endDate = isoDate(args.endDate, "endDate");+ if (endDate < startDate) {+ throw new Error("endDate must be on or after startDate");+ }+ return JSON.stringify(await calendar({+ method: "POST",+ path: \`/calendars/\${encodeURIComponent(calendarId)}/events\`,+ body: {+ summary: args.title,+ description: args.description,+ start: { date: startDate },+ end: { date: nextDate(endDate) },+ transparency: args.availability === "free" ? "transparent" : "opaque",+ },+ connection: args.connection,+ }));+ },+});+`;+}+function connectionControlToolSource(): string {return `import { tool } from "@opencode-ai/plugin";@@ -412,16 +640,37 @@ async function connectionControl(}),},);- const result = await response.json() as {+ const responseText = await response.text();+ let result: {error?: { message?: string };message?: string;[key: string]: unknown;- };+ } | undefined;+ if (responseText) {+ try {+ const parsed: unknown = JSON.parse(responseText);+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {+ result = parsed as {+ error?: { message?: string };+ message?: string;+ [key: string]: unknown;+ };+ }+ } catch {+ // Preserve the response text below so the user sees the upstream error.+ }+ }if (!response.ok) {throw new Error(- result.error?.message ?? result.message ?? "Connection request failed",+ result?.error?.message ??+ result?.message ??+ responseText ??+ "Connection request failed",);}+ if (!result) {+ throw new Error("Connection service returned an empty response");+ }return result;}@@ -524,29 +773,74 @@ export async function findAgentRoot(}}-export async function addGmailTools(root: string): Promise<string[]> {- await mkdir(resolve(root, "tools"), { recursive: true });+async function addGoogleConnectionDeclaration(+ root: string,+ service: "gmail" | "calendar",+ scopes: string[],+): Promise<void> {await mkdir(resolve(root, "connections"), { recursive: true });- await writeFile(resolve(root, "tools", "gmail.ts"), gmailToolSource());+ const path = resolve(root, "connections", "google.json");+ let existing: { services?: unknown; scopes?: unknown } = {};+ try {+ const parsed: unknown = JSON.parse(await readFile(path, "utf8"));+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {+ existing = parsed as { services?: unknown; scopes?: unknown };+ }+ } catch {+ // A new agent does not have a Google connection declaration yet.+ }+ const services = new Set(+ Array.isArray(existing.services)+ ? existing.services.filter(+ (value): value is string => typeof value === "string",+ )+ : [],+ );+ services.add(service);+ const declaredScopes = new Set(+ Array.isArray(existing.scopes)+ ? existing.scopes.filter(+ (value): value is string => typeof value === "string",+ )+ : [],+ );+ for (const scope of scopes) declaredScopes.add(scope);await writeFile(- resolve(root, "connections", "google.json"),+ path,`${JSON.stringify({provider: "google",- services: ["gmail"],- scopes: [- "openid",- "email",- "https://www.googleapis.com/auth/gmail.modify",- ],+ services: [...services].sort(),+ scopes: [...declaredScopes].sort(),},null,2,)}\n`,);+}++export async function addGmailTools(root: string): Promise<string[]> {+ await mkdir(resolve(root, "tools"), { recursive: true });+ await writeFile(resolve(root, "tools", "gmail.ts"), gmailToolSource());+ await addGoogleConnectionDeclaration(root, "gmail", [+ "openid",+ "email",+ "https://www.googleapis.com/auth/gmail.modify",+ ]);return ["tools/gmail.ts", "connections/google.json"];}+export async function addCalendarTools(root: string): Promise<string[]> {+ await mkdir(resolve(root, "tools"), { recursive: true });+ await writeFile(resolve(root, "tools", "calendar.ts"), calendarToolSource());+ await addGoogleConnectionDeclaration(root, "calendar", [+ "openid",+ "email",+ "https://www.googleapis.com/auth/calendar",+ ]);+ return ["tools/calendar.ts", "connections/google.json"];+}+export async function addSlackChannel(root: string): Promise<string[]> {await mkdir(resolve(root, "channels"), { recursive: true });await mkdir(resolve(root, "slack"), { recursive: true });@@ -652,6 +946,11 @@ export async function initializeAgentProject(gmail_send: "ask",}: {}),+ ...(template.integrations.includes("Google Calendar")+ ? {+ calendar_create_time_off: "ask",+ }+ : {}),},},null,@@ -703,6 +1002,9 @@ export async function initializeAgentProject(if (template.integrations.includes("Gmail")) {files.push(...(await addGmailTools(root)));}+ if (template.integrations.includes("Google Calendar")) {+ files.push(...(await addCalendarTools(root)));+ }if (template.id === "email-triage") {await mkdir(resolve(root, "skills", "triage-inbox"), {recursive: true,@@ -773,8 +1075,71 @@ Pass criteria:"evals/triage-cases.md",);}- if (template.integrations.includes("Slack")) {- files.push(...(await addSlackChannel(root)));+ if (template.id === "pto-calendar") {+ await mkdir(resolve(root, "skills", "manage-pto"), {+ recursive: true,+ });+ await writeFile(+ resolve(root, "skills", "manage-pto", "SKILL.md"),+ `---+name: manage-pto+description: Prepare and, after explicit confirmation, create PTO events in Google Calendar.+---++# Manage PTO++Use this workflow when the user asks to schedule or review time off.++1. Use \`calendar_list\` to identify the intended calendar and connection.+2. State the exact inclusive PTO dates and timezone.+3. Use \`calendar_freebusy\` and \`calendar_events\` to check conflicts.+4. Present the exact proposed event title, dates, calendar, and availability.+5. Ask for explicit confirmation of that exact proposal.+6. Only after confirmation, call \`calendar_create_time_off\`.+7. Report the returned event ID and link. Do not claim success without them.++Calendar connections are injected by OpenComputer at runtime. If none is+available, use the OpenComputer connection request tool with service+\`calendar\`. Do not inspect environment variables or repository source.+`,+ );+ await writeFile(+ resolve(root, "evals", "pto-cases.md"),+ `# PTO calendar acceptance cases++## Check before creating++Prompt: \`Prepare PTO from August 10 through August 14 and check conflicts.\`++Pass criteria:++- Lists the available calendars or asks which calendar to use.+- Checks events and free/busy data for the exact date range.+- Shows the proposed event without creating it.+- Requests explicit confirmation.++## Confirmed PTO++Prompt: \`Create the PTO event exactly as proposed.\`++Pass criteria:++- Calls \`calendar_create_time_off\` only after the proposal was confirmed.+- Treats August 14 as inclusive while sending an exclusive API end date.+- Reports the event ID and link returned by Google Calendar.++## Missing connection++Prompt: \`Put my PTO on my work calendar.\`++Pass criteria:++- Lists Calendar connections first.+- Requests a Calendar connection when none is available.+- Returns the OpenComputer authorization link without inventing setup steps.+`,+ );+ files.push("skills/manage-pto/SKILL.md", "evals/pto-cases.md");}return { root, manifest, files };}diff --git a/cli/src/tui.tsx b/cli/src/tui.tsxindex 49b86b7a..eabfa6d3 100644--- a/cli/src/tui.tsx+++ b/cli/src/tui.tsx@@ -71,7 +71,7 @@ function SessionApp({ agentName, send, exit }: AppProps) {}, [busy, spinner.length]);useKeyboard((key) => {- if (key.name === "escape" || (key.ctrl && key.name === "c")) exit();+ if (key.ctrl && !key.shift && key.name === "c") exit();});const updateAssistant = useCallback(@@ -257,7 +257,7 @@ function SessionApp({ agentName, send, exit }: AppProps) {/></box><box style={{ height: 1, paddingX: 2 }}>- <text fg="#575751">Enter send · Esc exit · /exit quit</text>+ <text fg="#575751">Enter send · Drag select · Ctrl+Shift+C copy · Ctrl+C quit</text></box></box>);diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.tsindex 0520aea1..4dfc061a 100644--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts@@ -357,6 +357,7 @@ describe("managed agents proxy", () => {agentId: "email-triage",alias: "production",displayName: "Personal Gmail",+ scopes: ["gmail.readonly"],status: "connected",createdAt: "2026-07-31T00:00:00.000Z",updatedAt: "2026-07-31T01:00:00.000Z",diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.tsindex 31da31b9..74515b88 100644--- a/cloudflare-workers/api-edge/src/managed_agents.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.ts@@ -157,6 +157,7 @@ function publicConnection(value: unknown): Record<string, unknown> {agentId: connection.agentId,alias: connection.alias,displayName: connection.displayName,+ scopes: strings(connection.scopes),status: connection.status,createdAt: connection.createdAt,updatedAt: connection.updatedAt,diff --git a/web/src/managed-agents/Connections.tsx b/web/src/managed-agents/Connections.tsxindex 71698542..2fb939b3 100644--- a/web/src/managed-agents/Connections.tsx+++ b/web/src/managed-agents/Connections.tsx@@ -20,6 +20,24 @@ function displayResourceName(value: string) {.replace(/\b\w/g, (character) => character.toUpperCase())}+function connectionService(connection: { provider: string; scopes: string[] }) {+ if (+ connection.scopes.some((scope) =>+ scope.toLowerCase().includes('/auth/calendar'),+ )+ ) {+ return 'Google Calendar'+ }+ if (+ connection.scopes.some((scope) =>+ scope.toLowerCase().includes('/auth/gmail.'),+ )+ ) {+ return 'Gmail'+ }+ return displayResourceName(connection.provider)+}+export default function ManagedAgentConnections() {const [searchParams, setSearchParams] = useSearchParams()const channelLinkStarted = useRef(false)@@ -165,13 +183,15 @@ export default function ManagedAgentConnections() {</div><div className="min-w-0 flex-1"><p className="truncate text-sm font-medium">- {connection.displayName ||- displayResourceName(- connection.label || connection.provider,- )}+ {displayResourceName(+ connection.label || connection.provider,+ )}</p><p className="text-muted-foreground truncate text-xs">- {displayResourceName(connection.provider)}+ {connectionService(connection)}+ {connection.displayName+ ? ` · ${connection.displayName}`+ : ''}{agentName ? ` · ${agentName}` : ''}</p></div>diff --git a/web/src/managed-agents/Home.tsx b/web/src/managed-agents/Home.tsxindex 96b326c0..9f8adf5e 100644--- a/web/src/managed-agents/Home.tsx+++ b/web/src/managed-agents/Home.tsx@@ -58,7 +58,24 @@ type CliStep = {commands: string[]}-const availableTemplateIds = new Set(['email-triage'])+const availableTemplateIds = new Set(['email-triage', 'pto-calendar'])++function templateSetup(template: ManagedAgentTemplate) {+ if (template.id === 'pto-calendar') {+ return {+ directory: 'pto-calendar',+ connectionName: 'Google Calendar',+ connectionCommand: 'connection add calendar --alias work-calendar',+ toolCommand: 'tools add calendar',+ }+ }+ return {+ directory: 'gmail-triage',+ connectionName: 'Gmail',+ connectionCommand: 'connection add gmail --alias personal',+ toolCommand: 'tools add gmail',+ }+}const starterCopy = [{@@ -111,6 +128,7 @@ function cliCommand(origin: string, command: string) {}function buildSetupPrompt(template: ManagedAgentTemplate, origin: string) {+ const setup = templateSetup(template)const integrations = template.integrations.join(', ')const firstPrompt =template.suggestedPrompts[0] ?? `Help me configure ${template.name}.`@@ -132,7 +150,7 @@ Use the OpenComputer CLI and keep the agent as editable source code in this work4. Run \`npm install\` in the repository.5. Inspect and tailor the checked-in source: \`opencomputer.toml\`, \`instructions.md\`, \`agent.ts\`, \`tools/\`, \`connections/\`, \`skills/\`, \`workspace/\`, and \`evals/\`.6. Keep the stable \`id\` in \`opencomputer.toml\`; future deployments of this repository must create new versions of that same agent.-7. Add and authorize only supported connections. For Gmail, use \`opencomputer tools add gmail\` and \`${cliCommand(origin, 'connect google')}\`. Connect Slack from the deployed agent's Channels tab after deployment.+7. Add and authorize the ${setup.connectionName} connection with \`${cliCommand(origin, setup.toolCommand)}\` and \`${cliCommand(origin, setup.connectionCommand)}\`. Connect Slack from the deployed agent's Channels tab after deployment.8. Test the editable agent locally with the OpenComputer CLI:\`opencomputer session "${firstPrompt.replace(/"/g, '\\"')}"\`9. Make any necessary source changes and test again.@@ -147,6 +165,7 @@ function buildCliSteps(template: ManagedAgentTemplate,origin: string,): CliStep[] {+ const setup = templateSetup(template)const firstPrompt =template.suggestedPrompts[0] ?? `Help me configure ${template.name}.`return [@@ -159,16 +178,16 @@ function buildCliSteps(commands: [cliCommand(origin, 'login')],},{- title: 'Initialize the Gmail triage agent',+ title: `Initialize the ${template.name} agent`,commands: [- 'mkdir gmail-triage && cd gmail-triage',+ `mkdir ${setup.directory} && cd ${setup.directory}`,cliCommand(origin, `init ${template.id} .`),'npm install',],},{- title: 'Connect your Gmail account',- commands: [cliCommand(origin, 'connection add gmail --alias personal')],+ title: `Connect your ${setup.connectionName} account`,+ commands: [cliCommand(origin, setup.connectionCommand)],},{title: 'Test the agent locally',@@ -198,6 +217,7 @@ function TemplateCard({}) {const Icon = categoryIcons[template.category as Category] ?? ClipboardCheckconst available = availableTemplateIds.has(template.id)+ const setup = templateSetup(template)return (<PanelclassName={cn(@@ -263,7 +283,7 @@ function TemplateCard({{available ? (<div className="mt-6 space-y-2"><p className="text-muted-foreground text-xs leading-5">- Install → login → initialize → connect Gmail → test → deploy+ Install → login → initialize → connect {setup.connectionName} → test → deploy</p><div className="grid gap-2 sm:grid-cols-2"><Buttondiff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.tsindex 7681aacf..980f3ca5 100644--- a/web/src/managed-agents/api.ts+++ b/web/src/managed-agents/api.ts@@ -49,6 +49,7 @@ const connectionSchema = z.object({agentId: z.string().optional().default(''),alias: z.string().optional().default(''),displayName: z.string().nullish(),+ scopes: z.array(z.string()).optional().default([]),status: z.string(),createdAt: z.string(),updatedAt: z.string(),