Skip to content

An open-source, faster Devin alternative

TypeScript

Add managed GitHub App connections (#735)

Mohamed Habib78ddd7a96689
diff --git a/agent/README.md b/agent/README.md
index bcd0a796..052f4ab2 100644
--- a/agent/README.md
+++ b/agent/README.md
@@ -90,6 +90,33 @@ the original request headers or managed secrets to the redirect destination.
Hooks may only be called while the managed runtime is rendering an agent.
+## Managed GitHub App connection
+
+For direct Git, `gh`, REST, and GraphQL access, declare a managed GitHub App
+provider and select it from the agent:
+
+```ts
+import { defineConnection, githubApp, useConnection } from "@opencomputer/agent";
+
+const github = defineConnection({
+ id: "github",
+ provider: githubApp({
+ permissions: { contents: "write", pull_requests: "write" },
+ }),
+});
+
+export default function Agent() {
+ useConnection(github);
+ return "Push a branch and create a pull request.";
+}
+```
+
+The installer chooses all or selected repositories in GitHub; omitting an
+additional repository list means the entire GitHub installation grant. Unlike
+HTTP connections, a short-lived installation token is placed in the eligible
+sandbox as `GH_TOKEN` and `GITHUB_TOKEN`, where sandbox code can read it. It
+expires after about one hour and must never be printed, committed, or logged.
+
## Code-defined tools
Define executable capabilities with OpenComputer's harness-neutral `tool()`
diff --git a/agent/src/index.test.ts b/agent/src/index.test.ts
index 6215b023..820c37f3 100644
--- a/agent/src/index.test.ts
+++ b/agent/src/index.test.ts
@@ -5,7 +5,9 @@ import {
defineConnection,
defineMemory,
documentMemory,
+ githubApp,
httpMemory,
+ useConnection,
useInput,
useMemory,
useSecret,
@@ -16,6 +18,78 @@ import {
const HOOKS = Symbol.for("opencomputer.agent-hooks");
+test("githubApp defines a frozen managed connection permission subset", () => {
+ const provider = githubApp({
+ permissions: {
+ contents: "write",
+ pull_requests: "write",
+ actions: "read",
+ metadata: "read",
+ },
+ });
+ const connection = defineConnection({ id: "github", provider });
+
+ assert.deepEqual(JSON.parse(JSON.stringify(connection)), {
+ kind: "connection",
+ id: "github",
+ provider: {
+ kind: "github-app",
+ permissions: {
+ contents: "write",
+ pull_requests: "write",
+ actions: "read",
+ metadata: "read",
+ },
+ },
+ });
+ assert.ok(Object.isFrozen(provider));
+ assert.ok(Object.isFrozen(provider.permissions));
+ assert.ok(Object.isFrozen(connection));
+});
+
+test("githubApp rejects empty, unsupported, and invalid permissions", () => {
+ assert.throws(
+ () => githubApp({ permissions: {} }),
+ /requires at least one permission/,
+ );
+ assert.throws(
+ () => githubApp({ permissions: { administration: "read" } as never }),
+ /does not support the administration permission/,
+ );
+ assert.throws(
+ () => githubApp({ permissions: { contents: "admin" } as never }),
+ /permission contents must be "read" or "write"/,
+ );
+ assert.throws(
+ () => githubApp({ permissions: { metadata: "write" } as never }),
+ /permission metadata must be "read"/,
+ );
+});
+
+test("useConnection selects a declared connection through the render host", () => {
+ const github = defineConnection({
+ id: "github",
+ origin: "https://api.github.com",
+ });
+ const selected: string[] = [];
+ const globals = globalThis as Record<PropertyKey, unknown>;
+ globals[HOOKS] = {
+ useConnection(connection: { id: string }) {
+ selected.push(connection.id);
+ },
+ };
+ try {
+ useConnection(github);
+ assert.deepEqual(selected, ["github"]);
+ } finally {
+ delete globals[HOOKS];
+ }
+ assert.throws(
+ () => useConnection(github),
+ /hooks can only run while rendering an agent/,
+ );
+});
+
/**
* Mirrors the host's render worker: a per-render scope with the projections
* the host resolved, keyed by resource id, and the ids the render selected.
diff --git a/agent/src/index.ts b/agent/src/index.ts
index 286fc7d2..e8ce5512 100644
--- a/agent/src/index.ts
+++ b/agent/src/index.ts
@@ -1,10 +1,6 @@
import { Cron } from "croner";
-import {
- memoryId,
- memoryProjection,
- type MemoryProjection,
-} from "./memory.js";
+import { memoryId, memoryProjection, type MemoryProjection } from "./memory.js";
export type DataValue =
| null
@@ -69,7 +65,10 @@ export interface ChannelMessageContext {
}
/** The turn outcomes an event subscription delivers. */
-export type OutcomeEventType = "turn.completed" | "turn.failed" | "turn.cancelled";
+export type OutcomeEventType =
+ | "turn.completed"
+ | "turn.failed"
+ | "turn.cancelled";
/**
* A recorded turn outcome of another session in the project, delivered by
@@ -176,6 +175,26 @@ export interface HttpConnectionRedirectOrigin {
readonly pathPrefix?: string;
}
+export type GitHubAppPermission = "read" | "write";
+
+export interface GitHubAppPermissions {
+ readonly contents?: GitHubAppPermission;
+ readonly pull_requests?: GitHubAppPermission;
+ readonly issues?: GitHubAppPermission;
+ readonly checks?: GitHubAppPermission;
+ readonly actions?: GitHubAppPermission;
+ readonly metadata?: "read";
+}
+
+export interface GitHubAppProvider {
+ readonly kind: "github-app";
+ readonly permissions: Readonly<GitHubAppPermissions>;
+}
+
+export interface GitHubConnectionDefinition extends ConnectionReference {
+ readonly provider: GitHubAppProvider;
+}
+
export interface McpServerDefinition extends ResourceReference {
readonly kind: "mcp";
readonly url: string;
@@ -604,6 +623,9 @@ export { defineMemory, documentMemory, httpMemory } from "./memory.js";
* - `useInput()` reads `scope.input`.
* - `useSessionData(key)` reads `scope.state[key]`.
* - `useTool(id)` adds to `scope.tools`; returned as `enabledTools`.
+ * - `useConnection(id)` adds to `scope.connections`; returned as
+ * `requiredConnections` so the host can make the declared connection
+ * available to this render.
* - `useMemory(id)` reads `scope.memory[id]`, the projection the host
* resolved for the session binding with that resource id (absent when the
* session has no binding for it), and adds the id to
@@ -615,6 +637,7 @@ interface AgentHooks {
useInput(): Readonly<AgentInput>;
useModel(model: ModelSelection): void;
useTool(tool: string | ResourceReference): void;
+ useConnection(connection: string | ResourceReference): void;
useSubagent(agent: string | ResourceReference): void;
useSessionData<T extends DataValue>(key: string): T | undefined;
useMcpServer(server: string | ResourceReference): void;
@@ -671,6 +694,45 @@ export function bearer(secret: SecretReference): SecretHeaderReference {
return secretHeader(secret, { prefix: "Bearer " });
}
+const GITHUB_APP_PERMISSION_KEYS = [
+ "actions",
+ "checks",
+ "contents",
+ "issues",
+ "metadata",
+ "pull_requests",
+] as const;
+
+export function githubApp(options: {
+ permissions: GitHubAppPermissions;
+}): GitHubAppProvider {
+ const entries = Object.entries(options?.permissions ?? {});
+ if (entries.length === 0) {
+ throw new Error("githubApp() requires at least one permission");
+ }
+ const permissions: Record<string, GitHubAppPermission> = {};
+ for (const [name, level] of entries) {
+ if (!(GITHUB_APP_PERMISSION_KEYS as readonly string[]).includes(name)) {
+ throw new Error(
+ `githubApp() does not support the ${name} permission; supported permissions are ${GITHUB_APP_PERMISSION_KEYS.join(", ")}`,
+ );
+ }
+ if (level !== "read" && level !== "write") {
+ throw new Error(
+ `githubApp() permission ${name} must be "read" or "write"`,
+ );
+ }
+ if (name === "metadata" && level !== "read") {
+ throw new Error('githubApp() permission metadata must be "read"');
+ }
+ permissions[name] = level;
+ }
+ return Object.freeze({
+ kind: "github-app",
+ permissions: Object.freeze(permissions),
+ });
+}
+
/**
* A service the platform holds an OAuth credential for.
*
@@ -771,7 +833,10 @@ export async function callService(request: ServiceRequest): Promise<Response> {
*/
async function unwrapServiceResponse(response: Response): Promise<Response> {
if (!response.ok) return response;
- const envelope = (await response.clone().json().catch(() => null)) as {
+ const envelope = (await response
+ .clone()
+ .json()
+ .catch(() => null)) as {
status?: unknown;
headers?: unknown;
body?: unknown;
@@ -824,13 +889,15 @@ export interface ConnectedService {
* it is the platform's own API, not an upstream service whose status codes
* the caller needs to see.
*/
-export async function listServices(options: {
- /** Restrict to one grant, e.g. `google`. Omit for everything. */
- provider?: string;
- /** Omit unusable accounts. Defaults to true. */
- connectedOnly?: boolean;
- signal?: AbortSignal;
-} = {}): Promise<ConnectedService[]> {
+export async function listServices(
+ options: {
+ /** Restrict to one grant, e.g. `google`. Omit for everything. */
+ provider?: string;
+ /** Omit unusable accounts. Defaults to true. */
+ connectedOnly?: boolean;
+ signal?: AbortSignal;
+ } = {},
+): Promise<ConnectedService[]> {
const runtime = globalThis as typeof globalThis & {
process?: { env?: Record<string, string | undefined> };
};
@@ -870,15 +937,36 @@ export async function listServices(options: {
);
}
-export function defineConnection(input: {
+interface HttpConnectionInput {
id: string;
origin: string;
headers?: Readonly<Record<string, string | SecretHeaderReference>>;
methods?: readonly string[];
pathPrefix?: string;
redirectOrigins?: readonly HttpConnectionRedirectOrigin[];
-}): HttpConnectionDefinition {
+}
+
+interface GitHubConnectionInput {
+ id: string;
+ provider: GitHubAppProvider;
+}
+
+export function defineConnection(
+ input: HttpConnectionInput,
+): HttpConnectionDefinition;
+export function defineConnection(
+ input: GitHubConnectionInput,
+): GitHubConnectionDefinition;
+export function defineConnection(
+ input: HttpConnectionInput | GitHubConnectionInput,
+): HttpConnectionDefinition | GitHubConnectionDefinition {
const id = identifier(input.id, "defineConnection");
+ if ("provider" in input) {
+ if (input.provider?.kind !== "github-app") {
+ throw new Error("defineConnection() received an unsupported provider");
+ }
+ return Object.freeze({ kind: "connection", id, provider: input.provider });
+ }
const origin = new URL(input.origin);
if (origin.protocol !== "https:" || origin.pathname !== "/") {
throw new Error("Connection origins must be HTTPS origins without a path");
@@ -1190,8 +1278,10 @@ function replyDestinations(
input: ChannelInputBase,
provider: ChannelProvider,
): Record<string, Readonly<ChannelDestinationDefinition>> {
- const destinations: Record<string, Readonly<ChannelDestinationDefinition>> =
- {};
+ const destinations: Record<
+ string,
+ Readonly<ChannelDestinationDefinition>
+ > = {};
for (const [name, destination] of Object.entries(input.destinations ?? {})) {
const destinationId = resourceIdentifier(name, "Channel destination");
if (destination.type !== "reply") {
@@ -1208,7 +1298,9 @@ function replyDestinations(
}
export function defineChannel(input: SlackChannelInput): SlackChannelDefinition;
-export function defineChannel(input: TwilioChannelInput): TwilioChannelDefinition;
+export function defineChannel(
+ input: TwilioChannelInput,
+): TwilioChannelDefinition;
export function defineChannel(input: EmailChannelInput): EmailChannelDefinition;
export function defineChannel(input: ChannelInput): ChannelDefinition {
const common = channelCommon(input);
@@ -1472,7 +1564,15 @@ export function defineTool<Output extends DataValue = DataValue>(
});
}
-export function useMemory(memory: string | ResourceReference): MemoryProjection {
+/**
+ * The projection the host recalled for this session's binding of `memory`.
+ * It never fetches: a session without that binding fails the render here,
+ * before inference. Calling it also selects the binding's permitted tools for
+ * this model request; omitting it exposes none of them.
+ */
+export function useMemory(
+ memory: string | ResourceReference,
+): MemoryProjection {
const id = memoryId(
typeof memory === "string" ? memory : memory.id,
"useMemory",
@@ -1486,6 +1586,8 @@ export const useModel = (model: ModelSelection): void =>
hooks().useModel(model);
export const useTool = (tool: string | ResourceReference): void =>
hooks().useTool(tool);
+export const useConnection = (connection: string | ResourceReference): void =>
+ hooks().useConnection(connection);
/**
* Declare that this agent reaches a managed service.
*
@@ -1500,7 +1602,6 @@ export const useTool = (tool: string | ResourceReference): void =>
*/
export const useService = (service: string): void =>
hooks().useService?.(service);
-
export const useSubagent = (agent: string | ResourceReference): void =>
hooks().useSubagent(agent);
export const useMcpServer = (server: string | ResourceReference): void =>
diff --git a/cli/src/api.ts b/cli/src/api.ts
index bd09d6a3..7d9a91d2 100644
--- a/cli/src/api.ts
+++ b/cli/src/api.ts
@@ -63,6 +63,24 @@ export interface ManagedSecretMetadata {
updatedAt: string;
}
+export interface ManagedGitHubStatus {
+ environments: Array<{
+ environment: "development" | "production";
+ state: "not_connected" | "active" | "suspended" | "deleted";
+ installation?: {
+ id: string;
+ githubInstallationId: number;
+ accountLogin: string;
+ accountType: string;
+ repositorySelection: "all" | "selected";
+ state: "active" | "suspended" | "deleted";
+ createdAt: string;
+ updatedAt: string;
+ };
+ }>;
+ app: { slug: string } | null;
+}
+
// Model access (work 011). The provider token is write-only; these shapes
// carry only normalized metadata.
export interface ModelAccessConnection {
@@ -471,6 +489,37 @@ export class OpenComputerClient {
);
}
+ githubStatus(projectId: string) {
+ return this.request<ManagedGitHubStatus>(
+ `/api/managed-agents/projects/${encodeURIComponent(projectId)}/github`,
+ );
+ }
+
+ connectGitHub(input: {
+ projectId: string;
+ environments?: Array<"development" | "production">;
+ }) {
+ return this.request<{ installUrl: string; authorizeUrl: string }>(
+ `/api/managed-agents/projects/${encodeURIComponent(input.projectId)}/github/connect`,
+ {
+ method: "POST",
+ body: JSON.stringify(
+ input.environments ? { environments: input.environments } : {},
+ ),
+ },
+ );
+ }
+
+ disconnectGitHub(input: {
+ projectId: string;
+ environment: "development" | "production";
+ }) {
+ return this.request<void>(
+ `/api/managed-agents/projects/${encodeURIComponent(input.projectId)}/github?environment=${input.environment}`,
+ { method: "DELETE" },
+ );
+ }
+
async inspectTemplate(repositoryUrl: string): Promise<TemplateInspection> {
const deadline = Date.now() + 10 * 60_000;
for (;;) {
@@ -965,6 +1014,13 @@ export class OpenComputerClient {
pathPrefix?: string;
redirectOrigins?: Array<{ origin: string; pathPrefix?: string }>;
}>;
+ githubConnections: Array<{
+ id: string;
+ provider: {
+ kind: "github-app";
+ permissions: Record<string, "read" | "write">;
+ };
+ }>;
memory: MemoryDeclaration[];
models: Array<{ provider: string; model: string }>;
projectDeployment?: {
diff --git a/cli/src/dev.ts b/cli/src/dev.ts
index c6bae34d..369cac80 100644
--- a/cli/src/dev.ts
+++ b/cli/src/dev.ts
@@ -65,6 +65,7 @@ async function registerBuiltDeployment(
channels: built.channels,
connections: built.connections,
httpConnections: built.httpConnections,
+ githubConnections: built.githubConnections,
memory: built.memory,
models: built.models,
...(projectDeployment ? { projectDeployment } : {}),
diff --git a/cli/src/doctor.test.ts b/cli/src/doctor.test.ts
index d8a6ebba..4805c5d6 100644
--- a/cli/src/doctor.test.ts
+++ b/cli/src/doctor.test.ts
@@ -59,6 +59,31 @@ test("doctor accepts the initialized project without contacting the API", async
}
});
+test("doctor accepts a managed GitHub provider without an HTTP origin", async () => {
+ const root = await mkdtemp(resolve(tmpdir(), "opencomputer-doctor-github-"));
+ try {
+ const initialized = await initializeAgentProject(root);
+ await writeFile(
+ resolve(initialized.agentRoot, "agent.ts"),
+ `import { defineConnection, githubApp, useConnection } from "@opencomputer/agent";
+const github = defineConnection({
+ id: "github",
+ provider: githubApp({ permissions: { contents: "write" } }),
+});
+export default function Agent() {
+ useConnection(github);
+ return "Use GitHub.";
+}
+`,
+ );
+ const result = await doctorProject(root);
+ assert.equal(result.ok, true);
+ assert.deepEqual(result.diagnostics, []);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
test("doctor parses single-line declarations and ignores comments", async () => {
const root = await mkdtemp(resolve(tmpdir(), "opencomputer-doctor-"));
try {
diff --git a/cli/src/doctor.ts b/cli/src/doctor.ts
index 6bd12a94..7da738ce 100644
--- a/cli/src/doctor.ts
+++ b/cli/src/doctor.ts
@@ -105,6 +105,10 @@ export async function doctorProject(projectRoot: string): Promise<DoctorResult>
}
if (name === "defineConnection") {
const definition = node.arguments[0];
+ const provider =
+ definition && ts.isObjectLiteralExpression(definition)
+ ? property(definition, "provider")
+ : undefined;
const origin =
definition && ts.isObjectLiteralExpression(definition)
? property(definition, "origin")
@@ -125,9 +129,10 @@ export async function doctorProject(projectRoot: string): Promise<DoctorResult>
);
}));
if (
- !origin ||
- !isLiteralHttpsOrigin(origin.initializer) ||
- !redirectsValid
+ !provider &&
+ (!origin ||
+ !isLiteralHttpsOrigin(origin.initializer) ||
+ !redirectsValid)
) {
const line =
syntax.getLineAndCharacterOfPosition(node.getStart(syntax)).line +
diff --git a/cli/src/project.test.ts b/cli/src/project.test.ts
index 90d51465..1d60e625 100644
--- a/cli/src/project.test.ts
+++ b/cli/src/project.test.ts
@@ -343,6 +343,7 @@ export default function Agent() {
subagents: string[];
connections: string[];
httpConnections: unknown[];
+ githubConnections: unknown[];
mcpServers: string[];
mcpServerDefinitions: Array<{
id: string;
@@ -361,6 +362,7 @@ export default function Agent() {
subagents: ["researcher"],
connections: [],
httpConnections: [],
+ githubConnections: [],
mcpServers: ["docs"],
mcpServerDefinitions: [
{ id: "docs", url: "https://mcp.example.com/" },
@@ -766,10 +768,11 @@ export const repository = defineTool({
);
await writeFile(
resolve(initialized.agentRoot, "agent.ts"),
- `import { useTool } from "@opencomputer/agent";
+ `import { useConnection, useTool } from "@opencomputer/agent";
import { repository } from "./tools/github.js";
export default function Agent() {
+ useConnection({ id: "github-api" });
useTool(repository);
return "Use GitHub when needed.";
}
@@ -810,6 +813,122 @@ export default function Agent() {
}
});
+test("the compiler records managed GitHub permissions as a provider connection", async () => {
+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-github-app-"));
+ const root = resolve(parent, "app");
+ try {
+ const initialized = await initializeAgentProject(root);
+ await mkdir(resolve(initialized.agentRoot, "connections"), {
+ recursive: true,
+ });
+ await writeFile(
+ resolve(initialized.agentRoot, "connections", "github.ts"),
+ `import { defineConnection, githubApp } from "@opencomputer/agent";
+
+export const github = defineConnection({
+ id: "github",
+ provider: githubApp({
+ permissions: {
+ pull_requests: "write",
+ contents: "write",
+ metadata: "read",
+ },
+ }),
+});
+`,
+ );
+ await writeFile(
+ resolve(initialized.agentRoot, "agent.ts"),
+ `import { useConnection } from "@opencomputer/agent";
+import { github } from "./connections/github.js";
+
+export default function Agent() {
+ useConnection(github);
+ return "Work with GitHub directly.";
+}
+`,
+ );
+
+ const built = await buildAgentArtifact(initialized.agentRoot);
+ assert.deepEqual(built.connections, ["github"]);
+ assert.deepEqual(built.httpConnections, []);
+ assert.deepEqual(built.githubConnections, [
+ {
+ id: "github",
+ provider: {
+ kind: "github-app",
+ permissions: {
+ contents: "write",
+ metadata: "read",
+ pull_requests: "write",
+ },
+ },
+ },
+ ]);
+ const manifest = JSON.parse(
+ await readFile(
+ resolve(initialized.agentRoot, ".opencomputer", "runtime", ".opencomputer", "reactive.json"),
+ "utf8",
+ ),
+ ) as { githubConnections: unknown[] };
+ assert.deepEqual(manifest.githubConnections, built.githubConnections);
+ } finally {
+ await rm(parent, { recursive: true, force: true });
+ }
+});
+
+test("the compiler rejects dynamic or unsupported GitHub permissions", async () => {
+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-github-invalid-"));
+ const root = resolve(parent, "app");
+ try {
+ const initialized = await initializeAgentProject(root);
+ await mkdir(resolve(initialized.agentRoot, "connections"), {
+ recursive: true,
+ });
+ const connection = resolve(
+ initialized.agentRoot,
+ "connections",
+ "github.ts",
+ );
+ await writeFile(
+ resolve(initialized.agentRoot, "agent.ts"),
+ `import "./connections/github.js";
+export default function Agent() { return "Use GitHub."; }
+`,
+ );
+ await writeFile(
+ connection,
+ `import { defineConnection, githubApp } from "@opencomputer/agent";
+const permissions = { contents: "write" } as const;
+export default defineConnection({
+ id: "github",
+ provider: githubApp({ permissions }),
+});
+`,
+ );
+ await assert.rejects(
+ buildAgentArtifact(initialized.agentRoot),
+ /githubApp\(\) options must be static/,
+ );
+
+ await writeFile(
+ connection,
+ `import { defineConnection, githubApp } from "@opencomputer/agent";
+export default defineConnection({
+ id: "github",
+ provider: githubApp({ permissions: { administration: "write" } }),
+});
+`,
+ );
+ await assert.rejects(
+ buildAgentArtifact(initialized.agentRoot),
+ /does not support the administration permission/,
+ );
+ } finally {
+ await rm(parent, { recursive: true, force: true });
+ }
+});
+
test("the compiler records managed MCP server definitions", async () => {
const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-mcp-"));
const root = resolve(parent, "app");
diff --git a/cli/src/project.ts b/cli/src/project.ts
index 37f82924..a81eec39 100644
--- a/cli/src/project.ts
+++ b/cli/src/project.ts
@@ -40,6 +40,7 @@ export interface BuiltAgentArtifact {
channels: string[];
connections: string[];
httpConnections: HttpConnectionManifest[];
+ githubConnections: GitHubConnectionManifest[];
memory: MemoryDeclaration[];
models: Array<{ provider: string; model: string }>;
body: Buffer;
@@ -82,6 +83,16 @@ export interface HttpConnectionManifest {
redirectOrigins?: Array<{ origin: string; pathPrefix?: string }>;
}
+export type GitHubAppPermission = "read" | "write";
+
+export interface GitHubConnectionManifest {
+ id: string;
+ provider: {
+ kind: "github-app";
+ permissions: Record<string, GitHubAppPermission>;
+ };
+}
+
export interface McpServerManifest {
id: string;
url: string;
@@ -477,9 +488,7 @@ export default function Agent() {
private: true,
type: "module",
scripts: {
- ...(spa
- ? { "dev:web": "vite", build: "tsc -b && vite build" }
- : {}),
+ ...(spa ? { "dev:web": "vite", build: "tsc -b && vite build" } : {}),
session: "opencomputer session",
deploy: "opencomputer deploy",
},
@@ -829,7 +838,9 @@ function declaredServiceProviders(agentSource: string): string[] {
}
return [
...new Set(
- declared.map((service) => MANAGED_SERVICE_PROVIDERS[service.trim().toLowerCase()]!),
+ declared.map(
+ (service) => MANAGED_SERVICE_PROVIDERS[service.trim().toLowerCase()]!,
+ ),
),
];
}
@@ -950,11 +961,12 @@ function definedMcpServers(
*/
type MemoryAuthoringFunction = "defineMemory" | "documentMemory" | "httpMemory";
-const MEMORY_AUTHORING_FUNCTIONS: ReadonlySet<string> = new Set<MemoryAuthoringFunction>([
- "defineMemory",
- "documentMemory",
- "httpMemory",
-]);
+const MEMORY_AUTHORING_FUNCTIONS: ReadonlySet<string> =
+ new Set<MemoryAuthoringFunction>([
+ "defineMemory",
+ "documentMemory",
+ "httpMemory",
+ ]);
const AGENT_PACKAGE = "@opencomputer/agent";
@@ -1003,8 +1015,14 @@ class MemorySourceResolver {
let file = this.files.get(path);
if (!file) {
const module = this.modules.find((candidate) => candidate.path === path);
- if (!module) throw new Error(`Agent source module ${path} is not in the build`);
- file = ts.createSourceFile(path, module.source, ts.ScriptTarget.Latest, true);
+ if (!module)
+ throw new Error(`Agent source module ${path} is not in the build`);
+ file = ts.createSourceFile(
+ path,
+ module.source,
+ ts.ScriptTarget.Latest,
+ true,
+ );
this.files.set(path, file);
}
return file;
@@ -1024,7 +1042,9 @@ class MemorySourceResolver {
...["ts", "tsx", "js", "jsx", "mts", "mjs", "cts", "cjs"].map(
(extension) => `${base}.${extension}`,
),
- ...["ts", "tsx", "js", "jsx"].map((extension) => `${base}/index.${extension}`),
+ ...["ts", "tsx", "js", "jsx"].map(
+ (extension) => `${base}/index.${extension}`,
+ ),
];
return candidates.find((candidate) =>
this.modules.some((module) => module.path === candidate),
@@ -1053,7 +1073,8 @@ class MemorySourceResolver {
: undefined;
if (!statement.exportClause) {
// export * from "..."
- for (const [name, fn] of from?.functions ?? []) result.functions.set(name, fn);
+ for (const [name, fn] of from?.functions ?? [])
+ result.functions.set(name, fn);
for (const name of from?.namespaces ?? []) result.namespaces.add(name);
continue;
}
@@ -1092,10 +1113,16 @@ class MemorySourceResolver {
for (const statement of this.file(path).statements) {
if (!ts.isImportDeclaration(statement)) continue;
const clause = statement.importClause;
- if (!clause || clause.isTypeOnly || !ts.isStringLiteral(statement.moduleSpecifier)) {
+ if (
+ !clause ||
+ clause.isTypeOnly ||
+ !ts.isStringLiteral(statement.moduleSpecifier)
+ ) {
continue;
}
- const from = this.exportsOf(this.target(path, statement.moduleSpecifier.text));
+ const from = this.exportsOf(
+ this.target(path, statement.moduleSpecifier.text),
+ );
if (!from.functions.size && !from.namespaces.size) continue;
const named = clause.namedBindings;
if (named && ts.isNamespaceImport(named)) {
@@ -1106,7 +1133,8 @@ class MemorySourceResolver {
const imported = (specifier.propertyName ?? specifier.name).text;
const fn = from.functions.get(imported);
if (fn) bindings.functions.set(specifier.name.text, fn);
- if (from.namespaces.has(imported)) bindings.namespaces.add(specifier.name.text);
+ if (from.namespaces.has(imported))
+ bindings.namespaces.add(specifier.name.text);
}
}
}
@@ -1158,12 +1186,19 @@ function assertMemoryFunctionsCalledDirectly(
const bindings = resolver.bindingsOf(path);
const visit = (node: ts.Node): void => {
if (isTypeOnlyContext(node)) return;
- if (ts.isExportDeclaration(node) && node.moduleSpecifier && node.exportClause &&
- ts.isNamedExports(node.exportClause) && ts.isStringLiteral(node.moduleSpecifier)) {
+ if (
+ ts.isExportDeclaration(node) &&
+ node.moduleSpecifier &&
+ node.exportClause &&
+ ts.isNamedExports(node.exportClause) &&
+ ts.isStringLiteral(node.moduleSpecifier)
+ ) {
// export { a as b } from "...": an aliased re-export of an authoring
// function would let importers call it under a name the compiler does
// not register from.
- const from = resolver.exportsOf(resolver.target(path, node.moduleSpecifier.text));
+ const from = resolver.exportsOf(
+ resolver.target(path, node.moduleSpecifier.text),
+ );
for (const specifier of node.exportClause.elements) {
if (specifier.isTypeOnly || !specifier.propertyName) continue;
const imported = specifier.propertyName.text;
@@ -1179,7 +1214,8 @@ function assertMemoryFunctionsCalledDirectly(
if (
ts.isCallExpression(node) &&
(node.expression.kind === ts.SyntaxKind.ImportKeyword ||
- (ts.isIdentifier(node.expression) && node.expression.text === "require"))
+ (ts.isIdentifier(node.expression) &&
+ node.expression.text === "require"))
) {
const argument = node.arguments[0];
if (argument && ts.isStringLiteralLike(argument)) {
@@ -1213,13 +1249,21 @@ function assertMemoryFunctionsCalledDirectly(
);
}
}
- if (bindings.namespaces.has(node.text) && !ts.isNamespaceImport(parent) &&
- !(ts.isImportSpecifier(parent) && parent.name === node)) {
+ if (
+ bindings.namespaces.has(node.text) &&
+ !ts.isNamespaceImport(parent) &&
+ !(ts.isImportSpecifier(parent) && parent.name === node)
+ ) {
const namespace = node.text;
- if (ts.isPropertyAccessExpression(parent) && parent.expression === node) {
+ if (
+ ts.isPropertyAccessExpression(parent) &&
+ parent.expression === node
+ ) {
const member = parent.name.text;
if (MEMORY_AUTHORING_FUNCTIONS.has(member)) {
- const called = ts.isCallExpression(parent.parent) && parent.parent.expression === parent;
+ const called =
+ ts.isCallExpression(parent.parent) &&
+ parent.parent.expression === parent;
throw new Error(
called
? `${path} calls ${namespace}.${member}(); ${DIRECT_CALL_HINT(member)}`
@@ -1228,7 +1272,10 @@ function assertMemoryFunctionsCalledDirectly(
}
return;
}
- if (ts.isElementAccessExpression(parent) && parent.expression === node) {
+ if (
+ ts.isElementAccessExpression(parent) &&
+ parent.expression === node
+ ) {
const key = parent.argumentExpression;
if (!ts.isStringLiteralLike(key)) {
throw new Error(
@@ -1236,7 +1283,9 @@ function assertMemoryFunctionsCalledDirectly(
);
}
if (MEMORY_AUTHORING_FUNCTIONS.has(key.text)) {
- const called = ts.isCallExpression(parent.parent) && parent.parent.expression === parent;
+ const called =
+ ts.isCallExpression(parent.parent) &&
+ parent.parent.expression === parent;
throw new Error(
called
? `${path} calls ${namespace}[${JSON.stringify(key.text)}](); ${DIRECT_CALL_HINT(key.text)}`
@@ -1285,10 +1334,7 @@ function literalObjectEntries(
`${label} cannot use methods or accessors; write each option as a literal property`,
);
}
- return [
- staticPropertyName(property.name, label),
- property.initializer,
- ];
+ return [staticPropertyName(property.name, label), property.initializer];
});
}
@@ -1462,9 +1508,15 @@ function definedMemory(
* naming both origins.
*/
export function mergeMemoryDeclarations(
- entries: ReadonlyArray<{ origin: string; memory: readonly MemoryDeclaration[] }>,
+ entries: ReadonlyArray<{
+ origin: string;
+ memory: readonly MemoryDeclaration[];
+ }>,
): MemoryDeclaration[] {
- const merged = new Map<string, { origin: string; declaration: MemoryDeclaration }>();
+ const merged = new Map<
+ string,
+ { origin: string; declaration: MemoryDeclaration }
+ >();
for (const { origin, memory } of entries) {
for (const declaration of memory) {
const existing = merged.get(declaration.id);
@@ -1656,7 +1708,9 @@ function replyDestinationsManifest(
throw new Error(`${path} has invalid destination ${name}`);
}
if (!ts.isObjectLiteralExpression(property.initializer)) {
- throw new Error(`${path} destination ${name} must be an object literal`);
+ throw new Error(
+ `${path} destination ${name} must be an object literal`,
+ );
}
const type = literalStringValue(
objectProperty(property.initializer, "type"),
@@ -1683,7 +1737,10 @@ function channelDefinition(
if (!input || !ts.isObjectLiteralExpression(input)) {
throw new Error(`${path} defineChannel() requires an object literal`);
}
- const id = literalStringValue(objectProperty(input, "id"), `${path} channel id`);
+ const id = literalStringValue(
+ objectProperty(input, "id"),
+ `${path} channel id`,
+ );
if (basename(path, ".ts") !== id || !AGENT_ID_PATTERN.test(id)) {
throw new Error(`${path} filename must match its valid channel id`);
}
@@ -1757,7 +1814,9 @@ function channelDefinition(
throw new Error(`${path} has invalid destination ${name}`);
}
if (!ts.isObjectLiteralExpression(property.initializer)) {
- throw new Error(`${path} destination ${name} must be an object literal`);
+ throw new Error(
+ `${path} destination ${name} must be an object literal`,
+ );
}
const destinationType = literalStringValue(
objectProperty(property.initializer, "type"),
@@ -1773,7 +1832,8 @@ function channelDefinition(
) {
throw new Error(`${path} destination ${name} is unsupported`);
}
- const required = visibility === "private" ? "groups:read" : "channels:read";
+ const required =
+ visibility === "private" ? "groups:read" : "channels:read";
if (!scopes.includes(required) || !scopes.includes("chat:write")) {
throw new Error(
`${path} destination ${name} requires ${required} and chat:write`,
@@ -1814,7 +1874,8 @@ function channelRegistration(
"channel",
);
const channel = channels.get(channelId);
- if (!channel) throw new Error(`${path} references unknown channel ${channelId}`);
+ if (!channel)
+ throw new Error(`${path} references unknown channel ${channelId}`);
const triggers = [
...new Set(
literalStringArray(objectProperty(input, "on"), `${path} triggers`),
@@ -1839,7 +1900,9 @@ function channelRegistration(
}
const event = triggerEvents[trigger];
if (!event || !channel.events.includes(event)) {
- throw new Error(`${path} trigger ${trigger} is not declared by ${channelId}`);
+ throw new Error(
+ `${path} trigger ${trigger} is not declared by ${channelId}`,
+ );
}
}
return {
@@ -1859,7 +1922,10 @@ function outboxDefinition(
if (!input || !ts.isObjectLiteralExpression(input)) {
throw new Error(`${path} defineOutbox() requires an object literal`);
}
- const id = literalStringValue(objectProperty(input, "id"), `${path} outbox id`);
+ const id = literalStringValue(
+ objectProperty(input, "id"),
+ `${path} outbox id`,
+ );
if (basename(path, ".ts") !== id || !AGENT_ID_PATTERN.test(id)) {
throw new Error(`${path} filename must match its valid outbox id`);
}
@@ -1869,7 +1935,9 @@ function outboxDefinition(
}
const channelExpression = objectProperty(delivery, "channel");
if (!channelExpression || !ts.isIdentifier(channelExpression)) {
- throw new Error(`${path} delivery.channel must reference an imported channel`);
+ throw new Error(
+ `${path} delivery.channel must reference an imported channel`,
+ );
}
const channelId = importedResourceId(
source,
@@ -1954,7 +2022,10 @@ function scheduleDefinition(
if (!input || !ts.isObjectLiteralExpression(input)) {
throw new Error(`${path} defineSchedule() requires an object literal`);
}
- const id = literalStringValue(objectProperty(input, "id"), `${path} schedule id`);
+ const id = literalStringValue(
+ objectProperty(input, "id"),
+ `${path} schedule id`,
+ );
if (basename(path, ".ts") !== id || !AGENT_ID_PATTERN.test(id)) {
throw new Error(`${path} filename must match its valid schedule id`);
}
@@ -2003,7 +2074,10 @@ function scheduleDefinition(
throw new Error(`${path} overlap must be "skip" or "allow"`);
}
const dispatchExpression = objectProperty(input, "dispatch");
- if (!dispatchExpression || !ts.isObjectLiteralExpression(dispatchExpression)) {
+ if (
+ !dispatchExpression ||
+ !ts.isObjectLiteralExpression(dispatchExpression)
+ ) {
throw new Error(`${path} dispatch must be an object literal`);
}
const textExpression = objectProperty(dispatchExpression, "text");
@@ -2047,20 +2121,25 @@ export async function readProjectResources(
): Promise<BuiltProjectResources> {
const opencomputer = resolve(projectRoot, "opencomputer");
const channelDefinitions = await Promise.all(
- (await typescriptFiles(resolve(opencomputer, "channels"))).map(async (path) =>
- channelDefinition(await readFile(path, "utf8"), path),
+ (await typescriptFiles(resolve(opencomputer, "channels"))).map(
+ async (path) => channelDefinition(await readFile(path, "utf8"), path),
),
);
- const channels = new Map(channelDefinitions.map((channel) => [channel.id, channel]));
+ const channels = new Map(
+ channelDefinitions.map((channel) => [channel.id, channel]),
+ );
if (channels.size !== channelDefinitions.length) {
throw new Error("Project channel IDs must be unique");
}
const outboxDefinitions = await Promise.all(
- (await typescriptFiles(resolve(opencomputer, "outboxes"))).map(async (path) =>
- outboxDefinition(await readFile(path, "utf8"), path, channels),
+ (await typescriptFiles(resolve(opencomputer, "outboxes"))).map(
+ async (path) =>
+ outboxDefinition(await readFile(path, "utf8"), path, channels),
),
);
- const outboxes = new Map(outboxDefinitions.map((outbox) => [outbox.id, outbox]));
+ const outboxes = new Map(
+ outboxDefinitions.map((outbox) => [outbox.id, outbox]),
+ );
if (outboxes.size !== outboxDefinitions.length) {
throw new Error("Project outbox IDs must be unique");
}
@@ -2097,7 +2176,9 @@ export async function readProjectResources(
),
);
}
- for (const path of await typescriptFiles(resolve(agent.root, "schedules"))) {
+ for (const path of await typescriptFiles(
+ resolve(agent.root, "schedules"),
+ )) {
schedules.push(
scheduleDefinition(await readFile(path, "utf8"), path, agent.localId),
);
@@ -2109,16 +2190,26 @@ export async function readProjectResources(
}
const manifest: ProjectResourceManifest = {
version: 1,
- channels: channelDefinitions.sort((left, right) => left.id.localeCompare(right.id)),
+ channels: channelDefinitions.sort((left, right) =>
+ left.id.localeCompare(right.id),
+ ),
channelRegistrations: channelRegistrations.sort((left, right) =>
- `${left.channelId}:${left.agentId}`.localeCompare(`${right.channelId}:${right.agentId}`),
+ `${left.channelId}:${left.agentId}`.localeCompare(
+ `${right.channelId}:${right.agentId}`,
+ ),
+ ),
+ outboxes: outboxDefinitions.sort((left, right) =>
+ left.id.localeCompare(right.id),
),
- outboxes: outboxDefinitions.sort((left, right) => left.id.localeCompare(right.id)),
outboxRegistrations: outboxRegistrations.sort((left, right) =>
- `${left.outboxId}:${left.agentId}`.localeCompare(`${right.outboxId}:${right.agentId}`),
+ `${left.outboxId}:${left.agentId}`.localeCompare(
+ `${right.outboxId}:${right.agentId}`,
+ ),
),
schedules: schedules.sort((left, right) =>
- `${left.agentId}:${left.id}`.localeCompare(`${right.agentId}:${right.id}`),
+ `${left.agentId}:${left.id}`.localeCompare(
+ `${right.agentId}:${right.id}`,
+ ),
),
gatedTools: gatedTools.sort((left, right) =>
`${left.agentId}:${left.toolId}`.localeCompare(
@@ -2231,6 +2322,10 @@ function definedHttpConnections(
if (!input || !ts.isObjectLiteralExpression(input)) {
throw new Error("defineConnection() requires an object literal");
}
+ if (objectProperty(input, "provider")) {
+ ts.forEachChild(node, visit);
+ return;
+ }
const id = literalStringValue(
objectProperty(input, "id"),
"connection id",
@@ -2370,6 +2465,148 @@ function definedHttpConnections(
return definitions;
}
+const GITHUB_APP_PERMISSION_KEYS = new Set([
+ "actions",
+ "checks",
+ "contents",
+ "issues",
+ "metadata",
+ "pull_requests",
+]);
+
+function definedGitHubConnections(
+ source: string,
+ path: string,
+): GitHubConnectionManifest[] {
+ const file = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);
+ const definitions: GitHubConnectionManifest[] = [];
+ const visit = (node: ts.Node): void => {
+ if (
+ ts.isCallExpression(node) &&
+ ts.isIdentifier(node.expression) &&
+ node.expression.text === "defineConnection"
+ ) {
+ const input = node.arguments[0];
+ if (!input || !ts.isObjectLiteralExpression(input)) {
+ throw new Error("defineConnection() requires an object literal");
+ }
+ const providerExpression = objectProperty(input, "provider");
+ if (!providerExpression) {
+ ts.forEachChild(node, visit);
+ return;
+ }
+ const id = literalStringValue(
+ objectProperty(input, "id"),
+ "connection id",
+ );
+ for (const property of input.properties) {
+ if (!ts.isPropertyAssignment(property)) {
+ throw new Error(
+ `Connection ${id} cannot use spreads or shorthand properties`,
+ );
+ }
+ const name = staticPropertyName(property.name, `Connection ${id}`);
+ if (name !== "id" && name !== "provider") {
+ throw new Error(
+ `GitHub connection ${id} does not support the ${name} option`,
+ );
+ }
+ }
+ if (
+ !ts.isCallExpression(providerExpression) ||
+ !ts.isIdentifier(providerExpression.expression) ||
+ providerExpression.expression.text !== "githubApp"
+ ) {
+ throw new Error(
+ `Connection ${id} provider must be an inline githubApp() call`,
+ );
+ }
+ const options = literalCallArgument(
+ providerExpression,
+ `Connection ${id} githubApp()`,
+ );
+ if (!options) {
+ throw new Error(`Connection ${id} githubApp() requires permissions`);
+ }
+ for (const property of options.properties) {
+ if (!ts.isPropertyAssignment(property)) {
+ throw new Error(
+ `Connection ${id} githubApp() options must be static`,
+ );
+ }
+ if (
+ staticPropertyName(property.name, `Connection ${id} githubApp()`) !==
+ "permissions"
+ ) {
+ throw new Error(
+ `Connection ${id} githubApp() only supports permissions`,
+ );
+ }
+ }
+ const permissionsExpression = objectProperty(options, "permissions");
+ if (
+ !permissionsExpression ||
+ !ts.isObjectLiteralExpression(permissionsExpression)
+ ) {
+ throw new Error(
+ `Connection ${id} githubApp() permissions must be an inline object literal`,
+ );
+ }
+ const permissions: Record<string, GitHubAppPermission> = {};
+ for (const property of permissionsExpression.properties) {
+ if (!ts.isPropertyAssignment(property)) {
+ throw new Error(
+ `Connection ${id} githubApp() permissions must use literal properties`,
+ );
+ }
+ const name = staticPropertyName(
+ property.name,
+ `Connection ${id} githubApp() permissions`,
+ );
+ if (!GITHUB_APP_PERMISSION_KEYS.has(name)) {
+ throw new Error(
+ `Connection ${id} githubApp() does not support the ${name} permission`,
+ );
+ }
+ const level = literalStringValue(
+ property.initializer,
+ `Connection ${id} githubApp() permission ${name}`,
+ );
+ if (level !== "read" && level !== "write") {
+ throw new Error(
+ `Connection ${id} githubApp() permission ${name} must be "read" or "write"`,
+ );
+ }
+ if (name === "metadata" && level !== "read") {
+ throw new Error(
+ `Connection ${id} githubApp() permission metadata must be "read"`,
+ );
+ }
+ permissions[name] = level;
+ }
+ if (Object.keys(permissions).length === 0) {
+ throw new Error(
+ `Connection ${id} githubApp() requires at least one permission`,
+ );
+ }
+ definitions.push({
+ id,
+ provider: {
+ kind: "github-app",
+ permissions: Object.fromEntries(
+ Object.entries(permissions).sort(([left], [right]) =>
+ left.localeCompare(right),
+ ),
+ ),
+ },
+ });
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(file);
+ return definitions;
+}
+
interface DefinedTool {
readonly id: string;
/** Has preview() and apply(), so the model's call is a proposal. */
@@ -2505,18 +2742,20 @@ function staticModelSelections(
ts.forEachChild(node, visit);
};
visit(file);
- return selections.filter(
- (selection, index) =>
- selections.findIndex(
- (candidate) =>
- candidate.provider === selection.provider &&
- candidate.model === selection.model,
- ) === index,
- ).sort((left, right) =>
- `${left.provider}/${left.model}`.localeCompare(
- `${right.provider}/${right.model}`,
- ),
- );
+ return selections
+ .filter(
+ (selection, index) =>
+ selections.findIndex(
+ (candidate) =>
+ candidate.provider === selection.provider &&
+ candidate.model === selection.model,
+ ) === index,
+ )
+ .sort((left, right) =>
+ `${left.provider}/${left.model}`.localeCompare(
+ `${right.provider}/${right.model}`,
+ ),
+ );
}
/**
@@ -2550,6 +2789,18 @@ export const useSecret = (value, options = {}) => {
};
export const secretHeader = (secret, options = {}) => Object.freeze({ kind: "secret-header", secret, ...options });
export const bearer = (secret) => secretHeader(secret, { prefix: "Bearer " });
+export const githubApp = (options) => {
+ const entries = Object.entries(options?.permissions || {});
+ if (!entries.length) throw new Error("githubApp() requires at least one permission");
+ const permissions = {};
+ for (const [name, level] of entries) {
+ if (!["actions", "checks", "contents", "issues", "metadata", "pull_requests"].includes(name)) throw new Error("githubApp() does not support the " + name + " permission");
+ if (level !== "read" && level !== "write") throw new Error("githubApp() permission " + name + " must be read or write");
+ if (name === "metadata" && level !== "read") throw new Error("githubApp() permission metadata must be read");
+ permissions[name] = level;
+ }
+ return Object.freeze({ kind: "github-app", permissions: Object.freeze(permissions) });
+};
export const callService = async (request) => {
const base = globalThis.process?.env?.OPENCOMPUTER_CONNECTIONS_URL;
const token = globalThis.process?.env?.OPENCOMPUTER_CONNECTION_TOKEN;
@@ -2605,6 +2856,10 @@ export const listServices = async (options = {}) => {
export const defineConnection = (input) => {
const connectionId = id(input.id, "defineConnection");
+ if (input.provider) {
+ if (input.provider.kind !== "github-app") throw new Error("defineConnection() received an unsupported provider");
+ return Object.freeze({ kind: "connection", id: connectionId, provider: input.provider });
+ }
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 || {})) {
@@ -2742,6 +2997,7 @@ export const useInput = () => hooks().useInput();
export const useCurrentInput = useInput;
export const useModel = (model) => hooks().useModel(model);
export const useTool = (tool) => hooks().useTool(tool);
+export const useConnection = (connection) => hooks().useConnection(connection);
export const useService = (service) => hooks().useService?.(service);
export const useSubagent = (agent) => hooks().useSubagent(agent);
export const useMcpServer = (server) => hooks().useMcpServer(server);
@@ -2788,10 +3044,10 @@ async function bundleAgentSourceModules(
{
name: "opencomputer-agent-runtime",
setup(build) {
- build.onResolve(
- { filter: /^@opencomputer\/agent$/ },
- () => ({ path: "api", namespace: "opencomputer-agent-runtime" }),
- );
+ build.onResolve({ filter: /^@opencomputer\/agent$/ }, () => ({
+ path: "api",
+ namespace: "opencomputer-agent-runtime",
+ }));
build.onLoad(
{ filter: /^api$/, namespace: "opencomputer-agent-runtime" },
() => ({ contents: agentApiRuntimeSource(), loader: "js" }),
@@ -2982,9 +3238,13 @@ the product or support surface presented to users.
const httpConnections = sourceModules.flatMap((module) =>
definedHttpConnections(module.source, module.path),
);
- const duplicateConnection = httpConnections.find(
+ const githubConnections = sourceModules.flatMap((module) =>
+ definedGitHubConnections(module.source, module.path),
+ );
+ const allConnections = [...httpConnections, ...githubConnections];
+ const duplicateConnection = allConnections.find(
(connection, index) =>
- httpConnections.findIndex(
+ allConnections.findIndex(
(candidate) => candidate.id === connection.id,
) !== index,
);
@@ -3062,15 +3322,16 @@ the product or support surface presented to users.
toolModules: toolModules.sort(),
subagents: literalHookIds(agentSource, "useSubagent"),
// Declared HTTP connections AND managed-service grants: the platform
- // reads one list, and a google grant absent from it makes every
+ // reads one list, and a provider grant absent from it makes every
// connected mailbox invisible to listServices().
connections: [
...new Set([
- ...httpConnections.map((connection) => connection.id),
+ ...allConnections.map((connection) => connection.id),
...declaredServiceProviders(agentSource),
]),
].sort(),
httpConnections,
+ githubConnections,
mcpServers: [
...new Set([
...mcpServerDefinitions.map((server) => server.id),
@@ -3120,11 +3381,13 @@ export async function buildAgentArtifact(
) as {
connections?: string[];
httpConnections?: HttpConnectionManifest[];
+ githubConnections?: GitHubConnectionManifest[];
memory?: MemoryDeclaration[];
models?: Array<{ provider: string; model: string }>;
};
const connections = [...new Set(reactive.connections ?? [])].sort();
const httpConnections = reactive.httpConnections ?? [];
+ const githubConnections = reactive.githubConnections ?? [];
const memory = reactive.memory ?? [];
const models = reactive.models ?? [];
const body = Buffer.from(
@@ -3140,6 +3403,7 @@ export async function buildAgentArtifact(
channels: [],
connections,
httpConnections,
+ githubConnections,
memory,
models,
body,
diff --git a/cli/src/template.ts b/cli/src/template.ts
index 985f7402..d457d579 100644
--- a/cli/src/template.ts
+++ b/cli/src/template.ts
@@ -5,6 +5,7 @@ import {
mergeMemoryDeclarations,
readProjectAgents,
readProjectResources,
+ type GitHubConnectionManifest,
type HttpConnectionManifest,
type MemoryDeclaration,
type ProjectResourceManifest,
@@ -49,6 +50,7 @@ export interface TemplateBuildArtifact {
body: string;
connections: string[];
httpConnections: HttpConnectionManifest[];
+ githubConnections: GitHubConnectionManifest[];
memory: MemoryDeclaration[];
}
@@ -326,6 +328,7 @@ export async function buildTemplateProject(
body: built.body.toString("utf8"),
connections: built.connections,
httpConnections: built.httpConnections,
+ githubConnections: built.githubConnections,
memory: built.memory,
});
for (const connection of built.connections)
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 13ddcce6..984b79ff 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -84,6 +84,7 @@ import * as webhooks from "./webhooks";
import { createAPIKey, hashAPIKey } from "./api_keys";
import {
handleAgentWebhookInvocation,
+ handleManagedGitHubCallback,
handleManagedAgentChannelConnection,
proxyManagedAgents,
} from "./managed_agents";
@@ -5472,6 +5473,12 @@ export default {
if (path.startsWith("/api/managed-agents/channel-connections/")) {
return handleManagedAgentChannelConnection(req, env);
}
+ if (
+ path === "/api/managed-agents/github/callback" &&
+ req.method === "GET"
+ ) {
+ return handleManagedGitHubCallback(req, env);
+ }
if (path.startsWith("/api/agent-webhooks/")) {
return handleAgentWebhookInvocation(req, env);
}
diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.ts
index 762e4092..7b8630d0 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts
@@ -3,6 +3,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import {
handleAgentWebhookInvocation,
handleManagedAgentChannelConnection,
+ handleManagedGitHubCallback,
hasBYOKPlanAccess,
mintManagedAgentsAssertion,
proxyManagedAgents,
@@ -52,6 +53,67 @@ describe("managed agents proxy", () => {
expect(Number(payload.exp) - Number(payload.iat)).toBe(120);
});
+ it("forwards managed GitHub project connection requests", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ Response.json({
+ installUrl:
+ "https://github.com/apps/opencomputer/installations/new?state=opaque",
+ authorizeUrl:
+ "https://github.com/login/oauth/authorize?client_id=test&state=opaque",
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const response = await proxyManagedAgents(
+ new Request(
+ "https://mo-oc-dev.com/api/managed-agents/projects/prj_test/github/connect",
+ {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ environments: ["development"] }),
+ },
+ ),
+ {
+ MANAGED_AGENTS_API_URL: "https://manage-agents.mo-oc-dev.com",
+ OC_MANAGED_AGENTS_SECRET: "test-secret",
+ },
+ { orgID: "org_test", userID: "user_test" },
+ "/api/managed-agents",
+ );
+
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toEqual({
+ installUrl:
+ "https://github.com/apps/opencomputer/installations/new?state=opaque",
+ authorizeUrl:
+ "https://github.com/login/oauth/authorize?client_id=test&state=opaque",
+ });
+ expect(fetchMock.mock.calls[0]?.[0].toString()).toBe(
+ "https://manage-agents.mo-oc-dev.com/v1/projects/prj_test/github/connect",
+ );
+ });
+
+ it("forwards the unauthenticated GitHub setup callback as HTML", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response("<html>connected</html>", {
+ headers: { "content-type": "text/html; charset=utf-8" },
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const response = await handleManagedGitHubCallback(
+ new Request(
+ "https://mo-oc-dev.com/api/managed-agents/github/callback?code=oauth-code&installation_id=123&state=opaque",
+ ),
+ { MANAGED_AGENTS_API_URL: "https://manage-agents.mo-oc-dev.com" },
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.headers.get("cache-control")).toBe("no-store");
+ await expect(response.text()).resolves.toContain("connected");
+ expect(fetchMock.mock.calls[0]?.[0].toString()).toBe(
+ "https://manage-agents.mo-oc-dev.com/v1/github/callback?code=oauth-code&installation_id=123&state=opaque",
+ );
+ });
+
it("allows BYOK for Pro and Max but not the base plan", async () => {
await expect(
hasBYOKPlanAccess(legacyPlanEnv("base"), "org_test"),
@@ -1484,6 +1546,18 @@ describe("managed agents proxy", () => {
},
},
],
+ githubConnections: [
+ {
+ id: "github",
+ provider: {
+ kind: "github-app",
+ permissions: {
+ contents: "write",
+ pull_requests: "write",
+ },
+ },
+ },
+ ],
memory: [
{
id: "requirements",
@@ -1535,6 +1609,18 @@ describe("managed agents proxy", () => {
origin: "https://api.github.com",
}),
],
+ githubConnections: [
+ {
+ id: "github",
+ provider: {
+ kind: "github-app",
+ permissions: {
+ contents: "write",
+ pull_requests: "write",
+ },
+ },
+ },
+ ],
memory: [
{
id: "requirements",
diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.ts
index b1fe813c..ec43ce53 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.ts
@@ -165,7 +165,8 @@ async function publicErrorResponse(upstream: Response): Promise<Response> {
message = "The requested agent resource was not found.";
} else if (upstream.status === 409) {
if (backendCode === "invalid_model_selection") {
- message = backendMessage || "The deployment selects an unavailable model.";
+ message =
+ backendMessage || "The deployment selects an unavailable model.";
} else if (backendCode === "destination_verification_failed") {
if (
backendMessage === "Invite the Slack app to this conversation first"
@@ -302,10 +303,16 @@ async function memoryResponse(
}
if (!upstream.ok) {
if (upstream.status >= 500) return publicErrorResponse(upstream);
- const body = record(await upstream.clone().json().catch(() => null));
+ const body = record(
+ await upstream
+ .clone()
+ .json()
+ .catch(() => null),
+ );
const error = record(body?.error);
const code =
- typeof error?.code === "string" && /^[a-z][a-z0-9_]{0,63}$/.test(error.code)
+ typeof error?.code === "string" &&
+ /^[a-z][a-z0-9_]{0,63}$/.test(error.code)
? error.code
: null;
const message =
@@ -637,7 +644,9 @@ function publicWebhook(
agentId: webhook.agentId,
name: webhook.name,
enabled: webhook.enabled,
- ...(typeof webhook.identity === "string" ? { identity: webhook.identity } : {}),
+ ...(typeof webhook.identity === "string"
+ ? { identity: webhook.identity }
+ : {}),
// The token is the credential; when this response carries it (create,
// rotate), the URL carries it too and is shown once. Listings never do.
...(publicOrigin && id
@@ -667,7 +676,9 @@ function publicWebhookRequest(value: unknown): Record<string, unknown> {
deploymentId: request.deploymentId,
sessionId: request.sessionId,
outcome: request.outcome,
- ...(typeof request.attempt === "number" ? { attempt: request.attempt } : {}),
+ ...(typeof request.attempt === "number"
+ ? { attempt: request.attempt }
+ : {}),
...(request.terminal === true ? { terminal: true } : {}),
...(request.error
? { error: "The webhook request could not start a session." }
@@ -832,8 +843,7 @@ const FAILURE_REASON_CODES: Record<string, PublicFailureCode> = {
// A parameter is the only runtime-derived text a public failure carries, so
// it must look like what it claims to be; anything else is dropped.
-const MODEL_ID =
- /^(?:[a-z][a-z0-9-]{0,31}\/)?[a-z0-9][a-z0-9._:-]{0,63}$/i;
+const MODEL_ID = /^(?:[a-z][a-z0-9-]{0,31}\/)?[a-z0-9][a-z0-9._:-]{0,63}$/i;
const TOOL_ID = /^[a-z0-9_][a-z0-9_.-]{0,63}$/i;
const CREDENTIAL_SHAPED =
/^(?:sk|osb|ghp|gho|ghs|ghu|ghr|github_pat|xox[abprs]|key|token|secret)[-_]/i;
@@ -865,7 +875,8 @@ const FAILURE_MESSAGE_RULES: ReadonlyArray<{
},
{
code: "model_unavailable",
- pattern: /\bmodel (?:is )?not (?:found|available|supported)\b|ModelNotFound/i,
+ pattern:
+ /\bmodel (?:is )?not (?:found|available|supported)\b|ModelNotFound/i,
},
{
code: "context_too_long",
@@ -885,7 +896,8 @@ const FAILURE_MESSAGE_RULES: ReadonlyArray<{
},
{
code: "tool_failed",
- pattern: /^(?:Unknown tool|Tool) "?([A-Za-z0-9_.-]+)"? (?:failed|is not (?:available|registered)|threw)/,
+ pattern:
+ /^(?:Unknown tool|Tool) "?([A-Za-z0-9_.-]+)"? (?:failed|is not (?:available|registered)|threw)/,
parameter: "tool",
},
{ code: "tool_failed", pattern: /^The tool has no edge implementation/ },
@@ -1092,6 +1104,12 @@ function publicSuccessBody(
if (method === "POST" && suffix === "/projects") {
return publicProject(body);
}
+ if (
+ /^\/github(?:\/connect)?$/.test(suffix) ||
+ /^\/projects\/[^/]+\/github(?:\/(?:connect|attach))?$/.test(suffix)
+ ) {
+ return stripPrivateValues(body);
+ }
if (
(method === "GET" || method === "PUT") &&
/^\/projects\/[^/]+\/secrets(?:\/[^/]+)?$/.test(suffix)
@@ -1585,6 +1603,9 @@ async function deploySourceAgent(
httpConnections: Array.isArray(body.httpConnections)
? body.httpConnections
: [],
+ githubConnections: Array.isArray(body.githubConnections)
+ ? body.githubConnections
+ : [],
memory: Array.isArray(body.memory) ? body.memory : [],
models,
...(body.projectDeployment && typeof body.projectDeployment === "object"
@@ -1617,10 +1638,24 @@ function isAllowedManagedAgentsRoute(method: string, suffix: string): boolean {
if ((method === "GET" || method === "POST") && suffix === "/projects") {
return true;
}
+ if (method === "GET" && suffix === "/github") return true;
+ if (method === "POST" && suffix === "/github/connect") return true;
if (method === "GET" && /^\/projects\/[^/]+$/.test(suffix)) return true;
if (method === "GET" && /^\/projects\/[^/]+\/source-archive$/.test(suffix)) {
return true;
}
+ if (
+ (method === "GET" || method === "DELETE") &&
+ /^\/projects\/[^/]+\/github$/.test(suffix)
+ ) {
+ return true;
+ }
+ if (
+ method === "POST" &&
+ /^\/projects\/[^/]+\/github\/(connect|attach)$/.test(suffix)
+ ) {
+ return true;
+ }
if (
(method === "GET" || method === "PUT" || method === "DELETE") &&
/^\/projects\/[^/]+\/secrets(?:\/[^/]+)?$/.test(suffix)
@@ -1715,6 +1750,49 @@ function isAllowedManagedAgentsRoute(method: string, suffix: string): boolean {
);
}
+export async function handleManagedGitHubCallback(
+ request: Request,
+ env: ManagedAgentsEnv,
+): Promise<Response> {
+ if (request.method !== "GET") {
+ return new Response("Method not allowed", { status: 405 });
+ }
+ const requestURL = new URL(request.url);
+ const base = (
+ env.MANAGED_AGENTS_API_URL ?? DEFAULT_MANAGED_AGENTS_API_URL
+ ).replace(/\/+$/, "");
+ const target = new URL(`${base}/v1/github/callback${requestURL.search}`);
+ if (target.protocol !== "https:" && target.hostname !== "localhost") {
+ return new Response("GitHub connection is unavailable", { status: 503 });
+ }
+ try {
+ const upstream = await fetch(target, { redirect: "manual" });
+ const headers = new Headers();
+ for (const name of [
+ "content-type",
+ "cache-control",
+ "content-security-policy",
+ "referrer-policy",
+ "x-content-type-options",
+ "x-frame-options",
+ ]) {
+ const value = upstream.headers.get(name);
+ if (value) headers.set(name, value);
+ }
+ headers.set("cache-control", "no-store");
+ return new Response(upstream.body, {
+ status: upstream.status,
+ statusText: upstream.statusText,
+ headers,
+ });
+ } catch {
+ return new Response("GitHub connection is temporarily unavailable", {
+ status: 502,
+ headers: { "content-type": "text/plain; charset=utf-8" },
+ });
+ }
+}
+
function channelConnectionPage(
action: string,
status: number,
@@ -1854,13 +1932,20 @@ const WEBHOOK_HEADERS_NOT_FORWARDED = new Set([
"x-request-id",
"x-api-key",
]);
-const WEBHOOK_HEADER_PREFIXES_NOT_FORWARDED = ["x-oc-", "cf-", "x-forwarded-", "x-real-"];
+const WEBHOOK_HEADER_PREFIXES_NOT_FORWARDED = [
+ "x-oc-",
+ "cf-",
+ "x-forwarded-",
+ "x-real-",
+];
function forwardableWebhookHeader(name: string): boolean {
const lower = name.toLowerCase();
return (
!WEBHOOK_HEADERS_NOT_FORWARDED.has(lower) &&
- !WEBHOOK_HEADER_PREFIXES_NOT_FORWARDED.some((prefix) => lower.startsWith(prefix))
+ !WEBHOOK_HEADER_PREFIXES_NOT_FORWARDED.some((prefix) =>
+ lower.startsWith(prefix),
+ )
);
}
@@ -1927,7 +2012,8 @@ export async function handleAgentWebhookInvocation(
});
if (authorization) headers.set("authorization", authorization);
for (const [name, value] of request.headers) {
- if (forwardableWebhookHeader(name) && !headers.has(name)) headers.set(name, value);
+ if (forwardableWebhookHeader(name) && !headers.has(name))
+ headers.set(name, value);
}
try {
const upstream = await fetch(target, {
diff --git a/docs/agents/capabilities.mdx b/docs/agents/capabilities.mdx
index 1938a3db..c4d70882 100644
--- a/docs/agents/capabilities.mdx
+++ b/docs/agents/capabilities.mdx
@@ -14,6 +14,7 @@ the narrowest capability that fits the job.
| 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)` |
| HTTP connection | A constrained authenticated outbound request | OpenComputer sends the declared request | Call `defineConnection().fetch()` inside a tool |
+| GitHub App connection | Direct Git and GitHub API access to an installation | The agent sandbox uses a short-lived installation token | `useConnection(github)` |
| Memory | Notes shared across sessions | OpenComputer stores documents; the agent reads and saves through memory tools | `useMemory(memory)` |
`useModel()` selects the model for a render, but it does not add an executable
@@ -49,7 +50,7 @@ across sessions that agents can save and owners can edit. A tool that
writes to your own database is a third option when the data belongs to your
application rather than to the agent's continuing work.
-## Connections are not managed accounts
+## HTTP connections are not managed accounts
`defineConnection()` declares a secret-backed HTTP destination. It is not an
OAuth account selector and does not itself give the model a tool. Call it from
@@ -57,5 +58,9 @@ a code-defined tool or attach it to an MCP definition that accepts the
declared authorization headers. The proposed [HTTP memory provider
contract](/agents/memory-providers) uses the same connection mechanism.
+A [managed GitHub App connection](/agents/github) is the exception: the user
+installs OpenComputer's App, chooses repositories in GitHub, and the eligible
+agent receives a short-lived installation token for direct Git and API calls.
+
See [Secrets and outbound requests](/agents/secrets) for the complete security
model.
diff --git a/docs/agents/github.mdx b/docs/agents/github.mdx
new file mode 100644
index 00000000..faad1dcb
--- /dev/null
+++ b/docs/agents/github.mdx
@@ -0,0 +1,122 @@
+---
+title: "GitHub App connections"
+description: "Give an agent direct Git and GitHub API access with the managed OpenComputer App"
+---
+
+A managed GitHub connection lets an agent clone repositories, push branches,
+use the `gh` CLI, and call GitHub's REST or GraphQL APIs as a GitHub App
+installation.
+
+## Declare access
+
+Declare the maximum permissions this agent needs, then select the connection
+with `useConnection()`:
+
+```tsx
+import {
+ defineConnection,
+ githubApp,
+ useConnection,
+} from "@opencomputer/agent";
+
+const github = defineConnection({
+ id: "github",
+ provider: githubApp({
+ permissions: {
+ contents: "write",
+ pull_requests: "write",
+ },
+ }),
+});
+
+export default function Agent() {
+ useConnection(github);
+ return "Work on the requested repository, push a branch, and open a PR.";
+}
+```
+
+The supported permissions are `actions`, `checks`, `contents`, `issues`,
+`metadata`, and `pull_requests`. `metadata` is read-only. Request only what the
+agent needs.
+
+`useConnection(github)` activates the declared connection for the agent. At
+session startup, OpenComputer sends the declaration's exact `permissions`
+object when it asks GitHub to mint the installation token. GitHub does not let
+that token exceed the permissions granted to the App installation.
+
+Effective authority is therefore the intersection of:
+
+- the managed OpenComputer GitHub App's permission ceiling;
+- the permissions declared in `githubApp({ permissions })`; and
+- the repositories selected in the attached GitHub installation.
+
+## Install the App
+
+Deploy the agent, open its project in the OpenComputer dashboard, and choose
+**GitHub**. Install the managed OpenComputer GitHub App into a user or
+organization account. GitHub lets the installer select all repositories or a
+specific set of repositories.
+
+That GitHub installation selection is the complete repository boundary. There
+is no second OpenComputer repository allowlist. If the installer selects all
+repositories, the agent can access every repository available to that
+installation; if specific repositories are selected, it can access only those
+repositories. Change the selection in GitHub's installation settings.
+
+Connections are attached independently to the project's development and
+production environments.
+
+## Use Git and the API
+
+Inside the agent sandbox, ordinary GitHub tooling works directly. `gh` reads
+the injected `GH_TOKEN` automatically:
+
+```bash
+git clone https://github.com/acme/service.git
+git -C service switch -c agent/update
+git -C service push -u origin agent/update
+gh pr create --repo acme/service --fill
+gh api repos/acme/service/pulls
+```
+
+OpenComputer mints a GitHub installation token whose permissions are limited
+to those declared by the deployed agent. GitHub installation tokens expire
+after about one hour.
+
+### Understand GitHub permission responses
+
+Installation tokens do not have OAuth scopes. That does not mean they are
+unscoped. Their authority comes from the permissions included when the token is
+minted and the repositories granted to the installation.
+
+`X-Accepted-GitHub-Permissions` describes the permissions an API **endpoint
+accepts or requires**. It does not describe the permissions granted to the
+token. In particular, `allows_permissionless_access=true` means that endpoint
+does not require a specific GitHub App permission; it does not mean the token
+has unrestricted or “permissionless” repository access. Likewise, a
+`permissions` object in an ordinary repository response is not an installation
+token introspection result.
+
+Use installation endpoints with an installation token. For example,
+`GET /installation/repositories` lists the repositories available to the
+installation. User endpoints such as `GET /user/repos` require a user token, so
+a `403` from those endpoints is expected and says nothing about whether the
+declared installation permissions were applied.
+
+See GitHub's documentation for
+[generating an installation access token](https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/authenticating-as-a-github-app-installation#generating-an-installation-access-token),
+[troubleshooting required permissions](https://docs.github.com/en/rest/using-the-rest-api/troubleshooting-the-rest-api#resource-not-accessible),
+and
+[listing repositories accessible to an installation](https://docs.github.com/en/rest/apps/installations#list-repositories-accessible-to-the-app-installation).
+
+<Warning>
+ The short-lived token is available inside the eligible agent's sandbox as
+ `GH_TOKEN` and `GITHUB_TOKEN` for the operation. Code running in that sandbox
+ can read it. Do not print it, write it into source, add it to a Git remote,
+ include it in a checkpoint, or send it to logs. Install the App only on
+ repositories you are comfortable granting to the agent.
+</Warning>
+
+Other `defineConnection()` providers continue to use OpenComputer's managed
+egress and secret proxy. This direct-token behavior is specific to managed
+GitHub App connections.
diff --git a/docs/docs.json b/docs/docs.json
index ea720d82..a242a78e 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -50,6 +50,7 @@
"agents/channels",
"agents/outboxes",
"agents/secrets",
+ "agents/github",
"agents/byok",
"agents/deployments"
]
diff --git a/web/src/components/app-shell-nav.ts b/web/src/components/app-shell-nav.ts
index 0ed230f5..539558ab 100644
--- a/web/src/components/app-shell-nav.ts
+++ b/web/src/components/app-shell-nav.ts
@@ -95,6 +95,11 @@ export function managedAgentsNav(options: {
label: 'Secrets',
icon: KeySquare,
},
+ {
+ to: `${projectPath}/connections`,
+ label: 'Connections',
+ icon: Plug,
+ },
{
to: `${projectPath}/byok`,
label: 'BYOK',
diff --git a/web/src/components/app-shell.test.ts b/web/src/components/app-shell.test.ts
index 09aa897b..a531ccd8 100644
--- a/web/src/components/app-shell.test.ts
+++ b/web/src/components/app-shell.test.ts
@@ -37,6 +37,7 @@ describe('managed agents navigation', () => {
'Webhooks',
'Memory',
'Secrets',
+ 'Connections',
'BYOK',
'Debug playground',
])
@@ -46,6 +47,9 @@ describe('managed agents navigation', () => {
expect(nav[1]?.items.find((item) => item.label === 'Secrets')?.icon).toBe(
KeySquare,
)
+ expect(nav[1]?.items.find((item) => item.label === 'Connections')?.to).toBe(
+ '/projects/project%20one/connections',
+ )
expect(nav[1]?.items.find((item) => item.label === 'BYOK')?.icon).toBe(
BrainCircuit,
)
diff --git a/web/src/managed-agents/Connections.tsx b/web/src/managed-agents/Connections.tsx
index 297f38b7..3aaa3db6 100644
--- a/web/src/managed-agents/Connections.tsx
+++ b/web/src/managed-agents/Connections.tsx
@@ -3,8 +3,15 @@ import { useQuery } from '@tanstack/react-query'
import { Loader2, Plug, Plus, Trash2 } from 'lucide-react'
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 { Panel, PanelContent } from '@/components/panel'
+import {
+ Panel,
+ PanelContent,
+ PanelDescription,
+ PanelHeader,
+ PanelTitle,
+} from '@/components/panel'
import { StatusBadge } from '@/components/status-badge'
import { Button } from '@/components/ui/button'
import {
@@ -19,14 +26,20 @@ import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
displayManagedAgentName,
+ addManagedGitHubConnection,
claimManagedAgentChannelIdentity,
disconnectManagedAgentConnection,
getManagedAgentConnections,
+ getManagedGitHubConnections,
getManagedAgents,
linkManagedAgentConnection,
refreshManagedAgentConnection,
type ManagedAgentConnection,
} from './api'
+import {
+ navigateAuthorizationWindow,
+ openAuthorizationWindow,
+} from './authorization-window'
function displayResourceName(value: string) {
return value
@@ -108,6 +121,10 @@ export default function ManagedAgentConnections() {
const [newAlias, setNewAlias] = useState('gmail')
const [addConnectionOpen, setAddConnectionOpen] = useState(false)
const [addConnectionError, setAddConnectionError] = useState<string>()
+ const [addingGitHubConnection, setAddingGitHubConnection] = useState(false)
+ const [syncingGitHubConnections, setSyncingGitHubConnections] =
+ useState(false)
+ const [githubConnectionError, setGithubConnectionError] = useState<string>()
const [removeConnectionError, setRemoveConnectionError] = useState<string>()
const [connectionToRemove, setConnectionToRemove] =
useState<ManagedAgentConnection>()
@@ -118,6 +135,10 @@ export default function ManagedAgentConnections() {
queryKey: ['managed-agent-connections'],
queryFn: loadManagedAgentConnections,
})
+ const githubConnections = useQuery({
+ queryKey: ['managed-github-connections'],
+ queryFn: getManagedGitHubConnections,
+ })
const agents = useQuery({
queryKey: ['managed-agents'],
queryFn: getManagedAgents,
@@ -155,7 +176,13 @@ export default function ManagedAgentConnections() {
}
connectionStarted.current = true
setConnectionRequestState('connecting')
- void linkManagedAgentConnection(requestedService, requestedAlias)
+ void (
+ requestedService === 'github'
+ ? addManagedGitHubConnection('existing').then((authorizationUrl) => ({
+ authorizationUrl,
+ }))
+ : linkManagedAgentConnection(requestedService, requestedAlias)
+ )
.then((result) => {
if (result.authorizationUrl) {
window.location.assign(result.authorizationUrl)
@@ -177,7 +204,7 @@ export default function ManagedAgentConnections() {
<div>
<PageHeader
title="Connections"
- description="Connect accounts and choose the aliases your agents use."
+ description="Manage services and GitHub organizations available to your agents."
actions={
<Button
onClick={() => {
@@ -224,6 +251,167 @@ export default function ManagedAgentConnections() {
</Panel>
)}
+ <Panel className="mb-4">
+ <PanelHeader className="items-center">
+ <div className="flex min-w-0 items-center gap-3">
+ <div className="bg-muted text-muted-foreground flex size-9 shrink-0 items-center justify-center rounded-md">
+ <GithubMark className="size-4" />
+ </div>
+ <div>
+ <PanelTitle>Managed GitHub</PanelTitle>
+ <PanelDescription className="mt-1">
+ Install OpenComputer for the GitHub organizations your agents
+ can work in.
+ </PanelDescription>
+ </div>
+ </div>
+ <div className="flex items-center gap-2">
+ <Button
+ type="button"
+ variant="ghost"
+ disabled={addingGitHubConnection || syncingGitHubConnections}
+ onClick={() => {
+ setGithubConnectionError(undefined)
+ let authorizationWindow: Window
+ try {
+ authorizationWindow = openAuthorizationWindow()
+ } catch (error) {
+ setGithubConnectionError(
+ error instanceof Error
+ ? error.message
+ : 'GitHub sync could not be started.',
+ )
+ return
+ }
+ setSyncingGitHubConnections(true)
+ void addManagedGitHubConnection('existing')
+ .then((authorizationUrl) =>
+ navigateAuthorizationWindow(
+ authorizationWindow,
+ authorizationUrl,
+ ),
+ )
+ .catch((error: unknown) => {
+ authorizationWindow.close()
+ setGithubConnectionError(
+ error instanceof Error
+ ? error.message
+ : 'GitHub sync could not be started.',
+ )
+ })
+ .finally(() => setSyncingGitHubConnections(false))
+ }}
+ >
+ {syncingGitHubConnections ? (
+ <Loader2 className="size-4 animate-spin" aria-hidden />
+ ) : null}
+ Sync installations
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ disabled={addingGitHubConnection || syncingGitHubConnections}
+ onClick={() => {
+ setGithubConnectionError(undefined)
+ let authorizationWindow: Window
+ try {
+ authorizationWindow = openAuthorizationWindow()
+ } catch (error) {
+ setGithubConnectionError(
+ error instanceof Error
+ ? error.message
+ : 'GitHub setup could not be started.',
+ )
+ return
+ }
+ setAddingGitHubConnection(true)
+ void addManagedGitHubConnection('install')
+ .then((authorizationUrl) =>
+ navigateAuthorizationWindow(
+ authorizationWindow,
+ authorizationUrl,
+ ),
+ )
+ .catch((error: unknown) => {
+ authorizationWindow.close()
+ setGithubConnectionError(
+ error instanceof Error
+ ? error.message
+ : 'GitHub setup could not be started.',
+ )
+ })
+ .finally(() => setAddingGitHubConnection(false))
+ }}
+ >
+ {addingGitHubConnection ? (
+ <Loader2 className="size-4 animate-spin" aria-hidden />
+ ) : (
+ <Plus className="size-4" aria-hidden />
+ )}
+ Add organization
+ </Button>
+ </div>
+ </PanelHeader>
+ <PanelContent>
+ {githubConnections.isLoading ? (
+ <div className="flex min-h-20 items-center justify-center">
+ <Loader2 className="text-muted-foreground size-5 animate-spin" />
+ </div>
+ ) : githubConnections.isError ? (
+ <div className="flex min-h-20 items-center justify-between gap-4">
+ <p className="text-muted-foreground text-sm">
+ GitHub installations are temporarily unavailable.
+ </p>
+ <Button
+ variant="outline"
+ onClick={() => void githubConnections.refetch()}
+ >
+ Try again
+ </Button>
+ </div>
+ ) : githubConnections.data?.connections.length ? (
+ <div className="grid gap-3 md:grid-cols-2">
+ {githubConnections.data.connections.map((connection) => (
+ <div
+ key={connection.id}
+ className="flex items-center gap-3 rounded-md border px-4 py-3"
+ >
+ <GithubMark className="text-muted-foreground size-4 shrink-0" />
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-sm font-medium">
+ {connection.accountLogin}
+ </p>
+ <p className="text-muted-foreground truncate text-xs">
+ {connection.repositorySelection === 'all'
+ ? 'All repositories'
+ : 'Selected repositories'}
+ </p>
+ </div>
+ <StatusBadge
+ status={
+ connection.state === 'active' ? 'connected' : 'stopped'
+ }
+ />
+ </div>
+ ))}
+ </div>
+ ) : (
+ <div className="py-4 text-center">
+ <p className="text-sm font-medium">No organizations added</p>
+ <p className="text-muted-foreground mt-1 text-sm">
+ Add a GitHub user or organization account, then choose which
+ repositories OpenComputer can access.
+ </p>
+ </div>
+ )}
+ {githubConnectionError ? (
+ <p className="text-destructive mt-3 text-sm">
+ {githubConnectionError}
+ </p>
+ ) : null}
+ </PanelContent>
+ </Panel>
+
{connections.isLoading ? (
<div className="flex min-h-48 items-center justify-center">
<Loader2 className="text-muted-foreground size-5 animate-spin" />
@@ -296,8 +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, Google Calendar, or GitHub to make it available to your
- agents.
+ Add Gmail or Google Calendar to make it available to your agents.
</p>
<Button
className="mt-4"
@@ -334,17 +521,34 @@ export default function ManagedAgentConnections() {
if (!alias || connectionRequestState === 'connecting') return
setAddConnectionError(undefined)
setConnectionRequestState('connecting')
+ let authorizationWindow: Window
+ try {
+ authorizationWindow = openAuthorizationWindow()
+ } catch (error) {
+ setConnectionRequestState('failed')
+ setAddConnectionError(
+ error instanceof Error
+ ? error.message
+ : 'The connection could not be started.',
+ )
+ return
+ }
void linkManagedAgentConnection(newService, alias)
.then((result) => {
if (result.authorizationUrl) {
- window.location.assign(result.authorizationUrl)
+ navigateAuthorizationWindow(
+ authorizationWindow,
+ result.authorizationUrl,
+ )
return
}
+ authorizationWindow.close()
setConnectionRequestState('connected')
setAddConnectionOpen(false)
void connections.refetch()
})
.catch((error: unknown) => {
+ authorizationWindow.close()
setConnectionRequestState('failed')
setAddConnectionError(
error instanceof Error
@@ -368,7 +572,6 @@ export default function ManagedAgentConnections() {
>
<option value="gmail">Gmail</option>
<option value="calendar">Google Calendar</option>
- <option value="github">GitHub</option>
</select>
</div>
<div className="grid gap-2">
diff --git a/web/src/managed-agents/Detail.test.ts b/web/src/managed-agents/Detail.test.ts
new file mode 100644
index 00000000..240ecb7b
--- /dev/null
+++ b/web/src/managed-agents/Detail.test.ts
@@ -0,0 +1,9 @@
+import { describe, expect, it } from 'vitest'
+import { PROJECT_DETAIL_TABS } from './Detail'
+
+describe('managed project detail tabs', () => {
+ it('routes managed connections and retains the GitHub compatibility alias', () => {
+ expect(PROJECT_DETAIL_TABS.has('connections')).toBe(true)
+ expect(PROJECT_DETAIL_TABS.has('github')).toBe(true)
+ })
+})
diff --git a/web/src/managed-agents/Detail.tsx b/web/src/managed-agents/Detail.tsx
index cbdce947..05b69497 100644
--- a/web/src/managed-agents/Detail.tsx
+++ b/web/src/managed-agents/Detail.tsx
@@ -78,6 +78,7 @@ import { ManagedAgentSchedules } from './Schedules'
import { ManagedAgentWebhooks } from './Webhooks'
import { ManagedProjectMemory } from './Memory'
import { ManagedProjectBYOK } from './BYOK'
+import { ManagedProjectGitHub } from './GitHub'
import { AgentMarkdown } from './AgentMarkdown'
import {
projectCloneCommand,
@@ -94,8 +95,25 @@ type DetailTab =
| 'webhooks'
| 'memory'
| 'secrets'
+ | 'connections'
+ | 'github'
| 'byok'
+export const PROJECT_DETAIL_TABS = new Set<DetailTab>([
+ 'playground',
+ 'deployments',
+ 'sessions',
+ 'channels',
+ 'outboxes',
+ 'schedules',
+ 'webhooks',
+ 'memory',
+ 'secrets',
+ 'connections',
+ 'github',
+ 'byok',
+])
+
const EMPTY_MANAGED_AGENT_EVENTS: ManagedAgentEvent[] = []
function formatDate(value: string) {
@@ -506,21 +524,11 @@ export default function ManagedAgentDetail({
const [standaloneTab, setStandaloneTab] = useState<DetailTab>('playground')
const [starterCopied, setStarterCopied] = useState(false)
const [continuationCopied, setContinuationCopied] = useState(false)
- const routeTab = params.tab as DetailTab | undefined
- const projectTabs = new Set<DetailTab>([
- 'playground',
- 'deployments',
- 'sessions',
- 'channels',
- 'outboxes',
- 'schedules',
- 'webhooks',
- 'memory',
- 'secrets',
- 'byok',
- ])
+ const requestedRouteTab = params.tab as DetailTab | undefined
+ const routeTab =
+ requestedRouteTab === 'github' ? 'connections' : requestedRouteTab
const activeTab = project
- ? routeTab && projectTabs.has(routeTab)
+ ? routeTab && PROJECT_DETAIL_TABS.has(routeTab)
? routeTab
: 'playground'
: standaloneTab
@@ -705,6 +713,9 @@ export default function ManagedAgentDetail({
...(project ? ([{ id: 'webhooks', label: 'Webhooks' }] as const) : []),
...(project ? ([{ id: 'memory', label: 'Memory' }] as const) : []),
...(project ? ([{ id: 'secrets', label: 'Secrets' }] as const) : []),
+ ...(project
+ ? ([{ id: 'connections', label: 'Connections' }] as const)
+ : []),
...(project ? ([{ id: 'byok', label: 'BYOK' }] as const) : []),
]
@@ -1209,6 +1220,13 @@ export default function ManagedAgentDetail({
projectSlug={project.project.slug}
/>
) : null}
+
+ {activeTab === 'connections' && project ? (
+ <ManagedProjectGitHub
+ projectId={project.project.id}
+ environment={environment}
+ />
+ ) : null}
</div>
)
}
diff --git a/web/src/managed-agents/GitHub.tsx b/web/src/managed-agents/GitHub.tsx
new file mode 100644
index 00000000..3f72bfa9
--- /dev/null
+++ b/web/src/managed-agents/GitHub.tsx
@@ -0,0 +1,222 @@
+import { useState } from 'react'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { GitBranch, Loader2, Unplug } from 'lucide-react'
+import { EmptyState } from '@/components/empty-state'
+import { GithubMark } from '@/components/github-mark'
+import {
+ Panel,
+ PanelContent,
+ PanelDescription,
+ PanelHeader,
+ PanelTitle,
+} from '@/components/panel'
+import { StatusBadge } from '@/components/status-badge'
+import { Button } from '@/components/ui/button'
+import { notifyError, notifySuccess } from '@/lib/errors'
+import {
+ addManagedGitHubConnection,
+ attachManagedGitHub,
+ disconnectManagedGitHub,
+ getManagedGitHubStatus,
+} from './api'
+import { launchAuthorizationWindow } from './authorization-window'
+
+export function ManagedProjectGitHub({
+ projectId,
+ environment,
+}: {
+ projectId: string
+ environment: 'development' | 'production'
+}) {
+ const queryClient = useQueryClient()
+ const [selectedConnectionId, setSelectedConnectionId] = useState('')
+ const [addingConnection, setAddingConnection] = useState(false)
+ const queryKey = ['managed-github', projectId]
+ const status = useQuery({
+ queryKey,
+ queryFn: () => getManagedGitHubStatus(projectId),
+ })
+ const current = status.data?.environments.find(
+ (candidate) => candidate.environment === environment,
+ )
+ const availableConnections = (status.data?.connections ?? []).filter(
+ (connection) => connection.state === 'active',
+ )
+ const connectionId = selectedConnectionId || availableConnections[0]?.id || ''
+ const attach = useMutation({
+ mutationFn: () =>
+ attachManagedGitHub({ projectId, environment, connectionId }),
+ onSuccess: async () => {
+ await queryClient.invalidateQueries({ queryKey })
+ notifySuccess(`GitHub attached to ${environment}.`)
+ },
+ onError: (error) =>
+ notifyError("Couldn't attach the GitHub connection.", error),
+ })
+ const disconnect = useMutation({
+ mutationFn: () => disconnectManagedGitHub({ projectId, environment }),
+ onSuccess: async () => {
+ await queryClient.invalidateQueries({ queryKey })
+ notifySuccess(`GitHub disconnected from ${environment}.`)
+ },
+ onError: (error) =>
+ notifyError("Couldn't disconnect the GitHub installation.", error),
+ })
+
+ if (status.isLoading) {
+ return (
+ <Panel>
+ <PanelContent className="text-muted-foreground flex items-center gap-2 text-sm">
+ <Loader2 className="size-4 animate-spin" /> Loading GitHub status…
+ </PanelContent>
+ </Panel>
+ )
+ }
+ if (status.isError) {
+ return (
+ <Panel>
+ <EmptyState
+ icon={GitBranch}
+ title="GitHub status is temporarily unavailable"
+ description="Try loading the project again."
+ action={
+ <Button variant="outline" onClick={() => void status.refetch()}>
+ Try again
+ </Button>
+ }
+ />
+ </Panel>
+ )
+ }
+
+ return (
+ <div className="space-y-5">
+ <Panel>
+ <PanelHeader>
+ <div>
+ <PanelTitle>GitHub</PanelTitle>
+ <PanelDescription className="mt-1 max-w-2xl">
+ Install the managed OpenComputer GitHub App and choose the
+ repositories it can access in GitHub. The installation’s
+ repository selection is the complete repository scope.
+ </PanelDescription>
+ </div>
+ <StatusBadge
+ status={current?.state === 'active' ? 'running' : 'stopped'}
+ />
+ </PanelHeader>
+ <PanelContent className="space-y-4">
+ {current?.installation && current.state !== 'deleted' ? (
+ <div className="flex flex-wrap items-center justify-between gap-4">
+ <div>
+ <p className="text-sm font-medium">
+ {current.installation.accountLogin}
+ </p>
+ <p className="text-muted-foreground mt-1 text-sm">
+ {current.installation.repositorySelection === 'all'
+ ? 'All repositories accessible to this installation'
+ : 'Only repositories selected in GitHub'}
+ {' · '}
+ {environment}
+ </p>
+ </div>
+ <Button
+ variant="outline"
+ disabled={disconnect.isPending}
+ onClick={() => disconnect.mutate()}
+ >
+ {disconnect.isPending ? (
+ <Loader2 className="animate-spin" />
+ ) : (
+ <Unplug />
+ )}
+ Disconnect
+ </Button>
+ </div>
+ ) : (
+ <div className="flex flex-wrap items-center justify-between gap-4">
+ <p className="text-muted-foreground max-w-2xl text-sm">
+ No GitHub installation is connected to {environment}.
+ </p>
+ {availableConnections.length ? (
+ <div className="flex flex-wrap items-center gap-2">
+ {availableConnections.length > 1 ? (
+ <select
+ value={connectionId}
+ onChange={(event) =>
+ setSelectedConnectionId(event.target.value)
+ }
+ className="border-input bg-background h-9 rounded-md border px-3 text-sm"
+ >
+ {availableConnections.map((connection) => (
+ <option key={connection.id} value={connection.id}>
+ {connection.accountLogin}
+ </option>
+ ))}
+ </select>
+ ) : null}
+ <Button
+ disabled={!connectionId || attach.isPending}
+ onClick={() => attach.mutate()}
+ >
+ {attach.isPending ? (
+ <Loader2 className="animate-spin" />
+ ) : (
+ <GithubMark className="size-4" />
+ )}
+ Attach GitHub connection
+ </Button>
+ </div>
+ ) : (
+ <Button
+ disabled={addingConnection}
+ onClick={() => {
+ setAddingConnection(true)
+ void launchAuthorizationWindow(() =>
+ addManagedGitHubConnection('install'),
+ )
+ .catch((error: unknown) =>
+ notifyError(
+ "Couldn't start the GitHub installation.",
+ error,
+ ),
+ )
+ .finally(() => setAddingConnection(false))
+ }}
+ >
+ {addingConnection ? (
+ <Loader2 className="size-4 animate-spin" />
+ ) : (
+ <GithubMark className="size-4" />
+ )}
+ Add GitHub connection
+ </Button>
+ )}
+ </div>
+ )}
+ {!status.data?.app ? (
+ <p className="text-destructive text-sm">
+ The managed GitHub App is not configured in this environment.
+ </p>
+ ) : null}
+ </PanelContent>
+ </Panel>
+
+ <Panel>
+ <PanelHeader>
+ <div>
+ <PanelTitle>Runtime credential warning</PanelTitle>
+ <PanelDescription className="mt-1 max-w-3xl">
+ When a deployed agent uses this connection, OpenComputer mints a
+ GitHub installation token with the permissions declared in code.
+ The token is available inside that agent’s sandbox for the
+ operation and expires after about one hour. Code running in the
+ sandbox can read it, so only install the App on repositories you
+ are comfortable granting to the agent.
+ </PanelDescription>
+ </div>
+ </PanelHeader>
+ </Panel>
+ </div>
+ )
+}
diff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.ts
index 4d834f11..cb5cce66 100644
--- a/web/src/managed-agents/api.ts
+++ b/web/src/managed-agents/api.ts
@@ -248,6 +248,39 @@ const runtimeVariablesResponseSchema = z.object({
variables: z.array(runtimeVariableSchema),
})
+const githubInstallationSchema = z.object({
+ id: z.string(),
+ githubInstallationId: z.number(),
+ accountLogin: z.string(),
+ accountType: z.string(),
+ repositorySelection: z.enum(['all', 'selected']),
+ state: z.enum(['active', 'suspended', 'deleted']),
+ createdAt: z.string(),
+ updatedAt: z.string(),
+})
+
+const githubStatusSchema = z.object({
+ environments: z.array(
+ z.object({
+ environment: z.enum(['development', 'production']),
+ state: z.enum(['not_connected', 'active', 'suspended', 'deleted']),
+ installation: githubInstallationSchema.optional(),
+ }),
+ ),
+ connections: z.array(githubInstallationSchema),
+ app: z.object({ slug: z.string() }).nullable(),
+})
+
+const githubConnectionsSchema = z.object({
+ connections: z.array(githubInstallationSchema),
+ app: z.object({ slug: z.string() }).nullable(),
+})
+
+const githubConnectSchema = z.object({
+ installUrl: z.string().url(),
+ authorizeUrl: z.string().url(),
+})
+
const connectionSchema = z.object({
id: z.string(),
kind: z.enum(['tool', 'channel']),
@@ -734,6 +767,69 @@ export async function getManagedProject(projectId: string) {
)
}
+export async function getManagedGitHubStatus(projectId: string) {
+ return apiFetch(
+ `/managed-agents/projects/${encodeURIComponent(projectId)}/github`,
+ undefined,
+ githubStatusSchema,
+ )
+}
+
+export async function connectManagedGitHub(input: {
+ projectId: string
+ environments: Array<'development' | 'production'>
+}) {
+ return apiFetch(
+ `/managed-agents/projects/${encodeURIComponent(input.projectId)}/github/connect`,
+ {
+ method: 'POST',
+ body: JSON.stringify({ environments: input.environments }),
+ },
+ githubConnectSchema,
+ )
+}
+
+export async function getManagedGitHubConnections() {
+ return apiFetch('/managed-agents/github', undefined, githubConnectionsSchema)
+}
+
+export async function addManagedGitHubConnection(mode: 'install' | 'existing') {
+ const result = await apiFetch(
+ '/managed-agents/github/connect',
+ { method: 'POST', body: '{}' },
+ githubConnectSchema,
+ )
+ return mode === 'existing' ? result.authorizeUrl : result.installUrl
+}
+
+export async function attachManagedGitHub(input: {
+ projectId: string
+ environment: 'development' | 'production'
+ connectionId: string
+}) {
+ return apiFetch(
+ `/managed-agents/projects/${encodeURIComponent(input.projectId)}/github/attach`,
+ {
+ method: 'POST',
+ body: JSON.stringify({
+ environment: input.environment,
+ connectionId: input.connectionId,
+ }),
+ },
+ z.object({ attached: z.boolean() }),
+ )
+}
+
+export async function disconnectManagedGitHub(input: {
+ projectId: string
+ environment: 'development' | 'production'
+}) {
+ return apiFetch<void>(
+ `/managed-agents/projects/${encodeURIComponent(input.projectId)}/github?environment=${input.environment}`,
+ { method: 'DELETE' },
+ )
+}
+
export async function getManagedModelAccessConnections() {
return (
await apiFetch(
diff --git a/web/src/managed-agents/authorization-window.ts b/web/src/managed-agents/authorization-window.ts
new file mode 100644
index 00000000..9b6b03b3
--- /dev/null
+++ b/web/src/managed-agents/authorization-window.ts
@@ -0,0 +1,30 @@
+export function openAuthorizationWindow() {
+ const authorizationWindow = window.open('about:blank', '_blank')
+ if (!authorizationWindow) {
+ throw new Error('Allow pop-ups for OpenComputer, then try again.')
+ }
+ authorizationWindow.opener = null
+ authorizationWindow.document.title = 'Connecting · OpenComputer'
+ authorizationWindow.document.body.textContent =
+ 'Opening secure authorization…'
+ return authorizationWindow
+}
+
+export function navigateAuthorizationWindow(
+ authorizationWindow: Window,
+ authorizationUrl: string,
+) {
+ authorizationWindow.location.replace(authorizationUrl)
+}
+
+export async function launchAuthorizationWindow(
+ authorizationUrl: () => Promise<string>,
+) {
+ const authorizationWindow = openAuthorizationWindow()
+ try {
+ navigateAuthorizationWindow(authorizationWindow, await authorizationUrl())
+ } catch (error) {
+ authorizationWindow.close()
+ throw error
+ }
+}