@opengeni/api-router 0.21.14 → 0.23.1

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 (54) hide show
  1. package/dist/app.d.ts +1 -0
  2. package/dist/app.js +1 -1
  3. package/dist/auth/managed-auth.d.ts +0 -30
  4. package/dist/{chunk-R5PDSH2A.js → chunk-T4T2PGU4.js} +3989 -1356
  5. package/dist/chunk-T4T2PGU4.js.map +1 -0
  6. package/dist/http/sse.d.ts +2 -0
  7. package/dist/index.js +29 -9
  8. package/dist/index.js.map +1 -1
  9. package/dist/integrations/oauth-client.d.ts +8 -0
  10. package/dist/integrations/slack-interactions.d.ts +7 -1
  11. package/dist/mcp/receipts.d.ts +28 -0
  12. package/dist/mcp/scheduled-task-view.d.ts +350 -0
  13. package/dist/mcp/toolspace.d.ts +9 -0
  14. package/dist/routes/transcription-recordings.d.ts +3 -0
  15. package/dist/sandbox/auth-callout.d.ts +2 -0
  16. package/dist/sandbox/channel-a.d.ts +5 -1
  17. package/dist/transcription/segmenter.d.ts +10 -0
  18. package/dist/transcription/service.d.ts +5 -0
  19. package/package.json +12 -12
  20. package/src/app.ts +39 -6
  21. package/src/auth/managed-auth.ts +0 -16
  22. package/src/http/sse.ts +101 -6
  23. package/src/index.ts +28 -3
  24. package/src/integrations/oauth-client.ts +36 -56
  25. package/src/integrations/slack-interactions.ts +123 -15
  26. package/src/mcp/documents.ts +42 -25
  27. package/src/mcp/receipts.ts +95 -0
  28. package/src/mcp/scheduled-task-view.ts +608 -0
  29. package/src/mcp/server.ts +812 -182
  30. package/src/mcp/toolspace.ts +75 -71
  31. package/src/observability.ts +3 -3
  32. package/src/routes/api-keys.ts +7 -1
  33. package/src/routes/codex.ts +7 -4
  34. package/src/routes/connections.ts +74 -3
  35. package/src/routes/enrollments.ts +54 -12
  36. package/src/routes/environments.ts +60 -11
  37. package/src/routes/files.ts +175 -65
  38. package/src/routes/install.ts +31 -1
  39. package/src/routes/machines.ts +1 -1
  40. package/src/routes/scheduled-tasks.ts +39 -14
  41. package/src/routes/sessions.ts +77 -12
  42. package/src/routes/transcription-recordings.ts +754 -0
  43. package/src/routes/transcriptions.ts +2 -0
  44. package/src/sandbox/auth-callout.ts +16 -4
  45. package/src/sandbox/channel-a.ts +124 -7
  46. package/src/sandbox/enrollment.ts +13 -3
  47. package/src/sandbox/machines.ts +1 -1
  48. package/src/sandbox/viewer.ts +29 -20
  49. package/src/transcription/providers/azure-openai.ts +4 -3
  50. package/src/transcription/providers/codex-subscription.ts +4 -1
  51. package/src/transcription/providers/openai.ts +7 -2
  52. package/src/transcription/segmenter.ts +260 -0
  53. package/src/transcription/service.ts +111 -10
  54. package/dist/chunk-R5PDSH2A.js.map +0 -1
@@ -4,6 +4,7 @@ import { type EventBus } from "@opengeni/events";
4
4
  import type { Observability } from "@opengeni/observability";
5
5
  export declare const SSE_QUEUED_FRAME_MAX_COUNT = 1;
6
6
  export declare const SSE_WRITE_STALL_TIMEOUT_MS = 30000;
7
+ export declare const SSE_HEARTBEAT_INTERVAL_MS = 15000;
7
8
  export type SseDeliveryBoundObservation = {
8
9
  reason: "desired_size_non_positive" | "stall_timeout" | "frame_too_large";
9
10
  desiredSize: number | null;
@@ -60,6 +61,7 @@ export declare function sseWorkspaceControlStream(db: Database, bus: EventBus, w
60
61
  export type SseDeliveryOptions = {
61
62
  maxQueuedBytes?: number;
62
63
  stallTimeoutMs?: number;
64
+ heartbeatIntervalMs?: number;
63
65
  observability?: Observability | undefined;
64
66
  onObservation?: ((observation: SseDeliveryBoundObservation) => void) | undefined;
65
67
  };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  createAppComposition,
3
3
  startSlackInteractionPump
4
- } from "./chunk-R5PDSH2A.js";
4
+ } from "./chunk-T4T2PGU4.js";
5
5
 
6
6
  // src/index.ts
7
7
  import {
@@ -41,11 +41,11 @@ function eventAttributes(attributes) {
41
41
  if (!attributes) {
42
42
  return void 0;
43
43
  }
44
- const sanitized = {};
44
+ const projected = {};
45
45
  for (const [key, value] of Object.entries(attributes)) {
46
- sanitized[key] = eventAttributeValue(value);
46
+ projected[key] = eventAttributeValue(value);
47
47
  }
48
- return sanitized;
48
+ return projected;
49
49
  }
50
50
  function eventAttributeValue(value) {
51
51
  if (value === null || value === void 0 || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
@@ -72,6 +72,7 @@ import {
72
72
  workspaceAgentPermissions
73
73
  } from "@opengeni/events";
74
74
  var AUTH_CALLOUT_SUBJECT = "$SYS.REQ.USER.AUTH";
75
+ var NATS_USER_JWT_TTL_SECONDS = 5 * 60;
75
76
  async function handleAuthorizationRequest(deps, requestBytes) {
76
77
  const requestJwt = Buffer.from(requestBytes).toString("utf8");
77
78
  const decoded = decodeAuthRequest(requestJwt);
@@ -109,10 +110,14 @@ async function handleAuthorizationRequest(deps, requestBytes) {
109
110
  });
110
111
  return deny("enrollment is not active");
111
112
  }
112
- if (enrollment.id !== claims.enrollmentId) {
113
+ if (enrollment.workspaceId !== claims.workspaceId || enrollment.id !== claims.enrollmentId || enrollment.id !== claims.agentId || claims.agentId !== claims.enrollmentId || claims.subjectPrefix !== `agent.${claims.workspaceId}.${claims.agentId}`) {
113
114
  return deny("enrollment identity mismatch");
114
115
  }
116
+ if (enrollment.credentialGeneration !== claims.credentialGeneration) {
117
+ return deny("enrollment credential generation mismatch");
118
+ }
115
119
  const permissions = workspaceAgentPermissions(claims.workspaceId);
120
+ const nowSeconds = Math.floor(Date.now() / 1e3);
116
121
  const userJwt = mintUserJwt({
117
122
  userPublicKey: decoded.userNkey,
118
123
  accountSeed: deps.callout.accountSeed,
@@ -125,7 +130,7 @@ async function handleAuthorizationRequest(deps, requestBytes) {
125
130
  audienceAccount: deps.callout.accountName,
126
131
  // Tie the credential's life to the bearer's remaining life: a revoked/expired
127
132
  // enrollment cannot outlive its bearer at the NATS layer either.
128
- expiresAtSeconds: claims.exp
133
+ expiresAtSeconds: Math.min(claims.exp, nowSeconds + NATS_USER_JWT_TTL_SECONDS)
129
134
  });
130
135
  const response = mintAuthResponse({
131
136
  userPublicKey: decoded.userNkey,
@@ -733,9 +738,11 @@ async function startApi() {
733
738
  { db: dbClient.db, settings, callout, observability },
734
739
  settings.natsUrl
735
740
  );
736
- } catch (error) {
741
+ } catch {
737
742
  observability.error("OpenGeni NATS auth-callout responder failed to start", {
738
- error: error instanceof Error ? error.message : String(error)
743
+ errorClass: "NatsAuthCalloutOperationError",
744
+ errorCode: "nats_auth_callout_start_failed",
745
+ origin: "api"
739
746
  });
740
747
  }
741
748
  } else {
@@ -783,7 +790,7 @@ function shouldCreateScheduleAfterUpdateError(error) {
783
790
  function temporalScheduleSpec(schedule) {
784
791
  if (schedule.type === "interval") {
785
792
  return {
786
- intervals: [{ every: `${schedule.everySeconds}s` }],
793
+ intervals: [temporalIntervalSpec(schedule)],
787
794
  ...schedule.startAt ? { startAt: new Date(schedule.startAt) } : {},
788
795
  ...schedule.endAt ? { endAt: new Date(schedule.endAt) } : {}
789
796
  };
@@ -816,6 +823,19 @@ function temporalScheduleSpec(schedule) {
816
823
  timezone: "UTC"
817
824
  };
818
825
  }
826
+ function temporalIntervalSpec(schedule) {
827
+ const every = `${schedule.everySeconds}s`;
828
+ if (!schedule.startAt) {
829
+ return { every };
830
+ }
831
+ const everyMilliseconds = BigInt(schedule.everySeconds) * 1000n;
832
+ const startMilliseconds = BigInt(new Date(schedule.startAt).getTime());
833
+ const offsetMilliseconds = (startMilliseconds % everyMilliseconds + everyMilliseconds) % everyMilliseconds;
834
+ return {
835
+ every,
836
+ ...offsetMilliseconds === 0n ? {} : { offset: `${offsetMilliseconds}ms` }
837
+ };
838
+ }
819
839
  function temporalMonth(monthIndex) {
820
840
  return TEMPORAL_MONTHS[monthIndex];
821
841
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/observability.ts","../src/sandbox/auth-callout.ts","../src/sandbox/metrics-ingestion.ts"],"sourcesContent":["import {\n dbSearchPath,\n getSettings,\n resolveNatsCalloutConfig,\n resolveNatsControlPlaneAuth,\n retryStartupDependency,\n startupRetryOptions,\n temporalConnectionOptions,\n} from \"@opengeni/config\";\nimport type {\n ScheduledTask,\n ScheduledTaskOverlapPolicy,\n ScheduledTaskScheduleSpec,\n} from \"@opengeni/contracts\";\nimport {\n assertRuntimeDatabasePosture,\n createDb,\n markSessionWorkflowWakeDelivered,\n runtimeDatabaseReadyCheck,\n type Database,\n} from \"@opengeni/db\";\nimport { createNatsEventBus, type ResponderConnection } from \"@opengeni/events\";\nimport { createObservability, logStartupDependencyRetry } from \"@opengeni/observability\";\nimport { SESSION_WORKFLOW_WAKE_DISPATCHER_SCHEDULE_ID } from \"@opengeni/core\";\nimport {\n Connection,\n Client as TemporalClient,\n ScheduleNotFoundError,\n ScheduleOverlapPolicy,\n WorkflowExecutionAlreadyStartedError,\n} from \"@temporalio/client\";\nimport type { ScheduleOptions, ScheduleSpec, ScheduleUpdateOptions } from \"@temporalio/client\";\nimport { createAppComposition, type DocumentIndexClient, type SessionWorkflowClient } from \"./app\";\nimport { observabilityEventLogger } from \"./observability\";\nimport { startAuthCalloutResponder } from \"./sandbox/auth-callout\";\nimport { startHelloIngestion, startMetricsIngestion } from \"./sandbox/metrics-ingestion\";\nimport { startSlackInteractionPump } from \"./integrations/slack-interactions\";\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(\n settings: ReturnType<typeof getSettings>,\n db: Database,\n): Promise<{\n client: SessionWorkflowClient;\n documentIndexer: DocumentIndexClient;\n close: () => Promise<void>;\n}> {\n const connection = await Connection.connect(temporalConnectionOptions(settings));\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 ({\n accountId,\n workspaceId,\n sessionId,\n workflowId,\n wakeRevision,\n interruptionRequested,\n }) => {\n await temporal.workflow.signalWithStart(\"sessionWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [{ accountId, workspaceId, sessionId }],\n signal: interruptionRequested ? \"sessionControl\" : \"queueChanged\",\n });\n await markSessionWorkflowWakeDelivered(db, {\n accountId,\n workspaceId,\n sessionId,\n temporalWorkflowId: workflowId,\n wakeRevision,\n });\n },\n requestSessionWorkflowWakeDispatch: async () => {\n await temporal.schedule\n .getHandle(SESSION_WORKFLOW_WAKE_DISPATCHER_SCHEDULE_ID)\n .trigger(ScheduleOverlapPolicy.BUFFER_ONE);\n },\n signalCodexCapacity: async ({\n accountId,\n workspaceId,\n sessionId,\n workflowId,\n wakeRevision,\n workflowWakeRevision,\n }) => {\n await temporal.workflow.signalWithStart(\"sessionWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [{ accountId, workspaceId, sessionId }],\n signal: \"codexCapacityChanged\",\n signalArgs: [wakeRevision],\n });\n await markSessionWorkflowWakeDelivered(db, {\n accountId,\n workspaceId,\n sessionId,\n temporalWorkflowId: workflowId,\n wakeRevision: workflowWakeRevision,\n });\n },\n signalApprovalDecision: async ({\n accountId,\n workspaceId,\n sessionId,\n eventId,\n workflowId,\n workflowWakeRevision,\n }) => {\n await temporal.workflow.signalWithStart(\"sessionWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [{ accountId, workspaceId, sessionId }],\n signal: \"approvalDecision\",\n signalArgs: [eventId],\n });\n await markSessionWorkflowWakeDelivered(db, {\n accountId,\n workspaceId,\n sessionId,\n temporalWorkflowId: workflowId,\n wakeRevision: workflowWakeRevision,\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\n .getHandle(temporalScheduleId)\n .delete()\n .catch(() => undefined);\n },\n triggerScheduledTask: async ({\n task,\n agentRunUsageIdempotencyKey,\n triggerWorkflowId,\n initiator,\n }) => {\n // Deterministic workflowId (derived from the trigger token by the\n // caller) + REJECT_DUPLICATE makes a retried manual trigger idempotent:\n // the second start collides on the id and is rejected instead of\n // spawning a second run. The shared idempotency key dedupes the charge.\n const workflowId = triggerWorkflowId;\n try {\n await temporal.workflow.start(\"scheduledTaskFireWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n workflowIdReusePolicy: \"REJECT_DUPLICATE\",\n args: [\n {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n taskId: task.id,\n triggerType: \"manual\",\n agentRunUsageIdempotencyKey,\n initiator,\n },\n ],\n });\n } catch (error) {\n // A duplicate trigger token started this run already; treat the retry\n // as a no-op so the (idempotent) usage charge stays the only effect.\n if (isWorkflowAlreadyStarted(error)) {\n return;\n }\n throw error;\n }\n },\n startRigVerification: async ({ workspaceId, changeId, versionId, workflowId }) => {\n const targetId = changeId ?? versionId;\n if (!targetId) {\n throw new Error(\"rig verification requires changeId or versionId\");\n }\n await temporal.workflow.start(\"rigVerificationWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId: workflowId ?? `rig-verification-${targetId}-${crypto.randomUUID()}`,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [\n {\n workspaceId,\n ...(changeId ? { changeId } : {}),\n ...(versionId ? { versionId } : {}),\n },\n ],\n });\n },\n check: async () => {\n await connection.workflowService.getSystemInfo({});\n },\n };\n const documentIndexer: DocumentIndexClient = {\n indexDocument: async (input) => {\n const { documentId } = input;\n const workflowId = `document-index-${documentId}-${crypto.randomUUID()}`;\n await temporal.workflow.start(\"documentIndexWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n args: [input],\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]) =>\n logStartupDependencyRetry(observability, event);\n const databasePosture = {\n rlsStrategy: settings.rlsStrategy,\n expectedRole: settings.runtimeDatabaseRole,\n targetSchema: settings.dbSchema.trim() || \"public\",\n } as const;\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 await retryStartupDependency(\n \"PostgreSQL runtime posture\",\n () => assertRuntimeDatabasePosture(dbClient.db, databasePosture),\n { ...retryOptions, onRetry },\n );\n bus = await retryStartupDependency(\n \"NATS\",\n () =>\n createNatsEventBus(\n settings.natsUrl,\n controlPlaneAuth\n ? { user: controlPlaneAuth.user, pass: controlPlaneAuth.password }\n : undefined,\n { logger: observabilityEventLogger(observability) },\n ),\n {\n ...retryOptions,\n onRetry,\n },\n );\n workflowClient = await retryStartupDependency(\n \"Temporal\",\n () => createTemporalWorkflowClient(settings, dbClient.db),\n {\n ...retryOptions,\n onRetry,\n },\n );\n } catch (error) {\n await Promise.allSettled([bus?.close(), workflowClient?.close(), dbClient.close()]);\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, routeDeps } = createAppComposition({\n settings,\n db: dbClient.db,\n bus,\n workflowClient: workflowClient.client,\n documentIndexer: workflowClient.documentIndexer,\n observability,\n readinessChecks: {\n db: runtimeDatabaseReadyCheck(dbClient.db, databasePosture),\n },\n });\n const server = Bun.serve({\n hostname: settings.apiHost,\n port: settings.apiPort,\n idleTimeout: 255,\n fetch: app.fetch,\n });\n const stopSlackInteractionPump = settings.slackSigningSecret\n ? startSlackInteractionPump(routeDeps)\n : undefined;\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({\n db: dbClient.db,\n bus,\n observability,\n });\n stopHelloIngestion = startHelloIngestion({\n db: dbClient.db,\n bus,\n observability,\n });\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 stopSlackInteractionPump?.();\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 {\n hour: schedule.hour,\n minute: schedule.minute,\n second: 0,\n ...(schedule.daysOfWeek ? { dayOfWeek: schedule.daysOfWeek } : {}),\n },\n ],\n timezone: schedule.timeZone,\n };\n }\n const runAt = new Date(schedule.runAt);\n return {\n calendars: [\n {\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 ],\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 {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n taskId: task.id,\n triggerType: \"scheduled\",\n },\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\n ? { typedSearchAttributes: options.typedSearchAttributes }\n : {}),\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 (\n value === null ||\n value === undefined ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\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; 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 {\n resolveEnrollmentSigningSecret,\n type NatsCalloutConfig,\n type Settings,\n} 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// + 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// refreshEnrollmentOpStream — reconcile `enrollments.op_stream` to the LIVE\n// runner capability the Hello reports, leaving legacy request/reply exec as the\n// fallback unless the runner advertises the streaming engine.\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 clearEnrollmentWentOffline,\n getEnrollment,\n ingestMachineMetricsSample,\n sessionsWithActiveOpOnEnrollment,\n setEnrollmentDisplayState,\n setEnrollmentOpStreamState,\n setEnrollmentWentOffline,\n touchEnrollmentLastSeen,\n type AppendEventInput,\n type Database,\n type MachineMetricsSample,\n} from \"@opengeni/db\";\nimport { appendAndPublishEvents, type EventBus } from \"@opengeni/events\";\nimport type { Observability } from \"@opengeni/observability\";\nimport {\n AgentEvent,\n GoingOfflineReason,\n Hello,\n goingOfflineReasonToJSON,\n type MetricsSample,\n} 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(\n subject: string,\n tail: \"events\" | \"hello\",\n): { 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(\n subject: string,\n): { 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(\n subject: string,\n): { 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:\n wire.sampledAtMs && Number(wire.sampledAtMs) > 0\n ? new Date(Number(wire.sampledAtMs))\n : 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 * Fan out one or more machine-LINK session events to the sessions that had an\n * active op running on the machine when its control link changed (per\n * `sessionsWithActiveOpOnEnrollment`) — the announce-only failure-visibility\n * plane. Each session's events are stamped on its OWN active turn. No matching\n * session ⇒ nothing is emitted (an idle-machine blip must never spam idle /\n * historical sessions). Called best-effort inside the handlers' fail-soft blocks.\n *\n * Each session's emission is ISOLATED: one session's append failing (a\n * session-specific constraint like a sequence collision from a racing writer, a\n * transient write error) is logged with that sessionId and skipped, never\n * aborting the fan-out — one session's failure must never cost the OTHER matching\n * sessions their events. A partial fan-out stays visible per-session in the logs.\n */\nasync function fanOutMachineLinkEvents(\n db: Database,\n bus: EventBus,\n observability: Observability | undefined,\n workspaceId: string,\n enrollmentId: string,\n build: (activeTurnId: string) => AppendEventInput[],\n): Promise<void> {\n const sessions = await sessionsWithActiveOpOnEnrollment(db, { workspaceId, enrollmentId });\n for (const session of sessions) {\n try {\n await appendAndPublishEvents(\n db,\n bus,\n workspaceId,\n session.sessionId,\n build(session.activeTurnId),\n );\n } catch (error) {\n observability?.warn?.(\"Failed to fan out a machine-link event to a session\", {\n workspaceId,\n sessionId: session.sessionId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\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 records the\n * machine-plane marker + fans out the link-plane session events. Decode failures\n * are reported + swallowed. `bus` (when present) enables the session-event\n * fan-out; the live consumer always supplies it, pure unit tests may omit it.\n */\nexport async function handleAgentEventPayload(\n db: Database,\n observability: Observability | undefined,\n payload: Uint8Array,\n subject: string,\n bus?: EventBus,\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 // A clean GoingOffline is the machine-plane's typed shutdown signal. Two things\n // happen, in this order:\n // 1. Record it ALWAYS on the machine plane (a Prometheus counter keyed by the\n // typed reason) so a fleet operator can see clean stops / self-updates /\n // host shutdowns. This fires unconditionally, independent of the DB.\n // 2. Stamp the enrollment's clean going-offline marker so the liveness\n // derivation reads the machine OFFLINE immediately instead of waiting out\n // the last_seen dead-detect window. Best-effort + fail-soft (like the rest\n // of this module): an unknown enrollment is a no-op and a DB error is\n // swallowed so a bad write never tears down the consumer. Deliberately does\n // NOT touch last-seen (a shutdown must not look \"more recently alive\").\n if (event.event?.$case === \"goingOffline\") {\n const reason = goingOfflineReasonToJSON(event.event.goingOffline.reason);\n observability?.incrementCounter({\n name: \"opengeni_machine_going_offline_total\",\n help: \"Total Connected Machine clean GoingOffline signals by typed reason.\",\n labels: { reason },\n });\n try {\n const enrollment = await getEnrollment(db, ids.workspaceId, ids.agentId);\n if (enrollment) {\n await setEnrollmentWentOffline(db, {\n accountId: enrollment.accountId,\n workspaceId: ids.workspaceId,\n enrollmentId: ids.agentId,\n reason,\n });\n // Fan out the link-plane events to the sessions with an active op on this\n // machine: machine.link.lost (its control link is going away) for every\n // clean going-offline, PLUS machine.runner.restarted when the reason is a\n // self-update restart specifically (link.lost fires for it too; this\n // distinguishes a restart from a plain stop / host shutdown).\n if (bus) {\n const isSelfUpdate =\n event.event.goingOffline.reason === GoingOfflineReason.GOING_OFFLINE_REASON_UPDATE;\n await fanOutMachineLinkEvents(\n db,\n bus,\n observability,\n ids.workspaceId,\n ids.agentId,\n (activeTurnId) => {\n const events: AppendEventInput[] = [\n { type: \"machine.link.lost\", turnId: activeTurnId, payload: { reason } },\n ];\n if (isSelfUpdate) {\n events.push({\n type: \"machine.runner.restarted\",\n turnId: activeTurnId,\n payload: {},\n });\n }\n return events;\n },\n );\n }\n }\n } catch (error) {\n observability?.warn?.(\"Failed to record a machine clean going-offline\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n return;\n }\n if (event.event?.$case !== \"heartbeat\") {\n return; // an unknown event kind → 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, {\n workspaceId: ids.workspaceId,\n agentId: ids.agentId,\n sample: metrics,\n });\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, deps.bus),\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/** Whether the runner's current Hello advertises the op-stream engine. */\nexport function helloReportsOpStream(hello: Hello): boolean {\n return hello.capabilities?.opStream === true;\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: {\n workspaceId: string;\n agentId: string;\n hasDisplay: boolean;\n desktopUnavailableReason?: string | null;\n },\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 * Reconcile `enrollments.op_stream` to what a Hello reports. Resolves the\n * enrollment first so the accountId remains the RLS principal and so a no-change\n * Hello short-circuits BEFORE issuing any write (the DB writer is itself\n * change-guarded as a backstop). An unknown/cross-workspace agentId is a no-op.\n */\nexport async function refreshEnrollmentOpStream(\n db: Database,\n input: {\n workspaceId: string;\n agentId: string;\n opStream: boolean;\n },\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.opStream === input.opStream) {\n // The capability is unchanged — do not even issue the UPDATE (no churn on a\n // steady-state Hello).\n return { updated: false };\n }\n return await setEnrollmentOpStreamState(db, {\n accountId: enrollment.accountId,\n workspaceId: input.workspaceId,\n enrollmentId: input.agentId,\n opStream: input.opStream,\n });\n}\n\n/**\n * Decode a raw `Hello` payload + refresh the enrollment's display cursor + clear\n * any pending clean going-offline marker and, when the reconnect actually cleared\n * one, fan out machine.link.restored to the sessions with an active op on the\n * machine (the per-message handler for the hello plane). Decode failures + write\n * failures are reported + swallowed — a Hello must NEVER break the agent's connect.\n * `bus` (when present) enables the link.restored fan-out.\n */\nexport async function handleHelloPayload(\n db: Database,\n observability: Observability | undefined,\n payload: Uint8Array,\n subject: string,\n bus?: EventBus,\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 await refreshEnrollmentOpStream(db, {\n workspaceId: ids.workspaceId,\n agentId: ids.agentId,\n opStream: helloReportsOpStream(hello),\n });\n } catch (error) {\n observability?.warn?.(\"Failed to refresh an enrollment's capabilities from a Hello\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n // A reconnect Hello re-announces the machine, so any pending clean going-offline\n // marker no longer holds — clear it so the liveness derivation stops reading the\n // machine offline. Best-effort + fail-soft, and change-guarded in the DB (a\n // steady-state Hello with no marker writes nothing), so this never breaks the\n // agent's connect and never churns. When a marker was ACTUALLY cleared (the\n // machine had been reported link.lost), fan out machine.link.restored to the\n // sessions with an active op on it — a restored only ever pairs a prior lost, so\n // a routine connect Hello (no marker) emits nothing.\n try {\n const enrollment = await getEnrollment(db, ids.workspaceId, ids.agentId);\n if (enrollment) {\n const { cleared } = await clearEnrollmentWentOffline(db, {\n accountId: enrollment.accountId,\n workspaceId: ids.workspaceId,\n enrollmentId: ids.agentId,\n });\n if (cleared && bus) {\n await fanOutMachineLinkEvents(\n db,\n bus,\n observability,\n ids.workspaceId,\n ids.agentId,\n (activeTurnId) => [{ type: \"machine.link.restored\", turnId: activeTurnId, payload: {} }],\n );\n }\n }\n } catch (error) {\n observability?.warn?.(\"Failed to clear a machine going-offline marker on 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, deps.bus),\n );\n}\n"],"mappings":";;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,0BAAoD;AAC7D,SAAS,qBAAqB,iCAAiC;AAC/D,SAAS,oDAAoD;AAC7D;AAAA,EACE;AAAA,EACA,UAAU;AAAA,EACV;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;AC3BA,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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,QAAQ,SAAS,CAAC;AAAA,IACzB,GAAI,QAAQ,mBAAmB,EAAE,kBAAkB,QAAQ,iBAAiB,IAAI,CAAC;AAAA,IACjF,GAAI,QAAQ,wBACR,EAAE,uBAAuB,QAAQ,sBAAsB,IACvD,CAAC;AAAA,EACP;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 {\n dbSearchPath,\n getSettings,\n resolveNatsCalloutConfig,\n resolveNatsControlPlaneAuth,\n retryStartupDependency,\n startupRetryOptions,\n temporalConnectionOptions,\n} from \"@opengeni/config\";\nimport type {\n ScheduledTask,\n ScheduledTaskOverlapPolicy,\n ScheduledTaskScheduleSpec,\n} from \"@opengeni/contracts\";\nimport {\n assertRuntimeDatabasePosture,\n createDb,\n markSessionWorkflowWakeDelivered,\n runtimeDatabaseReadyCheck,\n type Database,\n} from \"@opengeni/db\";\nimport { createNatsEventBus, type ResponderConnection } from \"@opengeni/events\";\nimport { createObservability, logStartupDependencyRetry } from \"@opengeni/observability\";\nimport { SESSION_WORKFLOW_WAKE_DISPATCHER_SCHEDULE_ID } from \"@opengeni/core\";\nimport {\n Connection,\n Client as TemporalClient,\n ScheduleNotFoundError,\n ScheduleOverlapPolicy,\n WorkflowExecutionAlreadyStartedError,\n} from \"@temporalio/client\";\nimport type { ScheduleOptions, ScheduleSpec, ScheduleUpdateOptions } from \"@temporalio/client\";\nimport { createAppComposition, type DocumentIndexClient, type SessionWorkflowClient } from \"./app\";\nimport { observabilityEventLogger } from \"./observability\";\nimport { startAuthCalloutResponder } from \"./sandbox/auth-callout\";\nimport { startHelloIngestion, startMetricsIngestion } from \"./sandbox/metrics-ingestion\";\nimport { startSlackInteractionPump } from \"./integrations/slack-interactions\";\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(\n settings: ReturnType<typeof getSettings>,\n db: Database,\n): Promise<{\n client: SessionWorkflowClient;\n documentIndexer: DocumentIndexClient;\n close: () => Promise<void>;\n}> {\n const connection = await Connection.connect(temporalConnectionOptions(settings));\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 ({\n accountId,\n workspaceId,\n sessionId,\n workflowId,\n wakeRevision,\n interruptionRequested,\n }) => {\n await temporal.workflow.signalWithStart(\"sessionWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [{ accountId, workspaceId, sessionId }],\n signal: interruptionRequested ? \"sessionControl\" : \"queueChanged\",\n });\n await markSessionWorkflowWakeDelivered(db, {\n accountId,\n workspaceId,\n sessionId,\n temporalWorkflowId: workflowId,\n wakeRevision,\n });\n },\n requestSessionWorkflowWakeDispatch: async () => {\n await temporal.schedule\n .getHandle(SESSION_WORKFLOW_WAKE_DISPATCHER_SCHEDULE_ID)\n .trigger(ScheduleOverlapPolicy.BUFFER_ONE);\n },\n signalCodexCapacity: async ({\n accountId,\n workspaceId,\n sessionId,\n workflowId,\n wakeRevision,\n workflowWakeRevision,\n }) => {\n await temporal.workflow.signalWithStart(\"sessionWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [{ accountId, workspaceId, sessionId }],\n signal: \"codexCapacityChanged\",\n signalArgs: [wakeRevision],\n });\n await markSessionWorkflowWakeDelivered(db, {\n accountId,\n workspaceId,\n sessionId,\n temporalWorkflowId: workflowId,\n wakeRevision: workflowWakeRevision,\n });\n },\n signalApprovalDecision: async ({\n accountId,\n workspaceId,\n sessionId,\n eventId,\n workflowId,\n workflowWakeRevision,\n }) => {\n await temporal.workflow.signalWithStart(\"sessionWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [{ accountId, workspaceId, sessionId }],\n signal: \"approvalDecision\",\n signalArgs: [eventId],\n });\n await markSessionWorkflowWakeDelivered(db, {\n accountId,\n workspaceId,\n sessionId,\n temporalWorkflowId: workflowId,\n wakeRevision: workflowWakeRevision,\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\n .getHandle(temporalScheduleId)\n .delete()\n .catch(() => undefined);\n },\n triggerScheduledTask: async ({\n task,\n agentRunUsageIdempotencyKey,\n triggerWorkflowId,\n initiator,\n }) => {\n // Deterministic workflowId (derived from the trigger token by the\n // caller) + REJECT_DUPLICATE makes a retried manual trigger idempotent:\n // the second start collides on the id and is rejected instead of\n // spawning a second run. The shared idempotency key dedupes the charge.\n const workflowId = triggerWorkflowId;\n try {\n await temporal.workflow.start(\"scheduledTaskFireWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n workflowIdReusePolicy: \"REJECT_DUPLICATE\",\n args: [\n {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n taskId: task.id,\n triggerType: \"manual\",\n agentRunUsageIdempotencyKey,\n initiator,\n },\n ],\n });\n } catch (error) {\n // A duplicate trigger token started this run already; treat the retry\n // as a no-op so the (idempotent) usage charge stays the only effect.\n if (isWorkflowAlreadyStarted(error)) {\n return;\n }\n throw error;\n }\n },\n startRigVerification: async ({ workspaceId, changeId, versionId, workflowId }) => {\n const targetId = changeId ?? versionId;\n if (!targetId) {\n throw new Error(\"rig verification requires changeId or versionId\");\n }\n await temporal.workflow.start(\"rigVerificationWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId: workflowId ?? `rig-verification-${targetId}-${crypto.randomUUID()}`,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [\n {\n workspaceId,\n ...(changeId ? { changeId } : {}),\n ...(versionId ? { versionId } : {}),\n },\n ],\n });\n },\n check: async () => {\n await connection.workflowService.getSystemInfo({});\n },\n };\n const documentIndexer: DocumentIndexClient = {\n indexDocument: async (input) => {\n const { documentId } = input;\n const workflowId = `document-index-${documentId}-${crypto.randomUUID()}`;\n await temporal.workflow.start(\"documentIndexWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n args: [input],\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]) =>\n logStartupDependencyRetry(observability, event);\n const databasePosture = {\n rlsStrategy: settings.rlsStrategy,\n expectedRole: settings.runtimeDatabaseRole,\n targetSchema: settings.dbSchema.trim() || \"public\",\n } as const;\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 await retryStartupDependency(\n \"PostgreSQL runtime posture\",\n () => assertRuntimeDatabasePosture(dbClient.db, databasePosture),\n { ...retryOptions, onRetry },\n );\n bus = await retryStartupDependency(\n \"NATS\",\n () =>\n createNatsEventBus(\n settings.natsUrl,\n controlPlaneAuth\n ? { user: controlPlaneAuth.user, pass: controlPlaneAuth.password }\n : undefined,\n { logger: observabilityEventLogger(observability) },\n ),\n {\n ...retryOptions,\n onRetry,\n },\n );\n workflowClient = await retryStartupDependency(\n \"Temporal\",\n () => createTemporalWorkflowClient(settings, dbClient.db),\n {\n ...retryOptions,\n onRetry,\n },\n );\n } catch (error) {\n await Promise.allSettled([bus?.close(), workflowClient?.close(), dbClient.close()]);\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, routeDeps } = createAppComposition({\n settings,\n db: dbClient.db,\n bus,\n workflowClient: workflowClient.client,\n documentIndexer: workflowClient.documentIndexer,\n observability,\n readinessChecks: {\n db: runtimeDatabaseReadyCheck(dbClient.db, databasePosture),\n },\n });\n const server = Bun.serve({\n hostname: settings.apiHost,\n port: settings.apiPort,\n idleTimeout: 255,\n fetch: app.fetch,\n });\n const stopSlackInteractionPump = settings.slackSigningSecret\n ? startSlackInteractionPump(routeDeps)\n : undefined;\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({\n db: dbClient.db,\n bus,\n observability,\n });\n stopHelloIngestion = startHelloIngestion({\n db: dbClient.db,\n bus,\n observability,\n });\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 {\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 errorClass: \"NatsAuthCalloutOperationError\",\n errorCode: \"nats_auth_callout_start_failed\",\n origin: \"api\",\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 stopSlackInteractionPump?.();\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: [temporalIntervalSpec(schedule)],\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 {\n hour: schedule.hour,\n minute: schedule.minute,\n second: 0,\n ...(schedule.daysOfWeek ? { dayOfWeek: schedule.daysOfWeek } : {}),\n },\n ],\n timezone: schedule.timeZone,\n };\n }\n const runAt = new Date(schedule.runAt);\n return {\n calendars: [\n {\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 ],\n timezone: \"UTC\",\n };\n}\n\nfunction temporalIntervalSpec(\n schedule: Extract<ScheduledTaskScheduleSpec, { type: \"interval\" }>,\n): NonNullable<ScheduleSpec[\"intervals\"]>[number] {\n const every = `${schedule.everySeconds}s` as `${number}s`;\n if (!schedule.startAt) {\n return { every };\n }\n\n // Temporal interval schedules match Epoch + (n * every) + offset. Its\n // top-level startAt only filters matching times before that boundary, so it\n // does not itself anchor the cadence. Derive the phase from startAt to make\n // the stored OpenGeni timestamp the first interval boundary rather than the\n // next epoch-aligned match.\n const everyMilliseconds = BigInt(schedule.everySeconds) * 1_000n;\n const startMilliseconds = BigInt(new Date(schedule.startAt).getTime());\n const offsetMilliseconds =\n ((startMilliseconds % everyMilliseconds) + everyMilliseconds) % everyMilliseconds;\n return {\n every,\n ...(offsetMilliseconds === 0n ? {} : { offset: `${offsetMilliseconds}ms` as `${number}ms` }),\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 {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n taskId: task.id,\n triggerType: \"scheduled\",\n },\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\n ? { typedSearchAttributes: options.typedSearchAttributes }\n : {}),\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 projected: Attributes = {};\n for (const [key, value] of Object.entries(attributes)) {\n projected[key] = eventAttributeValue(value);\n }\n return projected;\n}\n\nfunction eventAttributeValue(value: unknown): AttributeValue {\n if (\n value === null ||\n value === undefined ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\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; 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 at the exact credential\n// generation (a revoked or re-enrolled machine denies an old 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 {\n resolveEnrollmentSigningSecret,\n type NatsCalloutConfig,\n type Settings,\n} 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/** Keep live NATS credentials short-lived while never outliving the bearer. */\nexport const NATS_USER_JWT_TTL_SECONDS = 5 * 60;\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 (\n enrollment.workspaceId !== claims.workspaceId ||\n enrollment.id !== claims.enrollmentId ||\n enrollment.id !== claims.agentId ||\n claims.agentId !== claims.enrollmentId ||\n claims.subjectPrefix !== `agent.${claims.workspaceId}.${claims.agentId}`\n ) {\n return deny(\"enrollment identity mismatch\");\n }\n if (enrollment.credentialGeneration !== claims.credentialGeneration) {\n return deny(\"enrollment credential generation 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 nowSeconds = Math.floor(Date.now() / 1000);\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: Math.min(claims.exp, nowSeconds + NATS_USER_JWT_TTL_SECONDS),\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// + 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// refreshEnrollmentOpStream — reconcile `enrollments.op_stream` to the LIVE\n// runner capability the Hello reports, leaving legacy request/reply exec as the\n// fallback unless the runner advertises the streaming engine.\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 clearEnrollmentWentOffline,\n getEnrollment,\n ingestMachineMetricsSample,\n sessionsWithActiveOpOnEnrollment,\n setEnrollmentDisplayState,\n setEnrollmentOpStreamState,\n setEnrollmentWentOffline,\n touchEnrollmentLastSeen,\n type AppendEventInput,\n type Database,\n type MachineMetricsSample,\n} from \"@opengeni/db\";\nimport { appendAndPublishEvents, type EventBus } from \"@opengeni/events\";\nimport type { Observability } from \"@opengeni/observability\";\nimport {\n AgentEvent,\n GoingOfflineReason,\n Hello,\n goingOfflineReasonToJSON,\n type MetricsSample,\n} 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(\n subject: string,\n tail: \"events\" | \"hello\",\n): { 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(\n subject: string,\n): { 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(\n subject: string,\n): { 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:\n wire.sampledAtMs && Number(wire.sampledAtMs) > 0\n ? new Date(Number(wire.sampledAtMs))\n : 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 * Fan out one or more machine-LINK session events to the sessions that had an\n * active op running on the machine when its control link changed (per\n * `sessionsWithActiveOpOnEnrollment`) — the announce-only failure-visibility\n * plane. Each session's events are stamped on its OWN active turn. No matching\n * session ⇒ nothing is emitted (an idle-machine blip must never spam idle /\n * historical sessions). Called best-effort inside the handlers' fail-soft blocks.\n *\n * Each session's emission is ISOLATED: one session's append failing (a\n * session-specific constraint like a sequence collision from a racing writer, a\n * transient write error) is logged with that sessionId and skipped, never\n * aborting the fan-out — one session's failure must never cost the OTHER matching\n * sessions their events. A partial fan-out stays visible per-session in the logs.\n */\nasync function fanOutMachineLinkEvents(\n db: Database,\n bus: EventBus,\n observability: Observability | undefined,\n workspaceId: string,\n enrollmentId: string,\n build: (activeTurnId: string) => AppendEventInput[],\n): Promise<void> {\n const sessions = await sessionsWithActiveOpOnEnrollment(db, { workspaceId, enrollmentId });\n for (const session of sessions) {\n try {\n await appendAndPublishEvents(\n db,\n bus,\n workspaceId,\n session.sessionId,\n build(session.activeTurnId),\n );\n } catch (error) {\n observability?.warn?.(\"Failed to fan out a machine-link event to a session\", {\n workspaceId,\n sessionId: session.sessionId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\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 records the\n * machine-plane marker + fans out the link-plane session events. Decode failures\n * are reported + swallowed. `bus` (when present) enables the session-event\n * fan-out; the live consumer always supplies it, pure unit tests may omit it.\n */\nexport async function handleAgentEventPayload(\n db: Database,\n observability: Observability | undefined,\n payload: Uint8Array,\n subject: string,\n bus?: EventBus,\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 // A clean GoingOffline is the machine-plane's typed shutdown signal. Two things\n // happen, in this order:\n // 1. Record it ALWAYS on the machine plane (a Prometheus counter keyed by the\n // typed reason) so a fleet operator can see clean stops / self-updates /\n // host shutdowns. This fires unconditionally, independent of the DB.\n // 2. Stamp the enrollment's clean going-offline marker so the liveness\n // derivation reads the machine OFFLINE immediately instead of waiting out\n // the last_seen dead-detect window. Best-effort + fail-soft (like the rest\n // of this module): an unknown enrollment is a no-op and a DB error is\n // swallowed so a bad write never tears down the consumer. Deliberately does\n // NOT touch last-seen (a shutdown must not look \"more recently alive\").\n if (event.event?.$case === \"goingOffline\") {\n const reason = goingOfflineReasonToJSON(event.event.goingOffline.reason);\n observability?.incrementCounter({\n name: \"opengeni_machine_going_offline_total\",\n help: \"Total Connected Machine clean GoingOffline signals by typed reason.\",\n labels: { reason },\n });\n try {\n const enrollment = await getEnrollment(db, ids.workspaceId, ids.agentId);\n if (enrollment) {\n await setEnrollmentWentOffline(db, {\n accountId: enrollment.accountId,\n workspaceId: ids.workspaceId,\n enrollmentId: ids.agentId,\n reason,\n });\n // Fan out the link-plane events to the sessions with an active op on this\n // machine: machine.link.lost (its control link is going away) for every\n // clean going-offline, PLUS machine.runner.restarted when the reason is a\n // self-update restart specifically (link.lost fires for it too; this\n // distinguishes a restart from a plain stop / host shutdown).\n if (bus) {\n const isSelfUpdate =\n event.event.goingOffline.reason === GoingOfflineReason.GOING_OFFLINE_REASON_UPDATE;\n await fanOutMachineLinkEvents(\n db,\n bus,\n observability,\n ids.workspaceId,\n ids.agentId,\n (activeTurnId) => {\n const events: AppendEventInput[] = [\n { type: \"machine.link.lost\", turnId: activeTurnId, payload: { reason } },\n ];\n if (isSelfUpdate) {\n events.push({\n type: \"machine.runner.restarted\",\n turnId: activeTurnId,\n payload: {},\n });\n }\n return events;\n },\n );\n }\n }\n } catch (error) {\n observability?.warn?.(\"Failed to record a machine clean going-offline\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n return;\n }\n if (event.event?.$case !== \"heartbeat\") {\n return; // an unknown event kind → 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, {\n workspaceId: ids.workspaceId,\n agentId: ids.agentId,\n sample: metrics,\n });\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, deps.bus),\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/** Whether the runner's current Hello advertises the op-stream engine. */\nexport function helloReportsOpStream(hello: Hello): boolean {\n return hello.capabilities?.opStream === true;\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: {\n workspaceId: string;\n agentId: string;\n hasDisplay: boolean;\n desktopUnavailableReason?: string | null;\n },\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 * Reconcile `enrollments.op_stream` to what a Hello reports. Resolves the\n * enrollment first so the accountId remains the RLS principal and so a no-change\n * Hello short-circuits BEFORE issuing any write (the DB writer is itself\n * change-guarded as a backstop). An unknown/cross-workspace agentId is a no-op.\n */\nexport async function refreshEnrollmentOpStream(\n db: Database,\n input: {\n workspaceId: string;\n agentId: string;\n opStream: boolean;\n },\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.opStream === input.opStream) {\n // The capability is unchanged — do not even issue the UPDATE (no churn on a\n // steady-state Hello).\n return { updated: false };\n }\n return await setEnrollmentOpStreamState(db, {\n accountId: enrollment.accountId,\n workspaceId: input.workspaceId,\n enrollmentId: input.agentId,\n opStream: input.opStream,\n });\n}\n\n/**\n * Decode a raw `Hello` payload + refresh the enrollment's display cursor + clear\n * any pending clean going-offline marker and, when the reconnect actually cleared\n * one, fan out machine.link.restored to the sessions with an active op on the\n * machine (the per-message handler for the hello plane). Decode failures + write\n * failures are reported + swallowed — a Hello must NEVER break the agent's connect.\n * `bus` (when present) enables the link.restored fan-out.\n */\nexport async function handleHelloPayload(\n db: Database,\n observability: Observability | undefined,\n payload: Uint8Array,\n subject: string,\n bus?: EventBus,\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 await refreshEnrollmentOpStream(db, {\n workspaceId: ids.workspaceId,\n agentId: ids.agentId,\n opStream: helloReportsOpStream(hello),\n });\n } catch (error) {\n observability?.warn?.(\"Failed to refresh an enrollment's capabilities from a Hello\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n // A reconnect Hello re-announces the machine, so any pending clean going-offline\n // marker no longer holds — clear it so the liveness derivation stops reading the\n // machine offline. Best-effort + fail-soft, and change-guarded in the DB (a\n // steady-state Hello with no marker writes nothing), so this never breaks the\n // agent's connect and never churns. When a marker was ACTUALLY cleared (the\n // machine had been reported link.lost), fan out machine.link.restored to the\n // sessions with an active op on it — a restored only ever pairs a prior lost, so\n // a routine connect Hello (no marker) emits nothing.\n try {\n const enrollment = await getEnrollment(db, ids.workspaceId, ids.agentId);\n if (enrollment) {\n const { cleared } = await clearEnrollmentWentOffline(db, {\n accountId: enrollment.accountId,\n workspaceId: ids.workspaceId,\n enrollmentId: ids.agentId,\n });\n if (cleared && bus) {\n await fanOutMachineLinkEvents(\n db,\n bus,\n observability,\n ids.workspaceId,\n ids.agentId,\n (activeTurnId) => [{ type: \"machine.link.restored\", turnId: activeTurnId, payload: {} }],\n );\n }\n }\n } catch (error) {\n observability?.warn?.(\"Failed to clear a machine going-offline marker on 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, deps.bus),\n );\n}\n"],"mappings":";;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,0BAAoD;AAC7D,SAAS,qBAAqB,iCAAiC;AAC/D,SAAS,oDAAoD;AAC7D;AAAA,EACE;AAAA,EACA,UAAU;AAAA,EACV;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;AC3BA,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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J;AAAA,UACE,WAAW,KAAK;AAAA,UAChB,aAAa,KAAK;AAAA,UAClB,QAAQ,KAAK;AAAA,UACb,aAAa;AAAA,QACf;AAAA,MACF;AAAA,IACF;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,wBACR,EAAE,uBAAuB,QAAQ,sBAAsB,IACvD,CAAC;AAAA,EACP;AACF;","names":["response","getEnrollment"]}
@@ -45,3 +45,11 @@ export declare function completeMcpOAuthCallback(deps: OAuthClientDeps, input: {
45
45
  export declare function integrationBaseUrl(publicBaseUrl: string | undefined, requestUrl: string): string;
46
46
  export declare function requireIntegrationsStateSecret(settings: Settings): string;
47
47
  export declare function assertSlackAuthorizationServer(as: AuthorizationServerMetadata): void;
48
+ export type OAuthPublicErrorFields = {
49
+ errorClass: "OAuthOperationError";
50
+ errorCode: "oauth_operation_failed";
51
+ status?: number;
52
+ origin: "oauth";
53
+ };
54
+ /** Allowlisted projection for public telemetry; canonical OAuth errors stay exact. */
55
+ export declare function oauthPublicErrorFields(error: unknown): OAuthPublicErrorFields;
@@ -13,7 +13,7 @@ export declare const SLACK_TASK_INSTRUCTIONS: string;
13
13
  * selection at session creation while keeping Slack mutations out of the model
14
14
  * surface; interaction delivery remains owned by the durable delivery pump.
15
15
  */
16
- export declare const SLACK_TASK_FIRST_PARTY_MCP_TOOLS: ("artifacts_create" | "artifacts_get_source" | "artifacts_list" | "artifacts_publish" | "artifacts_rollback" | "environment_list" | "environment_set_variable" | "github_connect_link" | "github_repositories_list" | "goal_complete" | "goal_pause" | "goal_set" | "goal_update" | "memory_correct" | "memory_save" | "memory_search" | "preference_registry_get" | "preference_registry_summary" | "rig_get" | "rig_list" | "rig_promote" | "rig_propose_change" | "rig_verify" | "run_on" | "sandbox_attach" | "sandbox_provision" | "sandbox_swap" | "sandboxes_list" | "scheduled_task_runs_list" | "scheduled_tasks_create" | "scheduled_tasks_delete" | "scheduled_tasks_get" | "scheduled_tasks_list" | "scheduled_tasks_pause" | "scheduled_tasks_resume" | "scheduled_tasks_trigger" | "scheduled_tasks_update" | "session_create" | "session_events" | "session_get" | "session_pause" | "session_resume" | "session_send_message" | "session_steer" | "sessions_list" | "set_other_session_title" | "set_session_title" | "slack_bot_channel_history" | "slack_bot_delete_message" | "slack_bot_file_content" | "slack_bot_file_info" | "slack_bot_list_channels" | "slack_bot_list_files" | "slack_bot_list_users" | "slack_bot_post_message" | "slack_bot_thread_replies" | "social_connections_list" | "social_daily_analysis_context" | "social_mentions_live" | "social_post_reply" | "social_posts_recent" | "social_posts_sync" | "social_search_live" | "social_thread_fetch" | "variable_set_list" | "variable_set_set_variable")[];
16
+ export declare const SLACK_TASK_FIRST_PARTY_MCP_TOOLS: ("artifacts_create" | "artifacts_get_source" | "artifacts_list" | "artifacts_publish" | "artifacts_rollback" | "connected_machine_remove" | "environment_list" | "environment_set_variable" | "github_connect_link" | "github_repositories_list" | "goal_complete" | "goal_pause" | "goal_set" | "goal_update" | "memory_correct" | "memory_save" | "memory_search" | "preference_registry_get" | "preference_registry_summary" | "rig_get" | "rig_list" | "rig_promote" | "rig_propose_change" | "rig_verify" | "run_on" | "sandbox_attach" | "sandbox_provision" | "sandbox_swap" | "sandboxes_list" | "scheduled_task_runs_list" | "scheduled_tasks_create" | "scheduled_tasks_delete" | "scheduled_tasks_get" | "scheduled_tasks_list" | "scheduled_tasks_pause" | "scheduled_tasks_resume" | "scheduled_tasks_trigger" | "scheduled_tasks_update" | "session_create" | "session_events" | "session_get" | "session_pause" | "session_resume" | "session_send_message" | "session_steer" | "sessions_list" | "set_other_session_title" | "set_session_title" | "slack_bot_channel_history" | "slack_bot_delete_message" | "slack_bot_file_content" | "slack_bot_file_info" | "slack_bot_list_channels" | "slack_bot_list_files" | "slack_bot_list_users" | "slack_bot_post_message" | "slack_bot_thread_replies" | "social_connections_list" | "social_daily_analysis_context" | "social_mentions_live" | "social_post_reply" | "social_posts_recent" | "social_posts_sync" | "social_search_live" | "social_thread_fetch" | "variable_set_get_variable" | "variable_set_list" | "variable_set_set_variable")[];
17
17
  export type NormalizedSlackInteraction = {
18
18
  providerEventId: string;
19
19
  providerMessageId: string;
@@ -25,6 +25,12 @@ export type NormalizedSlackInteraction = {
25
25
  triggerKind: SlackInteractionTriggerKind;
26
26
  text: string;
27
27
  };
28
+ export declare function slackInteractionRoutePolicy(entry: Pick<SlackInteractionInboxEntry, "triggerKind" | "slackChannelId" | "slackThreadTs" | "slackMessageTs" | "slackUserId">): {
29
+ directMessageShortcut: boolean;
30
+ requiresChannelAccess: boolean;
31
+ visibility: "private" | "workspace";
32
+ initialRouteKey: string;
33
+ };
28
34
  export declare function verifySlackRequestSignature(input: {
29
35
  timestamp: string | null;
30
36
  signature: string | null;
@@ -0,0 +1,28 @@
1
+ import { type McpMutationReceiptType } from "@opengeni/contracts";
2
+ export type McpMutationReceiptInput = Omit<McpMutationReceiptType, "receiptVersion" | "timestamp" | "warnings"> & {
3
+ timestamp?: string;
4
+ warnings?: string[];
5
+ };
6
+ /**
7
+ * Build and validate a compact first-party MCP mutation receipt at the API
8
+ * boundary. Contract parsing is intentional: it prevents a handler from
9
+ * accidentally adding an unbounded entity or a copy of request fields.
10
+ */
11
+ export declare function mcpMutationReceipt(input: McpMutationReceiptInput): McpMutationReceiptType;
12
+ export type SessionCreateReceiptResult = {
13
+ session: {
14
+ id: string;
15
+ queueVersion: number;
16
+ status: string;
17
+ sandboxGroupId: string;
18
+ parentSessionId: string | null;
19
+ rootSessionId: string;
20
+ nestedAgentDepth: number;
21
+ effectiveMaxNestedAgentDepth: number;
22
+ };
23
+ outcome: "created" | "repaired" | "replayed";
24
+ changed: boolean;
25
+ usageRecording: "recorded" | "failed";
26
+ };
27
+ /** Project committed session-create truth without copying request fields. */
28
+ export declare function sessionCreateMutationReceipt(result: SessionCreateReceiptResult, idempotencyKeyRequested: boolean): McpMutationReceiptType;