@opengeni/api-router 0.4.0 → 0.5.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.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  createApp
3
- } from "./chunk-I2EDWHVF.js";
3
+ } from "./chunk-DQ5TIRDZ.js";
4
4
 
5
5
  // src/index.ts
6
6
  import { dbSearchPath, getSettings, resolveNatsCalloutConfig, resolveNatsControlPlaneAuth, retryStartupDependency, startupRetryOptions } from "@opengeni/config";
@@ -9,6 +9,34 @@ import { createNatsEventBus } from "@opengeni/events";
9
9
  import { createObservability, logStartupDependencyRetry } from "@opengeni/observability";
10
10
  import { Connection, Client as TemporalClient, ScheduleNotFoundError, ScheduleOverlapPolicy, WorkflowExecutionAlreadyStartedError } from "@temporalio/client";
11
11
 
12
+ // src/observability.ts
13
+ function observabilityEventLogger(observability) {
14
+ return {
15
+ debug: (message, attributes) => observability.debug(message, eventAttributes(attributes)),
16
+ warn: (message, attributes) => observability.warn(message, eventAttributes(attributes))
17
+ };
18
+ }
19
+ function eventAttributes(attributes) {
20
+ if (!attributes) {
21
+ return void 0;
22
+ }
23
+ const sanitized = {};
24
+ for (const [key, value] of Object.entries(attributes)) {
25
+ sanitized[key] = eventAttributeValue(value);
26
+ }
27
+ return sanitized;
28
+ }
29
+ function eventAttributeValue(value) {
30
+ if (value === null || value === void 0 || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
31
+ return value;
32
+ }
33
+ try {
34
+ return JSON.stringify(value);
35
+ } catch {
36
+ return String(value);
37
+ }
38
+ }
39
+
12
40
  // src/sandbox/auth-callout.ts
13
41
  import { resolveEnrollmentSigningSecret } from "@opengeni/config";
14
42
  import { verifyEnrollmentBearer } from "@opengeni/contracts";
@@ -94,7 +122,10 @@ async function startAuthCalloutResponder(deps, natsUrl) {
94
122
  { kind: "user-password", user: deps.callout.user, pass: deps.callout.password },
95
123
  AUTH_CALLOUT_SUBJECT,
96
124
  (bytes) => handleAuthorizationRequest(deps, bytes),
97
- { name: "opengeni-auth-callout" }
125
+ {
126
+ name: "opengeni-auth-callout",
127
+ ...deps.observability ? { logger: observabilityEventLogger(deps.observability) } : {}
128
+ }
98
129
  );
99
130
  deps.observability?.info?.("OpenGeni NATS auth-callout responder started", {
100
131
  subject: AUTH_CALLOUT_SUBJECT
@@ -106,7 +137,7 @@ async function startAuthCalloutResponder(deps, natsUrl) {
106
137
  import {
107
138
  getEnrollment as getEnrollment2,
108
139
  ingestMachineMetricsSample,
109
- setEnrollmentHasDisplay,
140
+ setEnrollmentDisplayState,
110
141
  touchEnrollmentLastSeen
111
142
  } from "@opengeni/db";
112
143
  import { AgentEvent, Hello } from "@opengeni/agent-proto";
@@ -207,21 +238,30 @@ function helloReportsDisplay(hello) {
207
238
  if (!caps) {
208
239
  return false;
209
240
  }
241
+ if (caps.desktopUnavailableReason) {
242
+ return false;
243
+ }
210
244
  return caps.desktop === true || caps.display != null;
211
245
  }
246
+ function helloDesktopUnavailableReason(hello) {
247
+ const reason = hello.capabilities?.desktopUnavailableReason;
248
+ return reason ? reason : null;
249
+ }
212
250
  async function refreshEnrollmentDisplay(db, input) {
251
+ const desktopUnavailableReason = input.desktopUnavailableReason ?? null;
213
252
  const enrollment = await getEnrollment2(db, input.workspaceId, input.agentId);
214
253
  if (!enrollment) {
215
254
  return { updated: false };
216
255
  }
217
- if (enrollment.hasDisplay === input.hasDisplay) {
256
+ if (enrollment.hasDisplay === input.hasDisplay && (enrollment.desktopUnavailableReason ?? null) === desktopUnavailableReason) {
218
257
  return { updated: false };
219
258
  }
220
- return await setEnrollmentHasDisplay(db, {
259
+ return await setEnrollmentDisplayState(db, {
221
260
  accountId: enrollment.accountId,
222
261
  workspaceId: input.workspaceId,
223
262
  enrollmentId: input.agentId,
224
- hasDisplay: input.hasDisplay
263
+ hasDisplay: input.hasDisplay,
264
+ desktopUnavailableReason
225
265
  });
226
266
  }
227
267
  async function handleHelloPayload(db, observability, payload, subject) {
@@ -243,7 +283,8 @@ async function handleHelloPayload(db, observability, payload, subject) {
243
283
  await refreshEnrollmentDisplay(db, {
244
284
  workspaceId: ids.workspaceId,
245
285
  agentId: ids.agentId,
246
- hasDisplay: helloReportsDisplay(hello)
286
+ hasDisplay: helloReportsDisplay(hello),
287
+ desktopUnavailableReason: helloDesktopUnavailableReason(hello)
247
288
  });
248
289
  } catch (error) {
249
290
  observability?.warn?.("Failed to refresh an enrollment's display from a Hello", {
@@ -345,6 +386,9 @@ async function createTemporalWorkflowClient(settings) {
345
386
  }
346
387
  throw error;
347
388
  }
389
+ },
390
+ check: async () => {
391
+ await connection.workflowService.getSystemInfo({});
348
392
  }
349
393
  };
350
394
  const documentIndexer = {
@@ -383,7 +427,8 @@ async function startApi() {
383
427
  "NATS",
384
428
  () => createNatsEventBus(
385
429
  settings.natsUrl,
386
- controlPlaneAuth ? { user: controlPlaneAuth.user, pass: controlPlaneAuth.password } : void 0
430
+ controlPlaneAuth ? { user: controlPlaneAuth.user, pass: controlPlaneAuth.password } : void 0,
431
+ { logger: observabilityEventLogger(observability) }
387
432
  ),
388
433
  {
389
434
  ...retryOptions,
package/dist/index.js.map CHANGED
@@ -1 +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,8B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MAAM;AAAA,MACN,cAAc;AAAA,MACd;AAAA,MACA,MAAM,CAAC;AAAA,QACL,WAAW,KAAK;AAAA,QAChB,aAAa,KAAK;AAAA,QAClB,QAAQ,KAAK;AAAA,QACb,aAAa;AAAA,MACf,CAAC;AAAA,IACH;AAAA,IACA,UAAU;AAAA,MACR,SAAS,sBAAsB,KAAK,aAAa;AAAA,MACjD,eAAe;AAAA,MACf,gBAAgB;AAAA,IAClB;AAAA,IACA,OAAO;AAAA,MACL,QAAQ,KAAK,WAAW;AAAA,MACxB,GAAI,KAAK,SAAS,SAAS,SAAS,EAAE,kBAAkB,EAAE,IAAI,CAAC;AAAA,IACjE;AAAA,IACA,MAAM;AAAA,MACJ,WAAW,KAAK;AAAA,MAChB,aAAa,KAAK;AAAA,MAClB,iBAAiB,KAAK;AAAA,MACtB,MAAM,KAAK;AAAA,IACb;AAAA,EACF;AACF;AAEA,SAAS,8BAA8B,SAAiD;AACtF,SAAO;AAAA,IACL,MAAM,QAAQ;AAAA,IACd,QAAQ,QAAQ;AAAA,IAChB,GAAI,QAAQ,WAAW,EAAE,UAAU,QAAQ,SAAS,IAAI,CAAC;AAAA,IACzD,OAAO,QAAQ,SAAS,CAAC;AAAA,IACzB,GAAI,QAAQ,mBAAmB,EAAE,kBAAkB,QAAQ,iBAAiB,IAAI,CAAC;AAAA,IACjF,GAAI,QAAQ,wBAAwB,EAAE,uBAAuB,QAAQ,sBAAsB,IAAI,CAAC;AAAA,EAClG;AACF;","names":["response","getEnrollment"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/observability.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 { observabilityEventLogger } from \"./observability\";\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 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 throw error;\n }\n },\n check: async () => {\n await connection.workflowService.getSystemInfo({});\n },\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 { logger: observabilityEventLogger(observability) },\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","import type { EventLogger } from \"@opengeni/events\";\nimport type { Attributes, AttributeValue, Observability } from \"@opengeni/observability\";\n\nexport function observabilityEventLogger(observability: Observability): EventLogger {\n return {\n debug: (message, attributes) => observability.debug(message, eventAttributes(attributes)),\n warn: (message, attributes) => observability.warn(message, eventAttributes(attributes)),\n };\n}\n\nfunction eventAttributes(attributes: Record<string, unknown> | undefined): Attributes | undefined {\n if (!attributes) {\n return undefined;\n }\n const sanitized: Attributes = {};\n for (const [key, value] of Object.entries(attributes)) {\n sanitized[key] = eventAttributeValue(value);\n }\n return sanitized;\n}\n\nfunction eventAttributeValue(value: unknown): AttributeValue {\n if (value === null || value === undefined || typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\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\";\nimport { observabilityEventLogger } from \"../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 {\n name: \"opengeni-auth-callout\",\n ...(deps.observability ? { logger: observabilityEventLogger(deps.observability) } : {}),\n },\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 setEnrollmentDisplayState,\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 // A CAPTURE-BLOCKED display is NOT a usable display: a Mac reports a display but\n // withholds `desktop` and sets `desktopUnavailableReason` when Screen Recording\n // (TCC) is not granted. Treating it as \"has display\" is exactly how the 0.1.3\n // incident hid — the machine claimed a desktop it could not capture, so it was\n // offered for computer-use and the model saw a blank. Gate it out here (the single\n // source of truth for `has_display`, consumed by both the machine state and the\n // capability negotiation). The `display`-present fallback is preserved for every\n // other case (e.g. a relay-less agent that reports a display but not `desktop`).\n if (caps.desktopUnavailableReason) {\n return false;\n }\n return caps.desktop === true || caps.display != null;\n}\n\n/**\n * The human, actionable reason a display is present but UNUSABLE (macOS Screen\n * Recording / TCC not granted), or null when capture is permitted / the machine is\n * headless. Normalizes the proto's non-optional \"\" empty string to null so the DB\n * carries a clean tri-state (a real reason vs. no reason) — the Machines dashboard\n * shows \"display: capture not granted\" only when this is non-null.\n */\nexport function helloDesktopUnavailableReason(hello: Hello): string | null {\n const reason = hello.capabilities?.desktopUnavailableReason;\n return reason ? reason : null;\n}\n\n/**\n * Reconcile `enrollments.has_display` (+ the capture-blocked reason) to what a Hello\n * reports. Resolves the enrollment (the accountId is the RLS principal + the\n * existence check + the current values). A no-change Hello short-circuits BEFORE\n * issuing any write (and the DB writer is itself change-guarded on BOTH fields as a\n * backstop), so a steady state never churns. An unknown/cross-workspace agentId is a\n * no-op.\n */\nexport async function refreshEnrollmentDisplay(\n db: Database,\n input: { workspaceId: string; agentId: string; hasDisplay: boolean; desktopUnavailableReason?: string | null },\n): Promise<{ updated: boolean }> {\n const desktopUnavailableReason = input.desktopUnavailableReason ?? null;\n const enrollment = await getEnrollment(db, input.workspaceId, input.agentId);\n if (!enrollment) {\n return { updated: false };\n }\n if (\n enrollment.hasDisplay === input.hasDisplay &&\n (enrollment.desktopUnavailableReason ?? null) === desktopUnavailableReason\n ) {\n // Both fields unchanged — do not even issue the UPDATE (no churn on a\n // steady-state Hello).\n return { updated: false };\n }\n return await setEnrollmentDisplayState(db, {\n accountId: enrollment.accountId,\n workspaceId: input.workspaceId,\n enrollmentId: input.agentId,\n hasDisplay: input.hasDisplay,\n desktopUnavailableReason,\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 desktopUnavailableReason: helloDesktopUnavailableReason(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;;;ACFlI,SAAS,yBAAyB,eAA2C;AAClF,SAAO;AAAA,IACL,OAAO,CAAC,SAAS,eAAe,cAAc,MAAM,SAAS,gBAAgB,UAAU,CAAC;AAAA,IACxF,MAAM,CAAC,SAAS,eAAe,cAAc,KAAK,SAAS,gBAAgB,UAAU,CAAC;AAAA,EACxF;AACF;AAEA,SAAS,gBAAgB,YAAyE;AAChG,MAAI,CAAC,YAAY;AACf,WAAO;AAAA,EACT;AACA,QAAM,YAAwB,CAAC;AAC/B,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,UAAU,GAAG;AACrD,cAAU,GAAG,IAAI,oBAAoB,KAAK;AAAA,EAC5C;AACA,SAAO;AACT;AAEA,SAAS,oBAAoB,OAAgC;AAC3D,MAAI,UAAU,QAAQ,UAAU,UAAa,OAAO,UAAU,YAAY,OAAO,UAAU,YAAY,OAAO,UAAU,WAAW;AACjI,WAAO;AAAA,EACT;AACA,MAAI;AACF,WAAO,KAAK,UAAU,KAAK;AAAA,EAC7B,QAAQ;AACN,WAAO,OAAO,KAAK;AAAA,EACrB;AACF;;;ACAA,SAAS,sCAA6E;AACtF,SAAS,8BAA8B;AACvC,SAAS,qBAAoC;AAC7C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAKA,IAAM,uBAAuB;AAiBpC,eAAsB,2BACpB,MACA,cAC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","getEnrollment"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opengeni/api-router",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
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
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -37,7 +37,8 @@
37
37
  "dev": "bun --watch src/index.ts",
38
38
  "start": "bun src/index.ts",
39
39
  "typecheck": "tsc --noEmit",
40
- "build": "tsup"
40
+ "build": "tsup",
41
+ "prepublishOnly": "bash ../../scripts/prepublish-guard"
41
42
  },
42
43
  "dependencies": {
43
44
  "@aws-sdk/client-s3": "^3.1044.0",
@@ -46,16 +47,16 @@
46
47
  "@modelcontextprotocol/sdk": "^1.29.0",
47
48
  "@opengeni/agent-proto": "^0.2.1",
48
49
  "@opengeni/codex": "^0.2.1",
49
- "@opengeni/config": "^0.2.4",
50
- "@opengeni/contracts": "^0.6.0",
51
- "@opengeni/core": "^0.4.0",
52
- "@opengeni/db": "^0.4.0",
53
- "@opengeni/documents": "^0.2.4",
54
- "@opengeni/events": "^0.2.4",
55
- "@opengeni/github": "^0.2.4",
50
+ "@opengeni/config": "^0.3.0",
51
+ "@opengeni/contracts": "^0.9.0",
52
+ "@opengeni/core": "^0.4.3",
53
+ "@opengeni/db": "^0.6.0",
54
+ "@opengeni/documents": "^0.2.7",
55
+ "@opengeni/events": "^0.2.7",
56
+ "@opengeni/github": "^0.2.7",
56
57
  "@opengeni/observability": "^0.2.1",
57
- "@opengeni/runtime": "^0.3.0",
58
- "@opengeni/storage": "^0.2.4",
58
+ "@opengeni/runtime": "^0.4.0",
59
+ "@opengeni/storage": "^0.2.7",
59
60
  "@temporalio/client": "^1.17.0",
60
61
  "better-auth": "^1.6.14",
61
62
  "hono": "^4.12.18",
@@ -63,12 +64,5 @@
63
64
  "resend": "^6.12.4",
64
65
  "stripe": "^22.2.0",
65
66
  "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
67
  }
74
68
  }
package/src/app.ts CHANGED
@@ -3,8 +3,9 @@ import {
3
3
  configuredAllowedReasoningEfforts,
4
4
  configuredModels,
5
5
  } from "@opengeni/config";
6
- import { ClientConfig } from "@opengeni/contracts";
6
+ import { ClientConfig, type AccessGrant } from "@opengeni/contracts";
7
7
  import { createDocumentServices, indexDocumentNow, type DocumentServices } from "@opengeni/documents";
8
+ import { dbSql } from "@opengeni/db";
8
9
  import { createObservability } from "@opengeni/observability";
9
10
  import { createObjectStorage } from "@opengeni/storage";
10
11
  import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
@@ -12,14 +13,16 @@ import { Hono } from "hono";
12
13
  import { cors } from "hono/cors";
13
14
  import { HTTPException } from "hono/http-exception";
14
15
  import type { ApiRouteDeps, AppDependencies, ObjectStorageDependency, SessionWorkflowClient } from "@opengeni/core";
15
- import { requireAccessGrant } from "@opengeni/core";
16
+ import { hasPermission, requireAccessGrant, requirePermission } from "@opengeni/core";
16
17
  import { createManagedAuth } from "./auth/managed-auth";
17
18
  import { createApiSandboxClient, makeResumeBoxById } from "./sandbox/access";
18
19
  import { requireLimit } from "@opengeni/core";
19
20
  import { buildOpenGeniMcpServer } from "./mcp/server";
21
+ import { isToolspaceGrant, prepareToolspaceMcpSurface } from "./mcp/toolspace";
20
22
  import { requireAccessKey } from "./http/auth";
21
23
  import { registerCapabilityRoutes } from "./routes/capabilities";
22
24
  import { registerCodexRoutes } from "./routes/codex";
25
+ import { registerConnectionRoutes } from "./routes/connections";
23
26
  import { registerDocumentRoutes } from "./routes/documents";
24
27
  import { registerEnrollmentRoutes } from "./routes/enrollments";
25
28
  import { registerMachineRoutes } from "./routes/machines";
@@ -166,15 +169,22 @@ export function createApp(deps: AppDependencies): Hono {
166
169
  service: deps.settings.serviceName,
167
170
  environment: deps.settings.environment,
168
171
  deploymentRevision: deps.settings.deploymentRevision,
172
+ ...(deps.settings.serverVersion ? { serverVersion: deps.settings.serverVersion } : {}),
169
173
  ok: true,
170
174
  }));
171
175
 
172
- app.get("/metrics", (c) => c.text(observability.prometheusMetrics(), 200, {
176
+ app.get("/readyz", async (c) => {
177
+ const result = await runReadinessChecks(readinessChecks(deps), 2_000);
178
+ return c.json(result, result.ok ? 200 : 503);
179
+ });
180
+
181
+ app.get("/metrics", async (c) => c.text(await observability.prometheusMetrics(), 200, {
173
182
  "content-type": "text/plain; version=0.0.4; charset=utf-8",
174
183
  }));
175
184
 
176
185
  app.get("/v1/config/client", (c) => c.json(ClientConfig.parse({
177
186
  deploymentRevision: deps.settings.deploymentRevision,
187
+ ...(deps.settings.serverVersion ? { serverVersion: deps.settings.serverVersion } : {}),
178
188
  defaultModel: deps.settings.openaiModel,
179
189
  allowedModels: configuredAllowedModels(deps.settings),
180
190
  // Provider-grouped model list for the picker. configuredModels() carries the
@@ -209,11 +219,21 @@ export function createApp(deps: AppDependencies): Hono {
209
219
 
210
220
  app.all("/v1/workspaces/:workspaceId/mcp", async (c) => {
211
221
  const workspaceId = c.req.param("workspaceId");
212
- const grant = await requireAccessGrant(c, routeDeps, workspaceId, "workspace:read");
222
+ const grant = await requireMcpAccessGrant(c, routeDeps, workspaceId);
223
+ const toolspace = isToolspaceGrant(routeDeps.settings, grant)
224
+ ? await prepareToolspaceMcpSurface({ deps: routeDeps, grant })
225
+ : null;
213
226
  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);
227
+ const mcp = buildOpenGeniMcpServer(routeDeps, grant, {
228
+ requestOrigin: new URL(c.req.url).origin,
229
+ toolspace,
230
+ });
231
+ try {
232
+ await mcp.connect(transport);
233
+ return await transport.handleRequest(c.req.raw);
234
+ } finally {
235
+ await toolspace?.close().catch(() => undefined);
236
+ }
217
237
  });
218
238
 
219
239
  registerFileRoutes(app, routeDeps);
@@ -224,6 +244,7 @@ export function createApp(deps: AppDependencies): Hono {
224
244
  registerInstallRoutes(app, routeDeps);
225
245
  registerWorkspaceRoutes(app, routeDeps);
226
246
  registerSocialRoutes(app, routeDeps);
247
+ registerConnectionRoutes(app, routeDeps);
227
248
  registerCapabilityRoutes(app, routeDeps);
228
249
  registerEnrollmentRoutes(app, routeDeps);
229
250
  registerMachineRoutes(app, routeDeps);
@@ -236,6 +257,18 @@ export function createApp(deps: AppDependencies): Hono {
236
257
  return app;
237
258
  }
238
259
 
260
+ async function requireMcpAccessGrant(c: Parameters<typeof requireAccessGrant>[0], deps: ApiRouteDeps, workspaceId: string): Promise<AccessGrant> {
261
+ const grant = await requireAccessGrant(c, deps, workspaceId);
262
+ if (hasPermission(grant.permissions, "workspace:read")) {
263
+ return grant;
264
+ }
265
+ if (isToolspaceGrant(deps.settings, grant)) {
266
+ return grant;
267
+ }
268
+ requirePermission(grant, "workspace:read");
269
+ return grant;
270
+ }
271
+
239
272
  function clientAuthConfig(settings: AppDependencies["settings"]) {
240
273
  if (settings.productAccessMode === "managed") {
241
274
  return { mode: "managedSession" as const, session: "cookie" as const };
@@ -265,8 +298,66 @@ export function httpStatusForError(error: unknown): number {
265
298
  return 500;
266
299
  }
267
300
 
301
+ type ReadinessCheckName = "db" | "nats" | "temporal";
302
+ type ReadinessChecks = Record<ReadinessCheckName, () => Promise<void> | void>;
303
+
304
+ function readinessChecks(deps: AppDependencies): ReadinessChecks {
305
+ return {
306
+ db: deps.readinessChecks?.db ?? (async () => {
307
+ await deps.db.execute(dbSql`select 1`);
308
+ }),
309
+ nats: deps.readinessChecks?.nats ?? (() => {
310
+ if (deps.bus.isConnected && !deps.bus.isConnected()) {
311
+ throw new Error("NATS is not connected");
312
+ }
313
+ }),
314
+ temporal: deps.readinessChecks?.temporal ?? deps.workflowClient.check ?? (() => {
315
+ throw new Error("Temporal readiness check unavailable");
316
+ }),
317
+ };
318
+ }
319
+
320
+ async function runReadinessChecks(checks: ReadinessChecks, timeoutMs: number): Promise<{
321
+ ok: boolean;
322
+ checks: Record<ReadinessCheckName, { ok: boolean; error?: string }>;
323
+ }> {
324
+ const entries = await Promise.all(
325
+ (Object.entries(checks) as Array<[ReadinessCheckName, () => Promise<void> | void]>)
326
+ .map(async ([name, check]) => {
327
+ try {
328
+ await withTimeout(Promise.resolve().then(check), timeoutMs);
329
+ return [name, { ok: true }] as const;
330
+ } catch (error) {
331
+ return [name, { ok: false, error: error instanceof Error ? error.message : String(error) }] as const;
332
+ }
333
+ }),
334
+ );
335
+ const result = Object.fromEntries(entries) as Record<ReadinessCheckName, { ok: boolean; error?: string }>;
336
+ return {
337
+ ok: Object.values(result).every((check) => check.ok),
338
+ checks: result,
339
+ };
340
+ }
341
+
342
+ async function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
343
+ let timer: ReturnType<typeof setTimeout> | undefined;
344
+ try {
345
+ return await Promise.race([
346
+ promise,
347
+ new Promise<never>((_, reject) => {
348
+ timer = setTimeout(() => reject(new Error(`readiness check timed out after ${timeoutMs}ms`)), timeoutMs);
349
+ }),
350
+ ]);
351
+ } finally {
352
+ if (timer) {
353
+ clearTimeout(timer);
354
+ }
355
+ }
356
+ }
357
+
268
358
  const routeLabelPatterns: Array<{ pattern: RegExp; label: string }> = [
269
359
  { pattern: /^\/healthz$/, label: "/healthz" },
360
+ { pattern: /^\/readyz$/, label: "/readyz" },
270
361
  { pattern: /^\/v1\/workspaces\/[^/]+\/codex\/connect\/start$/, label: "/v1/workspaces/:workspaceId/codex/connect/start" },
271
362
  { pattern: /^\/v1\/workspaces\/[^/]+\/codex\/connect\/poll$/, label: "/v1/workspaces/:workspaceId/codex/connect/poll" },
272
363
  { pattern: /^\/v1\/workspaces\/[^/]+\/codex\/status$/, label: "/v1/workspaces/:workspaceId/codex/status" },
@@ -311,6 +402,9 @@ const routeLabelPatterns: Array<{ pattern: RegExp; label: string }> = [
311
402
  { pattern: /^\/v1\/workspaces\/[^/]+\/document-bases\/[^/]+\/documents$/, label: "/v1/workspaces/:workspaceId/document-bases/:id/documents" },
312
403
  { pattern: /^\/v1\/workspaces\/[^/]+\/document-bases\/[^/]+\/search$/, label: "/v1/workspaces/:workspaceId/document-bases/:id/search" },
313
404
  { pattern: /^\/v1\/workspaces\/[^/]+\/document-bases\/[^/]+$/, label: "/v1/workspaces/:workspaceId/document-bases/:id" },
405
+ { pattern: /^\/v1\/workspaces\/[^/]+\/knowledge\/search$/, label: "/v1/workspaces/:workspaceId/knowledge/search" },
406
+ { pattern: /^\/v1\/workspaces\/[^/]+\/knowledge\/memories\/[^/]+$/, label: "/v1/workspaces/:workspaceId/knowledge/memories/:id" },
407
+ { pattern: /^\/v1\/workspaces\/[^/]+\/knowledge\/memories$/, label: "/v1/workspaces/:workspaceId/knowledge/memories" },
314
408
  { pattern: /^\/v1\/workspaces\/[^/]+\/github\/app$/, label: "/v1/workspaces/:workspaceId/github/app" },
315
409
  { pattern: /^\/v1\/workspaces\/[^/]+\/github\/repositories$/, label: "/v1/workspaces/:workspaceId/github/repositories" },
316
410
  { pattern: /^\/v1\/workspaces\/[^/]+\/github\/repositories\/sync$/, label: "/v1/workspaces/:workspaceId/github/repositories/sync" },
@@ -329,6 +423,11 @@ const routeLabelPatterns: Array<{ pattern: RegExp; label: string }> = [
329
423
  { pattern: /^\/v1\/workspaces\/[^/]+\/packs\/[^/]+$/, label: "/v1/workspaces/:workspaceId/packs/:id" },
330
424
  { pattern: /^\/v1\/workspaces\/[^/]+\/social\/connections$/, label: "/v1/workspaces/:workspaceId/social/connections" },
331
425
  { pattern: /^\/v1\/workspaces\/[^/]+\/social\/posts$/, label: "/v1/workspaces/:workspaceId/social/posts" },
426
+ { pattern: /^\/v1\/workspaces\/[^/]+\/connections$/, label: "/v1/workspaces/:workspaceId/connections" },
427
+ { pattern: /^\/v1\/workspaces\/[^/]+\/connections\/oauth\/start$/, label: "/v1/workspaces/:workspaceId/connections/oauth/start" },
428
+ { pattern: /^\/v1\/workspaces\/[^/]+\/connections\/[^/]+$/, label: "/v1/workspaces/:workspaceId/connections/:connectionId" },
429
+ { pattern: /^\/v1\/integrations\/oauth\/callback$/, label: "/v1/integrations/oauth/callback" },
430
+ { pattern: /^\/v1\/integrations\/oauth\/client-metadata\.json$/, label: "/v1/integrations/oauth/client-metadata.json" },
332
431
  { pattern: /^\/v1\/enrollments\/device\/start$/, label: "/v1/enrollments/device/start" },
333
432
  { pattern: /^\/v1\/enrollments\/device\/poll$/, label: "/v1/enrollments/device/poll" },
334
433
  { pattern: /^\/v1\/workspaces\/[^/]+\/enrollments\/device\/approve$/, label: "/v1/workspaces/:workspaceId/enrollments/device/approve" },