@opengeni/api-router 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/app.d.ts +16 -0
  2. package/dist/app.js +35 -0
  3. package/dist/app.js.map +1 -0
  4. package/dist/chunk-XSYUDIX3.js +6331 -0
  5. package/dist/chunk-XSYUDIX3.js.map +1 -0
  6. package/dist/index.d.ts +19 -0
  7. package/dist/index.js +567 -0
  8. package/dist/index.js.map +1 -0
  9. package/package.json +74 -0
  10. package/src/app.ts +351 -0
  11. package/src/auth/managed-auth.ts +237 -0
  12. package/src/http/auth.ts +92 -0
  13. package/src/http/common.ts +16 -0
  14. package/src/http/sse.ts +89 -0
  15. package/src/index.ts +362 -0
  16. package/src/mcp/documents.ts +57 -0
  17. package/src/mcp/server.ts +961 -0
  18. package/src/mcp/session-view.ts +281 -0
  19. package/src/routes/api-keys.ts +65 -0
  20. package/src/routes/billing.ts +495 -0
  21. package/src/routes/capabilities.ts +80 -0
  22. package/src/routes/codex.ts +393 -0
  23. package/src/routes/documents.ts +185 -0
  24. package/src/routes/enrollments.ts +357 -0
  25. package/src/routes/environments.ts +175 -0
  26. package/src/routes/files.ts +148 -0
  27. package/src/routes/github.ts +341 -0
  28. package/src/routes/install.ts +218 -0
  29. package/src/routes/machines.ts +107 -0
  30. package/src/routes/packs.ts +241 -0
  31. package/src/routes/scheduled-tasks.ts +126 -0
  32. package/src/routes/sessions.ts +1083 -0
  33. package/src/routes/social.ts +119 -0
  34. package/src/routes/workspaces.ts +206 -0
  35. package/src/sandbox/access.ts +89 -0
  36. package/src/sandbox/auth-callout.ts +178 -0
  37. package/src/sandbox/channel-a.ts +265 -0
  38. package/src/sandbox/enrollment.ts +498 -0
  39. package/src/sandbox/machines.ts +255 -0
  40. package/src/sandbox/metrics-ingestion.ts +289 -0
  41. package/src/sandbox/viewer.ts +993 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/sandbox/auth-callout.ts","../src/sandbox/metrics-ingestion.ts"],"sourcesContent":["import { dbSearchPath, getSettings, resolveNatsCalloutConfig, resolveNatsControlPlaneAuth, retryStartupDependency, startupRetryOptions } from \"@opengeni/config\";\nimport type { ScheduledTask, ScheduledTaskOverlapPolicy, ScheduledTaskScheduleSpec } from \"@opengeni/contracts\";\nimport { createDb } from \"@opengeni/db\";\nimport { createNatsEventBus, type ResponderConnection } from \"@opengeni/events\";\nimport { createObservability, logStartupDependencyRetry } from \"@opengeni/observability\";\nimport { Connection, Client as TemporalClient, ScheduleNotFoundError, ScheduleOverlapPolicy, WorkflowExecutionAlreadyStartedError } from \"@temporalio/client\";\nimport type { ScheduleOptions, ScheduleSpec, ScheduleUpdateOptions } from \"@temporalio/client\";\nimport { createApp, type DocumentIndexClient, type SessionWorkflowClient } from \"./app\";\nimport { startAuthCalloutResponder } from \"./sandbox/auth-callout\";\nimport { startHelloIngestion, startMetricsIngestion } from \"./sandbox/metrics-ingestion\";\n\n/**\n * A REJECT_DUPLICATE start collides on the deterministic workflowId when the\n * same manual trigger token fires twice. Temporal surfaces that as\n * WorkflowExecutionAlreadyStartedError; the caller treats it as an idempotent\n * no-op rather than a failure.\n */\nfunction isWorkflowAlreadyStarted(error: unknown): boolean {\n return error instanceof WorkflowExecutionAlreadyStartedError;\n}\n\nconst TEMPORAL_MONTHS = [\n \"JANUARY\",\n \"FEBRUARY\",\n \"MARCH\",\n \"APRIL\",\n \"MAY\",\n \"JUNE\",\n \"JULY\",\n \"AUGUST\",\n \"SEPTEMBER\",\n \"OCTOBER\",\n \"NOVEMBER\",\n \"DECEMBER\",\n] as const;\n\nexport async function createTemporalWorkflowClient(settings: ReturnType<typeof getSettings>): Promise<{\n client: SessionWorkflowClient;\n documentIndexer: DocumentIndexClient;\n close: () => Promise<void>;\n}> {\n const connection = await Connection.connect({ address: settings.temporalHost });\n const temporal = new TemporalClient({\n connection,\n namespace: settings.temporalNamespace,\n });\n const client: SessionWorkflowClient = {\n signalUserMessage: async ({ eventId, workflowId }) => {\n await temporal.workflow.getHandle(workflowId).signal(\"userMessage\", eventId);\n },\n wakeSessionWorkflow: async ({ accountId, workspaceId, sessionId, workflowId }) => {\n await temporal.workflow.signalWithStart(\"sessionWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [{ accountId, workspaceId, sessionId }],\n signal: \"queueChanged\",\n });\n },\n signalApprovalDecision: async ({ eventId, workflowId }) => {\n await temporal.workflow.getHandle(workflowId).signal(\"approvalDecision\", eventId);\n },\n signalInterrupt: async ({ accountId, workspaceId, sessionId, eventId, workflowId }) => {\n // Start-or-signal: an interrupt POSTed while the session is idle has no\n // running workflow execution to signal, and getHandle().signal() would\n // throw WorkflowNotFoundError -> a 500 (the operator-can't-stop bug). Like\n // wakeSessionWorkflow, signalWithStart delivers the signal to a live run\n // when one exists and otherwise starts a fresh sessionWorkflow that picks\n // the buffered `interrupt` up immediately. ALLOW_DUPLICATE matches the\n // wake path so a running execution is reused rather than rejected.\n await temporal.workflow.signalWithStart(\"sessionWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [{ accountId, workspaceId, sessionId }],\n signal: \"interrupt\",\n signalArgs: [eventId],\n });\n },\n syncScheduledTask: async ({ task }) => {\n const schedule = temporal.schedule.getHandle(task.temporalScheduleId);\n const options = temporalScheduleOptions(task, settings.temporalTaskQueue);\n try {\n await schedule.update(() => temporalScheduleUpdateOptions(options));\n } catch (error) {\n if (!shouldCreateScheduleAfterUpdateError(error)) {\n throw error;\n }\n await temporal.schedule.create(options);\n }\n },\n deleteScheduledTaskSchedule: async ({ temporalScheduleId }) => {\n await temporal.schedule.getHandle(temporalScheduleId).delete().catch(() => undefined);\n },\n\t triggerScheduledTask: async ({ task, agentRunUsageIdempotencyKey, triggerWorkflowId }) => {\n\t // Deterministic workflowId (derived from the trigger token by the\n\t // caller) + REJECT_DUPLICATE makes a retried manual trigger idempotent:\n\t // the second start collides on the id and is rejected instead of\n\t // spawning a second run. The shared idempotency key dedupes the charge.\n\t const workflowId = triggerWorkflowId ?? `scheduled-task-${task.id}-manual-${crypto.randomUUID()}`;\n\t try {\n\t await temporal.workflow.start(\"scheduledTaskFireWorkflow\", {\n\t taskQueue: settings.temporalTaskQueue,\n\t workflowId,\n\t workflowIdReusePolicy: \"REJECT_DUPLICATE\",\n\t args: [{\n\t accountId: task.accountId,\n\t workspaceId: task.workspaceId,\n\t taskId: task.id,\n\t triggerType: \"manual\",\n\t agentRunUsageIdempotencyKey,\n\t }],\n\t });\n\t } catch (error) {\n\t // A duplicate trigger token started this run already; treat the retry\n\t // as a no-op so the (idempotent) usage charge stays the only effect.\n\t if (isWorkflowAlreadyStarted(error)) {\n\t return;\n\t }\n\t throw error;\n\t }\n\t },\n };\n const documentIndexer: DocumentIndexClient = {\n indexDocument: async ({ accountId, workspaceId, documentId }) => {\n const workflowId = `document-index-${documentId}-${crypto.randomUUID()}`;\n await temporal.workflow.start(\"documentIndexWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n args: [{ accountId, workspaceId, documentId }],\n });\n },\n };\n return {\n client,\n documentIndexer,\n close: async () => {\n await connection.close();\n },\n };\n}\n\nexport async function startApi() {\n const settings = getSettings();\n const observability = createObservability(settings, { component: \"api\" });\n // Step I: standalone → dbSchema unset → searchPath undefined → today's plain\n // handle (public). Embedded → scoped to the dedicated schema + the host's RLS\n // strategy.\n const searchPath = dbSearchPath(settings);\n const dbClient = createDb(settings.databaseUrl, {\n ...(searchPath ? { searchPath } : {}),\n rlsStrategy: settings.rlsStrategy,\n });\n let bus: Awaited<ReturnType<typeof createNatsEventBus>> | undefined;\n let workflowClient: Awaited<ReturnType<typeof createTemporalWorkflowClient>> | undefined;\n const retryOptions = startupRetryOptions(settings);\n const onRetry = (event: Parameters<typeof logStartupDependencyRetry>[1]) => logStartupDependencyRetry(observability, event);\n // The PRIVILEGED control-plane NATS login (M-AUTH): when the server runs with\n // auth_callout, api/worker authenticate as a static account user permitted to\n // request `agent.*.rpc`. Null in local dev (anonymous connect — the bus default).\n const controlPlaneAuth = resolveNatsControlPlaneAuth(settings);\n try {\n bus = await retryStartupDependency(\n \"NATS\",\n () =>\n createNatsEventBus(\n settings.natsUrl,\n controlPlaneAuth ? { user: controlPlaneAuth.user, pass: controlPlaneAuth.password } : undefined,\n ),\n {\n ...retryOptions,\n onRetry,\n },\n );\n workflowClient = await retryStartupDependency(\"Temporal\", () => createTemporalWorkflowClient(settings), {\n ...retryOptions,\n onRetry,\n });\n } catch (error) {\n await Promise.allSettled([\n bus?.close(),\n workflowClient?.close(),\n dbClient.close(),\n ]);\n throw error;\n }\n if (!bus || !workflowClient) {\n await dbClient.close();\n throw new Error(\"OpenGeni API startup dependencies were not initialized\");\n }\n const app = createApp({\n settings,\n db: dbClient.db,\n bus,\n workflowClient: workflowClient.client,\n documentIndexer: workflowClient.documentIndexer,\n observability,\n });\n const server = Bun.serve({\n hostname: settings.apiHost,\n port: settings.apiPort,\n idleTimeout: 255,\n fetch: app.fetch,\n });\n // M10 — start the metrics-ingestion consumer (agent heartbeats → DB last-sample\n // + downsampled series), gated on the selfhosted flag. A no-op when disabled.\n let stopMetricsIngestion: (() => void) | undefined;\n // Reconcile enrollments.has_display to the LIVE capability the agent reports in\n // its connect Hello (has_display was frozen at the enroll-time snapshot). Gated\n // on the same selfhosted flag.\n let stopHelloIngestion: (() => void) | undefined;\n // M-AUTH — start the NATS auth-callout responder (the tenancy boundary): it\n // validates an agent's enrollment bearer presented at NATS connect and mints a\n // workspace-scoped user JWT. Gated on the selfhosted flag + a resolvable callout\n // config; without the callout plane it never starts (selfhosted agents simply\n // cannot connect — graceful). It runs on its OWN connection (the callout auth\n // user), separate from the privileged control-plane bus.\n let authCalloutResponder: ResponderConnection | undefined;\n if (settings.sandboxSelfhostedEnabled) {\n stopMetricsIngestion = startMetricsIngestion({ db: dbClient.db, bus, observability });\n stopHelloIngestion = startHelloIngestion({ db: dbClient.db, bus, observability });\n observability.info(\"OpenGeni machine-metrics + hello ingestion consumers started\", {});\n\n const callout = resolveNatsCalloutConfig(settings);\n if (callout) {\n try {\n authCalloutResponder = await startAuthCalloutResponder(\n { db: dbClient.db, settings, callout, observability },\n settings.natsUrl,\n );\n } catch (error) {\n // A responder start failure must not crash the API (other planes work); log\n // loudly — selfhosted agents will fail to connect until it is up.\n observability.error(\"OpenGeni NATS auth-callout responder failed to start\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n } else {\n observability.warn(\n \"OpenGeni selfhosted enabled but the NATS auth-callout plane is not configured; selfhosted agents cannot connect\",\n {},\n );\n }\n }\n observability.info(\"OpenGeni API listening\", {\n host: settings.apiHost,\n port: settings.apiPort,\n });\n return {\n server,\n close: async () => {\n server.stop(true);\n stopMetricsIngestion?.();\n stopHelloIngestion?.();\n await Promise.allSettled([\n authCalloutResponder?.close(),\n bus.close(),\n workflowClient.close(),\n dbClient.close(),\n ]);\n },\n };\n}\n\nif (import.meta.main) {\n await startApi();\n}\n\nexport function temporalOverlapPolicy(policy: ScheduledTaskOverlapPolicy): ScheduleOverlapPolicy {\n if (policy === \"skip\") {\n return ScheduleOverlapPolicy.SKIP;\n }\n if (policy === \"buffer_one\") {\n return ScheduleOverlapPolicy.BUFFER_ONE;\n }\n return ScheduleOverlapPolicy.ALLOW_ALL;\n}\n\nexport function shouldCreateScheduleAfterUpdateError(error: unknown): boolean {\n return error instanceof ScheduleNotFoundError;\n}\n\nexport function temporalScheduleSpec(schedule: ScheduledTaskScheduleSpec): ScheduleSpec {\n if (schedule.type === \"interval\") {\n return {\n intervals: [{ every: `${schedule.everySeconds}s` }],\n ...(schedule.startAt ? { startAt: new Date(schedule.startAt) } : {}),\n ...(schedule.endAt ? { endAt: new Date(schedule.endAt) } : {}),\n };\n }\n if (schedule.type === \"calendar\") {\n return {\n calendars: [{\n hour: schedule.hour,\n minute: schedule.minute,\n second: 0,\n ...(schedule.daysOfWeek ? { dayOfWeek: schedule.daysOfWeek } : {}),\n }],\n timezone: schedule.timeZone,\n };\n }\n const runAt = new Date(schedule.runAt);\n return {\n calendars: [{\n year: runAt.getUTCFullYear(),\n month: temporalMonth(runAt.getUTCMonth()),\n dayOfMonth: runAt.getUTCDate(),\n hour: runAt.getUTCHours(),\n minute: runAt.getUTCMinutes(),\n second: runAt.getUTCSeconds(),\n }],\n timezone: \"UTC\",\n };\n}\n\nfunction temporalMonth(monthIndex: number) {\n return TEMPORAL_MONTHS[monthIndex]!;\n}\n\nfunction temporalScheduleOptions(task: ScheduledTask, taskQueue: string): ScheduleOptions {\n return {\n scheduleId: task.temporalScheduleId,\n spec: temporalScheduleSpec(task.schedule),\n action: {\n type: \"startWorkflow\",\n workflowType: \"scheduledTaskFireWorkflow\",\n taskQueue,\n args: [{\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n taskId: task.id,\n triggerType: \"scheduled\",\n }],\n },\n policies: {\n overlap: temporalOverlapPolicy(task.overlapPolicy),\n catchupWindow: \"24h\",\n pauseOnFailure: false,\n },\n state: {\n paused: task.status === \"paused\",\n ...(task.schedule.type === \"once\" ? { remainingActions: 1 } : {}),\n },\n memo: {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n scheduledTaskId: task.id,\n name: task.name,\n },\n };\n}\n\nfunction temporalScheduleUpdateOptions(options: ScheduleOptions): ScheduleUpdateOptions {\n return {\n spec: options.spec,\n action: options.action,\n ...(options.policies ? { policies: options.policies } : {}),\n state: options.state ?? {},\n ...(options.searchAttributes ? { searchAttributes: options.searchAttributes } : {}),\n ...(options.typedSearchAttributes ? { typedSearchAttributes: options.typedSearchAttributes } : {}),\n };\n}\n","// apps/api/src/sandbox/auth-callout.ts — the NATS AUTH-CALLOUT responder (the\n// bring-your-own-compute M-AUTH tenancy boundary; dossier §10.1 NATS Accounts per\n// workspace + §17 the isolation smoke + §19 the NATS-Accounts-misconfig leak risk).\n//\n// THE BOUNDARY THIS CLOSES: an external agent connects to NATS presenting its\n// `oge_` enrollment bearer as the connect auth-token. nats-server (configured with\n// `auth_callout`) issues an authorization request on $SYS.REQ.USER.AUTH. THIS\n// responder:\n// 1. decodes the authorization request (the `user_nkey` the response must scope\n// to, the `server_id` for the response `aud`, and the presented `auth_token`);\n// 2. VALIDATES the bearer with verifyEnrollmentBearer (HMAC, via\n// resolveEnrollmentSigningSecret) — an invalid/expired/forged bearer is denied;\n// 3. confirms the enrollment is still ACTIVE in the DB (a revoked machine is\n// denied even with a still-unexpired bearer);\n// 4. signs a NATS user JWT granting pub/sub ONLY `agent.<ws>.>` + `_INBOX.>`\n// (deny-all-else by an allow-list) and returns it inside a signed\n// authorization-response JWT.\n//\n// That per-subject scope is the per-workspace ISOLATION: workspace A's agent is\n// cryptographically incapable of pub/sub on `agent.B.>`. nats-server enforces the\n// signed permission set; the boundary does not rely on subject naming alone (the M4\n// transport test proved the CODE constructs scoped subjects; THIS proves the SERVER\n// refuses cross-workspace access).\n//\n// SECURITY (§18): the bearer value + the account signing seed are NEVER logged. A\n// validation failure → a DENIAL response (the server refuses the connection); a\n// responder error → the request is left UNANSWERED (fail-closed; the server denies\n// on its callout timeout). The bearer's `exp` caps the minted credential's life so a\n// revoked/expired enrollment cannot outlive its bearer.\n\nimport { resolveEnrollmentSigningSecret, type NatsCalloutConfig, type Settings } from \"@opengeni/config\";\nimport { verifyEnrollmentBearer } from \"@opengeni/contracts\";\nimport { getEnrollment, type Database } from \"@opengeni/db\";\nimport {\n createResponderConnection,\n decodeAuthRequest,\n mintAuthResponse,\n mintUserJwt,\n workspaceAgentPermissions,\n type ResponderConnection,\n} from \"@opengeni/events\";\nimport type { Observability } from \"@opengeni/observability\";\n\n/** The NATS subject nats-server publishes authorization requests on (ADR-26). */\nexport const AUTH_CALLOUT_SUBJECT = \"$SYS.REQ.USER.AUTH\";\n\nexport interface AuthCalloutDeps {\n db: Database;\n settings: Settings;\n callout: NatsCalloutConfig;\n observability?: Observability;\n}\n\n/**\n * The pure validate→scoped-JWT decision, isolated from the NATS transport so it is\n * unit-testable. Given the raw authorization-request JWT bytes, returns the signed\n * authorization-response JWT bytes to reply with — a GRANT (embedding a scoped user\n * JWT) on success, a DENIAL (carrying `nats.error`, no user JWT) otherwise. NEVER\n * throws on a bad/invalid request: every failure becomes a signed denial (the\n * server then refuses the connection cleanly).\n */\nexport async function handleAuthorizationRequest(\n deps: AuthCalloutDeps,\n requestBytes: Uint8Array,\n): Promise<Uint8Array> {\n const requestJwt = Buffer.from(requestBytes).toString(\"utf8\");\n const decoded = decodeAuthRequest(requestJwt);\n if (!decoded) {\n // A malformed request we cannot even read the user_nkey/server_id from — there\n // is nothing to scope a response to. Leave it for the server's timeout by\n // throwing (the transport leaves it unanswered, fail-closed).\n deps.observability?.warn?.(\"auth-callout: undecodable authorization request\", {});\n throw new Error(\"undecodable authorization request\");\n }\n\n const deny = (reason: string): Uint8Array => {\n // A SIGNED denial: the server reads `nats.error` and refuses the connection.\n const response = mintAuthResponse({\n userPublicKey: decoded.userNkey,\n serverId: decoded.serverId,\n accountSeed: deps.callout.accountSeed,\n error: reason,\n });\n return Buffer.from(response, \"utf8\");\n };\n\n const bearer = decoded.authToken;\n if (!bearer) {\n return deny(\"missing enrollment bearer\");\n }\n\n const secret = resolveEnrollmentSigningSecret(deps.settings);\n if (!secret) {\n // The credential plane is off for this deployment — deny rather than mint an\n // unscoped credential. (The responder should not even be running in this case,\n // but fail-closed regardless.)\n return deny(\"enrollment credential plane disabled\");\n }\n\n const claims = await verifyEnrollmentBearer(secret, bearer);\n if (!claims) {\n // Invalid signature / malformed / expired bearer. NEVER log the bearer value.\n deps.observability?.warn?.(\"auth-callout: rejected an invalid enrollment bearer\", {});\n return deny(\"invalid or expired enrollment bearer\");\n }\n\n // Confirm the enrollment is still ACTIVE — a revoked machine is denied even with a\n // still-unexpired bearer (the revoke path flips status; this re-checks at connect).\n const enrollment = await getEnrollment(deps.db, claims.workspaceId, claims.enrollmentId);\n if (!enrollment || enrollment.status !== \"active\") {\n deps.observability?.warn?.(\"auth-callout: denied a revoked or unknown enrollment\", {\n workspaceId: claims.workspaceId,\n agentId: claims.agentId,\n });\n return deny(\"enrollment is not active\");\n }\n\n // Belt-and-braces: the bearer's agentId/enrollmentId must match the row we found.\n // (verifyEnrollmentBearer already binds them; this guards a future schema where\n // agentId != enrollmentId.)\n if (enrollment.id !== claims.enrollmentId) {\n return deny(\"enrollment identity mismatch\");\n }\n\n // GRANT: a user JWT scoped to ONLY this workspace's agent subtree + the reply\n // inbox. This allow-list IS the per-workspace isolation boundary.\n const permissions = workspaceAgentPermissions(claims.workspaceId);\n const userJwt = mintUserJwt({\n userPublicKey: decoded.userNkey,\n accountSeed: deps.callout.accountSeed,\n name: claims.agentId,\n permissions,\n // Server-config-mode placement: the embedded user JWT's `aud` is the account\n // the user binds to (the configured `auth_callout.account`). All agents +\n // the privileged control plane share this account so subjects route; the\n // per-workspace isolation is carried by the subject permissions above.\n audienceAccount: deps.callout.accountName,\n // Tie the credential's life to the bearer's remaining life: a revoked/expired\n // enrollment cannot outlive its bearer at the NATS layer either.\n expiresAtSeconds: claims.exp,\n });\n const response = mintAuthResponse({\n userPublicKey: decoded.userNkey,\n serverId: decoded.serverId,\n accountSeed: deps.callout.accountSeed,\n userJwt,\n });\n deps.observability?.info?.(\"auth-callout: granted a workspace-scoped NATS credential\", {\n workspaceId: claims.workspaceId,\n agentId: claims.agentId,\n });\n return Buffer.from(response, \"utf8\");\n}\n\n/**\n * Start the auth-callout responder: open a SEPARATE NATS connection authenticated\n * as the callout `auth_users` user, subscribe $SYS.REQ.USER.AUTH, and answer every\n * authorization request via {@link handleAuthorizationRequest}. Returns a handle\n * whose `close()` drains the connection. Gated by the caller (sandboxSelfhostedEnabled\n * + a resolvable callout config); a deployment without the callout plane never starts\n * it.\n */\nexport async function startAuthCalloutResponder(\n deps: AuthCalloutDeps,\n natsUrl: string,\n): Promise<ResponderConnection> {\n const connection = await createResponderConnection(\n natsUrl,\n { kind: \"user-password\", user: deps.callout.user, pass: deps.callout.password },\n AUTH_CALLOUT_SUBJECT,\n (bytes) => handleAuthorizationRequest(deps, bytes),\n { name: \"opengeni-auth-callout\" },\n );\n deps.observability?.info?.(\"OpenGeni NATS auth-callout responder started\", {\n subject: AUTH_CALLOUT_SUBJECT,\n });\n return connection;\n}\n","// apps/api/src/sandbox/metrics-ingestion.ts — the M10 metrics INGESTION consumer\n// (dossier §10.7 + §10.6) + the connect-Hello DISPLAY-REFRESH consumer. The\n// enrolled agent piggybacks a `MetricsSample` on its ~5s heartbeat (an\n// `AgentEvent` published one-way on `agent.<ws>.<id>.events`) and publishes a\n// `Hello` (its live self-description) on `agent.<ws>.<id>.hello` on every connect\n// /reconnect. This module owns the two agent→control-plane inbound consumers:\n//\n// `agent.*.*.events` (heartbeat) →\n// 1. touchEnrollmentLastSeen — the liveness cursor (online/reconnecting/offline\n// derivation + the M3 probe disambiguation).\n// 2. ingestMachineMetricsSample — UPSERT machine_metrics_latest (the \"now\" row)\n// + APPEND a machine_metrics_series row downsampled to ~1/min.\n// A GOING-OFFLINE event is not a metrics point — liveness flips via the lease/\n// probe path; we skip it here (no-op).\n//\n// `agent.*.*.hello` (connect) →\n// refreshEnrollmentDisplay — reconcile `enrollments.has_display` to the LIVE\n// capability the Hello reports. `has_display` was previously FROZEN at the\n// enroll-time offer snapshot; a machine that GAINS a display later (a Mac that\n// grants Screen Recording, a box whose Xvfb starts) or LOSES one never\n// re-surfaced. Consuming the Hello's `capabilities.desktop` / `display` makes\n// `has_display` track reality (both directions), which the desktop-capability\n// gate (packages/runtime capabilities.ts) keys off.\n//\n// Both consumers are BEST-EFFORT and fail-soft: a decode/DB error for one message\n// is logged + swallowed (the bus subscription already swallows handler throws) so\n// a metrics blip / a display-refresh write failure never tears down the consumer,\n// back-pressures the agent, or breaks its connect.\n\nimport {\n getEnrollment,\n ingestMachineMetricsSample,\n setEnrollmentHasDisplay,\n touchEnrollmentLastSeen,\n type Database,\n type MachineMetricsSample,\n} from \"@opengeni/db\";\nimport type { EventBus } from \"@opengeni/events\";\nimport type { Observability } from \"@opengeni/observability\";\nimport { AgentEvent, Hello, type MetricsSample } from \"@opengeni/agent-proto\";\n\n/** The wildcard subject the agent event plane publishes heartbeats on. */\nexport const AGENT_EVENTS_SUBJECT = \"agent.*.*.events\";\n\n/** The wildcard subject the agent publishes its connect Hello on. */\nexport const AGENT_HELLO_SUBJECT = \"agent.*.*.hello\";\n\n/**\n * Parse `agent.<ws>.<id>.<tail>` → `{ workspaceId, agentId }`, requiring the\n * expected tail token. Returns null for a subject that does not match the shape\n * (defensive — the subscription pattern already constrains it).\n */\nfunction parseAgentSubject(subject: string, tail: \"events\" | \"hello\"): { workspaceId: string; agentId: string } | null {\n const parts = subject.split(\".\");\n if (parts.length !== 4 || parts[0] !== \"agent\" || parts[3] !== tail) {\n return null;\n }\n return { workspaceId: parts[1]!, agentId: parts[2]! };\n}\n\n/** Parse `agent.<ws>.<id>.events` → `{ workspaceId, agentId }` (heartbeat plane). */\nexport function parseAgentEventSubject(subject: string): { workspaceId: string; agentId: string } | null {\n return parseAgentSubject(subject, \"events\");\n}\n\n/** Parse `agent.<ws>.<id>.hello` → `{ workspaceId, agentId }` (connect plane). */\nexport function parseAgentHelloSubject(subject: string): { workspaceId: string; agentId: string } | null {\n return parseAgentSubject(subject, \"hello\");\n}\n\n/**\n * Project a wire `MetricsSample` (proto, ms-stamped, GPU as a repeated list) to\n * the DB `MachineMetricsSample`. The proto byte/count fields are protobuf-encoded\n * as decimal strings (uint64) on the TS side (ts-proto `string`); coerce to\n * numbers. The DB carries a single `gpuUtilPercent` + `gpuMemUsedBytes`/Total —\n * we take the FIRST GPU (the dashboard surfaces the primary accelerator); absent\n * GPUs stay null (the not-reported contract). A zero on a non-GPU field is the\n * agent's \"not reported\" (we keep it null-friendly via `nullIfZero` only for the\n * GPU plane; cpu/mem/disk 0 is a legitimate reading the dashboard shows as 0).\n */\nexport function wireSampleToDbSample(wire: MetricsSample): MachineMetricsSample {\n const num = (v: string | number): number => (typeof v === \"number\" ? v : Number(v));\n const firstGpu = wire.gpus[0];\n return {\n cpuPercent: wire.cpuPercent,\n load1: wire.load1,\n load5: wire.load5,\n load15: wire.load15,\n memUsedBytes: num(wire.memUsedBytes),\n memTotalBytes: num(wire.memTotalBytes),\n diskUsedBytes: num(wire.diskUsedBytes),\n diskTotalBytes: num(wire.diskTotalBytes),\n gpuUtilPercent: firstGpu ? firstGpu.utilPercent : null,\n gpuMemUsedBytes: firstGpu ? num(firstGpu.memUsedBytes) : null,\n gpuMemTotalBytes: firstGpu ? num(firstGpu.memTotalBytes) : null,\n contention: wire.runQueue,\n // The sample carries its own wall-clock stamp (epoch ms); fall back to now on\n // a missing/zero stamp so a series row is never NULL-dated.\n sampledAt: wire.sampledAtMs && Number(wire.sampledAtMs) > 0 ? new Date(Number(wire.sampledAtMs)) : new Date(),\n };\n}\n\n/**\n * Ingest ONE decoded heartbeat for an enrolled machine. Resolves the enrollment's\n * accountId (needed for the RLS-scoped writes) from the enrollment row; an\n * unknown/cross-workspace agentId is ignored (no row → no write). Touches\n * last-seen + upserts latest + downsamples the series.\n */\nexport async function ingestHeartbeat(\n db: Database,\n input: { workspaceId: string; agentId: string; sample: MetricsSample },\n): Promise<{ ingested: boolean; seriesAppended: boolean }> {\n // The enrollment row is the source of the accountId (the RLS principal) and the\n // existence check. A revoked machine still reports its accountId, so we ingest\n // (the dashboard shows its last sample); a truly unknown id is a no-op.\n const enrollment = await getEnrollment(db, input.workspaceId, input.agentId);\n if (!enrollment) {\n return { ingested: false, seriesAppended: false };\n }\n const sample = wireSampleToDbSample(input.sample);\n await touchEnrollmentLastSeen(db, {\n accountId: enrollment.accountId,\n workspaceId: input.workspaceId,\n enrollmentId: input.agentId,\n });\n const result = await ingestMachineMetricsSample(db, {\n accountId: enrollment.accountId,\n workspaceId: input.workspaceId,\n enrollmentId: input.agentId,\n sample,\n });\n return { ingested: true, seriesAppended: result.seriesAppended };\n}\n\n/**\n * Decode a raw `AgentEvent` payload + ingest it (the per-message handler). A\n * heartbeat carrying a metrics sample is ingested; a going-offline (or a\n * heartbeat without metrics) is a no-op. Decode failures are reported + swallowed.\n */\nexport async function handleAgentEventPayload(\n db: Database,\n observability: Observability | undefined,\n payload: Uint8Array,\n subject: string,\n): Promise<void> {\n const ids = parseAgentEventSubject(subject);\n if (!ids) {\n return;\n }\n let event: AgentEvent;\n try {\n event = AgentEvent.decode(payload);\n } catch (error) {\n observability?.warn?.(\"Failed to decode an agent event for metrics ingestion\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n if (event.event?.$case !== \"heartbeat\") {\n return; // going-offline / unknown → not a metrics point.\n }\n const metrics = event.event.heartbeat.metrics;\n if (!metrics) {\n return; // a heartbeat without a sample → liveness already touched elsewhere.\n }\n try {\n await ingestHeartbeat(db, { workspaceId: ids.workspaceId, agentId: ids.agentId, sample: metrics });\n } catch (error) {\n observability?.warn?.(\"Failed to ingest a machine metrics heartbeat\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\n/**\n * Start the metrics-ingestion consumer: subscribe `agent.*.*.events` and ingest\n * every heartbeat. Gated by sandboxSelfhostedEnabled (the caller checks the flag;\n * a disabled deployment never starts the consumer). Returns the unsubscribe fn.\n */\nexport function startMetricsIngestion(deps: {\n db: Database;\n bus: EventBus;\n observability?: Observability;\n}): () => void {\n return deps.bus.subscribeAgentEvents(AGENT_EVENTS_SUBJECT, (payload, subject) =>\n handleAgentEventPayload(deps.db, deps.observability, payload, subject),\n );\n}\n\n// ── Connect-Hello display refresh ─────────────────────────────────────────────\n\n/**\n * The LIVE display presence the agent's Hello reports: a desktop framebuffer is\n * available (`capabilities.desktop`, which the agent sets true only when a display\n * probes AND it can stream it) OR a `Display` detail is present. An unset\n * Capabilities (or a headless machine) → false. This is what `has_display` should\n * track, replacing the enroll-time snapshot.\n */\nexport function helloReportsDisplay(hello: Hello): boolean {\n const caps = hello.capabilities;\n if (!caps) {\n return false;\n }\n return caps.desktop === true || caps.display != null;\n}\n\n/**\n * Reconcile `enrollments.has_display` to the display presence a Hello reports.\n * Resolves the enrollment (the accountId is the RLS principal + the existence\n * check + the current value). A no-change Hello short-circuits BEFORE issuing any\n * write (and the DB writer is itself change-guarded as a backstop), so a steady\n * state never churns. An unknown/cross-workspace agentId is a no-op.\n */\nexport async function refreshEnrollmentDisplay(\n db: Database,\n input: { workspaceId: string; agentId: string; hasDisplay: boolean },\n): Promise<{ updated: boolean }> {\n const enrollment = await getEnrollment(db, input.workspaceId, input.agentId);\n if (!enrollment) {\n return { updated: false };\n }\n if (enrollment.hasDisplay === input.hasDisplay) {\n // Unchanged — do not even issue the UPDATE (no churn on a steady-state Hello).\n return { updated: false };\n }\n return await setEnrollmentHasDisplay(db, {\n accountId: enrollment.accountId,\n workspaceId: input.workspaceId,\n enrollmentId: input.agentId,\n hasDisplay: input.hasDisplay,\n });\n}\n\n/**\n * Decode a raw `Hello` payload + refresh the enrollment's display cursor (the\n * per-message handler for the hello plane). Decode failures + write failures are\n * reported + swallowed — a display refresh must NEVER break the agent's connect.\n */\nexport async function handleHelloPayload(\n db: Database,\n observability: Observability | undefined,\n payload: Uint8Array,\n subject: string,\n): Promise<void> {\n const ids = parseAgentHelloSubject(subject);\n if (!ids) {\n return;\n }\n let hello: Hello;\n try {\n hello = Hello.decode(payload);\n } catch (error) {\n observability?.warn?.(\"Failed to decode an agent Hello for display refresh\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n try {\n await refreshEnrollmentDisplay(db, {\n workspaceId: ids.workspaceId,\n agentId: ids.agentId,\n hasDisplay: helloReportsDisplay(hello),\n });\n } catch (error) {\n observability?.warn?.(\"Failed to refresh an enrollment's display from a Hello\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\n/**\n * Start the Hello display-refresh consumer: subscribe `agent.*.*.hello` and\n * reconcile `has_display` to the live capability the agent reports on every\n * connect. Gated by sandboxSelfhostedEnabled (the caller checks the flag). Returns\n * the unsubscribe fn.\n */\nexport function startHelloIngestion(deps: {\n db: Database;\n bus: EventBus;\n observability?: Observability;\n}): () => void {\n return deps.bus.subscribeAgentEvents(AGENT_HELLO_SUBJECT, (payload, subject) =>\n handleHelloPayload(deps.db, deps.observability, payload, subject),\n );\n}\n"],"mappings":";;;;;AAAA,SAAS,cAAc,aAAa,0BAA0B,6BAA6B,wBAAwB,2BAA2B;AAE9I,SAAS,gBAAgB;AACzB,SAAS,0BAAoD;AAC7D,SAAS,qBAAqB,iCAAiC;AAC/D,SAAS,YAAY,UAAU,gBAAgB,uBAAuB,uBAAuB,4CAA4C;;;ACyBzI,SAAS,sCAA6E;AACtF,SAAS,8BAA8B;AACvC,SAAS,qBAAoC;AAC7C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAIA,IAAM,uBAAuB;AAiBpC,eAAsB,2BACpB,MACA,cACqB;AACrB,QAAM,aAAa,OAAO,KAAK,YAAY,EAAE,SAAS,MAAM;AAC5D,QAAM,UAAU,kBAAkB,UAAU;AAC5C,MAAI,CAAC,SAAS;AAIZ,SAAK,eAAe,OAAO,mDAAmD,CAAC,CAAC;AAChF,UAAM,IAAI,MAAM,mCAAmC;AAAA,EACrD;AAEA,QAAM,OAAO,CAAC,WAA+B;AAE3C,UAAMA,YAAW,iBAAiB;AAAA,MAChC,eAAe,QAAQ;AAAA,MACvB,UAAU,QAAQ;AAAA,MAClB,aAAa,KAAK,QAAQ;AAAA,MAC1B,OAAO;AAAA,IACT,CAAC;AACD,WAAO,OAAO,KAAKA,WAAU,MAAM;AAAA,EACrC;AAEA,QAAM,SAAS,QAAQ;AACvB,MAAI,CAAC,QAAQ;AACX,WAAO,KAAK,2BAA2B;AAAA,EACzC;AAEA,QAAM,SAAS,+BAA+B,KAAK,QAAQ;AAC3D,MAAI,CAAC,QAAQ;AAIX,WAAO,KAAK,sCAAsC;AAAA,EACpD;AAEA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EAAE,kBAAkB,QAAQ,iBAAiB,IAAI,CAAC;AAAA,IACjF,GAAI,QAAQ,wBAAwB,EAAE,uBAAuB,QAAQ,sBAAsB,IAAI,CAAC;AAAA,EAClG;AACF;","names":["response","getEnrollment"]}
package/package.json ADDED
@@ -0,0 +1,74 @@
1
+ {
2
+ "name": "@opengeni/api-router",
3
+ "version": "0.2.0",
4
+ "description": "OpenGeni HTTP surface: the Hono adapter/router (createApp), routes, MCP HTTP transport, and HTTP access adapters over @opengeni/core. An engine-distribution surface — its runtime closure includes engine-internal packages.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Cloudgeni-ai/opengeni.git",
9
+ "directory": "apps/api"
10
+ },
11
+ "type": "module",
12
+ "main": "./dist/index.js",
13
+ "module": "./dist/index.js",
14
+ "types": "./dist/index.d.ts",
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "import": "./dist/index.js"
19
+ },
20
+ "./app": {
21
+ "types": "./dist/app.d.ts",
22
+ "import": "./dist/app.js"
23
+ }
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "src"
28
+ ],
29
+ "engines": {
30
+ "node": ">=18"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public",
34
+ "provenance": true
35
+ },
36
+ "scripts": {
37
+ "dev": "bun --watch src/index.ts",
38
+ "start": "bun src/index.ts",
39
+ "typecheck": "tsc --noEmit",
40
+ "build": "tsup"
41
+ },
42
+ "dependencies": {
43
+ "@aws-sdk/client-s3": "^3.1044.0",
44
+ "@aws-sdk/s3-request-presigner": "^3.1044.0",
45
+ "@hono/zod-validator": "^0.7.6",
46
+ "@modelcontextprotocol/sdk": "^1.29.0",
47
+ "@opengeni/agent-proto": "^0.2.0",
48
+ "@opengeni/codex": "^0.2.0",
49
+ "@opengeni/config": "^0.2.0",
50
+ "@opengeni/contracts": "^0.3.0",
51
+ "@opengeni/core": "^0.2.0",
52
+ "@opengeni/db": "^0.2.0",
53
+ "@opengeni/documents": "^0.2.0",
54
+ "@opengeni/events": "^0.2.0",
55
+ "@opengeni/github": "^0.2.0",
56
+ "@opengeni/observability": "^0.2.0",
57
+ "@opengeni/runtime": "^0.2.0",
58
+ "@opengeni/storage": "^0.2.0",
59
+ "@temporalio/client": "^1.17.0",
60
+ "better-auth": "^1.6.14",
61
+ "hono": "^4.12.18",
62
+ "pg": "^8.21.0",
63
+ "resend": "^6.12.4",
64
+ "stripe": "^22.2.0",
65
+ "zod": "^4.2.1"
66
+ },
67
+ "devDependencies": {
68
+ "@opengeni/testing": "workspace:*",
69
+ "@types/pg": "^8.20.0",
70
+ "postgres": "^3.4.7",
71
+ "tsup": "^8.5.0",
72
+ "typescript": "^6.0.3"
73
+ }
74
+ }
package/src/app.ts ADDED
@@ -0,0 +1,351 @@
1
+ import {
2
+ configuredAllowedModels,
3
+ configuredAllowedReasoningEfforts,
4
+ configuredModels,
5
+ } from "@opengeni/config";
6
+ import { ClientConfig } from "@opengeni/contracts";
7
+ import { createDocumentServices, indexDocumentNow, type DocumentServices } from "@opengeni/documents";
8
+ import { createObservability } from "@opengeni/observability";
9
+ import { createObjectStorage } from "@opengeni/storage";
10
+ import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
11
+ import { Hono } from "hono";
12
+ import { cors } from "hono/cors";
13
+ import { HTTPException } from "hono/http-exception";
14
+ import type { ApiRouteDeps, AppDependencies, ObjectStorageDependency, SessionWorkflowClient } from "@opengeni/core";
15
+ import { requireAccessGrant } from "@opengeni/core";
16
+ import { createManagedAuth } from "./auth/managed-auth";
17
+ import { createApiSandboxClient, makeResumeBoxById } from "./sandbox/access";
18
+ import { requireLimit } from "@opengeni/core";
19
+ import { buildOpenGeniMcpServer } from "./mcp/server";
20
+ import { requireAccessKey } from "./http/auth";
21
+ import { registerCapabilityRoutes } from "./routes/capabilities";
22
+ import { registerCodexRoutes } from "./routes/codex";
23
+ import { registerDocumentRoutes } from "./routes/documents";
24
+ import { registerEnrollmentRoutes } from "./routes/enrollments";
25
+ import { registerMachineRoutes } from "./routes/machines";
26
+ import { registerEnvironmentRoutes } from "./routes/environments";
27
+ import { registerFileRoutes } from "./routes/files";
28
+ import { registerApiKeyRoutes } from "./routes/api-keys";
29
+ import { registerBillingRoutes } from "./routes/billing";
30
+ import { registerGitHubRoutes } from "./routes/github";
31
+ import { registerInstallRoutes } from "./routes/install";
32
+ import { registerPackRoutes } from "./routes/packs";
33
+ import { registerScheduledTaskRoutes } from "./routes/scheduled-tasks";
34
+ import { registerSessionRoutes } from "./routes/sessions";
35
+ import { registerSocialRoutes } from "./routes/social";
36
+ import { registerWorkspaceRoutes } from "./routes/workspaces";
37
+
38
+ export type {
39
+ ApiRouteDeps,
40
+ AppDependencies,
41
+ DocumentIndexClient,
42
+ ObjectStorageDependency,
43
+ SessionWorkflowClient,
44
+ } from "@opengeni/core";
45
+ export {
46
+ mergeResourceRefs,
47
+ mergeToolRefs,
48
+ normalizeResources,
49
+ validateFileResources,
50
+ validateGitHubRepositorySelection,
51
+ validateGitHubRepositorySelectionShape,
52
+ validateToolRefs,
53
+ withDefaultEnabledCapabilityMcpTools,
54
+ } from "@opengeni/core";
55
+ export { workflowIdForSession } from "@opengeni/core";
56
+ export { replaySessionEvents, sseSessionStream } from "./http/sse";
57
+
58
+ export function createApp(deps: AppDependencies): Hono {
59
+ const managedAuth = deps.managedAuth ?? createManagedAuth(deps.settings, deps.db);
60
+ const objectStorage = createObjectStorage(deps.settings);
61
+ let documentServices: DocumentServices | null = deps.documentServices ?? null;
62
+ const getDocumentServices = () => {
63
+ documentServices ??= createDocumentServices(deps.settings);
64
+ return documentServices;
65
+ };
66
+ const documentIndexer = deps.documentIndexer ?? {
67
+ indexDocument: async ({ accountId, workspaceId, documentId }: { accountId: string; workspaceId: string; documentId: string }) => {
68
+ if (!objectStorage) {
69
+ throw new HTTPException(503, { message: "object storage is not configured" });
70
+ }
71
+ return await indexDocumentNow(deps.db, objectStorage, workspaceId, documentId, getDocumentServices(), {
72
+ beforeEmbed: async ({ chunkCount }) => {
73
+ await requireLimit(routeDeps, { accountId, workspaceId, action: "document:index", quantity: chunkCount });
74
+ },
75
+ });
76
+ },
77
+ };
78
+ // The API process's own agent-loop-free sandbox client — the API-direct
79
+ // control-plane seam. Constructed from settings (resumes boxes by id
80
+ // in-process) unless a client was injected (tests). resumeBoxById is always
81
+ // concrete for routes; it throws SandboxResumeError when sandboxBackend=none.
82
+ const sandboxClient = deps.sandboxClient ?? createApiSandboxClient(deps.settings);
83
+ const resumeBoxById = deps.resumeBoxById ?? makeResumeBoxById(sandboxClient);
84
+ const routeDeps: ApiRouteDeps = {
85
+ ...deps,
86
+ githubStateSecret: deps.githubStateSecret ?? deps.settings.githubAppManifestStateSecret ?? crypto.randomUUID(),
87
+ managedAuth,
88
+ objectStorage,
89
+ documentIndexer,
90
+ getDocumentServices,
91
+ ...(sandboxClient ? { sandboxClient } : {}),
92
+ resumeBoxById,
93
+ };
94
+ const app = new Hono();
95
+ const observability = deps.observability ?? createObservability(deps.settings, { component: "api" });
96
+
97
+ app.use("*", cors({
98
+ credentials: true,
99
+ origin: (origin) => {
100
+ if (!origin) {
101
+ return null;
102
+ }
103
+ return allowedCorsOrigin(deps.settings.corsAllowOriginRegex, origin) ? origin : null;
104
+ },
105
+ }));
106
+
107
+ app.use("*", async (c, next) => {
108
+ const url = new URL(c.req.url);
109
+ const route = routeLabel(url.pathname);
110
+ const start = performance.now();
111
+ const span = observability.startSpan(`HTTP ${c.req.method} ${route}`, {
112
+ "http.request.method": c.req.method,
113
+ "url.path": url.pathname,
114
+ "opengeni.route": route,
115
+ });
116
+ try {
117
+ await next();
118
+ const status = c.res.status || 200;
119
+ const durationSeconds = (performance.now() - start) / 1000;
120
+ observability.recordHttpRequest({ method: c.req.method, route, status, durationSeconds });
121
+ span.end({
122
+ attributes: {
123
+ "http.response.status_code": status,
124
+ "opengeni.duration_ms": Math.round(durationSeconds * 1000),
125
+ },
126
+ });
127
+ observability.info("HTTP request completed", {
128
+ method: c.req.method,
129
+ route,
130
+ status,
131
+ durationMs: Math.round(durationSeconds * 1000),
132
+ traceId: span.traceId,
133
+ spanId: span.spanId,
134
+ });
135
+ } catch (error) {
136
+ const status = httpStatusForError(error);
137
+ const durationSeconds = (performance.now() - start) / 1000;
138
+ observability.recordHttpRequest({ method: c.req.method, route, status, durationSeconds });
139
+ span.end({
140
+ attributes: {
141
+ "http.response.status_code": status,
142
+ "opengeni.duration_ms": Math.round(durationSeconds * 1000),
143
+ },
144
+ error,
145
+ });
146
+ observability.error("HTTP request failed", {
147
+ method: c.req.method,
148
+ route,
149
+ status,
150
+ durationMs: Math.round(durationSeconds * 1000),
151
+ traceId: span.traceId,
152
+ spanId: span.spanId,
153
+ error: error instanceof Error ? error.message : String(error),
154
+ });
155
+ throw error;
156
+ }
157
+ });
158
+
159
+ app.use("*", requireAccessKey(deps.settings));
160
+
161
+ if (managedAuth) {
162
+ app.on(["GET", "POST"], "/v1/auth/*", (c) => managedAuth.handler(c.req.raw));
163
+ }
164
+
165
+ app.get("/healthz", (c) => c.json({
166
+ service: deps.settings.serviceName,
167
+ environment: deps.settings.environment,
168
+ deploymentRevision: deps.settings.deploymentRevision,
169
+ ok: true,
170
+ }));
171
+
172
+ app.get("/metrics", (c) => c.text(observability.prometheusMetrics(), 200, {
173
+ "content-type": "text/plain; version=0.0.4; charset=utf-8",
174
+ }));
175
+
176
+ app.get("/v1/config/client", (c) => c.json(ClientConfig.parse({
177
+ deploymentRevision: deps.settings.deploymentRevision,
178
+ defaultModel: deps.settings.openaiModel,
179
+ allowedModels: configuredAllowedModels(deps.settings),
180
+ // Provider-grouped model list for the picker. configuredModels() carries the
181
+ // union of the built-in allow-list and every registry provider's models, in
182
+ // selection order (default model first); project each to the client-safe
183
+ // ClientModel shape (ConfiguredModel.providerId → ClientModel.provider).
184
+ models: configuredModels(deps.settings).map((model) => ({
185
+ id: model.id,
186
+ label: model.label,
187
+ provider: model.providerId,
188
+ providerLabel: model.providerLabel,
189
+ api: model.api,
190
+ ...(model.contextWindowTokens === undefined ? {} : { contextWindowTokens: model.contextWindowTokens }),
191
+ })),
192
+ defaultReasoningEffort: deps.settings.openaiReasoningEffort,
193
+ allowedReasoningEfforts: configuredAllowedReasoningEfforts(deps.settings),
194
+ mcpServers: deps.settings.mcpServers.map((server) => ({
195
+ id: server.id,
196
+ name: server.name ?? server.id,
197
+ })),
198
+ fileUploads: {
199
+ enabled: objectStorage !== null,
200
+ maxSizeBytes: objectStorage?.maxSinglePutSizeBytes ?? 5_000_000_000,
201
+ },
202
+ productAccessMode: deps.settings.productAccessMode,
203
+ auth: clientAuthConfig(deps.settings),
204
+ // Channel-A structured services (P4.4) ride exec/readFile/createEditor,
205
+ // available on every real backend; `none` has no box so they are all off.
206
+ // Per-session availability is still negotiated on /stream-capabilities.
207
+ structuredServices: structuredServicesHint(deps.settings.sandboxBackend),
208
+ })));
209
+
210
+ app.all("/v1/workspaces/:workspaceId/mcp", async (c) => {
211
+ const workspaceId = c.req.param("workspaceId");
212
+ const grant = await requireAccessGrant(c, routeDeps, workspaceId, "workspace:read");
213
+ const transport = new WebStandardStreamableHTTPServerTransport({ enableJsonResponse: true });
214
+ const mcp = buildOpenGeniMcpServer(routeDeps, grant, { requestOrigin: new URL(c.req.url).origin });
215
+ await mcp.connect(transport);
216
+ return await transport.handleRequest(c.req.raw);
217
+ });
218
+
219
+ registerFileRoutes(app, routeDeps);
220
+ registerApiKeyRoutes(app, routeDeps);
221
+ registerBillingRoutes(app, routeDeps);
222
+ registerDocumentRoutes(app, routeDeps);
223
+ registerGitHubRoutes(app, routeDeps);
224
+ registerInstallRoutes(app, routeDeps);
225
+ registerWorkspaceRoutes(app, routeDeps);
226
+ registerSocialRoutes(app, routeDeps);
227
+ registerCapabilityRoutes(app, routeDeps);
228
+ registerEnrollmentRoutes(app, routeDeps);
229
+ registerMachineRoutes(app, routeDeps);
230
+ registerEnvironmentRoutes(app, routeDeps);
231
+ registerPackRoutes(app, routeDeps);
232
+ registerSessionRoutes(app, routeDeps);
233
+ registerScheduledTaskRoutes(app, routeDeps);
234
+ registerCodexRoutes(app, routeDeps);
235
+
236
+ return app;
237
+ }
238
+
239
+ function clientAuthConfig(settings: AppDependencies["settings"]) {
240
+ if (settings.productAccessMode === "managed") {
241
+ return { mode: "managedSession" as const, session: "cookie" as const };
242
+ }
243
+ if (settings.productAccessMode === "configured") {
244
+ return { mode: "configuredToken" as const, headerName: "authorization" as const, scheme: "bearer" as const };
245
+ }
246
+ if (settings.authRequired) {
247
+ return { mode: "deploymentKey" as const, headerName: "x-opengeni-access-key" as const };
248
+ }
249
+ return { mode: "none" as const };
250
+ }
251
+
252
+ function structuredServicesHint(backend: string): { fileSystem: boolean; git: boolean; terminalEvents: boolean } {
253
+ const hasBox = backend !== "none";
254
+ return { fileSystem: hasBox, git: hasBox, terminalEvents: hasBox };
255
+ }
256
+
257
+ export function allowedCorsOrigin(pattern: string, origin: string): boolean {
258
+ return new RegExp(`^(?:${pattern})$`).test(origin);
259
+ }
260
+
261
+ export function httpStatusForError(error: unknown): number {
262
+ if (error instanceof HTTPException) {
263
+ return error.status;
264
+ }
265
+ return 500;
266
+ }
267
+
268
+ const routeLabelPatterns: Array<{ pattern: RegExp; label: string }> = [
269
+ { pattern: /^\/healthz$/, label: "/healthz" },
270
+ { pattern: /^\/v1\/workspaces\/[^/]+\/codex\/connect\/start$/, label: "/v1/workspaces/:workspaceId/codex/connect/start" },
271
+ { pattern: /^\/v1\/workspaces\/[^/]+\/codex\/connect\/poll$/, label: "/v1/workspaces/:workspaceId/codex/connect/poll" },
272
+ { pattern: /^\/v1\/workspaces\/[^/]+\/codex\/status$/, label: "/v1/workspaces/:workspaceId/codex/status" },
273
+ { pattern: /^\/v1\/workspaces\/[^/]+\/codex\/usage$/, label: "/v1/workspaces/:workspaceId/codex/usage" },
274
+ { pattern: /^\/v1\/workspaces\/[^/]+\/codex$/, label: "/v1/workspaces/:workspaceId/codex" },
275
+ { pattern: /^\/metrics$/, label: "/metrics" },
276
+ { pattern: /^\/v1\/config\/client$/, label: "/v1/config/client" },
277
+ { pattern: /^\/v1\/billing$/, label: "/v1/billing" },
278
+ { pattern: /^\/v1\/billing\/checkout$/, label: "/v1/billing/checkout" },
279
+ { pattern: /^\/v1\/billing\/usage$/, label: "/v1/billing/usage" },
280
+ { pattern: /^\/v1\/billing\/entitlements$/, label: "/v1/billing/entitlements" },
281
+ { pattern: /^\/v1\/webhooks\/stripe$/, label: "/v1/webhooks/stripe" },
282
+ { pattern: /^\/v1\/workspaces\/[^/]+\/mcp$/, label: "/v1/workspaces/:workspaceId/mcp" },
283
+ { pattern: /^\/v1\/workspaces\/[^/]+\/mcp\/docs$/, label: "/v1/workspaces/:workspaceId/mcp/docs" },
284
+ { pattern: /^\/v1\/workspaces\/[^/]+\/sessions$/, label: "/v1/workspaces/:workspaceId/sessions" },
285
+ { pattern: /^\/v1\/workspaces\/[^/]+\/sessions\/[^/]+\/events\/stream$/, label: "/v1/workspaces/:workspaceId/sessions/:id/events/stream" },
286
+ { pattern: /^\/v1\/workspaces\/[^/]+\/sessions\/[^/]+\/events$/, label: "/v1/workspaces/:workspaceId/sessions/:id/events" },
287
+ { pattern: /^\/v1\/workspaces\/[^/]+\/sessions\/[^/]+\/turns\/reorder$/, label: "/v1/workspaces/:workspaceId/sessions/:id/turns/reorder" },
288
+ { pattern: /^\/v1\/workspaces\/[^/]+\/sessions\/[^/]+\/turns\/[^/]+$/, label: "/v1/workspaces/:workspaceId/sessions/:id/turns/:turnId" },
289
+ { pattern: /^\/v1\/workspaces\/[^/]+\/sessions\/[^/]+\/turns$/, label: "/v1/workspaces/:workspaceId/sessions/:id/turns" },
290
+ { pattern: /^\/v1\/workspaces\/[^/]+\/sessions\/[^/]+\/stream-capabilities$/, label: "/v1/workspaces/:workspaceId/sessions/:id/stream-capabilities" },
291
+ { pattern: /^\/v1\/workspaces\/[^/]+\/sessions\/[^/]+\/viewers\/[^/]+\/heartbeat$/, label: "/v1/workspaces/:workspaceId/sessions/:id/viewers/:viewerId/heartbeat" },
292
+ { pattern: /^\/v1\/workspaces\/[^/]+\/sessions\/[^/]+\/viewers\/[^/]+$/, label: "/v1/workspaces/:workspaceId/sessions/:id/viewers/:viewerId" },
293
+ { pattern: /^\/v1\/workspaces\/[^/]+\/sessions\/[^/]+\/viewers$/, label: "/v1/workspaces/:workspaceId/sessions/:id/viewers" },
294
+ { pattern: /^\/v1\/workspaces\/[^/]+\/sessions\/[^/]+\/goal$/, label: "/v1/workspaces/:workspaceId/sessions/:id/goal" },
295
+ { pattern: /^\/v1\/workspaces\/[^/]+\/sessions\/[^/]+$/, label: "/v1/workspaces/:workspaceId/sessions/:id" },
296
+ { pattern: /^\/v1\/workspaces\/[^/]+\/files\/uploads$/, label: "/v1/workspaces/:workspaceId/files/uploads" },
297
+ { pattern: /^\/v1\/workspaces\/[^/]+\/files\/uploads\/[^/]+\/complete$/, label: "/v1/workspaces/:workspaceId/files/uploads/:id/complete" },
298
+ { pattern: /^\/v1\/workspaces\/[^/]+\/files\/[^/]+\/download-url$/, label: "/v1/workspaces/:workspaceId/files/:id/download-url" },
299
+ { pattern: /^\/v1\/workspaces\/[^/]+\/files\/[^/]+$/, label: "/v1/workspaces/:workspaceId/files/:id" },
300
+ { pattern: /^\/v1\/workspaces\/[^/]+\/api-keys$/, label: "/v1/workspaces/:workspaceId/api-keys" },
301
+ { pattern: /^\/v1\/workspaces\/[^/]+\/api-keys\/[^/]+$/, label: "/v1/workspaces/:workspaceId/api-keys/:id" },
302
+ { pattern: /^\/v1\/workspaces\/[^/]+\/scheduled-tasks$/, label: "/v1/workspaces/:workspaceId/scheduled-tasks" },
303
+ { pattern: /^\/v1\/workspaces\/[^/]+\/scheduled-tasks\/[^/]+\/pause$/, label: "/v1/workspaces/:workspaceId/scheduled-tasks/:id/pause" },
304
+ { pattern: /^\/v1\/workspaces\/[^/]+\/scheduled-tasks\/[^/]+\/resume$/, label: "/v1/workspaces/:workspaceId/scheduled-tasks/:id/resume" },
305
+ { pattern: /^\/v1\/workspaces\/[^/]+\/scheduled-tasks\/[^/]+\/trigger$/, label: "/v1/workspaces/:workspaceId/scheduled-tasks/:id/trigger" },
306
+ { pattern: /^\/v1\/workspaces\/[^/]+\/scheduled-tasks\/[^/]+\/runs$/, label: "/v1/workspaces/:workspaceId/scheduled-tasks/:id/runs" },
307
+ { pattern: /^\/v1\/workspaces\/[^/]+\/scheduled-tasks\/[^/]+$/, label: "/v1/workspaces/:workspaceId/scheduled-tasks/:id" },
308
+ { pattern: /^\/v1\/workspaces\/[^/]+\/document-bases$/, label: "/v1/workspaces/:workspaceId/document-bases" },
309
+ { pattern: /^\/v1\/workspaces\/[^/]+\/document-bases\/[^/]+\/documents\/[^/]+\/reindex$/, label: "/v1/workspaces/:workspaceId/document-bases/:id/documents/:documentId/reindex" },
310
+ { pattern: /^\/v1\/workspaces\/[^/]+\/document-bases\/[^/]+\/documents\/[^/]+$/, label: "/v1/workspaces/:workspaceId/document-bases/:id/documents/:documentId" },
311
+ { pattern: /^\/v1\/workspaces\/[^/]+\/document-bases\/[^/]+\/documents$/, label: "/v1/workspaces/:workspaceId/document-bases/:id/documents" },
312
+ { pattern: /^\/v1\/workspaces\/[^/]+\/document-bases\/[^/]+\/search$/, label: "/v1/workspaces/:workspaceId/document-bases/:id/search" },
313
+ { pattern: /^\/v1\/workspaces\/[^/]+\/document-bases\/[^/]+$/, label: "/v1/workspaces/:workspaceId/document-bases/:id" },
314
+ { pattern: /^\/v1\/workspaces\/[^/]+\/github\/app$/, label: "/v1/workspaces/:workspaceId/github/app" },
315
+ { pattern: /^\/v1\/workspaces\/[^/]+\/github\/repositories$/, label: "/v1/workspaces/:workspaceId/github/repositories" },
316
+ { pattern: /^\/v1\/workspaces\/[^/]+\/github\/repositories\/sync$/, label: "/v1/workspaces/:workspaceId/github/repositories/sync" },
317
+ { pattern: /^\/v1\/workspaces\/[^/]+\/github\/app-manifest$/, label: "/v1/workspaces/:workspaceId/github/app-manifest" },
318
+ { pattern: /^\/v1\/workspaces\/[^/]+\/capabilities$/, label: "/v1/workspaces/:workspaceId/capabilities" },
319
+ { pattern: /^\/v1\/workspaces\/[^/]+\/capabilities\/discovery\/mcp-registry$/, label: "/v1/workspaces/:workspaceId/capabilities/discovery/mcp-registry" },
320
+ { pattern: /^\/v1\/workspaces\/[^/]+\/capabilities\/[^/]+\/enable$/, label: "/v1/workspaces/:workspaceId/capabilities/:id/enable" },
321
+ { pattern: /^\/v1\/workspaces\/[^/]+\/capabilities\/[^/]+\/disable$/, label: "/v1/workspaces/:workspaceId/capabilities/:id/disable" },
322
+ { pattern: /^\/v1\/workspaces\/[^/]+\/environments$/, label: "/v1/workspaces/:workspaceId/environments" },
323
+ { pattern: /^\/v1\/workspaces\/[^/]+\/environments\/[^/]+\/variables\/[^/]+$/, label: "/v1/workspaces/:workspaceId/environments/:id/variables/:name" },
324
+ { pattern: /^\/v1\/workspaces\/[^/]+\/environments\/[^/]+$/, label: "/v1/workspaces/:workspaceId/environments/:id" },
325
+ { pattern: /^\/v1\/workspaces\/[^/]+\/packs$/, label: "/v1/workspaces/:workspaceId/packs" },
326
+ { pattern: /^\/v1\/workspaces\/[^/]+\/packs\/installations$/, label: "/v1/workspaces/:workspaceId/packs/installations" },
327
+ { pattern: /^\/v1\/workspaces\/[^/]+\/packs\/marketing-social-daily-analysis\/scheduled-tasks$/, label: "/v1/workspaces/:workspaceId/packs/marketing-social-daily-analysis/scheduled-tasks" },
328
+ { pattern: /^\/v1\/workspaces\/[^/]+\/packs\/[^/]+\/enable$/, label: "/v1/workspaces/:workspaceId/packs/:id/enable" },
329
+ { pattern: /^\/v1\/workspaces\/[^/]+\/packs\/[^/]+$/, label: "/v1/workspaces/:workspaceId/packs/:id" },
330
+ { pattern: /^\/v1\/workspaces\/[^/]+\/social\/connections$/, label: "/v1/workspaces/:workspaceId/social/connections" },
331
+ { pattern: /^\/v1\/workspaces\/[^/]+\/social\/posts$/, label: "/v1/workspaces/:workspaceId/social/posts" },
332
+ { pattern: /^\/v1\/enrollments\/device\/start$/, label: "/v1/enrollments/device/start" },
333
+ { pattern: /^\/v1\/enrollments\/device\/poll$/, label: "/v1/enrollments/device/poll" },
334
+ { pattern: /^\/v1\/workspaces\/[^/]+\/enrollments\/device\/approve$/, label: "/v1/workspaces/:workspaceId/enrollments/device/approve" },
335
+ { pattern: /^\/v1\/workspaces\/[^/]+\/enrollments\/[^/]+\/revoke$/, label: "/v1/workspaces/:workspaceId/enrollments/:id/revoke" },
336
+ { pattern: /^\/v1\/workspaces\/[^/]+\/enrollments$/, label: "/v1/workspaces/:workspaceId/enrollments" },
337
+ { pattern: /^\/v1\/workspaces\/[^/]+\/machines\/[^/]+\/metrics\/series$/, label: "/v1/workspaces/:workspaceId/machines/:enrollmentId/metrics/series" },
338
+ { pattern: /^\/v1\/workspaces\/[^/]+\/machines$/, label: "/v1/workspaces/:workspaceId/machines" },
339
+ { pattern: /^\/v1\/github\/app-manifest\/callback$/, label: "/v1/github/app-manifest/callback" },
340
+ { pattern: /^\/v1\/github\/setup$/, label: "/v1/github/setup" },
341
+ { pattern: /^\/v1\/github\/install\/callback$/, label: "/v1/github/install/callback" },
342
+ { pattern: /^\/v1\/github\/oauth\/callback$/, label: "/v1/github/oauth/callback" },
343
+ ];
344
+
345
+ export function routeLabel(pathname: string): string {
346
+ const match = routeLabelPatterns.find(({ pattern }) => pattern.test(pathname));
347
+ if (match) {
348
+ return match.label;
349
+ }
350
+ return pathname.startsWith("/v1/") ? "/v1/unknown" : "/unknown";
351
+ }