An open-source, faster Devin alternative
TypeScript
Add Serverless Agent secrets, logs, and Debug playground (#615)
Mohamed Habib37936dfea4ae
diff --git a/agent/README.md b/agent/README.mdindex 3a69c846..96b63221 100644--- a/agent/README.md+++ b/agent/README.md@@ -30,6 +30,53 @@ Use `connection()` and `defineMcpServer()` for stable code declarations. Neverput credentials in these declarations: OpenComputer resolves secrets throughits managed gateway.+## Secret-backed HTTP connections++Declare the destination and the exact place a secret may be injected. The+secret reference is compiled into deployment metadata; its value never enters+the agent artifact or runtime:++```ts+import {+ bearer,+ defineConnection,+ defineTool,+ useConnection,+ useSecret,+ useTool,+} from "@opencomputer/agent";++const github = defineConnection({+ id: "github-api",+ origin: "https://api.github.com",+ methods: ["GET"],+ pathPrefix: "/repos/",+ headers: {+ Authorization: bearer(useSecret("GITHUB_TOKEN")),+ },+});++const repository = defineTool({+ name: "github_repository",+ description: "Read a GitHub repository.",+ async run() {+ const response = await github.fetch("/repos/opencomputer/example");+ return await response.json();+ },+});++export default function Agent() {+ useConnection(github);+ useTool(repository);+ return "Use GitHub when the user asks about a repository.";+}+```++`defineConnection().fetch()` sends a relative request through OpenComputer's+managed egress gateway. The gateway checks the deployment, agent, environment,+origin, path, and method before resolving and injecting the secret. Redirects+are not followed by the gateway.+Hooks may only be called while the managed runtime is rendering an agent.## Code-defined toolsdiff --git a/agent/package-lock.json b/agent/package-lock.jsonindex 9d48fc7f..f200d7aa 100644--- a/agent/package-lock.json+++ b/agent/package-lock.json@@ -1,12 +1,12 @@{"name": "@opencomputer/agent",- "version": "0.2.0",+ "version": "0.3.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@opencomputer/agent",- "version": "0.2.0",+ "version": "0.3.0","devDependencies": {"typescript": "^5.9.0"},diff --git a/agent/package.json b/agent/package.jsonindex c2601a34..1485d0d4 100644--- a/agent/package.json+++ b/agent/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/agent",- "version": "0.2.0",+ "version": "0.3.0","description": "Reactive agent authoring API for OpenComputer.","type": "module","main": "./dist/index.js",diff --git a/agent/src/index.ts b/agent/src/index.tsindex 0159c527..d60c7aa4 100644--- a/agent/src/index.ts+++ b/agent/src/index.ts@@ -20,6 +20,25 @@ export interface ConnectionReference extends ResourceReference {readonly kind: "connection";}+export interface SecretReference extends ResourceReference {+ readonly kind: "secret";+}++export interface SecretHeaderReference {+ readonly kind: "secret-header";+ readonly secret: SecretReference;+ readonly prefix?: string;+ readonly suffix?: string;+}++export interface HttpConnectionDefinition extends ConnectionReference {+ readonly origin: string;+ readonly headers: Readonly<Record<string, string | SecretHeaderReference>>;+ readonly methods?: readonly string[];+ readonly pathPrefix?: string;+ fetch(path: string, init?: RequestInit): Promise<Response>;+}+export interface McpServerDefinition extends ResourceReference {readonly kind: "mcp";readonly url: string;@@ -86,6 +105,106 @@ export function connection(id: string): ConnectionReference {return Object.freeze({ kind: "connection", id: identifier(id, "connection") });}+export function useSecret(name: string): SecretReference {+ const id = identifier(name, "useSecret");+ if (!/^[A-Z][A-Z0-9_]{0,127}$/.test(id)) {+ throw new Error(+ "Secret names must use uppercase letters, numbers, and underscores",+ );+ }+ return Object.freeze({ kind: "secret", id });+}++export function secretHeader(+ secret: SecretReference,+ options: { prefix?: string; suffix?: string } = {},+): SecretHeaderReference {+ return Object.freeze({ kind: "secret-header", secret, ...options });+}++export function bearer(secret: SecretReference): SecretHeaderReference {+ return secretHeader(secret, { prefix: "Bearer " });+}++export function defineConnection(input: {+ id: string;+ origin: string;+ headers?: Readonly<Record<string, string | SecretHeaderReference>>;+ methods?: readonly string[];+ pathPrefix?: string;+}): HttpConnectionDefinition {+ const id = identifier(input.id, "defineConnection");+ const origin = new URL(input.origin);+ if (origin.protocol !== "https:" || origin.pathname !== "/") {+ throw new Error("Connection origins must be HTTPS origins without a path");+ }+ for (const [name, value] of Object.entries(input.headers ?? {})) {+ if (+ ["api-key", "authorization", "cookie", "proxy-authorization", "x-api-key"].includes(+ name.toLowerCase(),+ ) &&+ typeof value === "string"+ ) {+ throw new Error(`${name} must use useSecret()`);+ }+ }+ const definition = {+ kind: "connection" as const,+ id,+ origin: origin.origin,+ headers: Object.freeze({ ...(input.headers ?? {}) }),+ ...(input.methods+ ? { methods: Object.freeze(input.methods.map((method) => method.toUpperCase())) }+ : {}),+ ...(input.pathPrefix ? { pathPrefix: input.pathPrefix } : {}),+ async fetch(path: string, init: RequestInit = {}): Promise<Response> {+ const runtime = globalThis as typeof globalThis & {+ process?: { env?: Record<string, string | undefined> };+ };+ const base = runtime.process?.env?.OPENCOMPUTER_CONNECTIONS_URL;+ const token = runtime.process?.env?.OPENCOMPUTER_CONNECTION_TOKEN;+ if (!base || !token) {+ throw new Error("OpenComputer managed egress is unavailable");+ }+ if (!path.startsWith("/")) {+ throw new Error("Connection requests require an absolute path");+ }+ const headers = Object.fromEntries(new Headers(init.headers).entries());+ const body =+ init.body === undefined || init.body === null+ ? undefined+ : typeof init.body === "string"+ ? init.body+ : (() => {+ throw new Error(+ "Managed connection request bodies must currently be strings",+ );+ })();+ if (body !== undefined && body.length > 5 * 1024 * 1024) {+ throw new Error("Managed connection request bodies cannot exceed 5 MiB");+ }+ return fetch(+ `${base.replace(/\/$/, "")}/${encodeURIComponent(id)}/fetch`,+ {+ method: "POST",+ headers: {+ authorization: `Bearer ${token}`,+ "content-type": "application/json",+ },+ body: JSON.stringify({+ method: (init.method ?? "GET").toUpperCase(),+ path,+ headers,+ ...(body === undefined ? {} : { body }),+ }),+ signal: init.signal,+ },+ );+ },+ };+ return Object.freeze(definition);+}+export function defineMcpServer(input: {id: string;url: string;diff --git a/cli/README.md b/cli/README.mdindex cfddb9f1..e1a86b58 100644--- a/cli/README.md+++ b/cli/README.md@@ -44,3 +44,38 @@ opencomputer run hello-world "Say hello"The CLI calls the public OpenComputer API and uses OpenComputer authentication.It does not require a separate backend account, key, or CLI.++## Secrets and managed egress++Secret values are read from a hidden prompt, or from standard input in CI.+They are write-only: list output contains names, scope, environment, and+allowed origins, never values.++```bash+# Project-level development secret. Allowed origins are inferred from code.+opencomputer secrets set GITHUB_TOKEN++# Agent-level production override.+opencomputer secrets set GITHUB_TOKEN \+ --agent current \+ --environment production++opencomputer secrets list --environment development+opencomputer secrets remove GITHUB_TOKEN --environment development+```++Agent code declares secret-backed destinations with `defineConnection()`,+`useSecret()`, and `useConnection()`. Requests use the managed gateway, which+injects a secret only for the declared origin, path, method, agent, and+environment. The plaintext secret is not added to the deployment or runtime.++## Logs++Read runtime stdout/stderr and managed-egress events from the public+OpenComputer API:++```bash+opencomputer logs+opencomputer logs --agent my-agent --environment development --follow+opencomputer logs --session <session-id> --json+```diff --git a/cli/package-lock.json b/cli/package-lock.jsonindex 1d67f8e3..83a3c4d7 100644--- a/cli/package-lock.json+++ b/cli/package-lock.json@@ -1,12 +1,12 @@{"name": "@opencomputer/cli",- "version": "0.4.6",+ "version": "0.4.7","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@opencomputer/cli",- "version": "0.4.6",+ "version": "0.4.7","dependencies": {"@opencode-ai/sdk": "1.18.4","ai": "^7.0.45",diff --git a/cli/package.json b/cli/package.jsonindex bb790aff..6d01cb3f 100644--- a/cli/package.json+++ b/cli/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/cli",- "version": "0.4.6",+ "version": "0.4.7","description": "Build, test, connect, deploy, and share OpenComputer agents as code.","type": "module","bin": {@@ -12,7 +12,7 @@],"scripts": {"clean": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\"",- "build:server": "tsc -p tsconfig.json",+ "build:server": "tsc -p tsconfig.json && node -e \"require('node:fs').chmodSync('dist/index.js', 0o755)\"","build:ui": "tsc -p tsconfig.ui.json --noEmit && vite build","build": "npm run clean && npm run build:server && npm run build:ui","test": "npm run build && node --test dist/*.test.js",diff --git a/cli/src/api.ts b/cli/src/api.tsindex 37c6cdbb..f424ad5d 100644--- a/cli/src/api.ts+++ b/cli/src/api.ts@@ -72,6 +72,29 @@ export interface ManagedAgentEvent {data: Record<string, unknown>;}+export interface ManagedSecretMetadata {+ name: string;+ projectId: string;+ environment: "development" | "production";+ agentId?: string;+ allowedOrigins: string[];+ createdAt: string;+ updatedAt: string;+}++export interface ManagedAgentLog {+ id: string;+ cursor: string;+ timestamp: string;+ level: "info" | "warn" | "error";+ event: string;+ environment: "development" | "production";+ agentId: string;+ deploymentId: string;+ sessionId: string;+ data: Record<string, unknown>;+}+export interface ManagedSessionSnapshot {id: string;status: string;@@ -213,12 +236,96 @@ export class OpenComputerClient {});}+ async secrets(input: {+ projectId: string;+ environment?: "development" | "production";+ agentId?: string;+ }): Promise<ManagedSecretMetadata[]> {+ const query = new URLSearchParams();+ if (input.environment) query.set("environment", input.environment);+ if (input.agentId) query.set("agentId", input.agentId);+ const suffix = query.size ? `?${query.toString()}` : "";+ const result = await this.request<{ secrets: ManagedSecretMetadata[] }>(+ `/api/managed-agents/projects/${encodeURIComponent(input.projectId)}/secrets${suffix}`,+ );+ return result.secrets;+ }++ putSecret(input: {+ projectId: string;+ name: string;+ value: string;+ environment: "development" | "production";+ agentId?: string;+ allowedOrigins: string[];+ }) {+ return this.request<ManagedSecretMetadata>(+ `/api/managed-agents/projects/${encodeURIComponent(input.projectId)}/secrets/${encodeURIComponent(input.name)}`,+ {+ method: "PUT",+ body: JSON.stringify({+ value: input.value,+ environment: input.environment,+ ...(input.agentId ? { agentId: input.agentId } : {}),+ allowedOrigins: input.allowedOrigins,+ }),+ },+ );+ }++ deleteSecret(input: {+ projectId: string;+ name: string;+ environment: "development" | "production";+ agentId?: string;+ }) {+ const query = new URLSearchParams({ environment: input.environment });+ if (input.agentId) query.set("agentId", input.agentId);+ return this.request<void>(+ `/api/managed-agents/projects/${encodeURIComponent(input.projectId)}/secrets/${encodeURIComponent(input.name)}?${query.toString()}`,+ { method: "DELETE" },+ );+ }++ logs(input: {+ agentId?: string;+ sessionId?: string;+ environment?: "development" | "production";+ after?: string;+ limit?: number;+ }) {+ const query = new URLSearchParams();+ if (input.agentId) query.set("agentId", input.agentId);+ if (input.sessionId) query.set("sessionId", input.sessionId);+ if (input.environment) query.set("environment", input.environment);+ if (input.after) query.set("after", input.after);+ if (input.limit) query.set("limit", String(input.limit));+ return this.request<{ logs: ManagedAgentLog[]; cursor: string }>(+ `/api/managed-agents/logs?${query.toString()}`,+ );+ }+registerDeployment(input: {agentId: string;name: string;alias: string;channels: string[];connections: string[];+ httpConnections: Array<{+ id: string;+ origin: string;+ headers: Record<+ string,+ string | {+ kind: "secret";+ name: string;+ prefix?: string;+ suffix?: string;+ }+ >;+ methods?: string[];+ pathPrefix?: string;+ }>;source: {digest: string;size: number;diff --git a/cli/src/commands.ts b/cli/src/commands.tsindex 9a18c492..1cd597eb 100644--- a/cli/src/commands.ts+++ b/cli/src/commands.ts@@ -3,12 +3,16 @@ import { rm } from "node:fs/promises";import {OpenComputerClient,type ManagedAgentEvent,+ type ManagedAgentLog,type ManagedSessionSnapshot,} from "./api.js";import { login, logout, openBrowser } from "./auth.js";import { resolveConfig } from "./config.js";import { runCloudDevelopment } from "./dev.js";-import { findOpenComputerProjectRoot } from "./binding.js";+import {+ ensureProjectBinding,+ findOpenComputerProjectRoot,+} from "./binding.js";import { runLocalAgent } from "./local.js";import {addSlackChannel,@@ -59,6 +63,98 @@ function option(args: string[], name: string): string | undefined {return value;}+function options(args: string[], name: string): string[] {+ const values: string[] = [];+ for (;;) {+ const value = option(args, name);+ if (value === undefined) return values;+ values.push(value);+ }+}++function environmentOption(+ value: string | undefined,+): "development" | "production" {+ if (!value || value === "development") return "development";+ if (value === "production") return "production";+ throw new Error("--environment must be development or production");+}++async function readSecretValue(): Promise<string> {+ if (!process.stdin.isTTY) {+ 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$/, "");+ if (!value) throw new Error("Secret value was empty");+ return value;+ }+ process.stderr.write("Secret value (hidden): ");+ process.stdin.setRawMode(true);+ process.stdin.resume();+ return new Promise<string>((resolve, reject) => {+ let value = "";+ const finish = (error?: Error): void => {+ process.stdin.off("data", onData);+ process.stdin.setRawMode(false);+ process.stdin.pause();+ process.stderr.write("\n");+ if (error) reject(error);+ else if (!value) reject(new Error("Secret value was empty"));+ else resolve(value);+ };+ const onData = (chunk: Buffer): void => {+ for (const byte of chunk) {+ if (byte === 3) return finish(new Error("Secret entry cancelled"));+ if (byte === 10 || byte === 13) return finish();+ if (byte === 8 || byte === 127) value = value.slice(0, -1);+ else value += String.fromCharCode(byte);+ }+ };+ process.stdin.on("data", onData);+ });+}++async function selectedProject(+ client: OpenComputerClient,+ config: Awaited<ReturnType<typeof resolveConfig>>,+ reference?: string,+): Promise<{ projectId: string; agentId: string }> {+ if (reference) {+ const project = (await client.projects()).find(+ (candidate) => candidate.id === reference || candidate.slug === reference,+ );+ if (!project) throw new Error(`Project ${reference} was not found.`);+ const agent = project.agents[0];+ if (!agent) throw new Error(`Project ${project.name} has no agents.`);+ return { projectId: project.id, agentId: agent.id };+ }+ const root = await findOpenComputerProjectRoot(process.cwd());+ const binding = await ensureProjectBinding(client, config, root, {+ interactive: false,+ });+ return { projectId: binding.projectId, agentId: binding.agentId };+}++function printLog(entry: ManagedAgentLog, json: boolean): void {+ if (json) {+ process.stdout.write(`${JSON.stringify(entry)}\n`);+ return;+ }+ const message =+ typeof entry.data.message === "string"+ ? entry.data.message+ : Object.keys(entry.data).length+ ? JSON.stringify(entry.data)+ : "";+ process.stdout.write(+ `${entry.timestamp} ${entry.level.toUpperCase().padEnd(5)} ` ++ `${entry.agentId} ${entry.sessionId} ${entry.event}` ++ `${message ? ` ${message}` : ""}\n`,+ );+}+async function requireAgentRoot(): Promise<string> {const root = await findAgentRoot();if (!root) {@@ -474,6 +570,7 @@ export async function runCommand(alias,channels: built.channels,connections: built.connections,+ httpConnections: built.httpConnections,source: {digest: built.digest,size: built.body.byteLength,@@ -521,6 +618,143 @@ export async function runCommand(return;}+ if (command === "secrets" || command === "secret") {+ const action = args.shift();+ const projectReference = option(args, "--project");+ const agentOption = option(args, "--agent");+ const environment = environmentOption(option(args, "--environment"));+ const project = await selectedProject(client, config, projectReference);+ const agentId = agentOption+ ? agentOption === "current"+ ? project.agentId+ : agentOption+ : undefined;+ if (action === "list") {+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);+ const secrets = await client.secrets({+ projectId: project.projectId,+ environment,+ ...(agentId ? { agentId } : {}),+ });+ if (globals.json) printJSON(secrets);+ else if (!secrets.length) process.stdout.write("No secrets.\n");+ else {+ for (const secret of secrets) {+ process.stdout.write(+ `${secret.name.padEnd(28)} ${secret.environment.padEnd(12)} ` ++ `${(secret.agentId ?? "project").padEnd(24)} ` ++ `${secret.allowedOrigins.join(", ")}\n`,+ );+ }+ }+ return;+ }+ const name = args.shift();+ if (!name) {+ throw new Error(+ "Use `opencomputer secrets set|list|remove <name>`.",+ );+ }+ if (action === "set") {+ const explicitOrigins = options(args, "--allow-origin");+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);+ let allowedOrigins = explicitOrigins;+ if (!allowedOrigins.length) {+ const built = await buildAgentArtifact(await requireAgentRoot());+ allowedOrigins = built.httpConnections+ .filter((connection) =>+ Object.values(connection.headers).some(+ (value) => typeof value !== "string" && value.name === name,+ ),+ )+ .map((connection) => connection.origin);+ }+ allowedOrigins = [...new Set(allowedOrigins)];+ if (!allowedOrigins.length) {+ throw new Error(+ `No connection uses ${name}. Pass --allow-origin https://api.example.com.`,+ );+ }+ const secret = await client.putSecret({+ projectId: project.projectId,+ name,+ value: await readSecretValue(),+ environment,+ ...(agentId ? { agentId } : {}),+ allowedOrigins,+ });+ if (globals.json) printJSON(secret);+ else {+ process.stdout.write(+ `Set ${secret.name} for ${secret.agentId ?? "project"} ` ++ `(${secret.environment}); allowed for ${secret.allowedOrigins.join(", ")}.\n`,+ );+ }+ return;+ }+ if (action === "remove" || action === "delete") {+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);+ await client.deleteSecret({+ projectId: project.projectId,+ name,+ environment,+ ...(agentId ? { agentId } : {}),+ });+ if (globals.json) printJSON({ deleted: true, name });+ else process.stdout.write(`Removed ${name}.\n`);+ return;+ }+ throw new Error("Use `opencomputer secrets set`, `list`, or `remove`.");+ }++ if (command === "logs") {+ const follow = flag(args, "--follow");+ let agentId = option(args, "--agent");+ const sessionId = option(args, "--session");+ const environmentValue = option(args, "--environment");+ const environment = environmentValue+ ? environmentOption(environmentValue)+ : undefined;+ const limitValue = option(args, "--limit");+ const limit = limitValue ? Number.parseInt(limitValue, 10) : 200;+ if (!Number.isFinite(limit) || limit < 1 || limit > 1_000) {+ throw new Error("--limit must be between 1 and 1000");+ }+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);+ if (!agentId && !sessionId) {+ try {+ agentId = (await selectedProject(client, config)).agentId;+ } catch {+ // Outside an initialized app, unfiltered logs cover the account.+ }+ }+ let cursor = "";+ let stopped = false;+ const stop = (): void => {+ stopped = true;+ };+ process.once("SIGINT", stop);+ try {+ do {+ const result = await client.logs({+ ...(agentId ? { agentId } : {}),+ ...(sessionId ? { sessionId } : {}),+ ...(environment ? { environment } : {}),+ ...(cursor ? { after: cursor } : {}),+ limit,+ });+ result.logs.forEach((entry) => printLog(entry, globals.json));+ cursor = result.cursor || cursor;+ if (follow && !stopped) {+ await new Promise((resolve) => setTimeout(resolve, 1_000));+ }+ } while (follow && !stopped);+ } finally {+ process.off("SIGINT", stop);+ }+ return;+ }+if (command === "session") {const local = flag(args, "--local");const remote = flag(args, "--remote");diff --git a/cli/src/dev.ts b/cli/src/dev.tsindex d6eb7c12..472c6c56 100644--- a/cli/src/dev.ts+++ b/cli/src/dev.ts@@ -28,6 +28,7 @@ export async function publishDevelopment(alias: DEVELOPMENT_ALIAS,channels: built.channels,connections: built.connections,+ httpConnections: built.httpConnections,source: {digest: built.digest,size: built.body.byteLength,diff --git a/cli/src/index.ts b/cli/src/index.tsindex ddc23d2b..081e6b40 100644--- a/cli/src/index.ts+++ b/cli/src/index.ts@@ -60,6 +60,10 @@ Usage:opencomputer connection add <gmail|calendar|github> [--alias <name>]opencomputer connection listopencomputer connection remove <alias|connection-id>+ opencomputer secrets set <name> [--environment development|production] [--agent <agent>|current]+ opencomputer secrets list [--environment development|production] [--agent <agent>|current]+ opencomputer secrets remove <name> [--environment development|production] [--agent <agent>|current]+ opencomputer logs [--agent <agent>] [--session <session-id>] [--environment development|production] [--follow]opencomputer channels list [--local|--remote]opencomputer channels disconnect slack [connection-id] [--local|--remote]opencomputer deploy [--alias <alias>]diff --git a/cli/src/project.test.ts b/cli/src/project.test.tsindex a5ee03aa..6ae53aa8 100644--- a/cli/src/project.test.ts+++ b/cli/src/project.test.ts@@ -9,8 +9,10 @@ import {} from "node:fs/promises";import { tmpdir } from "node:os";import { resolve } from "node:path";+import { pathToFileURL } from "node:url";import test from "node:test";import {+ buildAgentArtifact,findAgentRoot,initializeAgentProject,prepareAgent,@@ -52,8 +54,8 @@ test("init creates a multi-agent-ready project and React hello world app", async};assert.equal(packageJSON.scripts.dev, "opencomputer dev");assert.equal(packageJSON.scripts["dev:web"], "vite");- assert.equal(packageJSON.dependencies["@opencomputer/agent"], "^0.2.0");- assert.equal(packageJSON.devDependencies["@opencomputer/cli"], "^0.4.6");+ assert.equal(packageJSON.dependencies["@opencomputer/agent"], "^0.3.0");+ assert.equal(packageJSON.devDependencies["@opencomputer/cli"], "^0.4.7");assert.ok(packageJSON.devDependencies["@types/node"]);const viteConfig = await readFile(resolve(root, "vite.config.ts"), "utf8");assert.match(viteConfig, /command === "serve"/);@@ -159,6 +161,7 @@ export default function Agent() {toolModules: string[];subagents: string[];connections: string[];+ httpConnections: unknown[];mcpServers: string[];};assert.deepEqual(manifest, {@@ -172,6 +175,7 @@ export default function Agent() {toolModules: ["../tools/opencomputer-connections.js"],subagents: ["researcher"],connections: ["github"],+ httpConnections: [],mcpServers: ["docs"],});await assert.rejects(@@ -182,6 +186,105 @@ export default function Agent() {}});+test("the compiler records secret-backed HTTP connections without secret values", async () => {+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-egress-"));+ const root = resolve(parent, "app");+ try {+ const initialized = await initializeAgentProject(root);+ await mkdir(resolve(initialized.agentRoot, "tools"), { recursive: true });+ await writeFile(+ resolve(initialized.agentRoot, "tools", "github.ts"),+ `import { bearer, defineConnection, defineTool, useSecret } from "@opencomputer/agent";++export const github = defineConnection({+ id: "github-api",+ origin: "https://api.github.com",+ methods: ["GET"],+ pathPrefix: "/repos/",+ headers: { Authorization: bearer(useSecret("GITHUB_TOKEN")) },+});++export const repository = defineTool({+ name: "github_repository",+ description: "Read a GitHub repository",+ async run() {+ const response = await github.fetch("/repos/opencomputer/example");+ return await response.json();+ },+});+`,+ );+ await writeFile(+ resolve(initialized.agentRoot, "agent.ts"),+ `import { useConnection, useTool } from "@opencomputer/agent";+import { github, repository } from "./tools/github.js";++export default function Agent() {+ useConnection(github);+ useTool(repository);+ return "Use GitHub when needed.";+}+`,+ );++ const built = await buildAgentArtifact(initialized.agentRoot);+ await assert.doesNotReject(+ import(+ `${pathToFileURL(resolve(initialized.agentRoot, ".opencomputer", "runtime", "opencomputer-agent.js")).href}?test=${crypto.randomUUID()}`+ ),+ );+ assert.deepEqual(built.httpConnections, [+ {+ id: "github-api",+ origin: "https://api.github.com",+ methods: ["GET"],+ pathPrefix: "/repos/",+ headers: {+ Authorization: {+ kind: "secret",+ name: "GITHUB_TOKEN",+ prefix: "Bearer ",+ },+ },+ },+ ]);+ assert.ok(built.connections.includes("github-api"));+ assert.doesNotMatch(built.body.toString("utf8"), /actual-secret-value/);+ } finally {+ await rm(parent, { recursive: true, force: true });+ }+});++test("the compiler rejects hard-coded sensitive connection headers", async () => {+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-egress-secret-"));+ const root = resolve(parent, "app");+ try {+ const initialized = await initializeAgentProject(root);+ await writeFile(+ resolve(initialized.agentRoot, "agent.ts"),+ `import { defineConnection } from "@opencomputer/agent";++defineConnection({+ id: "unsafe-api",+ origin: "https://api.example.com",+ headers: { Authorization: "Bearer hard-coded" },+});++export default function Agent() {+ return "Hello";+}+`,+ );++ await assert.rejects(+ prepareAgent(initialized.agentRoot),+ /Authorization must use useSecret\(\)/,+ );+ } finally {+ await rm(parent, { recursive: true, force: true });+ }+});+test("the compiler packages OpenComputer tools for native OpenCode 2 registration", async () => {const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-v2-tools-"));const root = resolve(parent, "app");diff --git a/cli/src/project.ts b/cli/src/project.tsindex ca4104c1..c1e0c373 100644--- a/cli/src/project.ts+++ b/cli/src/project.ts@@ -22,11 +22,23 @@ export interface BuiltAgentArtifact {name: string;channels: string[];connections: string[];+ httpConnections: HttpConnectionManifest[];body: Buffer;digest: string;elapsedMs: number;}+export interface HttpConnectionManifest {+ id: string;+ origin: string;+ headers: Record<+ string,+ string | { kind: "secret"; name: string; prefix?: string; suffix?: string }+ >;+ methods?: string[];+ pathPrefix?: string;+}+export interface ProjectAgentSource {localId: string;root: string;@@ -489,12 +501,12 @@ export default function Agent() {deploy: "opencomputer deploy",},dependencies: {- "@opencomputer/agent": "^0.2.0",+ "@opencomputer/agent": "^0.3.0",react: "^19.2.0","react-dom": "^19.2.0",},devDependencies: {- "@opencomputer/cli": "^0.4.6",+ "@opencomputer/cli": "^0.4.7","@types/node": "^24.0.0","@types/react": "^19.2.0","@types/react-dom": "^19.2.0",@@ -904,6 +916,163 @@ function definedMcpServerIds(source: string): string[] {.sort();}+function objectProperty(+ object: ts.ObjectLiteralExpression,+ name: string,+): ts.Expression | undefined {+ const property = object.properties.find(+ (candidate): candidate is ts.PropertyAssignment =>+ ts.isPropertyAssignment(candidate) &&+ ((ts.isIdentifier(candidate.name) && candidate.name.text === name) ||+ (ts.isStringLiteral(candidate.name) && candidate.name.text === name)),+ );+ return property?.initializer;+}++function literalStringValue(+ expression: ts.Expression | undefined,+ label: string,+): string {+ if (!expression || !ts.isStringLiteralLike(expression)) {+ throw new Error(`${label} must be a string literal`);+ }+ return expression.text;+}++function secretNameFromExpression(expression: ts.Expression): string {+ if (+ !ts.isCallExpression(expression) ||+ !ts.isIdentifier(expression.expression) ||+ expression.expression.text !== "useSecret"+ ) {+ throw new Error("Connection secret headers must reference useSecret()");+ }+ return literalStringValue(expression.arguments[0], "useSecret name");+}++function connectionHeaderValue(+ expression: ts.Expression,+): HttpConnectionManifest["headers"][string] {+ if (ts.isStringLiteralLike(expression)) return expression.text;+ if (!ts.isCallExpression(expression) || !ts.isIdentifier(expression.expression)) {+ throw new Error(+ "Connection headers must be string literals, bearer(useSecret()), or secretHeader(useSecret())",+ );+ }+ const helper = expression.expression.text;+ if (helper === "bearer") {+ const secret = expression.arguments[0];+ if (!secret) throw new Error("bearer() requires useSecret()");+ return {+ kind: "secret",+ name: secretNameFromExpression(secret),+ prefix: "Bearer ",+ };+ }+ if (helper === "secretHeader") {+ const secret = expression.arguments[0];+ if (!secret) throw new Error("secretHeader() requires useSecret()");+ const result: {+ kind: "secret";+ name: string;+ prefix?: string;+ suffix?: string;+ } = { kind: "secret", name: secretNameFromExpression(secret) };+ const options = expression.arguments[1];+ if (options) {+ if (!ts.isObjectLiteralExpression(options)) {+ throw new Error("secretHeader options must be an object literal");+ }+ const prefix = objectProperty(options, "prefix");+ const suffix = objectProperty(options, "suffix");+ if (prefix) result.prefix = literalStringValue(prefix, "secretHeader prefix");+ if (suffix) result.suffix = literalStringValue(suffix, "secretHeader suffix");+ }+ return result;+ }+ throw new Error(`Unsupported connection header helper: ${helper}`);+}++function definedHttpConnections(+ source: string,+ path: string,+): HttpConnectionManifest[] {+ const file = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);+ const definitions: HttpConnectionManifest[] = [];+ const visit = (node: ts.Node): void => {+ if (+ ts.isCallExpression(node) &&+ ts.isIdentifier(node.expression) &&+ node.expression.text === "defineConnection"+ ) {+ const input = node.arguments[0];+ if (!input || !ts.isObjectLiteralExpression(input)) {+ throw new Error("defineConnection() requires an object literal");+ }+ const id = literalStringValue(objectProperty(input, "id"), "connection id");+ const originValue = literalStringValue(+ objectProperty(input, "origin"),+ `connection ${id} origin`,+ );+ const origin = new URL(originValue);+ if (origin.protocol !== "https:" || origin.pathname !== "/") {+ throw new Error(`Connection ${id} must use an HTTPS origin without a path`);+ }+ const headers: HttpConnectionManifest["headers"] = {};+ const headerExpression = objectProperty(input, "headers");+ if (headerExpression) {+ if (!ts.isObjectLiteralExpression(headerExpression)) {+ throw new Error(`Connection ${id} headers must be an object literal`);+ }+ for (const property of headerExpression.properties) {+ if (!ts.isPropertyAssignment(property)) {+ throw new Error(`Connection ${id} headers cannot use spreads`);+ }+ const name = ts.isIdentifier(property.name) || ts.isStringLiteral(property.name)+ ? property.name.text+ : undefined;+ if (!name) throw new Error(`Connection ${id} has an invalid header name`);+ const value = connectionHeaderValue(property.initializer);+ if (+ ["api-key", "authorization", "cookie", "proxy-authorization", "x-api-key"].includes(+ name.toLowerCase(),+ ) &&+ typeof value === "string"+ ) {+ throw new Error(`Connection ${id} header ${name} must use useSecret()`);+ }+ headers[name] = value;+ }+ }+ const definition: HttpConnectionManifest = {+ id,+ origin: origin.origin,+ headers,+ };+ const methods = objectProperty(input, "methods");+ if (methods) {+ if (!ts.isArrayLiteralExpression(methods)) {+ throw new Error(`Connection ${id} methods must be an array literal`);+ }+ definition.methods = methods.elements.map((method) =>+ literalStringValue(method, `connection ${id} method`).toUpperCase(),+ );+ }+ const pathPrefix = objectProperty(input, "pathPrefix");+ if (pathPrefix) {+ definition.pathPrefix = literalStringValue(+ pathPrefix,+ `connection ${id} pathPrefix`,+ );+ }+ definitions.push(definition);+ }+ ts.forEachChild(node, visit);+ };+ visit(file);+ return definitions;+}+function definedToolIds(source: string): string[] {return [...source.matchAll(@@ -926,6 +1095,44 @@ function id(value, kind) {return normalized;}export const connection = (value) => Object.freeze({ kind: "connection", id: id(value, "connection") });+export const useSecret = (value) => {+ const name = id(value, "useSecret");+ if (!/^[A-Z][A-Z0-9_]{0,127}$/.test(name)) throw new Error("Invalid secret name " + JSON.stringify(name));+ return Object.freeze({ kind: "secret", id: name });+};+export const secretHeader = (secret, options = {}) => Object.freeze({ kind: "secret-header", secret, ...options });+export const bearer = (secret) => secretHeader(secret, { prefix: "Bearer " });+export const defineConnection = (input) => {+ const connectionId = id(input.id, "defineConnection");+ const origin = new URL(input.origin);+ if (origin.protocol !== "https:" || origin.pathname !== "/") throw new Error("Connection origins must be HTTPS origins without a path");+ for (const [name, value] of Object.entries(input.headers || {})) {+ if (["api-key", "authorization", "cookie", "proxy-authorization", "x-api-key"].includes(name.toLowerCase()) && typeof value === "string") throw new Error(name + " must use useSecret()");+ }+ return Object.freeze({+ kind: "connection",+ ...input,+ id: connectionId,+ origin: origin.origin,+ headers: Object.freeze({ ...(input.headers || {}) }),+ async fetch(path, init = {}) {+ const base = globalThis.process?.env?.OPENCOMPUTER_CONNECTIONS_URL;+ const token = globalThis.process?.env?.OPENCOMPUTER_CONNECTION_TOKEN;+ if (!base || !token) throw new Error("OpenComputer managed egress is unavailable");+ if (!path.startsWith("/")) throw new Error("Connection requests require an absolute path");+ const headers = {};+ new Headers(init.headers).forEach((value, name) => { headers[name] = value; });+ if (init.body != null && typeof init.body !== "string") throw new Error("Managed connection request bodies must currently be strings");+ if (typeof init.body === "string" && init.body.length > 5 * 1024 * 1024) throw new Error("Managed connection request bodies cannot exceed 5 MiB");+ return fetch(base.replace(/\\\/$/, "") + "/" + encodeURIComponent(connectionId) + "/fetch", {+ method: "POST",+ headers: { authorization: "Bearer " + token, "content-type": "application/json" },+ body: JSON.stringify({ method: (init.method || "GET").toUpperCase(), path, headers, ...(init.body == null ? {} : { body: init.body }) }),+ signal: init.signal,+ });+ },+ });+};export const defineMcpServer = (input) => {const url = new URL(input.url);if (url.protocol !== "https:") throw new Error("MCP server URLs must use HTTPS");@@ -1141,6 +1348,17 @@ the product or support surface presented to users.`Tool id ${JSON.stringify(duplicateTool)} is defined more than once`,);}+ const httpConnections = [agentSource, ...toolSources.map((item) => item.source)]+ .flatMap((source, index) =>+ definedHttpConnections(source, index === 0 ? "agent.ts" : toolSources[index - 1]!.filename),+ );+ const duplicateConnection = httpConnections.find(+ (connection, index) =>+ httpConnections.findIndex((candidate) => candidate.id === connection.id) !== index,+ );+ if (duplicateConnection) {+ throw new Error(`Connection id ${JSON.stringify(duplicateConnection.id)} is defined more than once`);+ }await mkdir(resolve(runtime, ".opencomputer"), { recursive: true });await writeFile(resolve(runtime, ".opencomputer", "reactive.json"),@@ -1160,8 +1378,10 @@ the product or support surface presented to users....new Set([...literalHookIds(agentSource, "connection"),...literalHookIds(agentSource, "useConnection"),+ ...httpConnections.map((connection) => connection.id),]),].sort(),+ httpConnections,mcpServers: [...new Set([...definedMcpServerIds(agentSource),@@ -1219,7 +1439,16 @@ export async function buildAgentArtifact(const manifest = await readManifest(root);const runtime = await prepareAgent(root);const channels = await collectNames(root, "channels");- const connections = await collectNames(root, "connections");+ const reactive = JSON.parse(+ await readFile(resolve(runtime, ".opencomputer", "reactive.json"), "utf8"),+ ) as { connections?: string[]; httpConnections?: HttpConnectionManifest[] };+ const connections = [+ ...new Set([+ ...(await collectNames(root, "connections")),+ ...(reactive.connections ?? []),+ ]),+ ].sort();+ const httpConnections = reactive.httpConnections ?? [];const body = Buffer.from(JSON.stringify({version: 1,@@ -1232,6 +1461,7 @@ export async function buildAgentArtifact(name: manifest.name,channels,connections,+ httpConnections,body,digest: createHash("sha256").update(body).digest("hex"),elapsedMs: Math.round(performance.now() - startedAt),diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.tsindex 6785941e..fe3df6fa 100644--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts@@ -510,6 +510,20 @@ describe("managed agents proxy", () => {alias: "production",channels: [],connections: ["google"],+ httpConnections: [+ {+ id: "github-api",+ origin: "https://api.github.com",+ methods: ["GET"],+ headers: {+ Authorization: {+ kind: "secret",+ name: "GITHUB_TOKEN",+ prefix: "Bearer ",+ },+ },+ },+ ],createdAt: "2026-07-30T00:00:00.000Z",artifact: { bucket: "private-bucket" },imageArn: "arn:aws:private",@@ -530,6 +544,20 @@ describe("managed agents proxy", () => {alias: "production",channels: [],connections: ["google"],+ httpConnections: [+ {+ id: "github-api",+ origin: "https://api.github.com",+ methods: ["GET"],+ headers: {+ Authorization: {+ kind: "secret",+ name: "GITHUB_TOKEN",+ prefix: "Bearer ",+ },+ },+ },+ ],source: {digest,size: source.length,@@ -562,12 +590,144 @@ describe("managed agents proxy", () => {).toMatchObject({agentId: "gmail-summarizer",name: "Gentle Falcon",+ httpConnections: [+ expect.objectContaining({+ id: "github-api",+ origin: "https://api.github.com",+ }),+ ],});expect(JSON.stringify(await response.json())).not.toMatch(/bucket|imageArn|arn:aws|uploads\.test/i,);});+ it("forwards managed secret metadata and aggregate logs through the public contract", async () => {+ const fetchSpy = vi+ .fn()+ .mockResolvedValueOnce(+ Response.json({+ name: "GITHUB_TOKEN",+ projectId: "prj_1",+ environment: "development",+ allowedOrigins: ["https://api.github.com"],+ createdAt: "2026-08-10T00:00:00.000Z",+ updatedAt: "2026-08-10T00:00:00.000Z",+ }),+ )+ .mockResolvedValueOnce(+ Response.json({+ logs: [+ {+ id: "log_1",+ cursor: "cursor_1",+ timestamp: "2026-08-10T00:00:00.000Z",+ level: "info",+ event: "runtime.log",+ agentId: "agent-1",+ sessionId: "session-1",+ data: { message: "ready" },+ },+ ],+ cursor: "cursor_1",+ }),+ );+ vi.stubGlobal("fetch", fetchSpy);+ const environment = {+ OC_MANAGED_AGENTS_SECRET: "test-secret",+ MANAGED_AGENTS_API_URL: "https://managedagents.test",+ };+ const caller = { orgID: "org_test", userID: "user_test" };++ const secret = await proxyManagedAgents(+ new Request(+ "https://app.opencomputer.dev/api/managed-agents/projects/prj_1/secrets/GITHUB_TOKEN",+ {+ method: "PUT",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ value: "never-return-this",+ environment: "development",+ allowedOrigins: ["https://api.github.com"],+ }),+ },+ ),+ environment,+ caller,+ "/api/managed-agents",+ );+ expect(secret.status).toBe(200);+ expect(JSON.stringify(await secret.json())).not.toContain(+ "never-return-this",+ );++ const logs = await proxyManagedAgents(+ new Request(+ "https://app.opencomputer.dev/api/managed-agents/logs?agentId=agent-1",+ ),+ environment,+ caller,+ "/api/managed-agents",+ );+ expect(logs.status).toBe(200);+ await expect(logs.json()).resolves.toMatchObject({+ logs: [{ event: "runtime.log", data: { message: "ready" } }],+ });+ });++ it("forwards redacted reactive render snapshots for the debug playground", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () =>+ Response.json({+ events: [+ {+ id: "event_1",+ seq: 4,+ timestamp: "2026-08-10T00:00:00.000Z",+ sessionId: "session-1",+ turnId: "turn-1",+ type: "agent.rendered",+ data: {+ instructions: "Help with the current request.",+ platformInstructions: ["You are an OpenComputer agent."],+ enabledTools: ["search_docs"],+ runtimeToken: "never-return-this",+ },+ },+ ],+ }),+ ),+ );+ const response = await proxyManagedAgents(+ new Request(+ "https://app.opencomputer.dev/api/managed-agents/sessions/session-1/events?after=0",+ ),+ {+ OC_MANAGED_AGENTS_SECRET: "test-secret",+ MANAGED_AGENTS_API_URL: "https://managedagents.test",+ },+ { orgID: "org_test", userID: "user_test" },+ "/api/managed-agents",+ );+ expect(response.status).toBe(200);+ const body = await response.json();+ expect(body).toMatchObject({+ events: [+ {+ type: "agent.rendered",+ data: {+ instructions: "Help with the current request.",+ enabledTools: ["search_docs"],+ },+ },+ ],+ });+ expect(JSON.stringify(body)).not.toContain("never-return-this");+ expect(JSON.stringify(body)).not.toContain("You are an OpenComputer agent.");+ expect(JSON.stringify(body)).not.toContain("platformInstructions");+ });+it("redacts backend implementation errors", async () => {vi.stubGlobal("fetch",diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.tsindex 575fb0cd..8b64c78b 100644--- a/cloudflare-workers/api-edge/src/managed_agents.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.ts@@ -240,13 +240,15 @@ const PRIVATE_EVENT_KEYS = new Set(["runtime_id","runtimeToken","runtime_token",+ "platformInstructions",+ "platform_instructions",]);function publicEventData(type: string,value: unknown,): Record<string, unknown> {- if (type.startsWith("runtime.")) return {};+ if (type.startsWith("runtime.") && type !== "runtime.log") return {};if (type === "session.failed" || type === "turn.failed") {return { message: "The agent could not complete this request." };}@@ -293,6 +295,15 @@ function publicSuccessBody(if (method === "POST" && suffix === "/projects") {return publicProject(body);}+ if (+ (method === "GET" || method === "PUT") &&+ /^\/projects\/[^/]+\/secrets(?:\/[^/]+)?$/.test(suffix)+ ) {+ return stripPrivateValues(body);+ }+ if (method === "GET" && suffix === "/logs") {+ return stripPrivateValues(body);+ }if (method === "GET" && /^\/projects\/[^/]+$/.test(suffix)) {const project = publicProject(body.project);return {@@ -550,6 +561,9 @@ async function deploySourceAgent(alias: body.alias,channels: strings(body.channels),connections: strings(body.connections),+ httpConnections: Array.isArray(body.httpConnections)+ ? body.httpConnections+ : [],artifact,}),redirect: "manual",@@ -567,6 +581,13 @@ function isAllowedManagedAgentsRoute(method: string, suffix: string): boolean {return true;}if (method === "GET" && /^\/projects\/[^/]+$/.test(suffix)) return true;+ if (+ (method === "GET" || method === "PUT" || method === "DELETE") &&+ /^\/projects\/[^/]+\/secrets(?:\/[^/]+)?$/.test(suffix)+ ) {+ return true;+ }+ if (method === "GET" && suffix === "/logs") return true;if (method === "POST" && suffix === "/deployments") return true;if (method === "POST" && suffix === "/benchmarks/warm-pool") return true;if (method === "POST" && suffix === "/channel-connections/claim") {@@ -792,6 +813,7 @@ export async function proxyManagedAgents(try {const upstream = await fetch(target, init);if (!upstream.ok) return publicErrorResponse(upstream);+ if (upstream.status === 204) return new Response(null, { status: 204 });if (suffix.startsWith("/openrouter/")) {return upstream;}diff --git a/docs/agents/logs.mdx b/docs/agents/logs.mdxnew file mode 100644index 00000000..3be9b061--- /dev/null+++ b/docs/agents/logs.mdx@@ -0,0 +1,48 @@+---+title: "Logs"+description: "Inspect runtime output and managed-egress activity from the OpenComputer CLI"+---++OpenComputer collects runtime stdout and stderr together with managed-egress+events. Logs are indexed by project, environment, agent, and session so you can+inspect failures without opening the agent sandbox.++## Read the current agent's logs++From an initialized project:++```bash+npx opencomputer logs+```++The CLI uses the local project binding and current agent automatically. Follow+new entries while developing:++```bash+npx opencomputer logs --follow+```++## Filter logs++```bash+npx opencomputer logs --agent hello-world --environment development+npx opencomputer logs --session <session-id>+npx opencomputer logs --limit 200+```++Use JSON Lines for scripts and log processors:++```bash+npx opencomputer logs --follow --json+```++Each entry includes a stable cursor, timestamp, level, source, message, and+the applicable agent or session identifiers.++## Secret safety++Managed-egress logs describe the connection, method, destination path, status,+and timing. They do not contain injected secret values or secret-bearing+headers. Runtime request headers that could override managed credentials are+discarded by the gateway.+diff --git a/docs/agents/overview.mdx b/docs/agents/overview.mdxindex ab2c2953..b49dea57 100644--- a/docs/agents/overview.mdx+++ b/docs/agents/overview.mdx@@ -39,6 +39,12 @@ servers, and subagents needed for that render.<Card title="Sessions" icon="comments" href="/agents/sessions">Stream responses and inspect durable conversations.</Card>+ <Card title="Secrets" icon="key" href="/agents/secrets">+ Declare secret-backed connections without exposing credentials to agents.+ </Card>+ <Card title="Logs" icon="terminal" href="/agents/logs">+ Follow runtime and managed-egress activity from the CLI.+ </Card></CardGroup>## Start a project@@ -70,6 +76,8 @@ runs in OpenComputer's managed development cloud.- dashboard and CLI playground sessions- immutable deployments promoted through aliases such as `production`- user-scoped Gmail, Calendar, and GitHub connections+- project-level secrets with optional agent overrides and managed egress+- indexed runtime and egress logs available from the CLI- Slack channels connected to deployed agent aliasesThe dashboard is primarily an inspection and testing surface. Agent behaviordiff --git a/docs/agents/secrets.mdx b/docs/agents/secrets.mdxnew file mode 100644index 00000000..c00fa5c3--- /dev/null+++ b/docs/agents/secrets.mdx@@ -0,0 +1,88 @@+---+title: "Secrets and managed egress"+description: "Use project and agent secrets without exposing values to agent runtimes"+---++OpenComputer secrets are write-only values used by declared outbound+connections. Plaintext values are not included in source bundles, prompts,+deployment manifests, runtime environment variables, logs, or API responses.++## Declare a connection++```tsx+import {+ bearer,+ defineConnection,+ useConnection,+ useSecret,+} from "@opencomputer/agent";++const github = defineConnection({+ id: "github-api",+ origin: "https://api.github.com",+ methods: ["GET"],+ pathPrefix: "/repos/",+ headers: {+ Authorization: bearer(useSecret("GITHUB_TOKEN")),+ },+});++export default function Agent() {+ useConnection(github);+ return "Use GitHub when it helps answer the request.";+}+```++The origin must use HTTPS. OpenComputer rejects hard-coded sensitive headers+such as `Authorization`, `Cookie`, and `X-API-Key`; reference a managed secret+instead.++Tools can make requests through the same connection:++```tsx+const response = await github.fetch("/repos/opencomputer/example");+const repository = await response.json();+```++Only a relative path is accepted. OpenComputer checks the declared origin,+path prefix, method, agent, and environment before injecting the secret at the+outbound gateway.++## Set a project secret++```bash+npx opencomputer secrets set GITHUB_TOKEN+```++The CLI reads the value from a hidden prompt. When run from an initialized+project it can infer allowed origins from connections that reference the+secret. For CI, provide the value through standard input rather than a command+argument.++Project secrets are available to declared connections in every agent in the+project. Create an agent-specific override when one agent needs a different+credential:++```bash+npx opencomputer secrets set GITHUB_TOKEN --agent current+```++Secrets are separate for `development` and `production`:++```bash+npx opencomputer secrets set GITHUB_TOKEN --environment production+npx opencomputer secrets list --environment development+npx opencomputer secrets remove GITHUB_TOKEN --environment development+```++List output contains metadata such as the name, scope, environment, and+allowed origins. Secret values are never returned.++## Request path++The agent runtime sends a declared connection ID and relative request to its+local supervisor. The supervisor authenticates the runtime request to the+OpenComputer gateway. The gateway resolves the scoped secret, injects it for+that single upstream request, and streams the response back. The sandbox never+receives the provider credential.+diff --git a/docs/docs.json b/docs/docs.jsonindex d8ad0313..6a8322ac 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -35,6 +35,8 @@"agents/reactive-agents","agents/sessions","agents/connections",+ "agents/secrets",+ "agents/logs","agents/channels"]}@@ -314,56 +316,6 @@]}]- },- {- "tab": "Durable Agent Sessions",- "groups": [- {- "group": "Durable Agent Sessions",- "tag": "Preview",- "pages": [- "agent-sessions/overview",- "agent-sessions/quickstart",- "agent-sessions/agents",- "agent-sessions/revisions",- "agent-sessions/skills",- "agent-sessions/sessions",- "agent-sessions/agent-urls",- "agent-sessions/hooks",- "agent-sessions/credentials",- "agent-sessions/repos",- "agent-sessions/events",- "agent-sessions/authentication",- "agent-sessions/messaging",- "agent-sessions/webhooks",- "agent-sessions/slack",- "agent-sessions/runtimes",- "agent-sessions/runtime-tools",- "agent-sessions/watches",- "agent-sessions/schedules",- "agent-sessions/api-reference",- {- "group": "Frameworks",- "expanded": true,- "pages": [- "agent-sessions/flue"- ]- },- {- "group": "Labs",- "tag": "Labs",- "expanded": true,- "pages": [- "agent-sessions/custom-runtimes",- "agent-sessions/triggers",- "agent-sessions/channels",- "agent-sessions/workspaces",- "agent-sessions/artifacts"- ]- }- ]- }- ]}]},diff --git a/docs/llms.txt b/docs/llms.txtindex 13001c3d..65b06356 100644--- a/docs/llms.txt+++ b/docs/llms.txt@@ -10,4 +10,6 @@- [Reactive agents](https://docs.opencomputer.dev/agents/reactive-agents.md): Render instructions, models, tools, subagents, connections, and MCP servers from code.- [Sessions and playground](https://docs.opencomputer.dev/agents/sessions.md): Create and inspect durable conversations.- [Connections and MCP](https://docs.opencomputer.dev/agents/connections.md): Attach user-scoped services and managed MCP servers from code.+- [Secrets and managed egress](https://docs.opencomputer.dev/agents/secrets.md): Store scoped secrets and inject them only into declared outbound requests.+- [Logs](https://docs.opencomputer.dev/agents/logs.md): Inspect and follow runtime and managed-egress logs.- [Channels](https://docs.opencomputer.dev/agents/channels.md): Connect deployed agents to Slack.diff --git a/web/src/components/app-shell-nav.ts b/web/src/components/app-shell-nav.tsindex 9e1065d4..985e772e 100644--- a/web/src/components/app-shell-nav.ts+++ b/web/src/components/app-shell-nav.ts@@ -50,12 +50,6 @@ export function managedAgentsNav(options: {},{items: [- {- to: projectPath,- label: 'Agent playground',- icon: Bot,- end: true,- },{to: `${projectPath}/deployments`,label: 'Deployments',@@ -76,6 +70,17 @@ export function managedAgentsNav(options: {label: 'Schedules',icon: CalendarClock,},+ {+ to: `${projectPath}/secrets`,+ label: 'Secrets',+ icon: KeySquare,+ },+ {+ to: projectPath,+ label: 'Debug playground',+ icon: Bot,+ end: true,+ },],},)diff --git a/web/src/components/app-shell.test.ts b/web/src/components/app-shell.test.tsindex 281a260d..274b06d1 100644--- a/web/src/components/app-shell.test.ts+++ b/web/src/components/app-shell.test.ts@@ -18,13 +18,16 @@ describe('managed agents navigation', () => {'Back to all projects',])expect(nav[1]?.items.map((item) => item.label)).toEqual([- 'Agent playground','Deployments','Sessions','Channels','Schedules',+ 'Secrets',+ 'Debug playground',])- expect(nav[1]?.items[0]?.to).toBe('/projects/project%20one')+ expect(nav[1]?.items[nav[1].items.length - 1]?.to).toBe(+ '/projects/project%20one',+ )})it('reveals each advanced area independently', () => {diff --git a/web/src/managed-agents/DebugInspector.tsx b/web/src/managed-agents/DebugInspector.tsxnew file mode 100644index 00000000..cc6ae7a7--- /dev/null+++ b/web/src/managed-agents/DebugInspector.tsx@@ -0,0 +1,343 @@+import { useState } from 'react'+import {+ Activity,+ Bot,+ Braces,+ Cable,+ ChevronRight,+ FileCode2,+ Wrench,+} from 'lucide-react'+import { cn } from '@/lib/utils'+import {+ managedAgentRenderDebug,+ type ManagedAgentEvent,+ type ManagedAgentRenderDebug,+} from './api'++function eventSummary(event: ManagedAgentEvent) {+ if (event.type === 'runtime.log') {+ return typeof event.data.message === 'string'+ ? event.data.message+ : 'Runtime log'+ }+ if (event.type.startsWith('egress.')) {+ const method =+ typeof event.data.method === 'string' ? event.data.method : 'HTTP'+ const path = typeof event.data.path === 'string' ? event.data.path : ''+ const status =+ typeof event.data.status === 'number' ? ` ${event.data.status}` : ''+ return `${method} ${path}${status}`.trim()+ }+ if (event.type.startsWith('tool.')) {+ return typeof event.data.tool === 'string'+ ? event.data.tool+ : 'Tool activity'+ }+ if (event.type === 'turn.failed' || event.type === 'session.failed') {+ return typeof event.data.message === 'string'+ ? event.data.message+ : 'The runtime reported a failure'+ }+ if (event.type.startsWith('runtime.')) {+ return event.type.replace('runtime.', 'Runtime ')+ }+ return event.type+}++function RuntimeActivity({ events }: { events: ManagedAgentEvent[] }) {+ return (+ <details open className="group bg-background rounded-md border">+ <summary className="flex cursor-pointer list-none items-center gap-2 px-3 py-2 text-xs font-medium [&::-webkit-details-marker]:hidden">+ <Cable className="size-3.5" /> Runtime logs+ <span className="text-muted-foreground font-mono text-[9px]">+ {events.length}+ </span>+ <ChevronRight className="ml-auto size-3.5 transition-transform group-open:rotate-90" />+ </summary>+ <div className="max-h-72 overflow-y-auto border-t p-3">+ {events.length ? (+ <div className="space-y-2.5">+ {events.map((event) => (+ <div key={event.id ?? `${event.seq}:${event.type}`}>+ <div className="flex items-center gap-2">+ <span+ className={cn(+ 'font-mono text-[9px]',+ event.type === 'turn.failed' ||+ event.type === 'session.failed' ||+ event.data.level === 'error'+ ? 'text-destructive'+ : 'text-muted-foreground',+ )}+ >+ {event.type}+ </span>+ <span className="text-muted-foreground ml-auto text-[9px]">+ {event.timestamp+ ? new Date(event.timestamp).toLocaleTimeString()+ : ''}+ </span>+ </div>+ <p className="mt-0.5 text-xs leading-5 break-words whitespace-pre-wrap">+ {eventSummary(event)}+ </p>+ </div>+ ))}+ </div>+ ) : (+ <p className="text-muted-foreground text-xs">+ Logs will appear as soon as the runtime starts.+ </p>+ )}+ </div>+ </details>+ )+}++function ResourceList({ values: items }: { values: string[] }) {+ return items.length ? (+ <div className="flex flex-wrap gap-1.5">+ {items.map((item) => (+ <span+ key={item}+ className="bg-muted rounded px-1.5 py-1 font-mono text-[10px]"+ >+ {item}+ </span>+ ))}+ </div>+ ) : (+ <p className="text-muted-foreground text-xs">None active</p>+ )+}++function RenderChanges({+ current,+ previous,+}: {+ current: ManagedAgentRenderDebug+ previous?: ManagedAgentRenderDebug+}) {+ if (!previous) {+ return <p className="text-muted-foreground text-xs">Initial render</p>+ }+ const addedTools = current.enabledTools.filter(+ (tool) => !previous.enabledTools.includes(tool),+ )+ const removedTools = previous.enabledTools.filter(+ (tool) => !current.enabledTools.includes(tool),+ )+ const changes = [+ ...(current.instructionsHash !== previous.instructionsHash+ ? ['Prompt changed']+ : []),+ ...addedTools.map((tool) => `Tool added: ${tool}`),+ ...removedTools.map((tool) => `Tool removed: ${tool}`),+ ...(JSON.stringify(current.model) !== JSON.stringify(previous.model)+ ? ['Model changed']+ : []),+ ]+ return changes.length ? (+ <ul className="space-y-1 text-xs">+ {changes.map((change) => (+ <li key={change}>{change}</li>+ ))}+ </ul>+ ) : (+ <p className="text-muted-foreground text-xs">+ No prompt, model, or tool changes+ </p>+ )+}++export function DebugInspector({+ events,+ deploymentId,+}: {+ events: ManagedAgentEvent[]+ deploymentId?: string+}) {+ const renders = events.flatMap((event) => {+ const render = managedAgentRenderDebug(event)+ return render ? [{ event, render }] : []+ })+ const [selectedId, setSelectedId] = useState<string>()+ const selected =+ renders.find(({ render }) => render.renderId === selectedId) ??+ (renders.length ? renders[renders.length - 1] : null)+ const actualIndex = selected+ ? renders.findIndex(+ ({ render }) => render.renderId === selected.render.renderId,+ )+ : -1+ const previous =+ actualIndex > 0 ? renders[actualIndex - 1]?.render : undefined+ const activity = events+ .filter(+ (event) =>+ event.type === 'runtime.log' ||+ event.type === 'runtime.connected' ||+ event.type === 'runtime.disconnected' ||+ event.type === 'runtime.suspended' ||+ event.type === 'runtime.resumed' ||+ event.type === 'turn.started' ||+ event.type === 'turn.completed' ||+ event.type === 'turn.failed' ||+ event.type === 'session.failed' ||+ event.type.startsWith('tool.') ||+ event.type.startsWith('egress.'),+ )+ .slice(-50)++ return (+ <aside className="bg-muted/10 min-h-0 overflow-y-auto border-t xl:border-t-0 xl:border-l">+ <div className="border-b px-4 py-3">+ <p className="text-xs font-semibold tracking-wide uppercase">+ Debug inspector+ </p>+ <p className="text-muted-foreground mt-1 truncate font-mono text-[10px]">+ {deploymentId ?? 'Deployment is selected when the session starts'}+ </p>+ </div>++ <div className="space-y-4 p-4">+ {!selected ? (+ <div className="text-muted-foreground flex min-h-40 flex-col items-center justify-center rounded-md border border-dashed px-6 text-center text-sm">+ <Activity className="mb-3 size-6" />+ No reactive render was captured. Check the runtime logs below.+ </div>+ ) : (+ <>+ <div className="space-y-2">+ <p className="text-muted-foreground text-[10px] font-semibold tracking-wide uppercase">+ Renders+ </p>+ <div className="flex flex-wrap gap-1.5">+ {renders.map(({ render }, index) => (+ <button+ key={render.renderId}+ type="button"+ onClick={() => setSelectedId(render.renderId)}+ className={cn(+ 'rounded border px-2 py-1 font-mono text-[10px]',+ render.renderId === selected.render.renderId+ ? 'border-foreground bg-foreground text-background'+ : 'bg-background hover:bg-muted',+ )}+ >+ Render {index + 1}+ </button>+ ))}+ </div>+ </div>++ <div className="bg-background grid grid-cols-2 gap-3 rounded-md border p-3 text-xs">+ <div>+ <p className="text-muted-foreground">Model</p>+ <p className="mt-1 font-mono text-[10px] break-all">+ {selected.render.model+ ? `${selected.render.model.provider}/${selected.render.model.model}`+ : 'Default'}+ </p>+ </div>+ <div>+ <p className="text-muted-foreground">Provider turn</p>+ <p className="mt-1 font-mono">{selected.render.providerTurn}</p>+ </div>+ <div>+ <p className="text-muted-foreground">State version</p>+ <p className="mt-1 font-mono">{selected.render.stateVersion}</p>+ </div>+ <div>+ <p className="text-muted-foreground">Rendered</p>+ <p className="mt-1 text-[10px]">+ {new Date(selected.render.renderedAt).toLocaleTimeString()}+ </p>+ </div>+ </div>++ <details open className="group bg-background rounded-md border">+ <summary className="flex cursor-pointer list-none items-center gap-2 px-3 py-2 text-xs font-medium [&::-webkit-details-marker]:hidden">+ <Bot className="size-3.5" /> Agent prompt+ <ChevronRight className="ml-auto size-3.5 transition-transform group-open:rotate-90" />+ </summary>+ <pre className="max-h-64 overflow-auto border-t p-3 text-xs leading-5 whitespace-pre-wrap">+ {selected.render.instructions || 'No agent instructions'}+ </pre>+ </details>++ <details className="group bg-background rounded-md border">+ <summary className="flex cursor-pointer list-none items-center gap-2 px-3 py-2 text-xs font-medium [&::-webkit-details-marker]:hidden">+ <Braces className="size-3.5" /> Current input+ <ChevronRight className="ml-auto size-3.5 transition-transform group-open:rotate-90" />+ </summary>+ <div className="border-t p-3 text-xs">+ <p className="text-muted-foreground mb-2 capitalize">+ {selected.render.input.source}+ </p>+ <p className="whitespace-pre-wrap">+ {selected.render.input.text ?? 'No text input'}+ </p>+ </div>+ </details>++ <div className="bg-background space-y-3 rounded-md border p-3">+ <div>+ <p className="mb-2 flex items-center gap-2 text-xs font-medium">+ <Wrench className="size-3.5" /> Available tools+ </p>+ {selected.render.tools.length ? (+ <div className="space-y-2">+ {selected.render.tools.map((tool) => (+ <div key={tool.name}>+ <p className="font-mono text-[10px]">{tool.name}</p>+ <p className="text-muted-foreground mt-0.5 text-xs leading-5">+ {tool.description || 'No description'}+ </p>+ </div>+ ))}+ </div>+ ) : (+ <p className="text-muted-foreground text-xs">None active</p>+ )}+ </div>+ <div>+ <p className="text-muted-foreground mb-1.5 text-[10px] uppercase">+ Connections+ </p>+ <ResourceList values={selected.render.requiredConnections} />+ </div>+ <div>+ <p className="text-muted-foreground mb-1.5 text-[10px] uppercase">+ MCP servers+ </p>+ <ResourceList values={selected.render.enabledMcpServers} />+ </div>+ <div>+ <p className="text-muted-foreground mb-1.5 text-[10px] uppercase">+ Subagents+ </p>+ <ResourceList values={selected.render.enabledSubagents} />+ </div>+ <div>+ <p className="text-muted-foreground mb-1.5 text-[10px] uppercase">+ Skills+ </p>+ <ResourceList values={[]} />+ </div>+ </div>++ <div className="bg-background rounded-md border p-3">+ <p className="mb-2 flex items-center gap-2 text-xs font-medium">+ <FileCode2 className="size-3.5" /> Changes from previous render+ </p>+ <RenderChanges current={selected.render} previous={previous} />+ </div>+ </>+ )}+ <RuntimeActivity events={activity} />+ </div>+ </aside>+ )+}diff --git a/web/src/managed-agents/Detail.tsx b/web/src/managed-agents/Detail.tsxindex c08d4b5c..f2febe49 100644--- a/web/src/managed-agents/Detail.tsx+++ b/web/src/managed-agents/Detail.tsx@@ -54,9 +54,11 @@ import {type ManagedProjectOverview,} from './api'import { ManagedAgentChatTransport } from './chat-transport'+import { DebugInspector } from './DebugInspector'import { isNearScrollEnd } from './scroll-follow'import { createStartCommand, starterCommands } from './onboarding'import { projectContextSearch } from './project-context'+import { ManagedProjectSecrets } from './Secrets'import { ManagedSlackWizard } from './SlackWizard'type DetailTab =@@ -65,6 +67,7 @@ type DetailTab =| 'sessions'| 'channels'| 'schedules'+ | 'secrets'function formatDate(value: string) {return new Date(value).toLocaleString()@@ -293,6 +296,12 @@ function PlaygroundChat({}),[agentId, session?.id],)+ const debugEvents = useQuery({+ queryKey: ['managed-agent-session-events', liveSessionId],+ queryFn: () => getManagedAgentSessionEvents(liveSessionId!),+ enabled: Boolean(liveSessionId),+ refetchInterval: 1_000,+ })const { messages, sendMessage, status, stop, error } = useChat({id: session?.id ?? `new-${agentId}`,messages: initialMessages,@@ -303,6 +312,11 @@ function PlaygroundChat({void queryClient.invalidateQueries({queryKey: ['managed-agent-sessions', agentId],})+ if (liveSessionId) {+ void queryClient.invalidateQueries({+ queryKey: ['managed-agent-session-events', liveSessionId],+ })+ }},})const running = status === 'submitted' || status === 'streaming'@@ -329,116 +343,125 @@ function PlaygroundChat({}return (- <div className="flex h-full min-h-0 min-w-0 flex-col overflow-hidden">- <div className="flex items-center justify-between border-b px-5 py-3">- <div>- <p className="text-sm font-medium">- {session?.turns[0]?.input || 'New playground session'}- </p>- <p className="text-muted-foreground mt-0.5 font-mono text-[10px]">- {liveSessionId ?? 'A session is created when you send a message'}- </p>- </div>- {running ? (- <div className="text-muted-foreground flex items-center gap-2 text-xs">- <span className="bg-foreground size-1.5 animate-pulse rounded-full" />- Agent is working- </div>- ) : null}- </div>-- <div- ref={timelineRef}- onScroll={(event) => {- followOutputRef.current = isNearScrollEnd(event.currentTarget)- }}- className="min-h-0 flex-1 space-y-6 overflow-y-auto overscroll-contain px-5 py-6"- >- {messages.length === 0 ? (- <div className="text-muted-foreground flex min-h-80 flex-col items-center justify-center text-center">- <Bot className="mb-3 size-7" aria-hidden />- <p className="text-foreground text-sm font-medium">- Start a conversation+ <div className="grid h-full min-h-0 min-w-0 xl:grid-cols-[minmax(0,1fr)_24rem]">+ <div className="flex min-h-0 min-w-0 flex-col overflow-hidden">+ <div className="flex items-center justify-between border-b px-5 py-3">+ <div>+ <p className="text-sm font-medium">+ {session?.turns[0]?.input || 'New playground session'}</p>- <p className="mt-1 max-w-sm text-sm">- This runs the active deployment and keeps context across every- message in this playground session.+ <p className="text-muted-foreground mt-0.5 font-mono text-[10px]">+ {liveSessionId ?? 'A session is created when you send a message'}</p></div>- ) : (- messages.map((message, index) => {- const isLast = index === messages.length - 1- const messageRunning =- running && isLast && message.role === 'assistant'- const text = message.parts- .filter((part) => part.type === 'text')- .map((part) => part.text)- .join('')- return (- <div- key={message.id}- className={cn(- 'max-w-3xl',- message.role === 'user' && 'ml-auto max-w-2xl',- )}- >- <p className="text-muted-foreground mb-1.5 text-[10px] font-semibold tracking-wider uppercase">- {message.role === 'user' ? 'You' : 'Agent'}- </p>- {message.role === 'assistant' ? (- <MessageActivity message={message} running={messageRunning} />- ) : null}- {text ? (- message.role === 'user' ? (- <div className="bg-muted rounded-xl rounded-br-sm px-3.5 py-2.5 text-sm leading-6 whitespace-pre-wrap">- {text}- </div>- ) : (- <AgentMarkdown>{text}</AgentMarkdown>- )- ) : messageRunning ? (- <div className="text-muted-foreground flex items-center gap-2 text-sm">- <Loader2 className="size-4 animate-spin" />- Starting the agent…- </div>- ) : null}- </div>- )- })- )}- </div>+ {running ? (+ <div className="text-muted-foreground flex items-center gap-2 text-xs">+ <span className="bg-foreground size-1.5 animate-pulse rounded-full" />+ Agent is working+ </div>+ ) : null}+ </div>- <div className="bg-panel shrink-0 border-t p-4">- {error ? (- <p className="text-destructive mb-2 text-xs">{error.message}</p>- ) : null}<div- ref={composerRef}- className="bg-background focus-within:border-ring/60 rounded-lg border p-2 transition-colors"+ ref={timelineRef}+ onScroll={(event) => {+ followOutputRef.current = isNearScrollEnd(event.currentTarget)+ }}+ className="min-h-0 flex-1 space-y-6 overflow-y-auto overscroll-contain px-5 py-6">- <ChatTextarea- value={prompt}- onChange={(event) => setPrompt(event.target.value)}- onSend={send}- placeholder="Message this agent…"- className="min-h-12 border-0 px-2 shadow-none focus-visible:border-transparent"- />- <div className="flex items-center justify-between gap-3 px-1 pt-1">- <p className="text-muted-foreground text-[10px]">- Enter to send · Shift + Enter for a new line- </p>- {running ? (- <Button variant="outline" size="sm" onClick={() => void stop()}>- <Square className="fill-current" /> Stop- </Button>- ) : (- <Button size="sm" disabled={!prompt.trim()} onClick={send}>- <Send /> Send- </Button>- )}+ {messages.length === 0 ? (+ <div className="text-muted-foreground flex min-h-80 flex-col items-center justify-center text-center">+ <Bot className="mb-3 size-7" aria-hidden />+ <p className="text-foreground text-sm font-medium">+ Start a conversation+ </p>+ <p className="mt-1 max-w-sm text-sm">+ This runs the active deployment and keeps context across every+ message in this playground session.+ </p>+ </div>+ ) : (+ messages.map((message, index) => {+ const isLast = index === messages.length - 1+ const messageRunning =+ running && isLast && message.role === 'assistant'+ const text = message.parts+ .filter((part) => part.type === 'text')+ .map((part) => part.text)+ .join('')+ return (+ <div+ key={message.id}+ className={cn(+ 'max-w-3xl',+ message.role === 'user' && 'ml-auto max-w-2xl',+ )}+ >+ <p className="text-muted-foreground mb-1.5 text-[10px] font-semibold tracking-wider uppercase">+ {message.role === 'user' ? 'You' : 'Agent'}+ </p>+ {message.role === 'assistant' ? (+ <MessageActivity+ message={message}+ running={messageRunning}+ />+ ) : null}+ {text ? (+ message.role === 'user' ? (+ <div className="bg-muted rounded-xl rounded-br-sm px-3.5 py-2.5 text-sm leading-6 whitespace-pre-wrap">+ {text}+ </div>+ ) : (+ <AgentMarkdown>{text}</AgentMarkdown>+ )+ ) : messageRunning ? (+ <div className="text-muted-foreground flex items-center gap-2 text-sm">+ <Loader2 className="size-4 animate-spin" />+ Starting the agent…+ </div>+ ) : null}+ </div>+ )+ })+ )}+ </div>++ <div className="bg-panel shrink-0 border-t p-4">+ {error ? (+ <p className="text-destructive mb-2 text-xs">{error.message}</p>+ ) : null}+ <div+ ref={composerRef}+ className="bg-background focus-within:border-ring/60 rounded-lg border p-2 transition-colors"+ >+ <ChatTextarea+ value={prompt}+ onChange={(event) => setPrompt(event.target.value)}+ onSend={send}+ placeholder="Message this agent…"+ className="min-h-12 border-0 px-2 shadow-none focus-visible:border-transparent"+ />+ <div className="flex items-center justify-between gap-3 px-1 pt-1">+ <p className="text-muted-foreground text-[10px]">+ Enter to send · Shift + Enter for a new line+ </p>+ {running ? (+ <Button variant="outline" size="sm" onClick={() => void stop()}>+ <Square className="fill-current" /> Stop+ </Button>+ ) : (+ <Button size="sm" disabled={!prompt.trim()} onClick={send}>+ <Send /> Send+ </Button>+ )}+ </div></div></div></div>+ <DebugInspector+ events={debugEvents.data ?? events}+ deploymentId={session?.deploymentId}+ /></div>)}@@ -464,6 +487,7 @@ export default function ManagedAgentDetail({'sessions','channels','schedules',+ 'secrets',])const activeTab = project? routeTab && projectTabs.has(routeTab)@@ -612,11 +636,12 @@ export default function ManagedAgentDetail({}const tabs: Array<{ id: DetailTab; label: string }> = [- { id: 'playground', label: project ? 'Agent playground' : 'Playground' },+ { id: 'playground', label: project ? 'Debug playground' : 'Playground' },{ id: 'deployments', label: 'Deployments' },{ id: 'sessions', label: 'Sessions' },{ id: 'channels', label: 'Channels' },...(project ? ([{ id: 'schedules', label: 'Schedules' }] as const) : []),+ ...(project ? ([{ id: 'secrets', label: 'Secrets' }] as const) : []),]return (@@ -718,7 +743,7 @@ export default function ManagedAgentDetail({<Panel><EmptyStateicon={Bot}- title="Deploy the hello-world agent to use Agent playground"+ title="Deploy the hello-world agent to use Debug playground"description={`Create the starter locally, then sync it directly to ${environment}.`}action={<div className="flex max-w-xl flex-col items-center gap-3">@@ -951,6 +976,14 @@ export default function ManagedAgentDetail({values={project.schedules}/>) : null}++ {activeTab === 'secrets' && project ? (+ <ManagedProjectSecrets+ projectId={project.project.id}+ agents={project.project.agents}+ environment={environment}+ />+ ) : null}</div>)}diff --git a/web/src/managed-agents/Secrets.tsx b/web/src/managed-agents/Secrets.tsxnew file mode 100644index 00000000..019ad208--- /dev/null+++ b/web/src/managed-agents/Secrets.tsx@@ -0,0 +1,271 @@+import { type FormEvent, useState } from 'react'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { KeyRound, Loader2, Trash2 } from 'lucide-react'+import {+ Panel,+ PanelContent,+ PanelDescription,+ PanelHeader,+ PanelTitle,+} from '@/components/panel'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'+import { notifyError, notifySuccess } from '@/lib/errors'+import {+ deleteManagedProjectSecret,+ getManagedProjectSecrets,+ putManagedProjectSecret,+} from './api'++type Environment = 'development' | 'production'++function parseOrigins(value: string) {+ return [...new Set(value.split(/[\s,]+/).map((part) => part.trim()))].filter(+ Boolean,+ )+}++export function ManagedProjectSecrets({+ projectId,+ agents,+ environment,+}: {+ projectId: string+ agents: Array<{ id: string; name: string }>+ environment: Environment+}) {+ const queryClient = useQueryClient()+ const [name, setName] = useState('')+ const [value, setValue] = useState('')+ const [origins, setOrigins] = useState('')+ const [agentId, setAgentId] = useState('')+ const queryKey = ['managed-project-secrets', projectId, environment]+ const secrets = useQuery({+ queryKey,+ queryFn: () => getManagedProjectSecrets(projectId, environment),+ })+ const save = useMutation({+ mutationFn: putManagedProjectSecret,+ onSuccess: async () => {+ setName('')+ setValue('')+ setOrigins('')+ await queryClient.invalidateQueries({ queryKey })+ notifySuccess('Secret saved.', 'Its value remains write-only.')+ },+ onError: (error) => notifyError("Couldn't save the secret.", error),+ })+ const remove = useMutation({+ mutationFn: deleteManagedProjectSecret,+ onSuccess: async () => {+ await queryClient.invalidateQueries({ queryKey })+ notifySuccess('Secret removed.')+ },+ onError: (error) => notifyError("Couldn't remove the secret.", error),+ })+ const agentNames = new Map(agents.map((agent) => [agent.id, agent.name]))++ function submit(event: FormEvent) {+ event.preventDefault()+ const normalizedName = name.trim().toUpperCase()+ const allowedOrigins = parseOrigins(origins)+ if (!/^[A-Z][A-Z0-9_]{0,127}$/.test(normalizedName)) {+ notifyError(+ 'Use an uppercase secret name containing only letters, numbers, and underscores.',+ )+ return+ }+ if (!value) {+ notifyError('Enter a secret value.')+ return+ }+ save.mutate({+ projectId,+ environment,+ ...(agentId ? { agentId } : {}),+ name: normalizedName,+ value,+ allowedOrigins: allowedOrigins.length ? allowedOrigins : ['*'],+ })+ }++ return (+ <div className="space-y-4">+ <Panel>+ <PanelHeader>+ <div>+ <PanelTitle>Secrets</PanelTitle>+ <PanelDescription className="mt-1">+ Write-only values injected by the managed egress gateway for the+ selected environment. Values never enter agent runtimes or logs.+ </PanelDescription>+ </div>+ <span className="bg-muted rounded-md px-2 py-1 text-xs capitalize">+ {environment}+ </span>+ </PanelHeader>+ <PanelContent>+ <form onSubmit={submit} className="grid gap-4 lg:grid-cols-2">+ <div className="space-y-2">+ <Label htmlFor="secret-name">Name</Label>+ <Input+ id="secret-name"+ value={name}+ onChange={(event) => setName(event.target.value.toUpperCase())}+ placeholder="GITHUB_TOKEN"+ autoComplete="off"+ />+ </div>+ <div className="space-y-2">+ <Label htmlFor="secret-scope">Scope</Label>+ <select+ id="secret-scope"+ value={agentId}+ onChange={(event) => setAgentId(event.target.value)}+ className="border-input bg-background h-8 w-full rounded-md border px-2.5 text-sm outline-none"+ >+ <option value="">Entire project</option>+ {agents.map((agent) => (+ <option key={agent.id} value={agent.id}>+ Agent: {agent.name}+ </option>+ ))}+ </select>+ </div>+ <div className="space-y-2">+ <Label htmlFor="secret-value">Value</Label>+ <Input+ id="secret-value"+ type="password"+ value={value}+ onChange={(event) => setValue(event.target.value)}+ placeholder="Enter a new value"+ autoComplete="new-password"+ />+ <p className="text-muted-foreground text-xs">+ Existing values cannot be viewed. Saving the same name and scope+ replaces its value.+ </p>+ </div>+ <div className="space-y-2">+ <Label htmlFor="secret-origins">+ Allowed origins <span className="text-muted-foreground">(optional)</span>+ </Label>+ <Input+ id="secret-origins"+ value={origins}+ onChange={(event) => setOrigins(event.target.value)}+ placeholder="https://api.example.com"+ autoComplete="off"+ />+ <p className="text-muted-foreground text-xs">+ Separate multiple HTTPS origins with commas. Paths are not+ allowed. Leave blank to allow every public HTTPS host.+ </p>+ {!origins.trim() ? (+ <p className="text-amber-700 text-xs dark:text-amber-400">+ All hosts — not recommended. Prefer limiting this secret to+ the external APIs that need it.+ </p>+ ) : null}+ </div>+ <div className="lg:col-span-2">+ <Button type="submit" disabled={save.isPending}>+ {save.isPending ? (+ <Loader2 className="animate-spin" />+ ) : (+ <KeyRound />+ )}+ Save secret+ </Button>+ </div>+ </form>+ </PanelContent>+ </Panel>++ <Panel className="overflow-hidden">+ <PanelHeader>+ <div>+ <PanelTitle>Configured secrets</PanelTitle>+ <PanelDescription className="mt-1">+ Only names, scopes, and allowed destinations are visible.+ </PanelDescription>+ </div>+ </PanelHeader>+ {secrets.isLoading ? (+ <PanelContent className="text-muted-foreground flex items-center gap-2 text-sm">+ <Loader2 className="size-4 animate-spin" /> Loading secrets…+ </PanelContent>+ ) : secrets.isError ? (+ <PanelContent className="space-y-3">+ <p className="text-muted-foreground text-sm">+ Secrets are temporarily unavailable.+ </p>+ <Button variant="outline" onClick={() => void secrets.refetch()}>+ Try again+ </Button>+ </PanelContent>+ ) : secrets.data?.length ? (+ <div className="divide-y">+ {secrets.data.map((secret) => (+ <div+ key={`${secret.environment}:${secret.agentId ?? 'project'}:${secret.name}`}+ className="grid gap-3 px-5 py-4 md:grid-cols-[minmax(10rem,0.8fr)_minmax(10rem,0.8fr)_minmax(16rem,1.5fr)_auto] md:items-center"+ >+ <div>+ <p className="font-mono text-sm font-medium">{secret.name}</p>+ <p className="text-muted-foreground mt-1 text-xs">+ Updated {new Date(secret.updatedAt).toLocaleString()}+ </p>+ </div>+ <div>+ <p className="text-muted-foreground text-xs">Scope</p>+ <p className="mt-1 text-sm">+ {secret.agentId+ ? (agentNames.get(secret.agentId) ?? secret.agentId)+ : 'Entire project'}+ </p>+ </div>+ <div className="min-w-0">+ <p className="text-muted-foreground text-xs">+ Allowed origins+ </p>+ {secret.allowedOrigins.includes('*') ? (+ <p className="mt-1 text-xs text-amber-700 dark:text-amber-400">+ All hosts — not recommended+ </p>+ ) : (+ <p className="mt-1 truncate font-mono text-xs">+ {secret.allowedOrigins.join(', ')}+ </p>+ )}+ </div>+ <Button+ type="button"+ variant="destructive"+ size="sm"+ disabled={remove.isPending}+ onClick={() =>+ remove.mutate({+ projectId,+ environment: secret.environment,+ ...(secret.agentId ? { agentId: secret.agentId } : {}),+ name: secret.name,+ })+ }+ >+ <Trash2 /> Remove+ </Button>+ </div>+ ))}+ </div>+ ) : (+ <PanelContent className="text-muted-foreground text-sm">+ No secrets configured for {environment}.+ </PanelContent>+ )}+ </Panel>+ </div>+ )+}diff --git a/web/src/managed-agents/api.test.ts b/web/src/managed-agents/api.test.tsindex d1a2014a..165f7ab4 100644--- a/web/src/managed-agents/api.test.ts+++ b/web/src/managed-agents/api.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest'-import { displayManagedAgentName } from './api'+import { displayManagedAgentName, managedAgentRenderDebug } from './api'describe('displayManagedAgentName', () => {it('hides UUID-shaped legacy names without hiding readable stable names', () => {@@ -17,3 +17,41 @@ describe('displayManagedAgentName', () => {).toBe('Gentle Falcon')})})++describe('managedAgentRenderDebug', () => {+ it('parses reactive render snapshots and ignores unrelated events', () => {+ const event = {+ id: 'event-1',+ seq: 1,+ timestamp: '2026-08-10T00:00:00.000Z',+ sessionId: 'session-1',+ turnId: 'turn-1',+ type: 'agent.rendered',+ data: {+ renderId: 'render-1',+ responseId: 'response-1',+ providerTurn: 2,+ renderedAt: '2026-08-10T00:00:00.000Z',+ stateVersion: 3,+ instructions: 'Help the user.',+ instructionsHash: 'sha256:prompt',+ input: { source: 'user', text: 'Hello' },+ tools: [{ name: 'search', description: 'Search documentation' }],+ enabledTools: ['search'],+ requiredConnections: [],+ enabledMcpServers: [],+ enabledSubagents: [],+ model: { provider: 'openrouter', model: 'openai/gpt-5.2' },+ },+ }++ expect(managedAgentRenderDebug(event)).toMatchObject({+ renderId: 'render-1',+ instructions: 'Help the user.',+ enabledTools: ['search'],+ })+ expect(+ managedAgentRenderDebug({ ...event, type: 'runtime.log' }),+ ).toBeUndefined()+ })+})diff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.tsindex 924b2684..c94630fa 100644--- a/web/src/managed-agents/api.ts+++ b/web/src/managed-agents/api.ts@@ -47,6 +47,18 @@ const projectSchema = z.object({const projectsResponseSchema = z.object({ projects: z.array(projectSchema) })+const secretSchema = z.object({+ name: z.string(),+ projectId: z.string(),+ environment: z.enum(['development', 'production']),+ agentId: z.string().optional(),+ allowedOrigins: z.array(z.string()),+ createdAt: z.string(),+ updatedAt: z.string(),+})++const secretsResponseSchema = z.object({ secrets: z.array(secretSchema) })+const connectionSchema = z.object({id: z.string(),kind: z.enum(['tool', 'channel']),@@ -118,6 +130,23 @@ const eventSchema = z.object({data: z.record(z.string(), z.unknown()),})+const renderDebugSchema = z.object({+ renderId: z.string(),+ responseId: z.string(),+ providerTurn: z.number(),+ stateVersion: z.number(),+ instructionsHash: z.string(),+ instructions: z.string(),+ enabledTools: z.array(z.string()),+ enabledSubagents: z.array(z.string()),+ requiredConnections: z.array(z.string()),+ enabledMcpServers: z.array(z.string()),+ input: z.object({ source: z.string(), text: z.string().optional() }),+ tools: z.array(z.object({ name: z.string(), description: z.string() })),+ model: z.object({ provider: z.string(), model: z.string() }).optional(),+ renderedAt: z.string(),+})+const eventsResponseSchema = z.object({events: z.array(eventSchema),})@@ -167,10 +196,12 @@ export type ManagedProject = z.infer<typeof projectSchema>export type ManagedProjectOverview = z.infer<typeof projectOverviewSchema>export type ManagedAgentDeployment = z.infer<typeof deploymentSchema>export type ManagedAgentEvent = z.infer<typeof eventSchema>+export type ManagedAgentRenderDebug = z.infer<typeof renderDebugSchema>export type ManagedAgentSession = z.infer<typeof sessionSchema>export type ManagedAgentConnection = z.infer<typeof connectionSchema>export type ManagedAgentChannel = z.infer<typeof channelSchema>export type ManagedSlackManifest = z.infer<typeof slackManifestResponseSchema>+export type ManagedProjectSecret = z.infer<typeof secretSchema>const UUID_NAME =/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i@@ -214,6 +245,56 @@ export async function getManagedProject(projectId: string) {)}+export async function getManagedProjectSecrets(+ projectId: string,+ environment: 'development' | 'production',+) {+ return (+ await apiFetch(+ `/managed-agents/projects/${encodeURIComponent(projectId)}/secrets?environment=${encodeURIComponent(environment)}`,+ undefined,+ secretsResponseSchema,+ )+ ).secrets+}++export async function putManagedProjectSecret(input: {+ projectId: string+ environment: 'development' | 'production'+ agentId?: string+ name: string+ value: string+ allowedOrigins: string[]+}) {+ return apiFetch(+ `/managed-agents/projects/${encodeURIComponent(input.projectId)}/secrets/${encodeURIComponent(input.name)}`,+ {+ method: 'PUT',+ body: JSON.stringify({+ environment: input.environment,+ ...(input.agentId ? { agentId: input.agentId } : {}),+ value: input.value,+ allowedOrigins: input.allowedOrigins,+ }),+ },+ secretSchema,+ )+}++export async function deleteManagedProjectSecret(input: {+ projectId: string+ environment: 'development' | 'production'+ agentId?: string+ name: string+}) {+ const query = new URLSearchParams({ environment: input.environment })+ if (input.agentId) query.set('agentId', input.agentId)+ return apiFetch<void>(+ `/managed-agents/projects/${encodeURIComponent(input.projectId)}/secrets/${encodeURIComponent(input.name)}?${query.toString()}`,+ { method: 'DELETE' },+ )+}+export async function getManagedAgentConnections() {return (await apiFetch(@@ -332,6 +413,12 @@ export async function getManagedAgentSessionEvents(sessionId: string) {).events}+export function managedAgentRenderDebug(event: ManagedAgentEvent) {+ if (event.type !== 'agent.rendered') return undefined+ const parsed = renderDebugSchema.safeParse(event.data)+ return parsed.success ? parsed.data : undefined+}+export async function getManagedAgentSession(sessionId: string) {return apiFetch(`/managed-agents/sessions/${encodeURIComponent(sessionId)}`,