Skip to content

An open-source, faster Devin alternative

TypeScript

Add Linear connected service across SDK, CLI, dashboard, and docs (#768)

Mohamed Habib83d84409e4a7
diff --git a/agent/package-lock.json b/agent/package-lock.json
index ea72daab..d51561e3 100644
--- a/agent/package-lock.json
+++ b/agent/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@opencomputer/agent",
- "version": "0.7.4",
+ "version": "0.7.5",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@opencomputer/agent",
- "version": "0.7.4",
+ "version": "0.7.5",
"dependencies": {
"croner": "^9.1.0"
},
diff --git a/agent/package.json b/agent/package.json
index c78472c0..a28a8cad 100644
--- a/agent/package.json
+++ b/agent/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/agent",
- "version": "0.7.4",
+ "version": "0.7.5",
"description": "Reactive agent authoring API for OpenComputer.",
"type": "module",
"main": "./dist/index.js",
diff --git a/agent/src/index.ts b/agent/src/index.ts
index 6176f2a0..cb600178 100644
--- a/agent/src/index.ts
+++ b/agent/src/index.ts
@@ -494,7 +494,9 @@ export interface GatedToolDefinition<
readonly description: string;
readonly input?: ToolInputSchema;
readonly output?: ToolInputSchema;
- preview(context: ToolExecutionContext): ApprovalPreview | Promise<ApprovalPreview>;
+ preview(
+ context: ToolExecutionContext,
+ ): ApprovalPreview | Promise<ApprovalPreview>;
apply(context: GatedToolApplyContext): Output | Promise<Output>;
/**
* What the model calls. It does not write: it builds the preview, records
@@ -558,7 +560,9 @@ export async function publishApproval(
);
const idempotencyKey = input.idempotencyKey.trim();
if (!idempotencyKey || idempotencyKey.length > 256) {
- throw new Error("Approval idempotency keys must contain 1 to 256 characters");
+ throw new Error(
+ "Approval idempotency keys must contain 1 to 256 characters",
+ );
}
const runtime = globalThis as typeof globalThis & {
process?: { env?: Record<string, string | undefined> };
@@ -758,7 +762,8 @@ export type ManagedService =
| "calendar"
| "drive"
| "sheets"
- | "github";
+ | "github"
+ | "linear";
export interface ServiceRequest {
/** Which service. `google` is accepted as an alias for `gmail`. */
@@ -809,8 +814,9 @@ export async function callService(request: ServiceRequest): Promise<Response> {
if (!service) throw new Error("A service request needs a service");
// The provider segment routes the supervisor; the service in the body is what
// the platform resolves a credential for. GitHub and Google are separate
- // providers with separate grants, so the two cannot be collapsed.
- const provider = service === "github" ? "github" : "google";
+ // providers with separate grants, so they cannot be collapsed.
+ const provider =
+ service === "github" || service === "linear" ? service : "google";
const response = await fetch(`${base.replace(/\/$/, "")}/${provider}/fetch`, {
method: "POST",
headers: {
@@ -868,7 +874,7 @@ async function unwrapServiceResponse(response: Response): Promise<Response> {
/** A service account the platform holds a credential for, as listed. */
export interface ConnectedService {
readonly id: string;
- /** `google` or `github` — the grant, not the API being called. */
+ /** `google`, `github`, or `linear` — the grant, not the API being called. */
readonly provider: string;
/** The alias this account was connected under. Pass it as `label`. */
readonly label: string;
@@ -1479,7 +1485,9 @@ export interface GatedToolInput<Output extends DataValue = DataValue> {
* 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>;
+ preview(
+ context: ToolExecutionContext,
+ ): ApprovalPreview | Promise<ApprovalPreview>;
/** Runs only after somebody approves, from the arguments previewed above. */
apply(context: GatedToolApplyContext): Output | Promise<Output>;
}
diff --git a/cli/package-lock.json b/cli/package-lock.json
index 6eb34413..05390149 100644
--- a/cli/package-lock.json
+++ b/cli/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@opencomputer/cli",
- "version": "0.7.8",
+ "version": "0.7.9",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@opencomputer/cli",
- "version": "0.7.8",
+ "version": "0.7.9",
"dependencies": {
"@opencode-ai/sdk": "1.18.4",
"ai": "^7.0.45",
diff --git a/cli/package.json b/cli/package.json
index 54ceec68..6d07f9e3 100644
--- a/cli/package.json
+++ b/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/cli",
- "version": "0.7.8",
+ "version": "0.7.9",
"description": "Build, test, deploy, and share OpenComputer agents as code.",
"type": "module",
"bin": {
diff --git a/cli/src/api.ts b/cli/src/api.ts
index e8f8ace4..60b3c42c 100644
--- a/cli/src/api.ts
+++ b/cli/src/api.ts
@@ -311,7 +311,12 @@ export interface ManagedSessionSummary {
queued: number;
lastSettledTurn: { id: string; status: string; at: string } | null;
};
- result: { turnId: string; callId: string; reportedAt: string; data: unknown } | null;
+ result: {
+ turnId: string;
+ callId: string;
+ reportedAt: string;
+ data: unknown;
+ } | null;
}
export interface ManagedSessionPage {
@@ -688,7 +693,7 @@ export class OpenComputerClient {
// ── Connected services ───────────────────────────────────────────────────
// Accounts the platform holds an OAuth credential for, reached from an agent
// with callService(). The provider segment is the grant — google covers
- // gmail, calendar, drive and sheets; github is its own.
+ // gmail, calendar, drive and sheets; github and linear are their own.
async serviceConnections(): Promise<ServiceConnection[]> {
const result = await this.request<{ connections: ServiceConnection[] }>(
@@ -703,7 +708,10 @@ export class OpenComputerClient {
* signs in to OpenComputer.
*/
linkServiceConnection(input: { service: string; label?: string }) {
- const provider = input.service === "github" ? "github" : "google";
+ const provider =
+ input.service === "github" || input.service === "linear"
+ ? input.service
+ : "google";
return this.request<{
service: string;
label: string;
@@ -729,7 +737,10 @@ export class OpenComputerClient {
* actually authorized it.
*/
serviceConnectionStatus(input: { service: string; label: string }) {
- const provider = input.service === "github" ? "github" : "google";
+ const provider =
+ input.service === "github" || input.service === "linear"
+ ? input.service
+ : "google";
const query = new URLSearchParams({
service: input.service,
label: input.label,
@@ -740,11 +751,19 @@ export class OpenComputerClient {
status: string;
connectionId?: string;
scopes?: string[];
- }>(`/api/managed-agents/connections/${provider}/status?${query.toString()}`);
+ }>(
+ `/api/managed-agents/connections/${provider}/status?${query.toString()}`,
+ );
}
- disconnectServiceConnection(input: { service: string; connectionId: string }) {
- const provider = input.service === "github" ? "github" : "google";
+ disconnectServiceConnection(input: {
+ service: string;
+ connectionId: string;
+ }) {
+ const provider =
+ input.service === "github" || input.service === "linear"
+ ? input.service
+ : "google";
const query = new URLSearchParams({
service: input.service,
connectionId: input.connectionId,
@@ -1027,14 +1046,17 @@ export class OpenComputerClient {
const response = await this.request<{
environment: "development" | "production";
result: DatabaseResult;
- }>(`/api/managed-agents/projects/${encodeURIComponent(input.projectId)}/database/query`, {
- method: "POST",
- body: JSON.stringify({
- environment: input.environment,
- sql: input.sql,
- parameters: input.parameters ?? [],
- }),
- });
+ }>(
+ `/api/managed-agents/projects/${encodeURIComponent(input.projectId)}/database/query`,
+ {
+ method: "POST",
+ body: JSON.stringify({
+ environment: input.environment,
+ sql: input.sql,
+ parameters: input.parameters ?? [],
+ }),
+ },
+ );
return response.result;
}
@@ -1271,17 +1293,24 @@ export class OpenComputerClient {
: {}),
}),
});
- const body = (await response.json()) as Omit<CreateSessionResult, "created">;
+ const body = (await response.json()) as Omit<
+ CreateSessionResult,
+ "created"
+ >;
return { created: response.status === 201, ...body };
}
/** One page of session rows, newest created first; pass `cursor` for the next page. */
- async sessions(options: { cursor?: string; limit?: number } = {}): Promise<ManagedSessionPage> {
+ async sessions(
+ options: { cursor?: string; limit?: number } = {},
+ ): Promise<ManagedSessionPage> {
const query = new URLSearchParams();
if (options.cursor) query.set("cursor", options.cursor);
if (options.limit) query.set("limit", String(options.limit));
const suffix = query.size ? `?${query.toString()}` : "";
- return this.request<ManagedSessionPage>(`/api/managed-agents/sessions${suffix}`);
+ return this.request<ManagedSessionPage>(
+ `/api/managed-agents/sessions${suffix}`,
+ );
}
session(sessionId: string) {
diff --git a/cli/src/commands.ts b/cli/src/commands.ts
index 10596abb..47041ede 100644
--- a/cli/src/commands.ts
+++ b/cli/src/commands.ts
@@ -126,8 +126,13 @@ function environmentOption(
function databaseParameter(value: string): string | number | boolean | null {
try {
const parsed: unknown = JSON.parse(value);
- if (parsed === null || typeof parsed === "string" || typeof parsed === "boolean" ||
- (typeof parsed === "number" && Number.isFinite(parsed))) return parsed;
+ if (
+ parsed === null ||
+ typeof parsed === "string" ||
+ typeof parsed === "boolean" ||
+ (typeof parsed === "number" && Number.isFinite(parsed))
+ )
+ return parsed;
} catch {
// The error below explains the accepted CLI form.
}
@@ -147,12 +152,21 @@ function printDatabaseResult(result: {
}
process.stdout.write(`${result.columns.join("\t")}\n`);
for (const row of result.rows) {
- process.stdout.write(`${result.columns.map((column) => {
- const value = row[column];
- return value === null || value === undefined ? "NULL" : String(value).replace(/[\t\r\n]+/g, " ");
- }).join("\t")}\n`);
+ process.stdout.write(
+ `${result.columns
+ .map((column) => {
+ const value = row[column];
+ return value === null || value === undefined
+ ? "NULL"
+ : String(value).replace(/[\t\r\n]+/g, " ");
+ })
+ .join("\t")}\n`,
+ );
}
- if (result.truncated) process.stdout.write("Result truncated; add LIMIT and paginate the query.\n");
+ if (result.truncated)
+ process.stdout.write(
+ "Result truncated; add LIMIT and paginate the query.\n",
+ );
}
function consumeModelAccessProvider(
@@ -179,7 +193,9 @@ async function readTemplateSecretValue(): Promise<string> {
for await (const chunk of process.stdin) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
}
- const value = Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/, "");
+ const value = Buffer.concat(chunks)
+ .toString("utf8")
+ .replace(/\r?\n$/, "");
if (!value) throw new Error("Secret value was empty");
return value;
}
@@ -221,14 +237,16 @@ async function readStdinValue(enabled: boolean): Promise<string> {
throw new CLIError(
"value_stdin_required",
"--value-stdin requires piped standard input.",
- "Use `printf %s \"$VALUE\" | opencomputer ... --value-stdin`.",
+ 'Use `printf %s "$VALUE" | opencomputer ... --value-stdin`.',
);
}
const chunks: Buffer[] = [];
for await (const chunk of process.stdin) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
}
- const value = Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/, "");
+ const value = Buffer.concat(chunks)
+ .toString("utf8")
+ .replace(/\r?\n$/, "");
if (!value) throw new Error("Standard-input value was empty");
return value;
}
@@ -320,7 +338,9 @@ async function requireAgentRoot(): Promise<string> {
return root;
}
-function printSession(session: ManagedSessionSnapshot | ManagedSessionSummary): void {
+function printSession(
+ session: ManagedSessionSnapshot | ManagedSessionSummary,
+): void {
const deployment = session.deploymentId
? session.deploymentId.slice(session.deploymentId.lastIndexOf(":") + 1)
: "—";
@@ -692,7 +712,11 @@ async function runAgent(
(event) => printSessionProgress(event, json, verbose),
90_000,
);
- const turn = await client.createTurn(created.session.id, prompt, idempotencyKey);
+ const turn = await client.createTurn(
+ created.session.id,
+ prompt,
+ idempotencyKey,
+ );
let streamed = false;
let streamedText = "";
let completedText = "";
@@ -752,9 +776,14 @@ function printMemoryBindings(
return `Memory: ${resource} (collection, read)\n`;
}
const ensured = documents.find(
- (document) => document.resource === resource && document.id === binding.id,
+ (document) =>
+ document.resource === resource && document.id === binding.id,
);
- const state = ensured ? (ensured.created ? ", created" : ", existing") : "";
+ const state = ensured
+ ? ensured.created
+ ? ", created"
+ : ", existing"
+ : "";
return `Memory: ${resource}/${binding.id} (${binding.access ?? "read-write"}${state})\n`;
})
.join("");
@@ -826,9 +855,14 @@ export async function runCommand(
response: await client.projectSourceArchive(project.id),
directory: directory ?? project.slug,
});
- const binding = await ensureProjectBinding(client, config, checkout.directory, {
- project: project.id,
- });
+ const binding = await ensureProjectBinding(
+ client,
+ config,
+ checkout.directory,
+ {
+ project: project.id,
+ },
+ );
if (globals.json) printJSON({ checkout, binding });
else {
process.stdout.write(
@@ -875,9 +909,7 @@ export async function runCommand(
return;
}
if (action !== "deploy") {
- throw new Error(
- "Usage: opencomputer template <deploy|clone> ...",
- );
+ throw new Error("Usage: opencomputer template <deploy|clone> ...");
}
const projectNameOption = option(args, "--project-name");
const directoryOption = option(args, "--directory");
@@ -1016,9 +1048,14 @@ export async function runCommand(
`Template installation is still ${current.state}; ${current.projectUrl}`,
);
}
- const binding = await ensureProjectBinding(client, config, checkout.directory, {
- project: current.projectId,
- });
+ const binding = await ensureProjectBinding(
+ client,
+ config,
+ checkout.directory,
+ {
+ project: current.projectId,
+ },
+ );
if (globals.json) printJSON({ installation: current, checkout, binding });
else {
process.stdout.write(
@@ -1272,15 +1309,10 @@ export async function runCommand(
diagnosis,
);
}
- await runCloudDevelopment(
- client,
- config,
- root,
- {
- project,
- createProjectName,
- },
- );
+ await runCloudDevelopment(client, config, root, {
+ project,
+ createProjectName,
+ });
return;
}
@@ -1289,11 +1321,7 @@ export async function runCommand(
const projectReference = option(args, "--project");
const agentOption = option(args, "--agent");
const environment = environmentOption(option(args, "--environment"));
- const project = await selectedProject(
- client,
- config,
- projectReference,
- );
+ const project = await selectedProject(client, config, projectReference);
const agentId = agentOption
? agentOption === "current"
? project.agentId
@@ -1381,36 +1409,45 @@ export async function runCommand(
throw new Error("Use `opencomputer secrets set`, `list`, or `remove`.");
}
-/**
- * Which service a connected account is for.
- *
- * The listing reports the PROVIDER — `google` covers gmail, calendar, drive
- * and sheets — but the disconnect route wants the service. The grant's scopes
- * are what distinguish them.
- */
-function serviceOfConnection(connection: {
- provider: string;
- scopes?: string[];
-}): string {
- if (connection.provider === "github") return "github";
- const scopes = (connection.scopes ?? []).join(" ");
- if (scopes.includes("/auth/calendar")) return "calendar";
- if (scopes.includes("/auth/spreadsheets")) return "sheets";
- if (scopes.includes("/auth/drive")) return "drive";
- return "gmail";
-}
+ /**
+ * Which service a connected account is for.
+ *
+ * The listing reports the PROVIDER — `google` covers gmail, calendar, drive
+ * and sheets — but the disconnect route wants the service. The grant's scopes
+ * are what distinguish them.
+ */
+ function serviceOfConnection(connection: {
+ provider: string;
+ scopes?: string[];
+ }): string {
+ if (connection.provider === "github") return "github";
+ const scopes = (connection.scopes ?? []).join(" ");
+ if (scopes.includes("/auth/calendar")) return "calendar";
+ if (scopes.includes("/auth/spreadsheets")) return "sheets";
+ if (scopes.includes("/auth/drive")) return "drive";
+ return "gmail";
+ }
if (command === "connection" || command === "connections") {
// Accounts the platform holds an OAuth credential for. Nothing secret
// passes through here: `add` returns a link for the account's owner to
// open, and the token is minted and refreshed server-side.
- const SERVICES = ["gmail", "calendar", "drive", "sheets", "github"];
+ const SERVICES = [
+ "gmail",
+ "calendar",
+ "drive",
+ "sheets",
+ "github",
+ "linear",
+ ];
const action = args.shift();
if (action === "add" || action === "connect") {
const service = args.shift();
if (!service || !SERVICES.includes(service)) {
- throw new Error(`Use \`opencomputer connection add <${SERVICES.join("|")}>\``);
+ throw new Error(
+ `Use \`opencomputer connection add <${SERVICES.join("|")}>\``,
+ );
}
const label = option(args, "--alias") ?? option(args, "--label");
const noWait = flag(args, "--no-wait");
@@ -1520,7 +1557,9 @@ function serviceOfConnection(connection: {
if (action === "remove" || action === "disconnect") {
const target = args.shift();
if (!target) {
- throw new Error("Use `opencomputer connection remove <alias|connection-id>`");
+ throw new Error(
+ "Use `opencomputer connection remove <alias|connection-id>`",
+ );
}
const service = option(args, "--service");
if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);
@@ -1557,7 +1596,8 @@ function serviceOfConnection(connection: {
service: resolved,
connectionId: connection.id,
});
- if (globals.json) printJSON({ removed: connection.id, label: connection.label });
+ if (globals.json)
+ printJSON({ removed: connection.id, label: connection.label });
else process.stdout.write(`Removed ${connection.label} (${resolved}).\n`);
return;
}
@@ -1591,14 +1631,17 @@ function serviceOfConnection(connection: {
? await readStdinValue(true)
: await readTemplateSecretValue();
const connection = await client.connectModelAccessApiKey({
- provider: provider === "openrouter" ? "openrouter" : "openai_compatible",
+ provider:
+ provider === "openrouter" ? "openrouter" : "openai_compatible",
api_key: apiKey,
...(baseUrl ? { base_url: baseUrl } : {}),
...(label ? { label } : {}),
});
if (globals.json) printJSON(connection);
else {
- process.stdout.write(`Connected ${connection.label}; status ${connection.status}.\n`);
+ process.stdout.write(
+ `Connected ${connection.label}; status ${connection.status}.\n`,
+ );
if (projectReference) {
process.stdout.write(
`Next: opencomputer model-route set --project ${projectReference} --connection ${connection.id} --model <model>\n`,
@@ -1620,10 +1663,12 @@ function serviceOfConnection(connection: {
);
if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);
const currentAgentRoot = projectReference ? null : await findAgentRoot();
- const project =
- shouldBindModelAccessProject(projectReference, currentAgentRoot)
- ? await selectedProject(client, config, projectReference)
- : undefined;
+ const project = shouldBindModelAccessProject(
+ projectReference,
+ currentAgentRoot,
+ )
+ ? await selectedProject(client, config, projectReference)
+ : undefined;
const environments = project
? (["development", "production"] as const)
: [];
@@ -1716,11 +1761,12 @@ function serviceOfConnection(connection: {
const routes = await client.modelRoutes(project.projectId);
if (globals.json) printJSON(routes);
else if (!routes.length) process.stdout.write("No model routes.\n");
- else for (const route of routes) {
- process.stdout.write(
- `${route.environment.padEnd(11)} ${(route.agentId ?? "project").padEnd(20)} ${route.model} via ${route.connectionId} (${route.fallback}) r${route.revision}\n`,
- );
- }
+ else
+ for (const route of routes) {
+ process.stdout.write(
+ `${route.environment.padEnd(11)} ${(route.agentId ?? "project").padEnd(20)} ${route.model} via ${route.connectionId} (${route.fallback}) r${route.revision}\n`,
+ );
+ }
return;
}
const agentId = option(args, "--agent");
@@ -1728,7 +1774,8 @@ function serviceOfConnection(connection: {
const connectionId = option(args, "--connection");
const model = option(args, "--model");
const fallback = option(args, "--fallback") ?? "fail";
- if (!connectionId || !model) throw new Error("--connection and --model are required");
+ if (!connectionId || !model)
+ throw new Error("--connection and --model are required");
if (fallback !== "fail" && fallback !== "managed") {
throw new Error("--fallback must be fail or managed");
}
@@ -1746,7 +1793,10 @@ function serviceOfConnection(connection: {
),
);
if (globals.json) printJSON(routes);
- else process.stdout.write(`Set ${agentId ? `agent ${agentId}` : "project"} route for development and production.\n`);
+ else
+ process.stdout.write(
+ `Set ${agentId ? `agent ${agentId}` : "project"} route for development and production.\n`,
+ );
return;
}
if (action === "delete" || action === "remove") {
@@ -1761,7 +1811,10 @@ function serviceOfConnection(connection: {
),
);
if (globals.json) printJSON({ deleted: true });
- else process.stdout.write("Removed model route from development and production.\n");
+ else
+ process.stdout.write(
+ "Removed model route from development and production.\n",
+ );
return;
}
throw new Error("Use `opencomputer model-route set|list|delete`.");
@@ -1772,11 +1825,7 @@ function serviceOfConnection(connection: {
const projectReference = option(args, "--project");
const agentOption = option(args, "--agent");
const environment = environmentOption(option(args, "--environment"));
- const project = await selectedProject(
- client,
- config,
- projectReference,
- );
+ const project = await selectedProject(client, config, projectReference);
const agentId = agentOption
? agentOption === "current"
? project.agentId
@@ -1846,11 +1895,7 @@ function serviceOfConnection(connection: {
const projectReference = option(args, "--project");
const agentOption = option(args, "--agent");
const environment = environmentOption(option(args, "--environment"));
- const project = await selectedProject(
- client,
- config,
- projectReference,
- );
+ const project = await selectedProject(client, config, projectReference);
const agentId = await selectedSessionAgent(
client,
project,
@@ -1881,13 +1926,17 @@ function serviceOfConnection(connection: {
const name = args.shift()?.trim();
const identity = option(args, "--identity");
if (!name || args.length) {
- throw new Error("Use `opencomputer webhooks create <name> [--identity header:<name>|body:<json-pointer>]`.");
+ throw new Error(
+ "Use `opencomputer webhooks create <name> [--identity header:<name>|body:<json-pointer>]`.",
+ );
}
- const existing = (await client.webhooks({
- projectId: project.projectId,
- environment,
- agentId,
- })).find((candidate) => candidate.name === name);
+ const existing = (
+ await client.webhooks({
+ projectId: project.projectId,
+ environment,
+ agentId,
+ })
+ ).find((candidate) => candidate.name === name);
const webhook =
existing ??
(await client.createWebhook({
@@ -1912,7 +1961,8 @@ function serviceOfConnection(connection: {
return;
}
const webhookId = args.shift();
- const identityOption = action === "update" ? option(args, "--identity") : undefined;
+ const identityOption =
+ action === "update" ? option(args, "--identity") : undefined;
if (!webhookId || args.length) {
throw new Error(
"Use `opencomputer webhooks list|create|update|enable|disable|rotate-token|remove`.",
@@ -1920,7 +1970,9 @@ function serviceOfConnection(connection: {
}
if (action === "update") {
if (identityOption === undefined) {
- throw new Error("Use `opencomputer webhooks update <id> --identity header:<name>|body:<json-pointer>|none`.");
+ throw new Error(
+ "Use `opencomputer webhooks update <id> --identity header:<name>|body:<json-pointer>|none`.",
+ );
}
const webhook = await client.updateWebhook({
projectId: project.projectId,
@@ -1983,7 +2035,9 @@ function serviceOfConnection(connection: {
const parameters = options(args, "--parameter").map(databaseParameter);
const sql = args.shift();
if (action !== "query" || !sql || args.length) {
- throw new Error("Use `opencomputer database query <sql> [--environment development|production] [--parameter <json>]... [--project <id|slug>]`.");
+ throw new Error(
+ "Use `opencomputer database query <sql> [--environment development|production] [--parameter <json>]... [--project <id|slug>]`.",
+ );
}
const project = await selectedProject(client, config, projectReference);
const result = await client.databaseQuery({
@@ -2026,7 +2080,8 @@ function serviceOfConnection(connection: {
"Pass --resource <id> for each resource to export, or deploy an agent that declares memory.",
);
}
- const exported: Array<{ resource: string; id: string; path: string }> = [];
+ const exported: Array<{ resource: string; id: string; path: string }> =
+ [];
for (const resource of resources) {
const directory = resolvePath(out, resource);
await mkdir(directory, { recursive: true });
@@ -2046,7 +2101,11 @@ function serviceOfConnection(connection: {
environment,
});
const path = join(directory, `${document.id}.json`);
- await writeFile(path, `${JSON.stringify(document, null, 2)}\n`, "utf8");
+ await writeFile(
+ path,
+ `${JSON.stringify(document, null, 2)}\n`,
+ "utf8",
+ );
exported.push({ resource, id: document.id, path });
}
cursor = page.nextCursor ?? undefined;
@@ -2161,7 +2220,9 @@ function serviceOfConnection(connection: {
const supplied = await readMemoryText(args);
if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);
const current = await client.memoryDocument(target);
- let edited: Awaited<ReturnType<typeof editMemoryTextInEditor>> | undefined;
+ let edited:
+ | Awaited<ReturnType<typeof editMemoryTextInEditor>>
+ | undefined;
const text =
supplied ??
(edited = await editMemoryTextInEditor(
@@ -2180,7 +2241,9 @@ function serviceOfConnection(connection: {
etag: current.etag,
text,
...(summary !== undefined ? { summary } : {}),
- ...(edited ? { draft: { path: edited.path, discard: edited.discard } } : {}),
+ ...(edited
+ ? { draft: { path: edited.path, discard: edited.discard } }
+ : {}),
});
if (globals.json) printJSON(document);
else {
@@ -2215,7 +2278,8 @@ function serviceOfConnection(connection: {
const current = await client.memoryDocument(target);
await client.deleteMemoryDocument({ ...target, etag: current.etag });
if (globals.json) printJSON({ deleted: true, resource, id, environment });
- else process.stdout.write(`Removed ${resource}/${id} (${environment}).\n`);
+ else
+ process.stdout.write(`Removed ${resource}/${id} (${environment}).\n`);
return;
}
throw new Error(MEMORY_USAGE);
@@ -2243,9 +2307,7 @@ function serviceOfConnection(connection: {
insideProject = false;
}
if (insideProject) {
- agentId = (
- await selectedProject(client, config)
- ).agentId;
+ agentId = (await selectedProject(client, config)).agentId;
}
}
let cursor = "";
@@ -2284,11 +2346,7 @@ function serviceOfConnection(connection: {
const agentOption = option(args, "--agent");
const environment = environmentOption(option(args, "--environment"));
if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);
- const project = await selectedProject(
- client,
- config,
- projectReference,
- );
+ const project = await selectedProject(client, config, projectReference);
const agentId = await selectedSessionAgent(
client,
project,
@@ -2297,7 +2355,8 @@ function serviceOfConnection(connection: {
const channels = (await client.channels()).filter(
(channel) => channel.agentId === agentId && channel.alias === environment,
);
- if (globals.json) printJSON({ projectId: project.projectId, environment, channels });
+ if (globals.json)
+ printJSON({ projectId: project.projectId, environment, channels });
else if (!channels.length) process.stdout.write("No matching channels.\n");
else {
for (const channel of channels) {
@@ -2348,11 +2407,7 @@ function serviceOfConnection(connection: {
}
if (session.action === "create") {
const prompt = sessionArgs.join(" ").trim();
- const project = await selectedProject(
- client,
- config,
- undefined,
- );
+ const project = await selectedProject(client, config, undefined);
const agentId = await selectedSessionAgent(
client,
project,
@@ -2360,13 +2415,14 @@ function serviceOfConnection(connection: {
);
const agent = developmentAgentReference(agentId);
// Sessions from the CLI run on Development, so its memory is bound.
- const documents = session.createDocuments && session.memory
- ? await ensureMemoryDocuments(client, {
- projectId: project.projectId,
- environment: "development",
- bindings: session.memory,
- })
- : [];
+ const documents =
+ session.createDocuments && session.memory
+ ? await ensureMemoryDocuments(client, {
+ projectId: project.projectId,
+ environment: "development",
+ bindings: session.memory,
+ })
+ : [];
if (prompt) {
const result = await runAgent(
client,
diff --git a/cli/src/index.ts b/cli/src/index.ts
index fce11710..2a7a44ea 100644
--- a/cli/src/index.ts
+++ b/cli/src/index.ts
@@ -75,7 +75,7 @@ Usage:
opencomputer env set <name> --value-stdin [--environment development|production] [--agent <agent>|current]
opencomputer env list [--environment development|production] [--agent <agent>|current]
opencomputer env remove <name> [--environment development|production] [--agent <agent>|current]
- opencomputer connection add <gmail|calendar|drive|sheets|github> [--alias <name>] [--no-wait]
+ opencomputer connection add <gmail|calendar|drive|sheets|github|linear> [--alias <name>] [--no-wait]
opencomputer connection list
opencomputer connection remove <alias|connection-id> [--service <name>]
opencomputer model-access connect codex [--project <id|slug>]
@@ -148,7 +148,9 @@ main().catch((error: unknown) => {
if (process.argv.includes("--json")) {
process.stderr.write(`${JSON.stringify({ error: failure })}\n`);
} else {
- process.stderr.write(`opencomputer: ${failure.message}\nfix: ${failure.hint}\n`);
+ process.stderr.write(
+ `opencomputer: ${failure.message}\nfix: ${failure.hint}\n`,
+ );
}
process.exitCode = 1;
});
diff --git a/cli/src/project.test.ts b/cli/src/project.test.ts
index 64becd53..21960b3a 100644
--- a/cli/src/project.test.ts
+++ b/cli/src/project.test.ts
@@ -120,8 +120,12 @@ test("the compiler normalizes project channels, registrations, and outboxes", as
const opencomputer = resolve(root, "opencomputer");
await mkdir(resolve(opencomputer, "channels"), { recursive: true });
await mkdir(resolve(opencomputer, "outboxes"), { recursive: true });
- await mkdir(resolve(initialized.agentRoot, "channels"), { recursive: true });
- await mkdir(resolve(initialized.agentRoot, "outboxes"), { recursive: true });
+ await mkdir(resolve(initialized.agentRoot, "channels"), {
+ recursive: true,
+ });
+ await mkdir(resolve(initialized.agentRoot, "outboxes"), {
+ recursive: true,
+ });
await writeFile(
resolve(opencomputer, "channels", "team-slack.ts"),
`import { defineChannel } from "@opencomputer/agent";
@@ -213,8 +217,12 @@ test("the compiler normalizes code-defined agent schedules", async () => {
const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-schedules-"));
const root = resolve(parent, "app");
try {
- const initialized = await initializeAgentProject(root, undefined, { spa: false });
- await mkdir(resolve(initialized.agentRoot, "schedules"), { recursive: true });
+ const initialized = await initializeAgentProject(root, undefined, {
+ spa: false,
+ });
+ await mkdir(resolve(initialized.agentRoot, "schedules"), {
+ recursive: true,
+ });
await writeFile(
resolve(initialized.agentRoot, "schedules", "weekday-hygiene.ts"),
`import { defineSchedule } from "@opencomputer/agent";
@@ -373,9 +381,7 @@ export default function Agent() {
httpConnections: [],
githubConnections: [],
mcpServers: ["docs"],
- mcpServerDefinitions: [
- { id: "docs", url: "https://mcp.example.com/" },
- ],
+ mcpServerDefinitions: [{ id: "docs", url: "https://mcp.example.com/" }],
memory: [],
models: [
{
@@ -438,7 +444,9 @@ export default function Agent() {
});
test("the compiler enumerates literal model selections in a conditional", async () => {
- const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-model-conditional-"));
+ const parent = await mkdtemp(
+ resolve(tmpdir(), "opencomputer-model-conditional-"),
+ );
try {
const initialized = await initializeAgentProject(resolve(parent, "app"));
await writeFile(
@@ -456,7 +464,10 @@ export default function Agent() {
const runtime = await prepareAgent(initialized.agentRoot);
const manifest = JSON.parse(
- await readFile(resolve(runtime, ".opencomputer", "reactive.json"), "utf8"),
+ await readFile(
+ resolve(runtime, ".opencomputer", "reactive.json"),
+ "utf8",
+ ),
) as { models: Array<{ provider: string; model: string }> };
assert.deepEqual(manifest.models, [
{ provider: "openrouter", model: "anthropic/claude-haiku-4.5" },
@@ -468,7 +479,9 @@ export default function Agent() {
});
test("the compiler rejects a model selection it cannot register", async () => {
- const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-model-dynamic-"));
+ const parent = await mkdtemp(
+ resolve(tmpdir(), "opencomputer-model-dynamic-"),
+ );
try {
const initialized = await initializeAgentProject(resolve(parent, "app"));
await writeFile(
@@ -541,13 +554,17 @@ export default function Agent() {
// Without the platform's env there is no connection to call, and the
// failure must say so rather than fetching something arbitrary.
await assert.rejects(
- runtime.callService({ service: "gmail", path: "/gmail/v1/users/me/profile" }),
+ runtime.callService({
+ service: "gmail",
+ path: "/gmail/v1/users/me/profile",
+ }),
/managed connections are unavailable/,
);
const calls: Array<{ url: string; init: RequestInit }> = [];
const realFetch = globalThis.fetch;
- globalThis.process.env.OPENCOMPUTER_CONNECTIONS_URL = "https://edge.test/conn/";
+ globalThis.process.env.OPENCOMPUTER_CONNECTIONS_URL =
+ "https://edge.test/conn/";
globalThis.process.env.OPENCOMPUTER_CONNECTION_TOKEN = "rt-token";
// What a managed connection actually answers: the service's status and
// body inside an envelope, wrapped in a 200. A caller reading `ok` off the
@@ -559,12 +576,15 @@ export default function Agent() {
JSON.stringify({
status: 403,
headers: { "content-type": "application/json" },
- body: JSON.stringify({ error: { message: "Insufficient Permission" } }),
+ body: JSON.stringify({
+ error: { message: "Insufficient Permission" },
+ }),
}),
{ status: 200 },
);
}) as unknown as typeof globalThis.fetch;
let unwrapped: Response | undefined;
+ let linearResponse: Response | undefined;
try {
unwrapped = await runtime.callService({
service: "google",
@@ -573,17 +593,27 @@ export default function Agent() {
path: "/gmail/v1/users/me/messages/send",
body: "{}",
});
+ linearResponse = await runtime.callService({
+ service: "linear",
+ method: "POST",
+ path: "/graphql",
+ body: JSON.stringify({ query: "query { viewer { id } }" }),
+ });
} finally {
globalThis.fetch = realFetch;
delete globalThis.process.env.OPENCOMPUTER_CONNECTIONS_URL;
delete globalThis.process.env.OPENCOMPUTER_CONNECTION_TOKEN;
}
- assert.equal(calls.length, 1);
+ assert.equal(calls.length, 2);
// A trailing slash on the base must not produce a doubled one — the fix for
// the comment bug replaced a regex trim, so the behaviour needs pinning.
assert.equal(calls[0]!.url, "https://edge.test/conn/google/fetch");
- const sent = JSON.parse(String(calls[0]!.init.body)) as Record<string, unknown>;
+ assert.equal(calls[1]!.url, "https://edge.test/conn/linear/fetch");
+ const sent = JSON.parse(String(calls[0]!.init.body)) as Record<
+ string,
+ unknown
+ >;
// `google` is an alias the platform resolves to gmail; the SDK passes the
// caller's word through and only decides the PROVIDER segment itself.
assert.equal(sent.service, "google");
@@ -597,22 +627,35 @@ export default function Agent() {
assert.deepEqual(await unwrapped!.json(), {
error: { message: "Insufficient Permission" },
});
+ assert.equal(linearResponse!.status, 403);
// listServices routes to the reserved `opencomputer` provider segment and
// must send NO method and NO path — that body shape is the only thing
// distinguishing a platform action from managed egress on the same route.
assert.equal(typeof runtime.listServices, "function");
calls.length = 0;
- globalThis.process.env.OPENCOMPUTER_CONNECTIONS_URL = "https://edge.test/conn";
+ globalThis.process.env.OPENCOMPUTER_CONNECTIONS_URL =
+ "https://edge.test/conn";
globalThis.process.env.OPENCOMPUTER_CONNECTION_TOKEN = "rt-token";
globalThis.fetch = (async (url: string, init: RequestInit) => {
calls.push({ url: String(url), init });
return new Response(
JSON.stringify({
connections: [
- { id: "1", provider: "google", label: "alice", displayName: "[email protected]", status: "connected" },
+ {
+ id: "1",
+ provider: "google",
+ label: "alice",
+ displayName: "[email protected]",
+ status: "connected",
+ },
{ id: "2", provider: "google", label: "bob", status: "pending" },
- { id: "3", provider: "github", label: "default", status: "connected" },
+ {
+ id: "3",
+ provider: "github",
+ label: "default",
+ status: "connected",
+ },
],
}),
{ status: 200 },
@@ -627,7 +670,9 @@ export default function Agent() {
delete globalThis.process.env.OPENCOMPUTER_CONNECTION_TOKEN;
}
assert.equal(calls[0]!.url, "https://edge.test/conn/opencomputer/fetch");
- assert.deepEqual(JSON.parse(String(calls[0]!.init.body)), { action: "list" });
+ assert.deepEqual(JSON.parse(String(calls[0]!.init.body)), {
+ action: "list",
+ });
// Pending accounts are unusable and the github row is a different grant;
// a sweep that tried either would fail on a mailbox that does not exist.
assert.deepEqual(
@@ -639,6 +684,34 @@ export default function Agent() {
}
});
+test("the compiler records Linear as its own managed service provider", async () => {
+ const parent = await mkdtemp(
+ resolve(tmpdir(), "opencomputer-linear-service-"),
+ );
+ try {
+ const initialized = await initializeAgentProject(resolve(parent, "app"));
+ await writeFile(
+ resolve(initialized.agentRoot, "agent.ts"),
+ `import { useService } from "@opencomputer/agent";
+export default function Agent() {
+ useService("linear");
+ return "Work with Linear issues when asked.";
+}
+`,
+ );
+ const runtime = await prepareAgent(initialized.agentRoot);
+ const manifest = JSON.parse(
+ await readFile(
+ resolve(runtime, ".opencomputer", "reactive.json"),
+ "utf8",
+ ),
+ ) as { connections: string[] };
+ assert.deepEqual(manifest.connections, ["linear"]);
+ } finally {
+ await rm(parent, { recursive: true, force: true });
+ }
+});
+
test("a tool is gated by having preview and apply, not by the words appearing in it", async () => {
const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-gated-shape-"));
try {
@@ -682,7 +755,10 @@ export default function Agent() {
const runtime = await prepareAgent(initialized.agentRoot);
const manifest = JSON.parse(
- await readFile(resolve(runtime, ".opencomputer", "reactive.json"), "utf8"),
+ await readFile(
+ resolve(runtime, ".opencomputer", "reactive.json"),
+ "utf8",
+ ),
) as { tools: string[]; gatedTools: string[] };
assert.deepEqual(manifest.tools, ["draft"]);
assert.deepEqual(manifest.gatedTools, []);
@@ -727,7 +803,10 @@ export default function Agent() {
// wait — so the module load is where the incomplete pair is caught.
const runtime = await prepareAgent(initialized.agentRoot);
const manifest = JSON.parse(
- await readFile(resolve(runtime, ".opencomputer", "reactive.json"), "utf8"),
+ await readFile(
+ resolve(runtime, ".opencomputer", "reactive.json"),
+ "utf8",
+ ),
) as { gatedTools: string[] };
assert.deepEqual(manifest.gatedTools, ["cancel"]);
await assert.rejects(
@@ -876,7 +955,11 @@ export default function Agent() {
]);
const manifest = JSON.parse(
await readFile(
- resolve(await agentRuntimeDirectory(initialized.agentRoot), ".opencomputer", "reactive.json"),
+ resolve(
+ await agentRuntimeDirectory(initialized.agentRoot),
+ ".opencomputer",
+ "reactive.json",
+ ),
"utf8",
),
) as { githubConnections: unknown[] };
@@ -887,7 +970,9 @@ export default function Agent() {
});
test("the compiler rejects dynamic or unsupported GitHub permissions", async () => {
- const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-github-invalid-"));
+ const parent = await mkdtemp(
+ resolve(tmpdir(), "opencomputer-github-invalid-"),
+ );
const root = resolve(parent, "app");
try {
const initialized = await initializeAgentProject(root);
@@ -966,7 +1051,10 @@ export default function Agent() {
);
const runtime = await prepareAgent(initialized.agentRoot);
const manifest = JSON.parse(
- await readFile(resolve(runtime, ".opencomputer", "reactive.json"), "utf8"),
+ await readFile(
+ resolve(runtime, ".opencomputer", "reactive.json"),
+ "utf8",
+ ),
) as { mcpServerDefinitions: unknown[] };
assert.deepEqual(manifest.mcpServerDefinitions, [
{
@@ -981,7 +1069,9 @@ export default function Agent() {
});
test("packaged tools can publish to a registered outbox by id", async () => {
- const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-outbox-publish-"));
+ const parent = await mkdtemp(
+ resolve(tmpdir(), "opencomputer-outbox-publish-"),
+ );
const root = resolve(parent, "app");
const originalFetch = globalThis.fetch;
const originalUrl = process.env.OPENCOMPUTER_OUTBOX_URL;
@@ -1015,31 +1105,47 @@ export default function Agent() { useTool(notify); return "Notify reviewers."; }
const runtimeRoot = await prepareAgent(initialized.agentRoot);
const manifest = JSON.parse(
- await readFile(resolve(runtimeRoot, ".opencomputer", "reactive.json"), "utf8"),
+ await readFile(
+ resolve(runtimeRoot, ".opencomputer", "reactive.json"),
+ "utf8",
+ ),
) as { tools: string[] };
assert.ok(manifest.tools.includes("notify_reviewer"));
process.env.OPENCOMPUTER_OUTBOX_URL = "http://outbox.test/outboxes";
process.env.OPENCOMPUTER_OUTBOX_TOKEN = "runtime-token";
let request: { url: string; init?: RequestInit } | undefined;
- globalThis.fetch = (async (url: string | URL | Request, init?: RequestInit) => {
+ globalThis.fetch = (async (
+ url: string | URL | Request,
+ init?: RequestInit,
+ ) => {
request = { url: String(url), init };
- return Response.json({ id: "item-1", status: "pending", duplicate: false }, { status: 202 });
+ return Response.json(
+ { id: "item-1", status: "pending", duplicate: false },
+ { status: 202 },
+ );
}) as typeof fetch;
- const runtime = await import(
+ const runtime = (await import(
`${pathToFileURL(resolve(runtimeRoot, "opencomputer-agent.js")).href}?test=${crypto.randomUUID()}`
- ) as { publishOutbox(id: string, input: unknown): Promise<unknown> };
+ )) as { publishOutbox(id: string, input: unknown): Promise<unknown> };
await runtime.publishOutbox("review-requests", {
type: "pull-request.ready",
idempotencyKey: "example/repo#42",
content: { title: "Review requested" },
});
- assert.equal(request?.url, "http://outbox.test/outboxes/review-requests/items");
- assert.equal(new Headers(request?.init?.headers).get("authorization"), "Bearer runtime-token");
+ assert.equal(
+ request?.url,
+ "http://outbox.test/outboxes/review-requests/items",
+ );
+ assert.equal(
+ new Headers(request?.init?.headers).get("authorization"),
+ "Bearer runtime-token",
+ );
} finally {
globalThis.fetch = originalFetch;
if (originalUrl === undefined) delete process.env.OPENCOMPUTER_OUTBOX_URL;
else process.env.OPENCOMPUTER_OUTBOX_URL = originalUrl;
- if (originalToken === undefined) delete process.env.OPENCOMPUTER_OUTBOX_TOKEN;
+ if (originalToken === undefined)
+ delete process.env.OPENCOMPUTER_OUTBOX_TOKEN;
else process.env.OPENCOMPUTER_OUTBOX_TOKEN = originalToken;
await rm(parent, { recursive: true, force: true });
}
@@ -1122,9 +1228,9 @@ export default function Agent() {
) as { tools: string[]; toolModules: string[] };
assert.ok(manifest.tools.includes("hacker_news"));
assert.ok(manifest.toolModules.includes("../tools/hacker-news.js"));
- const tools = await import(
+ const tools = (await import(
`${pathToFileURL(resolve(runtime, "tools", "hacker-news.js")).href}?test=${crypto.randomUUID()}`
- ) as { hackerNews: { id: string } };
+ )) as { hackerNews: { id: string } };
assert.equal(tools.hackerNews.id, "hacker_news");
} finally {
await rm(parent, { recursive: true, force: true });
@@ -1191,12 +1297,21 @@ export default function Agent() {
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_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> });
+ 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." }),
+ JSON.stringify({
+ id: "apr_1",
+ status: "pending",
+ duplicate: false,
+ message: "Recorded for approval.",
+ }),
{ headers: { "content-type": "application/json" } },
);
}) as unknown as typeof globalThis.fetch;
@@ -1225,7 +1340,8 @@ export default function Agent() {
JSON.stringify({
error: {
code: "approval_needs_a_conversation",
- message: "This tool can only be used in a conversation where somebody can approve it.",
+ message:
+ "This tool can only be used in a conversation where somebody can approve it.",
},
}),
{ status: 409, headers: { "content-type": "application/json" } },
@@ -1326,15 +1442,22 @@ export default function Agent() {
type: "object",
properties: {
branch: { type: "string" },
- pr: { type: "object", properties: { number: { type: "integer" } }, required: ["number"] },
+ pr: {
+ type: "object",
+ properties: { number: { type: "integer" } },
+ required: ["number"],
+ },
},
required: ["branch"],
additionalProperties: false,
},
});
- const tools = await import(
+ const tools = (await import(
`${pathToFileURL(resolve(runtime, "tools", "report.js")).href}?test=${crypto.randomUUID()}`
- ) as { report: { id: string; result?: boolean }; lookup: { result?: boolean } };
+ )) as {
+ report: { id: string; result?: boolean };
+ lookup: { result?: boolean };
+ };
assert.equal(tools.report.result, true);
assert.equal("result" in tools.lookup, false);
} finally {
@@ -1443,7 +1566,9 @@ export const report = defineTool({
test("the compiler refuses a defineTool() form it cannot read instead of compiling an ordinary tool", async () => {
const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-result-tool-"));
const root = resolve(parent, "app");
- const tool = (declaration: string) => `import { defineTool } from "@opencomputer/agent";
+ const tool = (
+ declaration: string,
+ ) => `import { defineTool } from "@opencomputer/agent";
const marks = { result: true } as const;
const flag = true;
export const report = defineTool({
@@ -1460,21 +1585,49 @@ export const report = defineTool({
const initialized = await initializeAgentProject(root);
await mkdir(resolve(initialized.agentRoot, "tools"), { recursive: true });
const cases: Array<[string, RegExp]> = [
- ["...marks,", /tools\/report\.ts defineTool\("report"\) cannot spread \.\.\.marks/],
- ["result: flag,", /tools\/report\.ts defineTool\("report"\) result must be the literal true or false, not flag/],
- ["result: marks.result,", /result must be the literal true or false, not marks\.result/],
- ["result,", /result must be the literal true or false, not the shorthand property result/],
- ['["result"]: true,', /tools\/report\.ts defineTool\("report"\) cannot use the computed property name \["result"\]/],
+ [
+ "...marks,",
+ /tools\/report\.ts defineTool\("report"\) cannot spread \.\.\.marks/,
+ ],
+ [
+ "result: flag,",
+ /tools\/report\.ts defineTool\("report"\) result must be the literal true or false, not flag/,
+ ],
+ [
+ "result: marks.result,",
+ /result must be the literal true or false, not marks\.result/,
+ ],
+ [
+ "result,",
+ /result must be the literal true or false, not the shorthand property result/,
+ ],
+ [
+ '["result"]: true,',
+ /tools\/report\.ts defineTool\("report"\) cannot use the computed property name \["result"\]/,
+ ],
];
for (const [declaration, expected] of cases) {
- await writeFile(resolve(initialized.agentRoot, "tools", "report.ts"), tool(declaration));
- await assert.rejects(prepareAgent(initialized.agentRoot), expected, declaration);
+ await writeFile(
+ resolve(initialized.agentRoot, "tools", "report.ts"),
+ tool(declaration),
+ );
+ await assert.rejects(
+ prepareAgent(initialized.agentRoot),
+ expected,
+ declaration,
+ );
}
// The literal keyword, wrapped in the idiomatic `as const`, still reads.
- await writeFile(resolve(initialized.agentRoot, "tools", "report.ts"), tool("result: true as const,"));
+ await writeFile(
+ resolve(initialized.agentRoot, "tools", "report.ts"),
+ tool("result: true as const,"),
+ );
const runtime = await prepareAgent(initialized.agentRoot);
const manifest = JSON.parse(
- await readFile(resolve(runtime, ".opencomputer", "reactive.json"), "utf8"),
+ await readFile(
+ resolve(runtime, ".opencomputer", "reactive.json"),
+ "utf8",
+ ),
) as { resultTool?: { id: string } };
assert.equal(manifest.resultTool?.id, "report");
} finally {
@@ -1492,29 +1645,68 @@ test("the runtime shim refuses a tool module whose result metadata disagrees wit
const load = async (resultTool: string | null) => {
const path = resolve(parent, `shim-${resultTool ?? "none"}.js`);
await writeFile(path, agentApiRuntimeSource({ resultTool }));
- return (await import(`${pathToFileURL(path).href}?test=${crypto.randomUUID()}`)) as {
+ return (await import(
+ `${pathToFileURL(path).href}?test=${crypto.randomUUID()}`
+ )) as {
defineTool: (input: Record<string, unknown>) => { result?: boolean };
};
};
const output = { type: "object" };
const run = async () => ({});
const withReport = await load("report");
- assert.equal(withReport.defineTool({ name: "report", description: "d", output, result: true, run }).result, true);
- assert.equal("result" in withReport.defineTool({ name: "lookup", description: "d", run }), false);
+ assert.equal(
+ withReport.defineTool({
+ name: "report",
+ description: "d",
+ output,
+ result: true,
+ run,
+ }).result,
+ true,
+ );
+ assert.equal(
+ "result" in
+ withReport.defineTool({ name: "lookup", description: "d", run }),
+ false,
+ );
assert.throws(
- () => withReport.defineTool({ name: "lookup", description: "d", output, result: true, run }),
+ () =>
+ withReport.defineTool({
+ name: "lookup",
+ description: "d",
+ output,
+ result: true,
+ run,
+ }),
/Tool lookup declares result: true, but the deployment records report as its result tool/,
);
assert.throws(
- () => withReport.defineTool({ name: "report", description: "d", output, run }),
+ () =>
+ withReport.defineTool({
+ name: "report",
+ description: "d",
+ output,
+ run,
+ }),
/Tool report is the deployment's result tool, but the module does not declare result: true/,
);
const withoutResult = await load(null);
assert.throws(
- () => withoutResult.defineTool({ name: "report", description: "d", output, result: true, run }),
+ () =>
+ withoutResult.defineTool({
+ name: "report",
+ description: "d",
+ output,
+ result: true,
+ run,
+ }),
/Tool report declares result: true, but the deployment records no result tool/,
);
- assert.equal("result" in withoutResult.defineTool({ name: "report", description: "d", run }), false);
+ assert.equal(
+ "result" in
+ withoutResult.defineTool({ name: "report", description: "d", run }),
+ false,
+ );
} finally {
await rm(parent, { recursive: true, force: true });
}
@@ -1526,17 +1718,29 @@ test("the runtime shim refuses a tool module whose result metadata disagrees wit
// named import of one from a module inside the agent directory, is read
// without evaluation and pinned exactly as written.
test("the compiler reads the result tool's output schema from a const in the module or an imported const", async () => {
- const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-result-schema-"));
+ const parent = await mkdtemp(
+ resolve(tmpdir(), "opencomputer-result-schema-"),
+ );
const root = resolve(parent, "app");
const schema = {
type: "object",
- properties: { branch: { type: "string" }, checks: { type: "array", items: { type: "string" } } },
+ properties: {
+ branch: { type: "string" },
+ checks: { type: "array", items: { type: "string" } },
+ },
required: ["branch"],
additionalProperties: false,
};
const manifestOf = async (agentRoot: string) =>
JSON.parse(
- await readFile(resolve(await agentRuntimeDirectory(agentRoot), ".opencomputer", "reactive.json"), "utf8"),
+ await readFile(
+ resolve(
+ await agentRuntimeDirectory(agentRoot),
+ ".opencomputer",
+ "reactive.json",
+ ),
+ "utf8",
+ ),
) as { resultTool?: { id: string; output: Record<string, unknown> } };
try {
const initialized = await initializeAgentProject(root);
@@ -1561,7 +1765,10 @@ export const report = defineTool({
`,
);
await prepareAgent(initialized.agentRoot);
- assert.deepEqual((await manifestOf(initialized.agentRoot)).resultTool, { id: "report", output: schema });
+ assert.deepEqual((await manifestOf(initialized.agentRoot)).resultTool, {
+ id: "report",
+ output: schema,
+ });
// Imported from a module of the agent's own, under a different local name.
await writeFile(
@@ -1586,7 +1793,10 @@ export const report = defineTool({
`,
);
await prepareAgent(initialized.agentRoot);
- assert.deepEqual((await manifestOf(initialized.agentRoot)).resultTool, { id: "report", output: schema });
+ assert.deepEqual((await manifestOf(initialized.agentRoot)).resultTool, {
+ id: "report",
+ output: schema,
+ });
// A const exported under another name, read through the export list.
await writeFile(
@@ -1594,16 +1804,24 @@ export const report = defineTool({
`const base = ${JSON.stringify(schema)} as const;\nexport { base as reportSchema };\n`,
);
await prepareAgent(initialized.agentRoot);
- assert.deepEqual((await manifestOf(initialized.agentRoot)).resultTool, { id: "report", output: schema });
+ assert.deepEqual((await manifestOf(initialized.agentRoot)).resultTool, {
+ id: "report",
+ output: schema,
+ });
} finally {
await rm(parent, { recursive: true, force: true });
}
});
test("the compiler names the unsupported schema form instead of guessing", async () => {
- const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-result-schema-"));
+ const parent = await mkdtemp(
+ resolve(tmpdir(), "opencomputer-result-schema-"),
+ );
const root = resolve(parent, "app");
- const tool = (imports: string, output: string) => `import { defineTool } from "@opencomputer/agent";
+ const tool = (
+ imports: string,
+ output: string,
+ ) => `import { defineTool } from "@opencomputer/agent";
${imports}
export const report = defineTool({
name: "report",
@@ -1628,19 +1846,62 @@ export { defineTool as reexported } from "@opencomputer/agent";
`,
);
const cases: Array<[string, string, RegExp]> = [
- ["", "build()", /defineTool\("report"\) output must be an inline object literal, a const object literal declared in the same module, or a named import of such a const from a module inside the agent directory, not build\(\)/],
- ["let mutable = { type: \"object\" };", "mutable", /output references mutable, which is declared with let or var; declare it as a const object literal/],
- ["const computed = build();\nfunction build() { return {}; }", "computed", /output references computed, whose value is not a static object literal: build\(\)/],
- ["import { built } from \"../schemas.js\";", "built", /output references built, exported by schemas\.ts, whose value is not a static object literal: build\(\)/],
- ["import { renamed } from \"../schemas.js\";", "renamed", /output references renamed, exported by schemas\.ts \(declared there as local\), whose value is not a static object literal: build\(\)/],
- ["import { reexported } from \"../schemas.js\";", "reexported", /output references reexported, which schemas\.ts re-exports from another module; import it from the module that declares it/],
- ["import { useTool } from \"@opencomputer/agent\";", "useTool", /output references useTool, imported from @opencomputer\/agent; a schema must be a const declared in a module inside the agent directory/],
- ["import * as schemas from \"../schemas.js\";", "schemas.local", /output must be an inline object literal, .* not schemas\.local/],
- ["", "missing", /output references missing, which is neither a const declared in this module nor a named import from a module inside the agent directory/],
+ [
+ "",
+ "build()",
+ /defineTool\("report"\) output must be an inline object literal, a const object literal declared in the same module, or a named import of such a const from a module inside the agent directory, not build\(\)/,
+ ],
+ [
+ 'let mutable = { type: "object" };',
+ "mutable",
+ /output references mutable, which is declared with let or var; declare it as a const object literal/,
+ ],
+ [
+ "const computed = build();\nfunction build() { return {}; }",
+ "computed",
+ /output references computed, whose value is not a static object literal: build\(\)/,
+ ],
+ [
+ 'import { built } from "../schemas.js";',
+ "built",
+ /output references built, exported by schemas\.ts, whose value is not a static object literal: build\(\)/,
+ ],
+ [
+ 'import { renamed } from "../schemas.js";',
+ "renamed",
+ /output references renamed, exported by schemas\.ts \(declared there as local\), whose value is not a static object literal: build\(\)/,
+ ],
+ [
+ 'import { reexported } from "../schemas.js";',
+ "reexported",
+ /output references reexported, which schemas\.ts re-exports from another module; import it from the module that declares it/,
+ ],
+ [
+ 'import { useTool } from "@opencomputer/agent";',
+ "useTool",
+ /output references useTool, imported from @opencomputer\/agent; a schema must be a const declared in a module inside the agent directory/,
+ ],
+ [
+ 'import * as schemas from "../schemas.js";',
+ "schemas.local",
+ /output must be an inline object literal, .* not schemas\.local/,
+ ],
+ [
+ "",
+ "missing",
+ /output references missing, which is neither a const declared in this module nor a named import from a module inside the agent directory/,
+ ],
];
for (const [imports, output, expected] of cases) {
- await writeFile(resolve(initialized.agentRoot, "tools", "report.ts"), tool(imports, output));
- await assert.rejects(prepareAgent(initialized.agentRoot), expected, output);
+ await writeFile(
+ resolve(initialized.agentRoot, "tools", "report.ts"),
+ tool(imports, output),
+ );
+ await assert.rejects(
+ prepareAgent(initialized.agentRoot),
+ expected,
+ output,
+ );
}
} finally {
await rm(parent, { recursive: true, force: true });
@@ -1648,7 +1909,9 @@ export { defineTool as reexported } from "@opencomputer/agent";
});
test("the compiler packages agent source modules outside the tools directory", async () => {
- const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-source-modules-"));
+ const parent = await mkdtemp(
+ resolve(tmpdir(), "opencomputer-source-modules-"),
+ );
const root = resolve(parent, "app");
try {
const initialized = await initializeAgentProject(root);
@@ -1688,9 +1951,9 @@ export default function Agent() {
assert.ok(!artifact.files.some((file) => file.path === "settings.json"));
assert.ok(artifact.files.some((file) => file.path === "agent.js"));
assert.ok(built.connections.includes("fixture-github"));
- const packaged = await import(
+ const packaged = (await import(
`${pathToFileURL(resolve(await agentRuntimeDirectory(initialized.agentRoot), "agent.js")).href}?test=${crypto.randomUUID()}`
- ) as { default(): string };
+ )) as { default(): string };
assert.equal(
packaged.default(),
"Review missing tests in opencomputer/example.",
@@ -1735,7 +1998,9 @@ test("the compiler accepts Twilio and email channels alongside Slack", async ()
try {
const initialized = await initializeAgentProject(root);
await mkdir(resolve(root, "opencomputer", "channels"), { recursive: true });
- await mkdir(resolve(initialized.agentRoot, "channels"), { recursive: true });
+ await mkdir(resolve(initialized.agentRoot, "channels"), {
+ recursive: true,
+ });
await writeFile(
resolve(root, "opencomputer", "channels", "shop-sms.ts"),
@@ -1796,7 +2061,9 @@ test("the compiler rejects a trigger the provider cannot deliver", async () => {
try {
const initialized = await initializeAgentProject(root);
await mkdir(resolve(root, "opencomputer", "channels"), { recursive: true });
- await mkdir(resolve(initialized.agentRoot, "channels"), { recursive: true });
+ await mkdir(resolve(initialized.agentRoot, "channels"), {
+ recursive: true,
+ });
await writeFile(
resolve(root, "opencomputer", "channels", "shop-sms.ts"),
`import { defineChannel } from "@opencomputer/agent";
@@ -1923,8 +2190,14 @@ test("the compiler registers memory declarations in the artifact manifest", asyn
const root = resolve(parent, "app");
try {
const initialized = await initializeAgentProject(root);
- await writeFile(resolve(initialized.agentRoot, "memory.ts"), REQUIREMENTS_MEMORY);
- await writeFile(resolve(initialized.agentRoot, "knowledge.ts"), KNOWLEDGE_MEMORY);
+ await writeFile(
+ resolve(initialized.agentRoot, "memory.ts"),
+ REQUIREMENTS_MEMORY,
+ );
+ await writeFile(
+ resolve(initialized.agentRoot, "knowledge.ts"),
+ KNOWLEDGE_MEMORY,
+ );
await writeFile(
resolve(initialized.agentRoot, "agent.ts"),
`import { useInput, useMemory, useModel } from "@opencomputer/agent";
@@ -1942,11 +2215,17 @@ export default function Agent() {
);
const built = await buildAgentArtifact(initialized.agentRoot);
- assert.deepEqual(built.memory, [KNOWLEDGE_DECLARATION, REQUIREMENTS_DECLARATION]);
+ assert.deepEqual(built.memory, [
+ KNOWLEDGE_DECLARATION,
+ REQUIREMENTS_DECLARATION,
+ ]);
assert.ok(built.connections.includes("memory-service"));
const runtime = await agentRuntimeDirectory(initialized.agentRoot);
const manifest = JSON.parse(
- await readFile(resolve(runtime, ".opencomputer", "reactive.json"), "utf8"),
+ await readFile(
+ resolve(runtime, ".opencomputer", "reactive.json"),
+ "utf8",
+ ),
) as { memory: unknown; tools: string[] };
assert.deepEqual(manifest.memory, built.memory);
assert.deepEqual(manifest.tools, []);
@@ -1955,17 +2234,29 @@ export default function Agent() {
// resolves one projection per session binding into scope.memory and
// records which ids the render selected.
const scope = {
- input: { source: "user", text: "hello" } as { source: string; text: string },
+ input: { source: "user", text: "hello" } as {
+ source: string;
+ text: string;
+ },
memory: {
requirements: {
text: "Node.js 22, no paid services.",
- sources: [{ id: "workshop", title: "Workshop requirements", revision: "r1", updatedAt: "2026-09-10T12:00:00.000Z" }],
+ sources: [
+ {
+ id: "workshop",
+ title: "Workshop requirements",
+ revision: "r1",
+ updatedAt: "2026-09-10T12:00:00.000Z",
+ },
+ ],
writable: true,
},
} as Record<string, unknown>,
selectedMemory: new Set<string>(),
};
- (globalThis as Record<PropertyKey, unknown>)[Symbol.for("opencomputer.agent-hooks")] = {
+ (globalThis as Record<PropertyKey, unknown>)[
+ Symbol.for("opencomputer.agent-hooks")
+ ] = {
useInput: () => scope.input,
useModel: () => undefined,
useMemory(id: string) {
@@ -1989,7 +2280,9 @@ export default function Agent() {
/Memory "knowledge" is not bound to this session/,
);
} finally {
- delete (globalThis as Record<PropertyKey, unknown>)[Symbol.for("opencomputer.agent-hooks")];
+ delete (globalThis as Record<PropertyKey, unknown>)[
+ Symbol.for("opencomputer.agent-hooks")
+ ];
}
// The runtime shim normalizes a definition to its manifest entry.
@@ -2000,8 +2293,18 @@ export default function Agent() {
documentMemory: () => unknown;
};
assert.deepEqual(
- JSON.parse(JSON.stringify(shim.defineMemory({ id: "notes", description: " Notes. " }))),
- { kind: "memory", version: 1, id: "notes", description: "Notes.", provider: { kind: "document", maxBytes: 8192 } },
+ JSON.parse(
+ JSON.stringify(
+ shim.defineMemory({ id: "notes", description: " Notes. " }),
+ ),
+ ),
+ {
+ kind: "memory",
+ version: 1,
+ id: "notes",
+ description: "Notes.",
+ provider: { kind: "document", maxBytes: 8192 },
+ },
);
} finally {
await rm(parent, { recursive: true, force: true });
@@ -2013,10 +2316,16 @@ test("the compiler deduplicates identical memory declarations and rejects confli
const root = resolve(parent, "app");
try {
const initialized = await initializeAgentProject(root);
- await writeFile(resolve(initialized.agentRoot, "memory.ts"), REQUIREMENTS_MEMORY);
+ await writeFile(
+ resolve(initialized.agentRoot, "memory.ts"),
+ REQUIREMENTS_MEMORY,
+ );
await writeFile(
resolve(initialized.agentRoot, "memory-again.ts"),
- REQUIREMENTS_MEMORY.replace("export const requirements", "export const again"),
+ REQUIREMENTS_MEMORY.replace(
+ "export const requirements",
+ "export const again",
+ ),
);
await writeFile(
resolve(initialized.agentRoot, "agent.ts"),
@@ -2034,10 +2343,10 @@ export default function Agent() {
await writeFile(
resolve(initialized.agentRoot, "memory-again.ts"),
- REQUIREMENTS_MEMORY.replace("export const requirements", "export const again").replace(
- "maxBytes: 8_192",
- "maxBytes: 4_096",
- ),
+ REQUIREMENTS_MEMORY.replace(
+ "export const requirements",
+ "export const again",
+ ).replace("maxBytes: 8_192", "maxBytes: 4_096"),
);
await assert.rejects(
buildAgentArtifact(initialized.agentRoot),
@@ -2049,12 +2358,17 @@ export default function Agent() {
});
test("the compiler validates memory declarations", async () => {
- const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-memory-invalid-"));
+ const parent = await mkdtemp(
+ resolve(tmpdir(), "opencomputer-memory-invalid-"),
+ );
const root = resolve(parent, "app");
try {
const initialized = await initializeAgentProject(root);
const build = async (memorySource: string, agentSource?: string) => {
- await writeFile(resolve(initialized.agentRoot, "memory.ts"), memorySource);
+ await writeFile(
+ resolve(initialized.agentRoot, "memory.ts"),
+ memorySource,
+ );
await writeFile(
resolve(initialized.agentRoot, "agent.ts"),
agentSource ??
@@ -2080,23 +2394,43 @@ export default function Agent() {
/tool remember input cannot declare the reserved memory argument/,
);
await assert.rejects(
- build(http(`[{ name: "remember", description: "Save.", access: "write", input: { type: "object", required: ["memory"] } }]`)),
+ build(
+ http(
+ `[{ name: "remember", description: "Save.", access: "write", input: { type: "object", required: ["memory"] } }]`,
+ ),
+ ),
/tool remember input cannot declare the reserved memory argument/,
);
await assert.rejects(
- build(http(`[{ name: "Remember", description: "Save.", access: "write", input: { type: "object" } }]`)),
+ build(
+ http(
+ `[{ name: "Remember", description: "Save.", access: "write", input: { type: "object" } }]`,
+ ),
+ ),
/tool names must use 1 to 32 lowercase letters, numbers, and underscores/,
);
await assert.rejects(
- build(http(`[{ name: "remember", description: "Save.", access: "admin", input: { type: "object" } }]`)),
+ build(
+ http(
+ `[{ name: "remember", description: "Save.", access: "admin", input: { type: "object" } }]`,
+ ),
+ ),
/access must be "read" or "write"/,
);
await assert.rejects(
- build(http(`[{ name: "remember", description: "Save.", access: "read", input: { type: "object", properties: { a: { $ref: "#/x" } } } }]`)),
+ build(
+ http(
+ `[{ name: "remember", description: "Save.", access: "read", input: { type: "object", properties: { a: { $ref: "#/x" } } } }]`,
+ ),
+ ),
/input cannot use \$ref/,
);
await assert.rejects(
- build(http(`[${Array.from({ length: 9 }, (_, i) => `{ name: "t${i}", description: "T.", access: "read", input: { type: "object" } }`).join(", ")}]`)),
+ build(
+ http(
+ `[${Array.from({ length: 9 }, (_, i) => `{ name: "t${i}", description: "T.", access: "read", input: { type: "object" } }`).join(", ")}]`,
+ ),
+ ),
/at most 8 tools/,
);
await assert.rejects(
@@ -2116,15 +2450,33 @@ export default function Agent() {
/references unknown connection elsewhere/,
);
await assert.rejects(
- build(REQUIREMENTS_MEMORY.replace("export const requirements", "export const memory").replace("8_192", "16_385")),
+ build(
+ REQUIREMENTS_MEMORY.replace(
+ "export const requirements",
+ "export const memory",
+ ).replace("8_192", "16_385"),
+ ),
/maxBytes must be a whole number between 1 and 16384/,
);
await assert.rejects(
- build(REQUIREMENTS_MEMORY.replace("export const requirements", "export const memory").replace('"requirements"', '"Requirements"')),
+ build(
+ REQUIREMENTS_MEMORY.replace(
+ "export const requirements",
+ "export const memory",
+ ).replace('"requirements"', '"Requirements"'),
+ ),
/must use lowercase letters, numbers, and single hyphens/,
);
await assert.rejects(
- build(REQUIREMENTS_MEMORY.replace("export const requirements", "export const memory").replace("provider: documentMemory({ maxBytes: 8_192 })", "provider: custom")),
+ build(
+ REQUIREMENTS_MEMORY.replace(
+ "export const requirements",
+ "export const memory",
+ ).replace(
+ "provider: documentMemory({ maxBytes: 8_192 })",
+ "provider: custom",
+ ),
+ ),
/provider must be an inline documentMemory\(\) or httpMemory\(\) call/,
);
@@ -2132,7 +2484,10 @@ export default function Agent() {
// cannot take a memory tool's fixed name.
await assert.rejects(
build(
- REQUIREMENTS_MEMORY.replace("export const requirements", "export const memory"),
+ REQUIREMENTS_MEMORY.replace(
+ "export const requirements",
+ "export const memory",
+ ),
`import { useMemory } from "@opencomputer/agent";
export default function Agent() {
@@ -2144,7 +2499,10 @@ export default function Agent() {
);
await assert.rejects(
build(
- REQUIREMENTS_MEMORY.replace("export const requirements", "export const memory"),
+ REQUIREMENTS_MEMORY.replace(
+ "export const requirements",
+ "export const memory",
+ ),
`import { useMemory, useTool } from "@opencomputer/agent";
import { memory } from "./memory";
@@ -2162,7 +2520,9 @@ export default function Agent() {
});
test("the compiler rejects memory declarations it cannot register as written", async () => {
- const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-memory-literal-"));
+ const parent = await mkdtemp(
+ resolve(tmpdir(), "opencomputer-memory-literal-"),
+ );
const root = resolve(parent, "app");
try {
const initialized = await initializeAgentProject(root);
@@ -2177,8 +2537,12 @@ export default function Agent() {
`,
);
const build = async (memorySource: string, extra?: [string, string]) => {
- await writeFile(resolve(initialized.agentRoot, "memory.ts"), memorySource);
- if (extra) await writeFile(resolve(initialized.agentRoot, extra[0]), extra[1]);
+ await writeFile(
+ resolve(initialized.agentRoot, "memory.ts"),
+ memorySource,
+ );
+ if (extra)
+ await writeFile(resolve(initialized.agentRoot, extra[0]), extra[1]);
return buildAgentArtifact(initialized.agentRoot);
};
const declaration = (provider: string) =>
@@ -2201,7 +2565,10 @@ ${declaration("documentMemory({ maxBytes: 4_096 })")}});
export const memory = declareMemory({
${declaration("undefined")}});
`,
- ["lib.ts", 'export { defineMemory as declareMemory } from "@opencomputer/agent";\n'],
+ [
+ "lib.ts",
+ 'export { defineMemory as declareMemory } from "@opencomputer/agent";\n',
+ ],
),
/lib\.ts exports defineMemory as declareMemory; the compiler registers memory only from a direct defineMemory\(\) call/,
);
@@ -2358,7 +2725,8 @@ export const memory = lib.defineMemory({ id: "notes", description: "Notes." });
resolve(initialized.agentRoot, "lib.ts"),
'export { defineMemory, documentMemory } from "@opencomputer/agent";\n',
);
- const built = await build(`import type { MemoryDefinition } from "@opencomputer/agent";
+ const built =
+ await build(`import type { MemoryDefinition } from "@opencomputer/agent";
import { defineMemory, documentMemory } from "./lib";
type Declared = typeof defineMemory;
@@ -2410,7 +2778,8 @@ export default function Agent() {
}
`,
);
- const unrelated = await build(`export const labels = { defineMemory: "Memory settings" };
+ const unrelated =
+ await build(`export const labels = { defineMemory: "Memory settings" };
function defineMemory(input: { id: string }) {
return { ...input, defineMemory: true };
@@ -2425,11 +2794,16 @@ export const spelled = "defineMemory";
});
test("a registered memory declaration is the definition the artifact executes", async () => {
- const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-memory-parity-"));
+ const parent = await mkdtemp(
+ resolve(tmpdir(), "opencomputer-memory-parity-"),
+ );
const root = resolve(parent, "app");
try {
const initialized = await initializeAgentProject(root);
- await writeFile(resolve(initialized.agentRoot, "knowledge.ts"), KNOWLEDGE_MEMORY);
+ await writeFile(
+ resolve(initialized.agentRoot, "knowledge.ts"),
+ KNOWLEDGE_MEMORY,
+ );
await writeFile(
resolve(initialized.agentRoot, "agent.ts"),
`import { defineMemory, documentMemory, useMemory } from "@opencomputer/agent";
@@ -2451,7 +2825,16 @@ export default function Agent() {
const runtime = await agentRuntimeDirectory(initialized.agentRoot);
const module = (await import(
`${pathToFileURL(resolve(runtime, "agent.js")).href}?test=${crypto.randomUUID()}`
- )) as Record<string, { kind: string; version: number; id: string; description: string; provider: unknown }>;
+ )) as Record<
+ string,
+ {
+ kind: string;
+ version: number;
+ id: string;
+ description: string;
+ provider: unknown;
+ }
+ >;
const executed = ["knowledge", "notes", "requirements"].map((name) => {
const definition = module[name]!;
assert.equal(definition.kind, "memory");
@@ -2469,7 +2852,11 @@ export default function Agent() {
assert.deepEqual(built.memory, executed);
assert.deepEqual(built.memory, [
KNOWLEDGE_DECLARATION,
- { id: "notes", description: "Notes.", provider: { kind: "document", maxBytes: 8192 } },
+ {
+ id: "notes",
+ description: "Notes.",
+ provider: { kind: "document", maxBytes: 8192 },
+ },
REQUIREMENTS_DECLARATION,
]);
@@ -2478,7 +2865,9 @@ export default function Agent() {
const shim = (await import(
`${pathToFileURL(resolve(runtime, "opencomputer-agent.js")).href}?test=${crypto.randomUUID()}`
)) as {
- defineMemory: (input: unknown) => { provider: { tools?: Array<{ input: Record<string, unknown> }> } };
+ defineMemory: (input: unknown) => {
+ provider: { tools?: Array<{ input: Record<string, unknown> }> };
+ };
documentMemory: (input?: unknown) => unknown;
httpMemory: (input: unknown) => unknown;
};
@@ -2493,7 +2882,11 @@ export default function Agent() {
assert.throws(
() =>
shim.httpMemory({
- connection: { kind: "connection", id: "memory-service", methods: ["GET"] },
+ connection: {
+ kind: "connection",
+ id: "memory-service",
+ methods: ["GET"],
+ },
}),
/httpMemory requires connection memory-service to allow POST/,
);
@@ -2515,7 +2908,9 @@ export default function Agent() {
const schema = definition.provider.tools![0]!.input;
assert.ok(Object.isFrozen(schema));
assert.ok(Object.isFrozen(schema.properties));
- assert.ok(Object.isFrozen((schema.properties as Record<string, unknown>).fact));
+ assert.ok(
+ Object.isFrozen((schema.properties as Record<string, unknown>).fact),
+ );
} finally {
await rm(parent, { recursive: true, force: true });
}
@@ -2539,9 +2934,20 @@ test("prepareAgent builds into a cache under node_modules, never into the agent'
const runtime = await prepareAgent(initialized.agentRoot);
assert.equal(
runtime,
- resolve(root, "node_modules", ".cache", "opencomputer", "agents", "hello-world", "runtime"),
+ resolve(
+ root,
+ "node_modules",
+ ".cache",
+ "opencomputer",
+ "agents",
+ "hello-world",
+ "runtime",
+ ),
+ );
+ assert.equal(
+ existsSync(resolve(initialized.agentRoot, ".opencomputer")),
+ false,
);
- assert.equal(existsSync(resolve(initialized.agentRoot, ".opencomputer")), false);
assert.equal(existsSync(resolve(runtime, "AGENTS.md")), true);
} finally {
await rm(root, { recursive: true, force: true });
diff --git a/cli/src/project.ts b/cli/src/project.ts
index ff1d38e9..34f7a3ab 100644
--- a/cli/src/project.ts
+++ b/cli/src/project.ts
@@ -833,6 +833,7 @@ const MANAGED_SERVICE_PROVIDERS: Readonly<Record<string, string>> = {
drive: "google",
sheets: "google",
github: "github",
+ linear: "linear",
};
function declaredServiceProviders(agentSource: string): string[] {
@@ -1122,7 +1123,11 @@ class MemorySourceResolver {
* re-export is refused with the module to import from). Every other form
* fails with the form named, so the fix is one edit.
*/
- staticObjectBinding(path: string, name: string, label: string): ts.Expression {
+ staticObjectBinding(
+ path: string,
+ name: string,
+ label: string,
+ ): ts.Expression {
const file = this.file(path);
const local = localVariable(file, name);
if (local) {
@@ -1136,7 +1141,8 @@ class MemorySourceResolver {
if (!ts.isImportDeclaration(statement)) continue;
const clause = statement.importClause;
const specifier = statement.moduleSpecifier;
- if (!clause || clause.isTypeOnly || !ts.isStringLiteral(specifier)) continue;
+ if (!clause || clause.isTypeOnly || !ts.isStringLiteral(specifier))
+ continue;
if (clause.name?.text === name) {
throw new Error(
`${label} references ${name}, the default import of ${specifier.text}; import a named const from a module inside the agent directory`,
@@ -1177,10 +1183,13 @@ class MemorySourceResolver {
for (const statement of file.statements) {
if (
ts.isVariableStatement(statement) &&
- statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)
+ statement.modifiers?.some(
+ (modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword,
+ )
) {
const declaration = statement.declarationList.declarations.find(
- (candidate) => ts.isIdentifier(candidate.name) && candidate.name.text === exported,
+ (candidate) =>
+ ts.isIdentifier(candidate.name) && candidate.name.text === exported,
);
if (declaration) {
return staticObjectInitializer(
@@ -1194,7 +1203,8 @@ class MemorySourceResolver {
const clause = statement.exportClause;
if (!clause || !ts.isNamedExports(clause)) continue;
const element = clause.elements.find(
- (candidate) => !candidate.isTypeOnly && candidate.name.text === exported,
+ (candidate) =>
+ !candidate.isTypeOnly && candidate.name.text === exported,
);
if (!element) continue;
if (statement.moduleSpecifier) {
@@ -1210,7 +1220,9 @@ class MemorySourceResolver {
);
}
const where =
- localName === exported ? `exported by ${target}` : `exported by ${target} (declared there as ${localName})`;
+ localName === exported
+ ? `exported by ${target}`
+ : `exported by ${target} (declared there as ${localName})`;
return staticObjectInitializer(
local,
`${label} references ${name}, ${where}, which is`,
@@ -2234,7 +2246,8 @@ async function typescriptFiles(directory: string): Promise<string[]> {
.sort();
}
-const DATABASE_MIGRATION_NAME = /^\d{3,}_[a-z0-9]+(?:[a-z0-9_-]*[a-z0-9])?\.sql$/;
+const DATABASE_MIGRATION_NAME =
+ /^\d{3,}_[a-z0-9]+(?:[a-z0-9_-]*[a-z0-9])?\.sql$/;
const MAX_DATABASE_MIGRATION_BYTES = 256 * 1024;
const MAX_DATABASE_MIGRATIONS_BYTES = 1024 * 1024;
@@ -2827,7 +2840,8 @@ function unwrapStatic(expression: ts.Expression): ts.Expression {
if (ts.isParenthesizedExpression(current)) current = current.expression;
else if (ts.isAsExpression(current)) current = current.expression;
else if (ts.isSatisfiesExpression(current)) current = current.expression;
- else if (ts.isTypeAssertionExpression(current)) current = current.expression;
+ else if (ts.isTypeAssertionExpression(current))
+ current = current.expression;
else if (ts.isNonNullExpression(current)) current = current.expression;
else return current;
}
@@ -2839,11 +2853,15 @@ interface LocalVariable {
}
/** The top-level variable statement that declares `name` in `file`, if any. */
-function localVariable(file: ts.SourceFile, name: string): LocalVariable | undefined {
+function localVariable(
+ file: ts.SourceFile,
+ name: string,
+): LocalVariable | undefined {
for (const statement of file.statements) {
if (!ts.isVariableStatement(statement)) continue;
const declaration = statement.declarationList.declarations.find(
- (candidate) => ts.isIdentifier(candidate.name) && candidate.name.text === name,
+ (candidate) =>
+ ts.isIdentifier(candidate.name) && candidate.name.text === name,
);
if (declaration) return { statement, declaration };
}
@@ -2862,15 +2880,21 @@ function staticObjectInitializer(
valuePrefix: string,
): ts.Expression {
if (!(variable.statement.declarationList.flags & ts.NodeFlags.Const)) {
- throw new Error(`${declaredPrefix} declared with let or var; declare it as a const object literal`);
+ throw new Error(
+ `${declaredPrefix} declared with let or var; declare it as a const object literal`,
+ );
}
const initializer = variable.declaration.initializer;
if (!initializer) {
- throw new Error(`${declaredPrefix} declared without a value; declare it as a const object literal`);
+ throw new Error(
+ `${declaredPrefix} declared without a value; declare it as a const object literal`,
+ );
}
const value = unwrapStatic(initializer);
if (!ts.isObjectLiteralExpression(value)) {
- throw new Error(`${valuePrefix} value is not a static object literal: ${initializer.getText()}`);
+ throw new Error(
+ `${valuePrefix} value is not a static object literal: ${initializer.getText()}`,
+ );
}
return value;
}
@@ -2891,7 +2915,9 @@ function declaredSchema(
resolver: MemorySourceResolver | undefined,
): Record<string, unknown> | undefined {
if (!member) {
- throw new Error(`${label.replace(/ output$/, "")} is the result tool and must declare output as ${SCHEMA_FORMS}`);
+ throw new Error(
+ `${label.replace(/ output$/, "")} is the result tool and must declare output as ${SCHEMA_FORMS}`,
+ );
}
const expression = ts.isShorthandPropertyAssignment(member)
? member.name
@@ -2899,16 +2925,23 @@ function declaredSchema(
? unwrapStatic(member.initializer)
: undefined;
if (!expression) {
- throw new Error(`${label} must be ${SCHEMA_FORMS}, not a method or accessor`);
+ throw new Error(
+ `${label} must be ${SCHEMA_FORMS}, not a method or accessor`,
+ );
}
if (ts.isObjectLiteralExpression(expression)) {
return staticJsonValue(expression, label) as Record<string, unknown>;
}
if (ts.isIdentifier(expression)) {
if (!resolver) return undefined;
- return staticJsonValue(resolver.staticObjectBinding(path, expression.text, label), label) as Record<string, unknown>;
+ return staticJsonValue(
+ resolver.staticObjectBinding(path, expression.text, label),
+ label,
+ ) as Record<string, unknown>;
}
- throw new Error(`${label} must be ${SCHEMA_FORMS}, not ${expression.getText()}`);
+ throw new Error(
+ `${label} must be ${SCHEMA_FORMS}, not ${expression.getText()}`,
+ );
}
const DEFINE_TOOL_FORM_HINT =
@@ -2977,21 +3010,30 @@ function definedTools(
const reason = ts.isShorthandPropertyAssignment(resultMember)
? "the shorthand property result"
: ts.isPropertyAssignment(resultMember)
- ? unwrapStatic(resultMember.initializer).kind === ts.SyntaxKind.TrueKeyword
+ ? unwrapStatic(resultMember.initializer).kind ===
+ ts.SyntaxKind.TrueKeyword
? undefined
- : unwrapStatic(resultMember.initializer).kind === ts.SyntaxKind.FalseKeyword
+ : unwrapStatic(resultMember.initializer).kind ===
+ ts.SyntaxKind.FalseKeyword
? undefined
: resultMember.initializer.getText()
: "a method or accessor";
if (reason !== undefined) {
- throw new Error(`${label} result must be the literal true or false, not ${reason}`);
+ throw new Error(
+ `${label} result must be the literal true or false, not ${reason}`,
+ );
}
result =
- unwrapStatic((resultMember as ts.PropertyAssignment).initializer).kind ===
- ts.SyntaxKind.TrueKeyword;
+ unwrapStatic((resultMember as ts.PropertyAssignment).initializer)
+ .kind === ts.SyntaxKind.TrueKeyword;
}
const output = result
- ? declaredSchema(objectMember(argument, "output"), path, `${label} output`, resolver)
+ ? declaredSchema(
+ objectMember(argument, "output"),
+ path,
+ `${label} output`,
+ resolver,
+ )
: undefined;
tools.push({
id,
@@ -3155,7 +3197,7 @@ export const callService = async (request) => {
if (!request?.path?.startsWith("/")) throw new Error("Service requests require an absolute path");
const service = String(request.service ?? "").trim().toLowerCase();
if (!service) throw new Error("A service request needs a service");
- const provider = service === "github" ? "github" : "google";
+ const provider = service === "github" || service === "linear" ? service : "google";
const root = base.endsWith("/") ? base.slice(0, -1) : base;
const response = await fetch(root + "/" + provider + "/fetch", {
method: "POST",
@@ -3455,7 +3497,9 @@ function compiledModulePath(path: string): string {
* An agent outside an app (no `opencomputer/project.ts` above it) caches
* under its own directory.
*/
-export async function agentRuntimeDirectory(agentRoot: string): Promise<string> {
+export async function agentRuntimeDirectory(
+ agentRoot: string,
+): Promise<string> {
const root = resolve(agentRoot);
let directory = root;
let projectRoot: string | undefined;
@@ -3614,7 +3658,11 @@ the product or support surface presented to users.
for (const candidate of toolSources) {
// 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, sourceResolver);
+ const defined = definedTools(
+ candidate.source,
+ candidate.path,
+ sourceResolver,
+ );
if (defined.length > 0) {
reactiveTools.push(...defined.map((tool) => tool.id));
gatedTools.push(
@@ -3624,7 +3672,11 @@ the product or support surface presented to users.
resultTools.push(
...defined
.filter((tool) => tool.result)
- .map((tool) => ({ id: tool.id, output: tool.output!, path: candidate.path })),
+ .map((tool) => ({
+ id: tool.id,
+ output: tool.output!,
+ path: candidate.path,
+ })),
);
}
}
@@ -3648,7 +3700,9 @@ the product or support surface presented to users.
}
// 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));
+ 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`,
diff --git a/create-start/package.json b/create-start/package.json
index 30f6dc38..7ebc2ce4 100644
--- a/create-start/package.json
+++ b/create-start/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/create-start",
- "version": "0.7.8",
+ "version": "0.7.9",
"description": "Create a hello-world OpenComputer agent application.",
"type": "module",
"bin": {
@@ -18,7 +18,7 @@
"node": ">=22.0.0"
},
"dependencies": {
- "@opencomputer/cli": "0.7.8"
+ "@opencomputer/cli": "0.7.9"
},
"publishConfig": {
"access": "public"
diff --git a/docs/agents/capabilities.mdx b/docs/agents/capabilities.mdx
index fa4cfb43..7a93bc05 100644
--- a/docs/agents/capabilities.mdx
+++ b/docs/agents/capabilities.mdx
@@ -10,7 +10,7 @@ the narrowest capability that fits the job.
| --- | --- | --- | --- |
| Code-defined tool | One typed operation you implement | Your TypeScript `run()` function | `useTool(tool)` |
| Tool that waits for approval | A write a person should agree to first | Your `preview()` shows it; your `apply()` runs after a decision | `useTool(tool)` — the same tool, defined with `preview`/`apply` instead of `run` |
-| Connected service | Gmail, Calendar, Drive, Sheets or GitHub, on someone's connected account | OpenComputer attaches and refreshes the credential | `useService("gmail")`, then `callService()` in a tool |
+| Connected service | Google services, GitHub, or Linear, on someone's connected account | OpenComputer attaches and refreshes the credential | `useService("gmail")`, then `callService()` in a tool |
| MCP server | A service that already publishes a collection of tools | The remote MCP server | `useMcpServer(server)` |
| Skill | A reusable procedure, checklist, or supporting files | The agent follows the loaded instructions | Place it under `skills/` |
| Subagent | Delegating a focused task to another project agent | The delegated agent | `useSubagent(agentId)` |
diff --git a/docs/agents/services.mdx b/docs/agents/services.mdx
index 87f3a31d..981b24a4 100644
--- a/docs/agents/services.mdx
+++ b/docs/agents/services.mdx
@@ -1,6 +1,6 @@
---
title: "Connected services"
-description: "Call Gmail, Calendar, Drive, Sheets and GitHub with a credential the platform holds and refreshes"
+description: "Call Google services, GitHub, and Linear with a credential the platform holds and refreshes"
---
Some credentials cannot be a secret you set. An OAuth token is short-lived,
@@ -52,12 +52,12 @@ For minting several links at once, `--no-wait` prints the link and exits.
`--json` does the same and is the one to script against.
Omitting the label connects it as `default`, which is what the examples below
-assume. **`default` is a literal name, not a fallback**: if you connect an
-account as `support`, a call that passes no `label` looks for one called
-`default` and gets a `404` even though `support` is the only account you have.
+assume. Calls do not need a label when exactly one eligible account is
+connected. When several accounts are eligible, pass the label to select one;
+otherwise the call returns `409 connection_alias_required` and lists them.
The provider segment in the URL is the grant, not the service — `google` for
-gmail, calendar, drive and sheets; `github` for github.
+gmail, calendar, drive and sheets; `github` for GitHub; and `linear` for Linear.
**Listing what is connected:**
@@ -126,8 +126,9 @@ without it, `listServices()` returns nothing.
| `drive` | `www.googleapis.com` | Google |
| `sheets` | `www.googleapis.com` | Google |
| `github` | GitHub's API | GitHub |
+| `linear` | `api.linear.app/graphql` | Linear |
-The Google services share one grant; GitHub is its own. A name outside that
+The Google services share one grant; GitHub and Linear each have their own. A name outside that
list fails the build rather than the request.
<Note>
@@ -189,6 +190,31 @@ await callService({
});
```
+Linear uses one GraphQL endpoint. Send a JSON GraphQL document with `POST`:
+
+```tsx
+const response = await callService({
+ service: "linear",
+ method: "POST",
+ path: "/graphql",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ query: `query Viewer { viewer { id name email } }`,
+ }),
+});
+const result = (await response.json()) as {
+ data?: unknown;
+ errors?: Array<{ message: string }>;
+};
+if (!response.ok || result.errors?.length) {
+ throw new Error(result.errors?.[0]?.message ?? `linear: ${response.status}`);
+}
+```
+
+Linear may report GraphQL errors in a successful HTTP response, so check both
+`response.ok` and `errors`. The Linear connection accepts only `POST /graphql`;
+other paths and methods fail at the broker.
+
## 4. Several accounts
Accounts are connected and disconnected long after the artifact is built, so
@@ -224,7 +250,7 @@ export const sweep = defineTool({
| `id` | The connection's id, for the disconnect route |
| `label` | The alias it was connected under. Pass this as `label`. |
| `displayName` | Who the account belongs to, e.g. the mailbox address |
-| `provider` | `google` or `github` |
+| `provider` | `google`, `github`, or `linear` |
| `scopes` | What was granted at consent |
| `status` | `connected` accounts are usable |
@@ -239,7 +265,7 @@ A proxied request is not an unrestricted `fetch`.
| | |
| --- | --- |
-| Methods | `GET`, `POST`, `PUT`, `PATCH`, `DELETE` |
+| Methods | `GET`, `POST`, `PUT`, `PATCH`, `DELETE`; Linear is `POST` only |
| Request headers | Only `accept`, `content-type`, `if-match`, `if-none-match` |
| Request body | 4 MB |
| Response body | 4 MB |
@@ -261,7 +287,7 @@ collections rather than asking for them in one call.
| You see | It means | Do this |
| --- | --- | --- |
-| `404 connection_not_found` | No account under **that label** — often a call with no `label` while the account was connected as something else | `opencomputer connection list` to see the labels, then pass the matching one — or connect an account |
+| `404 connection_not_found` | No eligible connected account exists, or no account matches the requested `label` | `opencomputer connection list` to inspect the accounts, then connect one or correct the label |
| `409 connection_alias_required` | Several accounts connected, no `label` given | Pass `label`; the message lists them |
| `403` from the service | The consent is narrower than the call needs | Reconnect the account with wider access |
| `listServices()` returns `[]` | The service is not declared | Add `useService("gmail")` |
diff --git a/docs/agents/tools.mdx b/docs/agents/tools.mdx
index e38c2e99..88070add 100644
--- a/docs/agents/tools.mdx
+++ b/docs/agents/tools.mdx
@@ -267,7 +267,7 @@ the credential outside the agent runtime; see
short-lived environment credentials so Git and `gh` work directly. Never
embed credentials in tool source or return them to the model.
-For Gmail, Calendar, Drive, Sheets or GitHub, the credential belongs to whoever
+For Google services, GitHub, or Linear, the credential belongs to whoever
connected the account and the platform refreshes it — call those with
[`callService`](/agents/services) instead.
diff --git a/web/src/components/service-logo.tsx b/web/src/components/service-logo.tsx
new file mode 100644
index 00000000..43273889
--- /dev/null
+++ b/web/src/components/service-logo.tsx
@@ -0,0 +1,50 @@
+import { Plug } from 'lucide-react'
+
+type ServiceLogoProps = {
+ service?: 'gmail' | 'calendar' | 'drive' | 'sheets' | 'linear'
+ className?: string
+}
+
+const logos = {
+ gmail: {
+ label: 'Gmail',
+ color: '#EA4335',
+ path: 'M24 5.457v13.909c0 .904-.732 1.636-1.636 1.636h-3.819V11.73L12 16.64l-6.545-4.91v9.273H1.636A1.636 1.636 0 0 1 0 19.366V5.457c0-2.023 2.309-3.178 3.927-1.964L5.455 4.64 12 9.548l6.545-4.91 1.528-1.145C21.69 2.28 24 3.434 24 5.457z',
+ },
+ calendar: {
+ label: 'Google Calendar',
+ color: '#4285F4',
+ path: 'M18.316 5.684H24v12.632h-5.684V5.684zM5.684 24h12.632v-5.684H5.684V24zM18.316 5.684V0H1.895A1.894 1.894 0 0 0 0 1.895v16.421h5.684V5.684h12.632zm-7.207 6.25v-.065c.272-.144.5-.349.687-.617s.279-.595.279-.982c0-.379-.099-.72-.3-1.025a2.05 2.05 0 0 0-.832-.714 2.703 2.703 0 0 0-1.197-.257c-.6 0-1.094.156-1.481.467-.386.311-.65.671-.793 1.078l1.085.452c.086-.249.224-.461.413-.633.189-.172.445-.257.767-.257.33 0 .602.088.816.264a.86.86 0 0 1 .322.703c0 .33-.12.589-.36.778-.24.19-.535.284-.886.284h-.567v1.085h.633c.407 0 .748.109 1.02.327.272.218.407.499.407.843 0 .336-.129.614-.387.832s-.565.327-.924.327c-.351 0-.651-.103-.897-.311-.248-.208-.422-.502-.521-.881l-1.096.452c.178.616.505 1.082.977 1.401.472.319.984.478 1.538.477a2.84 2.84 0 0 0 1.293-.291c.382-.193.684-.458.902-.794.218-.336.327-.72.327-1.149 0-.429-.115-.797-.344-1.105a2.067 2.067 0 0 0-.881-.689zm2.093-1.931.602.913L15 10.045v5.744h1.187V8.446h-.827l-2.158 1.557zM22.105 0h-3.289v5.184H24V1.895A1.894 1.894 0 0 0 22.105 0zm-3.289 23.5 4.684-4.684h-4.684V23.5zM0 22.105C0 23.152.848 24 1.895 24h3.289v-5.184H0v3.289z',
+ },
+ drive: {
+ label: 'Google Drive',
+ color: '#0F9D58',
+ path: 'M12.01 1.485c-2.082 0-3.754.02-3.743.047.01.02 1.708 3.001 3.774 6.62l3.76 6.574h3.76c2.081 0 3.753-.02 3.742-.047-.005-.02-1.708-3.001-3.775-6.62l-3.76-6.574zm-4.76 1.73a789.828 789.861 0 0 0-3.63 6.319L0 15.868l1.89 3.298 1.885 3.297 3.62-6.335 3.618-6.33-1.88-3.287C8.1 4.704 7.255 3.22 7.25 3.214zm2.259 12.653-.203.348c-.114.198-.96 1.672-1.88 3.287a423.93 423.948 0 0 1-1.698 2.97c-.01.026 3.24.042 7.222.042h7.244l1.796-3.157c.992-1.734 1.85-3.23 1.906-3.323l.104-.167h-7.249z',
+ },
+ sheets: {
+ label: 'Google Sheets',
+ color: '#0F9D58',
+ path: 'M11.318 12.545H7.91v-1.909h3.41v1.91zM14.728 0v6h6l-6-6zm1.363 10.636h-3.41v1.91h3.41v-1.91zm0 3.273h-3.41v1.91h3.41v-1.91zM20.727 6.5v15.864c0 .904-.732 1.636-1.636 1.636H4.909a1.636 1.636 0 0 1-1.636-1.636V1.636C3.273.732 4.005 0 4.909 0h9.318v6.5h6.5zm-3.273 2.773H6.545v7.909h10.91v-7.91zm-6.136 4.636H7.91v1.91h3.41v-1.91z',
+ },
+ linear: {
+ label: 'Linear',
+ color: '#5E6AD2',
+ path: 'M2.886 4.18A11.982 11.982 0 0 1 11.99 0C18.624 0 24 5.376 24 12.009c0 3.64-1.62 6.903-4.18 9.105L2.887 4.18ZM1.817 5.626l16.556 16.556c-.524.33-1.075.62-1.65.866L.951 7.277c.247-.575.537-1.126.866-1.65ZM.322 9.163l14.515 14.515c-.71.172-1.443.282-2.195.322L0 11.358a12 12 0 0 1 .322-2.195Zm-.17 4.862 9.823 9.824a12.02 12.02 0 0 1-9.824-9.824Z',
+ },
+} as const
+
+export function ServiceLogo({ service, className }: ServiceLogoProps) {
+ if (!service) return <Plug className={className} aria-hidden />
+
+ const logo = logos[service]
+ return (
+ <svg
+ className={className}
+ viewBox="0 0 24 24"
+ aria-hidden
+ style={{ color: logo.color }}
+ >
+ <path d={logo.path} fill="currentColor" />
+ </svg>
+ )
+}
diff --git a/web/src/managed-agents/Connections.tsx b/web/src/managed-agents/Connections.tsx
index 63e99138..40193888 100644
--- a/web/src/managed-agents/Connections.tsx
+++ b/web/src/managed-agents/Connections.tsx
@@ -5,6 +5,7 @@ import { useSearchParams } from 'react-router-dom'
import { ConfirmDialog } from '@/components/confirm-dialog'
import { GithubMark } from '@/components/github-mark'
import { PageHeader } from '@/components/page-header'
+import { ServiceLogo } from '@/components/service-logo'
import {
Panel,
PanelContent,
@@ -72,8 +73,9 @@ function connectionService(connection: { provider: string; scopes: string[] }) {
function connectionServiceId(
connection: ManagedAgentConnection,
-): 'gmail' | 'calendar' | 'drive' | 'sheets' | 'github' | undefined {
+): 'gmail' | 'calendar' | 'drive' | 'sheets' | 'github' | 'linear' | undefined {
if (connection.provider === 'github') return 'github'
+ if (connection.provider === 'linear') return 'linear'
if (connection.provider !== 'google') return undefined
// Returning undefined here strands the connection: the page skips it when
// reconciling and cannot disconnect it either.
@@ -91,7 +93,7 @@ async function loadManagedAgentConnections() {
const service = connectionServiceId(connection)
if (!service) return Promise.resolve()
return refreshManagedAgentConnection(
- service === 'github' ? 'github' : 'google',
+ service === 'github' || service === 'linear' ? service : 'google',
service,
connection.id,
)
@@ -432,11 +434,16 @@ export default function ManagedAgentConnections() {
<div className="grid gap-3 md:grid-cols-2">
{connections.data.map((connection) => {
const agentName = agentNames.get(connection.agentId)
+ const service = connectionServiceId(connection)
return (
<Panel key={connection.id}>
<PanelContent className="flex items-center gap-3">
<div className="bg-muted text-muted-foreground flex size-9 shrink-0 items-center justify-center rounded-md">
- <Plug className="size-4" aria-hidden />
+ {service === 'github' ? (
+ <GithubMark className="size-4" />
+ ) : (
+ <ServiceLogo service={service} className="size-4" />
+ )}
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">
@@ -453,7 +460,7 @@ export default function ManagedAgentConnections() {
</p>
</div>
<StatusBadge status={connection.status} />
- {connectionServiceId(connection) ? (
+ {service ? (
<Button
type="button"
variant="ghost"
@@ -477,7 +484,7 @@ export default function ManagedAgentConnections() {
</div>
<p className="text-sm font-medium">No connections yet</p>
<p className="text-muted-foreground mt-1 max-w-sm text-sm">
- Add Gmail or Google Calendar to make it available to your agents.
+ Add Google, GitHub, or Linear accounts for your agents.
</p>
<Button
className="mt-4"
@@ -567,6 +574,7 @@ export default function ManagedAgentConnections() {
<option value="calendar">Google Calendar</option>
<option value="drive">Google Drive</option>
<option value="sheets">Google Sheets</option>
+ <option value="linear">Linear</option>
</select>
</div>
<div className="grid gap-2">
@@ -634,7 +642,7 @@ export default function ManagedAgentConnections() {
setRemovingConnection(true)
setRemoveConnectionError(undefined)
void disconnectManagedAgentConnection(
- service === 'github' ? 'github' : 'google',
+ service === 'github' || service === 'linear' ? service : 'google',
service,
connectionToRemove.id,
)
diff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.ts
index 9353acf8..99589363 100644
--- a/web/src/managed-agents/api.ts
+++ b/web/src/managed-agents/api.ts
@@ -1332,7 +1332,7 @@ export async function linkManagedAgentConnection(
}
export async function refreshManagedAgentConnection(
- provider: 'google' | 'github',
+ provider: 'google' | 'github' | 'linear',
service: string,
connectionId: string,
) {
@@ -1345,7 +1345,7 @@ export async function refreshManagedAgentConnection(
}
export async function disconnectManagedAgentConnection(
- provider: 'google' | 'github',
+ provider: 'google' | 'github' | 'linear',
service: string,
connectionId: string,
) {