Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4598,6 +4598,7 @@ export interface operations {
credentialStatus: "connected";
/** @default [] */
accountTags: string[];
tags?: string[];
/** @enum {string} */
agentKind?: "codex" | "claude" | "pi";
/** @default [] */
Expand Down Expand Up @@ -4842,6 +4843,7 @@ export interface operations {
credentialStatus: "connected";
/** @default [] */
accountTags: string[];
tags?: string[];
/** @enum {string} */
agentKind?: "codex" | "claude" | "pi";
/** @default [] */
Expand All @@ -4855,6 +4857,7 @@ export interface operations {
credentialStatus: "connected";
/** @default [] */
accountTags: string[];
tags?: string[];
/** @enum {string} */
agentKind?: "codex" | "claude" | "pi";
/** @default [] */
Expand Down Expand Up @@ -7670,10 +7673,11 @@ export interface operations {
integrations: {
/** Format: uuid */
id: string;
credentialId: string;
name: string;
description: string | null;
/** @enum {string} */
kind: "bearer" | "github" | "linear" | "model";
kind: "bearer" | "github" | "linear" | "model" | "fly" | "exe" | "amp" | "clickup" | "x";
/** @enum {string} */
policy: "baseline" | "requestable" | "disabled";
available: boolean;
Expand Down Expand Up @@ -7824,10 +7828,11 @@ export interface operations {
integrations: {
/** Format: uuid */
id: string;
credentialId: string;
name: string;
description: string | null;
/** @enum {string} */
kind: "bearer" | "github" | "linear" | "model";
kind: "bearer" | "github" | "linear" | "model" | "fly" | "exe" | "amp" | "clickup" | "x";
/** @enum {string} */
policy: "baseline" | "requestable" | "disabled";
available: boolean;
Expand Down Expand Up @@ -7876,10 +7881,11 @@ export interface operations {
integrations: {
/** Format: uuid */
id: string;
credentialId: string;
name: string;
description: string | null;
/** @enum {string} */
kind: "bearer" | "github" | "linear" | "model";
kind: "bearer" | "github" | "linear" | "model" | "fly" | "exe" | "amp" | "clickup" | "x";
/** @enum {string} */
policy: "baseline" | "requestable" | "disabled";
available: boolean;
Expand Down
71 changes: 71 additions & 0 deletions packages/api/migrations/0059_all_proxy_integration_policies.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
-- All outbound API credentials share the agent integration registry and policy.
-- Tail signing secrets authenticate inbound webhooks and are deliberately excluded.
ALTER TABLE app.agent_integrations DROP CONSTRAINT agent_integrations_kind_check;
ALTER TABLE app.agent_integrations ADD CONSTRAINT agent_integrations_kind_check
CHECK(kind IN ('bearer','github','linear','model','fly','exe','amp','clickup','x'));

CREATE FUNCTION app.agent_connection_changed() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE
t uuid; connection_kind text; k text; c text; n text; d text;
BEGIN
IF TG_OP='DELETE' THEN t=OLD.tenant_id; connection_kind=OLD.kind;
ELSE t=NEW.tenant_id; connection_kind=NEW.kind; END IF;
IF connection_kind IN ('linear','clickup') THEN
k=connection_kind; c=connection_kind;
n=CASE k WHEN 'linear' THEN 'Linear' ELSE 'ClickUp' END;
d=CASE k WHEN 'linear' THEN 'Linear GraphQL API' ELSE 'ClickUp API' END;
ELSIF connection_kind LIKE 'exe:%' THEN
k='exe'; c=substring(connection_kind FROM 5); n='exe.dev · '||c; d='exe.dev account API';
ELSIF connection_kind LIKE 'amp:%' THEN
k='amp'; c=substring(connection_kind FROM 5); n='Amp · '||c; d='Amp project API';
ELSE RETURN NULL;
END IF;
PERFORM app.sync_agent_integration(t,k,c,n,d,TG_OP<>'DELETE');
RETURN NULL;
END;
$$;
DROP TRIGGER agent_linear_sync ON app.connections;
CREATE TRIGGER agent_connection_sync AFTER INSERT OR UPDATE OR DELETE ON app.connections
FOR EACH ROW EXECUTE FUNCTION app.agent_connection_changed();

CREATE FUNCTION app.agent_fly_changed() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP='DELETE' THEN
PERFORM app.sync_agent_integration(OLD.tenant_id,'fly','fly','Fly.io · '||OLD.organization_name,'Fly Machines API',false);
ELSE
-- Switching organizations revokes prior approvals, just like disconnecting.
IF TG_OP='UPDATE' AND OLD.organization_slug<>NEW.organization_slug THEN
PERFORM app.sync_agent_integration(OLD.tenant_id,'fly','fly','Fly.io · '||OLD.organization_name,'Fly Machines API',false);
END IF;
PERFORM app.sync_agent_integration(NEW.tenant_id,'fly','fly','Fly.io · '||NEW.organization_name,'Fly Machines API',true);
END IF;
RETURN NULL;
END;
$$;
CREATE TRIGGER agent_fly_sync AFTER INSERT OR UPDATE OR DELETE ON app.fly_connections
FOR EACH ROW EXECUTE FUNCTION app.agent_fly_changed();

INSERT INTO app.agent_integrations(tenant_id,kind,credential_id,name,description,available)
SELECT tenant_id,
CASE WHEN kind='clickup' THEN 'clickup' WHEN kind LIKE 'exe:%' THEN 'exe' ELSE 'amp' END,
CASE WHEN kind='clickup' THEN kind ELSE substring(kind FROM 5) END,
CASE WHEN kind='clickup' THEN 'ClickUp' WHEN kind LIKE 'exe:%' THEN 'exe.dev · '||substring(kind FROM 5) ELSE 'Amp · '||substring(kind FROM 5) END,
CASE WHEN kind='clickup' THEN 'ClickUp API' WHEN kind LIKE 'exe:%' THEN 'exe.dev account API' ELSE 'Amp project API' END,true
FROM app.connections WHERE kind='clickup' OR kind LIKE 'exe:%' OR kind LIKE 'amp:%';
INSERT INTO app.agent_integrations(tenant_id,kind,credential_id,name,description,available)
SELECT tenant_id,'fly','fly','Fly.io · '||organization_name,'Fly Machines API',true FROM app.fly_connections;
CREATE FUNCTION app.agent_x_changed() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP='DELETE' THEN
PERFORM app.sync_agent_integration(OLD.tenant_id,'x',OLD.id::text,'X · '||OLD.name,'X API v2',false);
ELSE
PERFORM app.sync_agent_integration(NEW.tenant_id,'x',NEW.id::text,'X · '||NEW.name,'X API v2',NEW.status='connected');
END IF;
RETURN NULL;
END;
$$;
CREATE TRIGGER agent_x_sync AFTER INSERT OR UPDATE OR DELETE ON app.x_connections
FOR EACH ROW EXECUTE FUNCTION app.agent_x_changed();
INSERT INTO app.agent_integrations(tenant_id,kind,credential_id,name,description,available)
SELECT tenant_id,'x',id::text,'X · '||name,'X API v2',status='connected' FROM app.x_connections;
INSERT INTO app.schema_migrations(version) VALUES ('0059_all_proxy_integration_policies') ON CONFLICT DO NOTHING;
2 changes: 1 addition & 1 deletion packages/api/src/agent-api-contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ export const integrationScopePattern = /^integration:([0-9a-f]{8}-[0-9a-f]{4}-[0
export const isIntegrationScope = (scope: string) => integrationScopePattern.test(scope);
export const integrationRef = z.uuid();
export const apiPolicyInput = z.object({ policy: z.enum(["baseline", "requestable", "disabled"]), expectedRevision: z.number().int().positive() }).strict();
export const apiPolicy = z.object({ id: integrationRef, name: z.string(), description: z.string().nullable(), kind: z.enum(["bearer", "github", "linear", "model"]), policy: z.enum(["baseline", "requestable", "disabled"]), available: z.boolean(), revision: z.number().int(), requiredScope: z.string() });
export const apiPolicy = z.object({ id: integrationRef, credentialId: z.string(), name: z.string(), description: z.string().nullable(), kind: z.enum(["bearer", "github", "linear", "model", "fly", "exe", "amp", "clickup", "x"]), policy: z.enum(["baseline", "requestable", "disabled"]), available: z.boolean(), revision: z.number().int(), requiredScope: z.string() });
export const apiPolicyList = z.object({ integrations: z.array(apiPolicy) });
export const apiReflection = z.object({ identity: z.object({ id: z.uuid(), kind: z.enum(["oauth", "run"]) }), scopes: z.array(z.string()), integrations: z.array(apiPolicy.extend({ access: z.enum(["granted", "requestable", "unavailable"]), instructions: z.string() })) });
export const requestApiInput = z.object({
Expand Down
25 changes: 20 additions & 5 deletions packages/api/src/agent-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ import type { z } from "zod";
export class AgentApiError extends Error {
constructor(readonly status: number, readonly code: string, message: string, readonly scope?: string) { super(message); }
}
export type AgentIntegration = {id: string; kind: "bearer" | "model" | "github" | "linear"; credential_id: string; name: string; description: string | null; available: boolean; policy: "baseline" | "requestable" | "disabled"; epoch: number; revision: number};
export type AgentIntegration = {id: string; kind: "bearer" | "model" | "github" | "linear" | "fly" | "exe" | "amp" | "clickup" | "x"; credential_id: string; name: string; description: string | null; available: boolean; policy: "baseline" | "requestable" | "disabled"; epoch: number; revision: number};
export const requiredIntegrationScope = (row: AgentIntegration) => `integration:${row.id}:${row.epoch}`;
const STORAGE_BLOCK_BYTES = 1024 * 1024;
const forbidden = () => new AgentApiError(403, "forbidden", "This integration is not authorized.");
const invalidIdentity = () => new AgentApiError(401, "invalid_token", "The agent authorization is no longer active.");
const publicIntegration = (row: AgentIntegration) => ({ id: row.id, kind: row.kind, name: row.name, description: row.description, available: row.available, policy: row.policy, revision: row.revision, requiredScope: requiredIntegrationScope(row) });
const publicIntegration = (row: AgentIntegration) => ({ id: row.id, kind: row.kind, credentialId: row.credential_id, name: row.name, description: row.description, available: row.available, policy: row.policy, revision: row.revision, requiredScope: requiredIntegrationScope(row) });

/** Restrict the generic X v2 proxy to resources with an explicit OAuth-scope
* mapping. Unsupported resources and credential-management routes fail closed. */
Expand Down Expand Up @@ -83,8 +83,11 @@ export class AgentApiService {
case "bearer": return Array.isArray(config.portableIntegrationIds) && config.portableIntegrationIds.includes(row.credential_id);
case "github": return Array.isArray(config.githubInstallationIds) && config.githubInstallationIds.includes(Number(row.credential_id));
case "linear": return config.linearConnectionId === "linear";
case "x": return Array.isArray(config.xConnectionIds) && config.xConnectionIds.includes(row.credential_id);
case "model": return config.modelAccess === "portable" && config.modelAccountId === row.credential_id;
}
// Execution-provider credentials are not implicitly selected by a run.
return false;
}
async authorize(integration: string) {
const identity = await this.identity();
Expand All @@ -111,12 +114,13 @@ export class AgentApiService {
if (!(error instanceof AgentApiError) || error.status === 401) throw error;
access = error.code === "insufficient_scope" ? "requestable" : "unavailable";
}
result.push({...publicIntegration(row), access, instructions: row.kind === "linear" ? "Use request_api with path /graphql and a JSON GraphQL body." : row.kind === "model" ? "Use request_api with an OpenAI-compatible path relative to /v1." : "Use request_api with a relative API path and query. Access covers this integration, bounded by the upstream credential permissions."});
result.push({...publicIntegration(row), access, instructions: row.kind === "x" ? "Use request_api with an X API v2 path, such as /2/users/me. Only granted OAuth scopes and supported resources are available." : row.kind === "linear" ? "Use request_api with path /graphql and a JSON GraphQL body." : row.kind === "exe" ? "Use request_api with POST /exec and a text/plain exe.dev command body." : row.kind === "amp" ? "Use request_api with a path relative to the configured Amp API base." : row.kind === "clickup" ? "Use request_api with a path relative to /api/v2." : row.kind === "fly" ? "Use request_api with a Fly Machines API path, such as /v1/apps." : row.kind === "model" ? "Use request_api with an OpenAI-compatible path relative to /v1." : "Use request_api with a relative API path and query. Access covers this integration, bounded by the upstream credential permissions."});
}
return {identity: {id: identity.id, kind: identity.kind}, scopes: normalizeScopes(this.auth.scopes), integrations: result};
}
async forward(integration: string, path: string, request: Request) {
const grant = await this.authorize(integration);
if (grant.integration.kind === "x") return this.forwardX(grant.integration.credential_id, path, request);
let credential;
try { credential = await resolveAgentCredential(this.env, this.auth.tenantId, grant.integration.kind, grant.integration.credential_id, path); }
catch { throw new AgentApiError(502, "credential_unavailable", "The upstream credential could not be resolved."); }
Expand All @@ -129,7 +133,14 @@ export class AgentApiService {
}
async forwardX(connectionId: string, path: string, request: Request) {
const identity = await this.identity();
if (identity.kind !== "run" || !Array.isArray(identity.config?.xConnectionIds) || !identity.config.xConnectionIds.includes(connectionId)) throw forbidden();
let apiGrant: {integration: AgentIntegration} | undefined;
if (identity.kind === "run") {
if (!Array.isArray(identity.config?.xConnectionIds) || !identity.config.xConnectionIds.includes(connectionId)) throw forbidden();
} else {
const row = (await this.database.pool.query<{id: string}>("SELECT id FROM app.agent_integrations WHERE tenant_id=$1 AND kind='x' AND credential_id=$2", [this.auth.tenantId, connectionId])).rows[0];
if (!row) throw forbidden();
apiGrant = await this.authorize(row.id);
}
const required = xRequiredScope(path, request.method);
if (!required) throw forbidden();
const repository = new XConnectionRepository(this.database, this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY);
Expand Down Expand Up @@ -159,7 +170,11 @@ export class AgentApiService {
if (!accessToken) throw forbidden();
const currentIdentity = await this.identity();
const current = await repository.get(connectionId);
if (currentIdentity.kind !== "run" || !Array.isArray(currentIdentity.config?.xConnectionIds) || !currentIdentity.config.xConnectionIds.includes(connectionId) || current?.status !== "connected" || !current.scopes.includes(required) || !current.grantedScopes.includes(required)) throw forbidden();
if (apiGrant) {
const currentGrant = await this.authorize(apiGrant.integration.id);
if (currentGrant.integration.epoch !== apiGrant.integration.epoch) throw forbidden();
} else if (currentIdentity.kind !== "run" || !Array.isArray(currentIdentity.config?.xConnectionIds) || !currentIdentity.config.xConnectionIds.includes(connectionId)) throw forbidden();
if (current?.status !== "connected" || !current.scopes.includes(required) || !current.grantedScopes.includes(required)) throw forbidden();
try { return await forwardRunOutbound(request, { origin: "https://api.x.com", path: path, credential: accessToken }); }
catch { throw new AgentApiError(502, "proxy_failed", "The X API request failed. Check X API access, credits, and rate limits, then retry if safe."); }
}
Expand Down
29 changes: 29 additions & 0 deletions packages/api/src/agent-credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,40 @@ import { CredentialRepository } from "./postgres/credential-repository";
import { resolveRunProviderCredentials } from "./provider-credentials";
import type { OutboundCredential } from "./run-outbound-forwarder";
import { resolveManagedModelCredential } from "./managed-model-credentials";
import { CLICKUP_API_BASE } from "./clickup";
import { ConnectionRepository } from "./postgres/connection-repository";
import { FlyConnectionRepository } from "./postgres/fly-connection-repository";
import { isPublicHttpsOrigin } from "./public-address";

/** Only call after shared identity/grant authorization. No caller origin or secret. */
export async function resolveAgentCredential(env: Env, tenantId: string, kind: string, credentialId: string, relativePath: string): Promise<OutboundCredential | null> {
const database = databaseFor(env);
if (kind === "fly") {
if (credentialId !== "fly") return null;
const token = await new FlyConnectionRepository(database, tenantId, env.CREDENTIAL_ENCRYPTION_KEY).token();
return token ? {origin: "https://api.machines.dev", path: relativePath, credential: token} : null;
}
if (kind === "exe" || kind === "amp" || kind === "clickup") {
if (kind === "clickup" && credentialId !== "clickup") return null;
const connection = await new ConnectionRepository(database, tenantId, env.CREDENTIAL_ENCRYPTION_KEY)
.get<{apiToken?: string; accessToken?: string; apiBaseUrl?: string}>(kind === "clickup" ? kind : `${kind}:${credentialId}`);
const credential = kind === "exe" ? connection?.apiToken : connection?.accessToken;
if (!credential) return null;
if (kind === "exe") return {origin: "https://exe.dev", path: relativePath, credential};
if (kind === "clickup") {
const base = new URL(CLICKUP_API_BASE), target = new URL(`${CLICKUP_API_BASE}${relativePath}`);
if (!target.pathname.startsWith(`${base.pathname}/`)) return null;
return {origin: target.origin, path: `${target.pathname}${target.search}`, credential, authorization: "raw"};
}
const base = new URL(connection?.apiBaseUrl || "https://ampcode.com/api/cloud/v1");
if (!isPublicHttpsOrigin(base.origin, env.APP_ORIGIN) || base.username || base.password || base.search || base.hash) return null;
const prefix = base.pathname.replace(/\/$/, "");
const target = new URL(`${base.origin}${prefix}${relativePath}`);
// Relative dot segments must not escape the configured API prefix.
if (!target.pathname.startsWith(`${prefix}/`)) return null;
return {origin: base.origin, path: `${target.pathname}${target.search}`, credential};
}
if (!["bearer", "github", "linear", "model"].includes(kind)) return null;
const modelAccountId = credentialId;
const prefix = kind === "bearer" ? `/integrations/${credentialId}` : kind === "github" ? `/providers/github/${credentialId}` : kind === "linear" ? "/providers/linear" : "/providers/model/v1";
const separator = relativePath.indexOf("?");
Expand Down
4 changes: 3 additions & 1 deletion packages/api/src/clickup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@ export function matchingClickUpTask(task: ClickUpTask, listId: string, rules: Ma
});
}

export const CLICKUP_API_BASE = "https://api.clickup.com/api/v2";

export const clickUpHeaders = (token: string) => ({ Authorization: token, "Content-Type": "application/json" });

export async function clickUpJson(token: string, path: string): Promise<any> {
const response = await fetch(`https://api.clickup.com/api/v2${path}`, { headers: clickUpHeaders(token) });
const response = await fetch(`${CLICKUP_API_BASE}${path}`, { headers: clickUpHeaders(token) });
const body = await response.json().catch(() => ({})) as any;
if (!response.ok) throw new Error(body.err ?? body.error ?? `ClickUp request failed (${response.status})`);
return body;
Expand Down
Loading