@opengeni/api-router 3.1.3-canary.38890816741001 → 3.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/observability.ts","../src/sandbox/auth-callout.ts","../src/sandbox/connection-authority.ts","../src/sandbox/metrics-ingestion.ts","../src/memory-slack-delivery.ts","../src/scheduled-task-lifecycle.ts","../src/scheduled-task-blockers.ts","../src/temporal-schedule-sync.ts","../src/native-push-dispatch.ts","../src/workspace-webhook-dispatch.ts","../src/editable-artifact-websocket.ts","../src/editable-artifact-source-session.ts","../src/http/websocket-upgrade-dispatch.ts","../src/editable-artifact-production.ts","../src/editable-artifact-live-hints.ts","../src/editable-artifact-native-kernel.ts","../src/editable-artifact-office-import.ts","../src/editable-artifact-workspace-files.ts","../src/fatal-process-boundary.ts"],"sourcesContent":["import { scheduledTaskKnowledgeSource } from \"@opengeni/contracts\";\nimport {\n dbSearchPath,\n getSettings,\n resolveFirstPartyDelegationSecret,\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 isRetryableRuntimeDatabaseStartupError,\n createDb,\n markSessionWorkflowWakeDelivered,\n runtimeDatabaseReadyCheck,\n type Database,\n} from \"@opengeni/db\";\nimport { createNatsEventBus, type ResponderConnection } from \"@opengeni/events\";\nimport {\n createObservability,\n logStartupDependencyRetry,\n type Observability,\n} from \"@opengeni/observability\";\nimport { createObjectStorage } from \"@opengeni/storage\";\nimport { isArtifactRuntimeConfigured } from \"@opengeni/artifact-tool/runtime/development\";\nimport {\n resolveCatalogSettings,\n SESSION_WORKFLOW_WAKE_DISPATCH_REQUESTED_SIGNAL,\n SESSION_WORKFLOW_WAKE_DISPATCHER_WORKFLOW_ID,\n SESSION_WORKFLOW_WAKE_DISPATCHER_WORKFLOW_TYPE,\n} 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 { observabilityEventBusOptions } from \"./observability\";\nimport { startAuthCalloutResponder } from \"./sandbox/auth-callout\";\nimport { startHelloIngestion, startMetricsIngestion } from \"./sandbox/metrics-ingestion\";\nimport { createAutomaticAgentUpdater } from \"./sandbox/agent-update\";\nimport { startSlackInteractionPump } from \"./integrations/slack-interactions\";\nimport { startMemorySlackPublicationPump } from \"./memory-slack-delivery\";\nimport { startTemporalScheduleCleanupPump } from \"./temporal-schedule-cleanup\";\nimport { startScheduledTaskLifecyclePump } from \"./scheduled-task-lifecycle\";\nimport { createTemporalScheduleSynchronizer } from \"./temporal-schedule-sync\";\nimport { startNativePushDispatchPump } from \"./native-push-dispatch\";\nimport { startWorkspaceWebhookDispatchPump } from \"./workspace-webhook-dispatch\";\nimport { cleanupScheduledTaskConnectorAuthorization } from \"./scheduled-task-deletion\";\nimport {\n EDITABLE_ARTIFACT_LIVE_WEBSOCKET_MAX_MESSAGE_BYTES,\n EditableArtifactWebSocketTransport,\n} from \"./editable-artifact-websocket\";\nimport { editableArtifactSourceSessionAuthorizer } from \"./editable-artifact-source-session\";\nimport type { ApiWebSocketConnection } from \"./api-websocket\";\nimport { InteractionFrameProxyTransport } from \"./interaction-frame-proxy\";\nimport { apiRequestBindingsForTransportPeer } from \"./http/request-source\";\nimport { startApiMetricsListener } from \"./http/metrics-listener\";\nimport { createLocalBrowserBoundary } from \"./http/local-browser-boundary\";\nimport { dispatchApiWebSocketUpgrade } from \"./http/websocket-upgrade-dispatch\";\nimport {\n createStandaloneEditableArtifactApplication,\n type StandaloneEditableArtifactApplication,\n} from \"./editable-artifact-production\";\nimport { installApiFatalProcessBoundary } from \"./fatal-process-boundary\";\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 scheduledTasks = createTemporalScheduleSynchronizer({\n db,\n withDeadline: (deadline, work) => temporal.withDeadline(deadline, work),\n upsert: async (task) => {\n const options = temporalScheduleOptions(task, settings.temporalTaskQueue);\n try {\n await temporal.schedule\n .getHandle(task.temporalScheduleId)\n .update(() => temporalScheduleUpdateOptions(options));\n } catch (error) {\n if (!shouldCreateScheduleAfterUpdateError(error)) throw error;\n await temporal.schedule.create(options);\n }\n },\n remove: async (temporalScheduleId) => {\n try {\n await temporal.schedule.getHandle(temporalScheduleId).delete();\n } catch (error) {\n if (!(error instanceof ScheduleNotFoundError)) throw error;\n }\n },\n });\n const client: SessionWorkflowClient = {\n triggerAutomationRun: async ({ accountId, workspaceId, runId }) => {\n try {\n await temporal.workflow.start(\"automationRunWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId: `automation-run:${runId}`,\n workflowIdReusePolicy: \"REJECT_DUPLICATE\",\n args: [{ accountId, workspaceId, runId }],\n });\n } catch (error) {\n if (isWorkflowAlreadyStarted(error)) return;\n throw error;\n }\n },\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 onSignalAccepted,\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 onSignalAccepted?.();\n return await markSessionWorkflowWakeDelivered(db, {\n accountId,\n workspaceId,\n sessionId,\n temporalWorkflowId: workflowId,\n wakeRevision,\n });\n },\n requestSessionWorkflowWakeDispatch: async () => {\n await temporal.workflow.signalWithStart(SESSION_WORKFLOW_WAKE_DISPATCHER_WORKFLOW_TYPE, {\n taskQueue: settings.temporalTaskQueue,\n workflowId: SESSION_WORKFLOW_WAKE_DISPATCHER_WORKFLOW_ID,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [],\n signal: SESSION_WORKFLOW_WAKE_DISPATCH_REQUESTED_SIGNAL,\n });\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, onFailure }) => scheduledTasks.sync(task, onFailure),\n deleteScheduledTaskSchedule: async ({ temporalScheduleId }) =>\n scheduledTasks.remove(temporalScheduleId),\n triggerScheduledTask: async ({\n task,\n agentRunUsageIdempotencyKey,\n triggerWorkflowId,\n initiator,\n credentialRestriction,\n triggerType = \"manual\",\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,\n agentRunUsageIdempotencyKey,\n initiator,\n ...(credentialRestriction ? { credentialRestriction } : {}),\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(\"sandbox environment verification requires changeId or versionId\");\n }\n try {\n await temporal.workflow.start(\"rigVerificationWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId: workflowId ?? `rig-verification-${targetId}-${crypto.randomUUID()}`,\n workflowIdReusePolicy: \"REJECT_DUPLICATE\",\n args: [\n {\n workspaceId,\n ...(changeId ? { changeId } : {}),\n ...(versionId ? { versionId } : {}),\n },\n ],\n });\n } catch (error) {\n // A lost start acknowledgement is indistinguishable from a retry. The\n // caller-owned workflow id makes both cases the same successful start.\n if (isWorkflowAlreadyStarted(error)) return;\n throw error;\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 options: {\n settings?: ReturnType<typeof getSettings>;\n observability?: Observability;\n } = {},\n) {\n const settings = options.settings ?? getSettings();\n const observability =\n options.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 max: settings.apiDatabasePoolMax,\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 exact generation-fenced agent RPC subjects. Null in local dev\n // (anonymous connect — the bus default).\n const controlPlaneAuth = resolveNatsControlPlaneAuth(settings);\n try {\n // Browser, Computer, Terminal, and Files can cold-create the home sandbox\n // directly from this API process. Resolve the same private-registry Modal\n // image before the API becomes reachable so the first human interaction\n // does not pay the provider import/build latency. This mirrors the turn\n // worker's startup boundary and is a no-op for provider-native image IDs,\n // public images, and non-Modal backends.\n const { ensureModalRegistryImage } = await import(\"@opengeni/runtime/sandbox\");\n await retryStartupDependency(\n \"Modal private-registry image\",\n () => ensureModalRegistryImage(settings),\n { ...retryOptions, onRetry },\n );\n await retryStartupDependency(\n \"PostgreSQL runtime posture\",\n () => assertRuntimeDatabasePosture(dbClient.db, databasePosture),\n { ...retryOptions, onRetry, shouldRetry: isRetryableRuntimeDatabaseStartupError },\n );\n const resolvedCatalog = await retryStartupDependency(\n \"model catalog\",\n () => resolveCatalogSettings(dbClient.db, settings),\n { ...retryOptions, onRetry },\n );\n observability.info(\"Opengeni model catalog resolved\", {\n catalogSource: resolvedCatalog.source,\n catalogVersion: resolvedCatalog.version,\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 observabilityEventBusOptions(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 objectStorage = createObjectStorage(settings);\n let editableArtifactComposition: StandaloneEditableArtifactApplication | undefined;\n if (objectStorage && isArtifactRuntimeConfigured()) {\n try {\n editableArtifactComposition = await createStandaloneEditableArtifactApplication({\n db: dbClient.db,\n bus,\n objectStorage,\n });\n } catch (error) {\n await Promise.allSettled([bus.close(), workflowClient.close(), dbClient.close()]);\n throw error;\n }\n }\n const { app, routeDeps } = createAppComposition({\n settings,\n db: dbClient.db,\n bus,\n workflowClient: workflowClient.client,\n documentIndexer: workflowClient.documentIndexer,\n objectStorage,\n ...(editableArtifactComposition\n ? {\n editableArtifacts: editableArtifactComposition.application,\n editableArtifactExports: editableArtifactComposition.durableExports,\n editableArtifactAgent: editableArtifactComposition.agent,\n editableArtifactOfficeImports: editableArtifactComposition.officeImports,\n }\n : {}),\n observability,\n readinessChecks: {\n db: runtimeDatabaseReadyCheck(dbClient.db, databasePosture),\n },\n });\n if (!routeDeps.editableArtifacts) {\n observability.warn(\"editable artifact engine is not composed\", {\n subsystem: \"editable_artifacts\",\n behavior: \"http_and_websocket_fail_closed\",\n });\n }\n const artifactWebSockets = new EditableArtifactWebSocketTransport(\n routeDeps.editableArtifacts,\n editableArtifactSourceSessionAuthorizer(routeDeps),\n );\n const interactionFrameProxies = new InteractionFrameProxyTransport(\n resolveFirstPartyDelegationSecret(settings),\n );\n // WebSocket upgrades bypass the Hono app, so the local-mode browser boundary\n // (http/local-browser-boundary.ts) is applied to them in the dispatcher;\n // every other request meets it in the Hono middleware.\n const localBrowserBoundary = createLocalBrowserBoundary(settings, {\n warn: (message, attributes) => observability.warn(message, attributes),\n });\n const webSocketUpgrades = [interactionFrameProxies, artifactWebSockets];\n const server = Bun.serve<ApiWebSocketConnection>({\n hostname: settings.apiHost,\n port: settings.apiPort,\n idleTimeout: 255,\n fetch: (request, bunServer) => {\n const upgrade = dispatchApiWebSocketUpgrade(\n request,\n bunServer,\n webSocketUpgrades,\n localBrowserBoundary,\n );\n if (upgrade.handled) return upgrade.response;\n return app.fetch(\n request,\n apiRequestBindingsForTransportPeer(bunServer.requestIP(request)?.address),\n );\n },\n websocket: {\n maxPayloadLength: EDITABLE_ARTIFACT_LIVE_WEBSOCKET_MAX_MESSAGE_BYTES,\n backpressureLimit: 16 * 1024 * 1024,\n closeOnBackpressureLimit: true,\n open: (socket) => socket.data.attach(socket),\n message: (socket, message) => socket.data.receive(message),\n close: (socket) => socket.data.transportClosed(),\n },\n });\n const metricsServer = startApiMetricsListener(settings, observability);\n const stopSlackInteractionPump = settings.slackSigningSecret\n ? startSlackInteractionPump(routeDeps)\n : undefined;\n const stopMemorySlackPublicationPump = startMemorySlackPublicationPump(routeDeps);\n const stopWorkspaceWebhookDispatchPump = startWorkspaceWebhookDispatchPump({\n db: dbClient.db,\n settings,\n observability,\n });\n const stopNativePushDispatchPump = startNativePushDispatchPump({\n db: dbClient.db,\n settings,\n observability,\n });\n const stopTemporalScheduleCleanupPump = startTemporalScheduleCleanupPump({\n db: dbClient.db,\n cleanupConnectorAuthorization: async (claim) =>\n await cleanupScheduledTaskConnectorAuthorization(routeDeps, claim),\n deleteSchedule: async (temporalScheduleId) => {\n await workflowClient.client.deleteScheduledTaskSchedule({ temporalScheduleId });\n },\n observability,\n });\n const stopScheduledTaskLifecyclePump = startScheduledTaskLifecyclePump({\n db: dbClient.db,\n sync: (task) => workflowClient.client.syncScheduledTask({ task }),\n bus,\n observability,\n });\n // M10 — start the metrics-ingestion consumer (agent heartbeats → DB last-sample\n // + downsampled series), gated on the selfhosted flag. A no-op when disabled.\n let stopMetricsIngestion: (() => void) | undefined;\n // Reconcile enrollments.has_display to the LIVE capability the agent reports in\n // its connect Hello (has_display was frozen at the enroll-time snapshot). Gated\n // on the same selfhosted flag.\n let stopHelloIngestion: (() => void) | undefined;\n // M-AUTH — start the NATS auth-callout responder (the tenancy boundary): it\n // validates an agent's enrollment bearer presented at NATS connect and mints a\n // workspace-scoped user JWT. Gated on the selfhosted flag + a resolvable callout\n // config; without the callout plane it never starts (selfhosted agents simply\n // cannot connect — graceful). It runs on its OWN connection (the callout auth\n // user), separate from the privileged control-plane bus.\n let authCalloutResponder: ResponderConnection | undefined;\n if (settings.sandboxSelfhostedEnabled) {\n stopMetricsIngestion = startMetricsIngestion({\n db: dbClient.db,\n bus,\n observability,\n agentUpdates: createAutomaticAgentUpdater({\n db: dbClient.db,\n bus,\n settings,\n observability,\n }),\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 ...(metricsServer ? { metricsPort: settings.apiMetricsPort } : {}),\n });\n return {\n server,\n close: async () => {\n server.stop(true);\n metricsServer?.stop(true);\n stopSlackInteractionPump?.();\n await stopMemorySlackPublicationPump();\n stopMetricsIngestion?.();\n stopHelloIngestion?.();\n await stopTemporalScheduleCleanupPump();\n await stopScheduledTaskLifecyclePump();\n await stopWorkspaceWebhookDispatchPump();\n await stopNativePushDispatchPump();\n // Write queued presence before the database pool closes.\n await routeDeps.userPresence?.close().catch(() => undefined);\n await Promise.allSettled([\n Promise.resolve(editableArtifactComposition?.close()),\n authCalloutResponder?.close(),\n bus.close(),\n workflowClient.close(),\n dbClient.close(),\n ]);\n },\n };\n}\n\nif (import.meta.main) {\n const fatalBoundary = installApiFatalProcessBoundary();\n try {\n const settings = getSettings();\n const observability = createObservability(settings, { component: \"api\" });\n fatalBoundary.attachObservability(observability);\n await startApi({ settings, observability });\n fatalBoundary.markRunning();\n } catch (error) {\n await fatalBoundary.reportStartupFailure(error);\n }\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 === \"manual\") {\n throw new Error(\"manual scheduled tasks do not have a Temporal Schedule spec\");\n }\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: scheduledTaskEffectivelyPaused(task),\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 scheduledTaskEffectivelyPaused(task: ScheduledTask): boolean {\n if (task.status === \"paused\") return true;\n if (!scheduledTaskKnowledgeSource(task)) return false;\n const control = task.metadata.knowledgeSourceSync;\n if (!control || typeof control !== \"object\") return false;\n const record = control as Record<string, unknown>;\n return record.sourceEnabled === false || record.connectionPaused === true;\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 {\n natsSubscriptionTerminationCounter,\n type EventBusOptions,\n type EventLogger,\n} from \"@opengeni/events\";\nimport type { Attributes, AttributeValue, Observability } from \"@opengeni/observability\";\n\n/** Logger plus the closed-label subscription-termination counter for NATS connections. */\nexport function observabilityEventBusOptions(\n observability: Observability,\n): Pick<EventBusOptions, \"logger\" | \"onSubscriptionTerminated\"> {\n return {\n logger: observabilityEventLogger(observability),\n onSubscriptionTerminated: natsSubscriptionTerminationCounter(observability),\n };\n}\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. atomically claims the daemon instance named in CONNECT;\n// 5. signs a NATS user JWT granting pub/sub ONLY that exact process subtree +\n// `_INBOX.>` (deny-all-else by an allow-list) and returns it inside a signed\n// authorization-response JWT.\n//\n// That exact scope is both the tenancy boundary and routing fence: workspace A\n// cannot reach B, and an old/duplicate process cannot subscribe to its successor's\n// work. nats-server enforces the signed permission set; the boundary does not rely\n// on naming alone.\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 { createHash } from \"node:crypto\";\nimport { createLogThrottle, type LogThrottle } from \"@opengeni/observability\";\nimport {\n resolveEnrollmentSigningSecret,\n type NatsCalloutConfig,\n type Settings,\n} from \"@opengeni/config\";\nimport { verifyEnrollmentBearer } from \"@opengeni/contracts\";\nimport { claimEnrollmentConnection, getEnrollment, type Database } from \"@opengeni/db\";\nimport {\n createResponderConnection,\n decodeAuthRequest,\n mintAuthResponse,\n mintUserJwt,\n parseAgentConnectionName,\n workspaceAgentPermissions,\n type ResponderConnection,\n} from \"@opengeni/events\";\nimport type { Observability } from \"@opengeni/observability\";\nimport { observabilityEventBusOptions } from \"../observability\";\nimport { AGENT_CONNECTION_LEASE_MS } from \"./connection-authority\";\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;\nexport interface AuthCalloutDeps {\n db: Database;\n settings: Settings;\n callout: NatsCalloutConfig;\n observability?: Observability;\n /** Bounds repeated denial warnings; defaults to one process-wide throttle. */\n denialWarningThrottle?: LogThrottle;\n}\n\n/** A stale or revoked machine re-dials on its reconnect backoff forever, so an\n * unthrottled denial warning repeats every few seconds per machine. Log each\n * distinct machine's first denial, then at most once per interval with the\n * count of denials it hid. The denial decision itself is never throttled. */\nexport const AUTH_CALLOUT_DENIAL_WARNING_INTERVAL_MS = 60_000;\nconst processDenialWarningThrottle = createLogThrottle({\n intervalMs: AUTH_CALLOUT_DENIAL_WARNING_INTERVAL_MS,\n maxKeys: 1_024,\n});\n\n/** Closed denial vocabulary. The public log projection drops identifiers, so\n * `reason` is what tells an operator which throttle key a count belongs to. */\ntype AuthCalloutDenialReason = \"invalid_bearer\" | \"inactive_enrollment\" | \"duplicate_runner\";\n\nfunction warnDenial(\n deps: AuthCalloutDeps,\n key: string,\n reason: AuthCalloutDenialReason,\n message: string,\n attributes: Record<string, string | number> = {},\n): void {\n const admission = (deps.denialWarningThrottle ?? processDenialWarningThrottle).admit(key);\n if (!admission) return;\n deps.observability?.warn?.(message, {\n ...attributes,\n reason,\n ...(admission.suppressedCount > 0 ? { suppressedCount: admission.suppressedCount } : {}),\n });\n}\n\n/** Closed reasons a Connected Machine agent's NATS connect is refused. */\ntype MachineConnectDenialReason =\n | \"undecodable\"\n | \"missing_bearer\"\n | \"plane_disabled\"\n | \"invalid_bearer\"\n | \"inactive_enrollment\"\n | \"identity_mismatch\"\n | \"generation_mismatch\"\n | \"invalid_instance\"\n | \"duplicate_runner\";\n\n/** Count every machine connect decision; identifiers never become labels. */\nfunction recordMachineConnect(\n deps: AuthCalloutDeps,\n outcome: \"granted\" | \"denied\",\n reason: MachineConnectDenialReason | \"none\",\n): void {\n try {\n deps.observability?.incrementCounter({\n name: \"opengeni_machine_connect_total\",\n help: \"Connected Machine agent NATS connect decisions (auth callout) by outcome and closed denial reason.\",\n labels: { outcome, reason },\n });\n } catch {\n // Telemetry never changes the signed connect decision.\n }\n}\n\n/** A process-local dedupe key for a rejected bearer. The digest is never\n * logged, and the bearer value never leaves this function. */\nfunction rejectedBearerKey(bearer: string): string {\n return `invalid-bearer:${createHash(\"sha256\").update(bearer).digest(\"hex\").slice(0, 32)}`;\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 recordMachineConnect(deps, \"denied\", \"undecodable\");\n throw new Error(\"undecodable authorization request\");\n }\n\n const deny = (code: MachineConnectDenialReason, reason: string): Uint8Array => {\n recordMachineConnect(deps, \"denied\", code);\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_bearer\", \"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(\"plane_disabled\", \"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 warnDenial(\n deps,\n rejectedBearerKey(bearer),\n \"invalid_bearer\",\n \"auth-callout: rejected an invalid enrollment bearer\",\n );\n return deny(\"invalid_bearer\", \"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 warnDenial(\n deps,\n `inactive:${claims.workspaceId}:${claims.agentId}`,\n \"inactive_enrollment\",\n \"auth-callout: denied a revoked or unknown enrollment\",\n { workspaceId: claims.workspaceId, agentId: claims.agentId },\n );\n return deny(\"inactive_enrollment\", \"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(\"identity_mismatch\", \"enrollment identity mismatch\");\n }\n if (enrollment.credentialGeneration !== claims.credentialGeneration) {\n return deny(\"generation_mismatch\", \"enrollment credential generation mismatch\");\n }\n\n const connectionInstanceId = parseAgentConnectionName(decoded.name);\n if (!connectionInstanceId) {\n return deny(\"invalid_instance\", \"missing or invalid agent connection instance\");\n }\n const claim = await claimEnrollmentConnection(deps.db, {\n workspaceId: claims.workspaceId,\n enrollmentId: claims.enrollmentId,\n credentialGeneration: claims.credentialGeneration,\n connectionInstanceId,\n leaseMs: AGENT_CONNECTION_LEASE_MS,\n });\n if (!claim.claimed) {\n warnDenial(\n deps,\n `duplicate:${claims.workspaceId}:${claims.agentId}`,\n \"duplicate_runner\",\n \"auth-callout: denied a duplicate live runner\",\n { workspaceId: claims.workspaceId, agentId: claims.agentId },\n );\n return deny(\"duplicate_runner\", \"another runner instance currently owns this enrollment\");\n }\n\n // GRANT: the operational subject includes the exact claimed process instance.\n // A previous socket may remain open until its short JWT expires, but no control\n // request is routed to its old subject after a successor claims authority.\n const permissions = workspaceAgentPermissions(\n claims.workspaceId,\n claims.agentId,\n connectionInstanceId,\n );\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 recordMachineConnect(deps, \"granted\", \"none\");\n deps.observability?.info?.(\"auth-callout: granted a workspace-scoped NATS credential\", {\n workspaceId: claims.workspaceId,\n agentId: claims.agentId,\n connectionGeneration: claim.connectionGeneration,\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 ? observabilityEventBusOptions(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","/** Five-second heartbeats get four missed intervals before another daemon may\n * claim the enrollment. Server time is authoritative. */\nexport const AGENT_CONNECTION_LEASE_MS = 20_000;\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 the exact process events subject) and publishes a\n// `Hello` (its live self-description) on the exact process hello subject on every connect\n// /reconnect. This module owns the two agent→control-plane inbound consumers:\n//\n// `agent.*.*.connection.*.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.*.*.connection.*.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. Exec is unavailable unless the runner\n// 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. Event ingestion drains the NATS\n// subscription immediately into exact-subject queues: different runner connections\n// progress concurrently, one runner's ordering is preserved, and consecutive queued\n// heartbeats collapse latest-wins. A delayed heartbeat backlog therefore cannot keep\n// renewing a dead runner's short connection lease one stale message at a time.\n\nimport {\n clearEnrollmentWentOffline,\n disconnectAttachedBrowserDevices,\n advanceEnrollmentAgentUpdate,\n enrollmentMacPermissionCapabilities,\n enrollmentMacPermissions,\n getEnrollment,\n getLiveEnrollmentConnection,\n ingestMachineMetricsSample,\n reconcileAttachedBrowserInventory,\n releaseEnrollmentConnection,\n renewEnrollmentConnection,\n sessionsWithActiveOpOnEnrollment,\n setEnrollmentDisplayState,\n setEnrollmentAgentRuntime,\n setEnrollmentOpStreamState,\n type AppendEventInput,\n type Database,\n type EnrollmentMacPermissions,\n type MachineMetricsSample,\n} from \"@opengeni/db\";\nimport {\n AttachedBrowserConnectionEnd as AttachedBrowserConnectionEndContract,\n AttachedBrowserInventorySnapshot as AttachedBrowserInventoryContract,\n type AttachedBrowserInventorySnapshot as AttachedBrowserInventoryContractValue,\n type AttachedBrowserConnectionEnd as AttachedBrowserConnectionEndValue,\n} from \"@opengeni/contracts\";\nimport { appendAndPublishEvents, type EventBus } from \"@opengeni/events\";\nimport type { Observability } from \"@opengeni/observability\";\nimport { normalizeConnectedMachineWorkspaceRoot } from \"@opengeni/runtime/sandbox\";\nimport type { AutomaticAgentUpdater } from \"./agent-update\";\nimport {\n AgentEvent,\n AgentUpdateStage,\n Arch,\n AttachedBrowserConnectionEndReason as WireConnectionEndReason,\n GoingOfflineReason,\n Hello,\n Os,\n goingOfflineReasonToJSON,\n type AttachedBrowserConnectionEnd as WireAttachedBrowserConnectionEnd,\n type AttachedBrowserInventorySnapshot as WireAttachedBrowserInventorySnapshot,\n type MetricsSample,\n} from \"@opengeni/agent-proto\";\nimport { AGENT_CONNECTION_LEASE_MS } from \"./connection-authority\";\nimport { reconcileScreenControlOnHello } from \"./screen-control\";\n\n/** The wildcard subject the agent event plane publishes heartbeats on. */\nexport const AGENT_EVENTS_SUBJECT = \"agent.*.*.connection.*.events\";\n\n/** The wildcard subject the agent publishes its connect Hello on. */\nexport const AGENT_HELLO_SUBJECT = \"agent.*.*.connection.*.hello\";\n\ntype QueuedAgentEvent = {\n payload: Uint8Array;\n subject: string;\n heartbeat: boolean;\n};\n\ntype AgentEventQueueState = {\n scheduled: boolean;\n pending: QueuedAgentEvent[];\n};\n\ntype ScheduledAgentEventQueue = {\n subject: string;\n state: AgentEventQueueState;\n};\n\nexport type AgentEventIngestionScheduler = {\n enqueue: (payload: Uint8Array, subject: string) => void;\n whenIdle: () => Promise<void>;\n close: () => void;\n};\n\nfunction payloadIsHeartbeat(payload: Uint8Array): boolean {\n try {\n return AgentEvent.decode(payload).event?.$case === \"heartbeat\";\n } catch {\n // Preserve the normal decoder/logging path for malformed events. They are\n // barriers rather than heartbeat-coalescing candidates.\n return false;\n }\n}\n\n/**\n * Drain agent events without making every Connected Machine wait behind one\n * deployment-wide serial DB queue. Each exact process subject retains FIFO order;\n * separate subjects drain concurrently. Consecutive pending heartbeats for one\n * subject are latest-wins because they are point-in-time liveness/metrics samples,\n * while GoingOffline and update-progress events remain ordered barriers.\n */\nexport function createAgentEventIngestionScheduler(\n handler: (payload: Uint8Array, subject: string) => void | Promise<void>,\n options: { maxConcurrentSubjects?: number; onHeartbeatCoalesced?: () => void } = {},\n): AgentEventIngestionScheduler {\n const maxConcurrentSubjects = options.maxConcurrentSubjects ?? 32;\n if (!Number.isSafeInteger(maxConcurrentSubjects) || maxConcurrentSubjects <= 0) {\n throw new RangeError(\"maxConcurrentSubjects must be a positive safe integer\");\n }\n\n const states = new Map<string, AgentEventQueueState>();\n const readySubjects: ScheduledAgentEventQueue[] = [];\n const idleWaiters = new Set<() => void>();\n let accepting = true;\n let activeSubjects = 0;\n\n const resolveIdleWaiters = (): void => {\n if (states.size !== 0) return;\n for (const resolve of idleWaiters) resolve();\n idleWaiters.clear();\n };\n\n async function drain(subject: string, state: AgentEventQueueState): Promise<void> {\n while (true) {\n const event = state.pending.shift();\n if (!event) break;\n try {\n await handler(event.payload, event.subject);\n } catch {\n // Agent-event ingestion is best-effort. One bad event must not strand the\n // exact-subject queue or prevent later heartbeats from restoring liveness.\n }\n }\n\n activeSubjects -= 1;\n state.scheduled = false;\n if (state.pending.length > 0) {\n schedule(subject, state);\n } else {\n if (states.get(subject) === state) states.delete(subject);\n resolveIdleWaiters();\n }\n pump();\n }\n\n function pump(): void {\n while (activeSubjects < maxConcurrentSubjects) {\n const next = readySubjects.shift();\n if (!next) return;\n if (states.get(next.subject) !== next.state || !next.state.scheduled) continue;\n activeSubjects += 1;\n void drain(next.subject, next.state);\n }\n }\n\n function schedule(subject: string, state: AgentEventQueueState): void {\n if (state.scheduled) return;\n state.scheduled = true;\n readySubjects.push({ subject, state });\n pump();\n }\n\n return {\n enqueue(payload, subject) {\n if (!accepting) return;\n const heartbeat = payloadIsHeartbeat(payload);\n let state = states.get(subject);\n if (!state) {\n state = { scheduled: false, pending: [] };\n states.set(subject, state);\n }\n\n const queued = { payload, subject, heartbeat };\n const lastIndex = state.pending.length - 1;\n if (heartbeat && lastIndex >= 0 && state.pending[lastIndex]!.heartbeat) {\n state.pending[lastIndex] = queued;\n options.onHeartbeatCoalesced?.();\n } else {\n state.pending.push(queued);\n }\n\n schedule(subject, state);\n },\n async whenIdle() {\n if (states.size === 0) return;\n await new Promise<void>((resolve) => idleWaiters.add(resolve));\n },\n close() {\n accepting = false;\n for (const state of states.values()) {\n state.pending.length = 0;\n }\n resolveIdleWaiters();\n },\n };\n}\n\n/**\n * Parse `agent.<ws>.<id>.connection.<instance>.<tail>` into its exact authority,\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; connectionInstanceId: string } | null {\n const parts = subject.split(\".\");\n if (\n parts.length !== 6 ||\n parts[0] !== \"agent\" ||\n parts[3] !== \"connection\" ||\n !parts[4] ||\n parts[5] !== tail\n ) {\n return null;\n }\n return {\n workspaceId: parts[1]!,\n agentId: parts[2]!,\n connectionInstanceId: parts[4]!,\n };\n}\n\n/** Parse the exact process events subject (heartbeat plane). */\nexport function parseAgentEventSubject(\n subject: string,\n): { workspaceId: string; agentId: string; connectionInstanceId: string } | null {\n return parseAgentSubject(subject, \"events\");\n}\n\n/** Parse the exact process hello subject (connect plane). */\nexport function parseAgentHelloSubject(\n subject: string,\n): { workspaceId: string; agentId: string; connectionInstanceId: 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/** Validate and project one wire inventory before it reaches durable browser\n * discovery. Unknown enum values and unsafe uint64 counters reject the whole\n * authoritative snapshot instead of partially disconnecting good endpoints. */\nexport function wireAttachedBrowserInventoryToContract(\n wire: WireAttachedBrowserInventorySnapshot,\n): AttachedBrowserInventoryContractValue {\n return AttachedBrowserInventoryContract.parse({\n bridgeGeneration: wire.bridgeGeneration,\n revision: safeWireInteger(wire.revision, \"browser inventory revision\"),\n devices: wire.devices.map((device) => ({\n id: device.id,\n name: device.name,\n profileLabel: device.profileLabel.trim() || null,\n browserName: device.browserName,\n browserVersion: device.browserVersion,\n extensionVersion: device.extensionVersion,\n platform: wireBrowserPlatform(device.platform),\n architecture: wireBrowserArchitecture(device.arch),\n connectionGeneration: device.connectionGeneration,\n inventoryRevision: safeWireInteger(\n device.inventoryRevision,\n \"attached browser inventory revision\",\n ),\n tabCount: safeWireInteger(device.tabCount, \"attached browser tab count\"),\n capabilities: device.capabilities,\n })),\n connectionEnds: (wire.connectionEnds ?? []).flatMap(wireConnectionEndToContract),\n });\n}\n\nconst WIRE_CONNECTION_END_REASONS = new Map<\n WireConnectionEndReason,\n AttachedBrowserConnectionEndValue[\"reason\"]\n>([\n [\n WireConnectionEndReason.ATTACHED_BROWSER_CONNECTION_END_REASON_BROWSER_CLOSED_PORT,\n \"browser_closed_port\",\n ],\n [\n WireConnectionEndReason.ATTACHED_BROWSER_CONNECTION_END_REASON_BROWSER_MESSAGE_INVALID,\n \"browser_message_invalid\",\n ],\n [\n WireConnectionEndReason.ATTACHED_BROWSER_CONNECTION_END_REASON_BROWSER_OUTPUT_FAILED,\n \"browser_output_failed\",\n ],\n [\n WireConnectionEndReason.ATTACHED_BROWSER_CONNECTION_END_REASON_NATIVE_HOST_LOST,\n \"native_host_lost\",\n ],\n [WireConnectionEndReason.ATTACHED_BROWSER_CONNECTION_END_REASON_AGENT_REJECTED, \"agent_rejected\"],\n]);\n\n/** Connection ends are diagnostics. One the contract cannot hold (a future\n * reason, or the generation of a hello the bridge rejected as malformed) is\n * dropped instead of rejecting the authoritative device inventory. */\nfunction wireConnectionEndToContract(\n wire: WireAttachedBrowserConnectionEnd,\n): AttachedBrowserConnectionEndValue[] {\n const reason = WIRE_CONNECTION_END_REASONS.get(wire.reason);\n const endedAtMs = Number(wire.endedAtUnixMs);\n if (!reason || !Number.isSafeInteger(endedAtMs) || endedAtMs <= 0) return [];\n const parsed = AttachedBrowserConnectionEndContract.safeParse({\n deviceId: wire.deviceId,\n connectionGeneration: wire.connectionGeneration,\n reason,\n detail: wire.detail.slice(0, 512) || null,\n endedAt: new Date(endedAtMs).toISOString(),\n connectedMs: Math.min(Number(wire.connectedMs) || 0, Number.MAX_SAFE_INTEGER),\n });\n return parsed.success ? [parsed.data] : [];\n}\n\nfunction safeWireInteger(value: string | number, label: string): number {\n let parsed: bigint;\n try {\n parsed = BigInt(value);\n } catch {\n throw new Error(`${label} is not an integer`);\n }\n if (parsed < 0n || parsed > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new Error(`${label} is outside the safe integer range`);\n }\n return Number(parsed);\n}\n\nfunction wireBrowserPlatform(platform: Os): \"linux\" | \"macos\" | \"windows\" {\n switch (platform) {\n case Os.OS_LINUX:\n return \"linux\";\n case Os.OS_MACOS:\n return \"macos\";\n case Os.OS_WINDOWS:\n return \"windows\";\n default:\n throw new Error(\"attached browser platform is unspecified or unsupported\");\n }\n}\n\nfunction wireBrowserArchitecture(architecture: Arch): \"x64\" | \"arm64\" {\n switch (architecture) {\n case Arch.ARCH_X86_64:\n return \"x64\";\n case Arch.ARCH_AARCH64:\n return \"arm64\";\n default:\n throw new Error(\"attached browser architecture is unspecified or unsupported\");\n }\n}\n\nasync function ingestAttachedBrowserInventory(\n db: Database,\n input: {\n workspaceId: string;\n agentId: string;\n inventory: WireAttachedBrowserInventorySnapshot;\n },\n): Promise<void> {\n const enrollment = await getEnrollment(db, input.workspaceId, input.agentId);\n if (!enrollment) return;\n await reconcileAttachedBrowserInventory(db, {\n accountId: enrollment.accountId,\n workspaceId: input.workspaceId,\n enrollmentId: input.agentId,\n snapshot: wireAttachedBrowserInventoryToContract(input.inventory),\n });\n}\n\n/**\n * Ingest the OPTIONAL metrics sample carried by an already-authorized heartbeat.\n * Connection renewal is deliberately owned by the outer event handler and runs\n * before optional telemetry/inventory work, so telemetry absence or failure can\n * never make a healthy runner lose authority.\n */\nasync function ingestHeartbeatMetrics(\n db: Database,\n input: {\n accountId: string;\n workspaceId: string;\n agentId: string;\n sample: MetricsSample;\n },\n): Promise<{ ingested: boolean; seriesAppended: boolean }> {\n const sample = wireSampleToDbSample(input.sample);\n const result = await ingestMachineMetricsSample(db, {\n accountId: input.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 agentUpdates?: AutomaticAgentUpdater | null,\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 const released = await releaseEnrollmentConnection(db, {\n accountId: enrollment.accountId,\n workspaceId: ids.workspaceId,\n enrollmentId: ids.agentId,\n connectionInstanceId: ids.connectionInstanceId,\n reason,\n });\n // A late goodbye from a superseded process is not the current machine\n // going offline. It must not disconnect browsers or fan out link loss.\n if (!released.released) return;\n try {\n await disconnectAttachedBrowserDevices(db, {\n accountId: enrollment.accountId,\n workspaceId: ids.workspaceId,\n enrollmentId: ids.agentId,\n });\n } catch (error) {\n observability?.warn?.(\"Failed to disconnect attached browsers with their machine\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\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 === \"agentUpdateProgress\") {\n const enrollment = await getEnrollment(db, ids.workspaceId, ids.agentId).catch(() => null);\n if (!enrollment || enrollment.connectionInstanceId !== ids.connectionInstanceId) return;\n const progress = event.event.agentUpdateProgress;\n const status = (() => {\n switch (progress.stage) {\n case AgentUpdateStage.AGENT_UPDATE_STAGE_ACCEPTED:\n return \"accepted\" as const;\n case AgentUpdateStage.AGENT_UPDATE_STAGE_WAITING_FOR_IDLE:\n return \"waiting_for_idle\" as const;\n case AgentUpdateStage.AGENT_UPDATE_STAGE_DOWNLOADING:\n return \"downloading\" as const;\n case AgentUpdateStage.AGENT_UPDATE_STAGE_VERIFYING:\n return \"verifying\" as const;\n case AgentUpdateStage.AGENT_UPDATE_STAGE_APPLYING:\n return \"applying\" as const;\n case AgentUpdateStage.AGENT_UPDATE_STAGE_RESTARTING:\n return \"restarting\" as const;\n case AgentUpdateStage.AGENT_UPDATE_STAGE_FAILED:\n return \"failed\" as const;\n default:\n return null;\n }\n })();\n if (!status) return;\n try {\n await advanceEnrollmentAgentUpdate(db, {\n accountId: enrollment.accountId,\n workspaceId: ids.workspaceId,\n enrollmentId: ids.agentId,\n connectionInstanceId: ids.connectionInstanceId,\n connectionGeneration: enrollment.connectionGeneration,\n operationId: progress.operationId,\n status,\n expectedBinarySha256: /^[0-9a-f]{64}$/.test(progress.expectedBinarySha256)\n ? progress.expectedBinarySha256\n : null,\n errorCode: progress.errorCode || null,\n retryable: progress.retryable,\n rolledBack: progress.rolledBack,\n });\n } catch (error) {\n observability?.warn?.(\"Failed to ingest a machine self-update progress event\", {\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 heartbeat = event.event.heartbeat;\n const enrollment = await getEnrollment(db, ids.workspaceId, ids.agentId).catch(() => null);\n if (!enrollment || enrollment.connectionInstanceId !== ids.connectionInstanceId) return;\n try {\n const renewed = await renewEnrollmentConnection(db, {\n accountId: enrollment.accountId,\n workspaceId: ids.workspaceId,\n enrollmentId: ids.agentId,\n connectionInstanceId: ids.connectionInstanceId,\n leaseMs: AGENT_CONNECTION_LEASE_MS,\n });\n if (!renewed.renewed) return;\n } catch (error) {\n observability?.warn?.(\"Failed to renew a machine connection heartbeat\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n // A live machine behind its promoted build is asked to update; the decision\n // reads only this enrollment, and a request never blocks heartbeat ingestion.\n agentUpdates?.consider(enrollment);\n if (heartbeat.attachedBrowserInventory) {\n try {\n await ingestAttachedBrowserInventory(db, {\n workspaceId: ids.workspaceId,\n agentId: ids.agentId,\n inventory: heartbeat.attachedBrowserInventory,\n });\n } catch (error) {\n observability?.warn?.(\"Failed to ingest an attached-browser inventory\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n if (heartbeat.desktopStatus) {\n try {\n const status = heartbeat.desktopStatus;\n const available = status.available && !status.unavailableReason;\n const reason = status.unavailableReason || null;\n const macPermissions = status.macPermissions;\n const stored = enrollmentMacPermissions(enrollment.agentCapabilities);\n // The heartbeat already read the exact enrollment. Steady state adds no\n // extra query; the change path re-reads and fences its eventual write.\n if (\n enrollment.hasDisplay !== available ||\n (enrollment.desktopUnavailableReason ?? null) !== reason ||\n enrollment.agentCapabilities?.desktop !== available ||\n (macPermissions !== undefined &&\n (stored?.screenRecording !== macPermissions.screenRecording ||\n stored?.accessibility !== macPermissions.accessibility ||\n stored?.inputMonitoring !== macPermissions.inputMonitoring))\n ) {\n await refreshEnrollmentDisplay(db, {\n workspaceId: ids.workspaceId,\n agentId: ids.agentId,\n hasDisplay: available,\n desktopUnavailableReason: reason,\n runtimeDesktop: available,\n ...(macPermissions ? { macPermissions } : {}),\n connectionInstanceId: ids.connectionInstanceId,\n });\n }\n } catch (error) {\n observability?.warn?.(\"Failed to refresh a machine desktop heartbeat\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n const metrics = heartbeat.metrics;\n if (!metrics) return;\n try {\n await ingestHeartbeatMetrics(db, {\n accountId: enrollment.accountId,\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 exact process 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 agentUpdates?: AutomaticAgentUpdater | null;\n}): () => void {\n const scheduler = createAgentEventIngestionScheduler(\n (payload, subject) =>\n handleAgentEventPayload(\n deps.db,\n deps.observability,\n payload,\n subject,\n deps.bus,\n deps.agentUpdates,\n ),\n {\n onHeartbeatCoalesced: () =>\n deps.observability?.incrementCounter({\n name: \"opengeni_machine_heartbeat_coalesced_total\",\n help: \"Connected Machine heartbeats collapsed while an exact runner event queue was busy.\",\n }),\n },\n );\n const unsubscribe = deps.bus.subscribeAgentEvents(AGENT_EVENTS_SUBJECT, (payload, subject) => {\n scheduler.enqueue(payload, subject);\n });\n return () => {\n unsubscribe();\n scheduler.close();\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\nexport function helloRuntimeCapabilities(hello: Hello): Record<string, boolean> {\n const caps = hello.capabilities;\n // Absence is an older-agent/unknown signal, not a fabricated set of false claims.\n // Keep the durable cursor empty so reconnects from legacy agents remain a\n // no-op and future capability additions do not get silently fabricated.\n if (!caps) return {};\n return {\n exec: caps.exec === true,\n filesystem: caps.filesystem === true,\n git: caps.git === true,\n pty: caps.pty === true,\n desktop: caps.desktop === true,\n opStream: caps.opStream === true,\n browserBridge: caps.browserBridge === true,\n operationResourcePolicy: caps.operationResourcePolicy === true,\n operationCpuQuota: caps.operationCpuQuota === true,\n transactionalFsWrite: caps.transactionalFsWrite === true,\n credentialRenew: caps.credentialRenew === true,\n screenControl: caps.consentedScreenControl === true,\n ...(caps.macPermissions ? enrollmentMacPermissionCapabilities(caps.macPermissions) : {}),\n };\n}\n\nfunction helloCompletedUpdate(hello: Hello): {\n operationId: string;\n targetVersion: string;\n binarySha256: string;\n} | null {\n if (\n !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(\n hello.completedUpdateOperationId,\n ) ||\n !/^(?:v)?\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/.test(hello.completedUpdateTargetVersion) ||\n !/^[0-9a-f]{64}$/.test(hello.completedUpdateBinarySha256)\n ) {\n return null;\n }\n return {\n operationId: hello.completedUpdateOperationId,\n targetVersion: hello.completedUpdateTargetVersion,\n binarySha256: hello.completedUpdateBinarySha256,\n };\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 runtimeDesktop?: boolean;\n macPermissions?: EnrollmentMacPermissions;\n connectionInstanceId?: string;\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 (input.runtimeDesktop === undefined ||\n enrollment.agentCapabilities?.desktop === input.runtimeDesktop) &&\n (input.macPermissions === undefined ||\n JSON.stringify(enrollmentMacPermissions(enrollment.agentCapabilities)) ===\n JSON.stringify({\n screenRecording: input.macPermissions.screenRecording,\n accessibility: input.macPermissions.accessibility,\n inputMonitoring: input.macPermissions.inputMonitoring,\n }))\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 ...(input.runtimeDesktop !== undefined ? { runtimeDesktop: input.runtimeDesktop } : {}),\n ...(input.macPermissions ? { macPermissions: input.macPermissions } : {}),\n ...(input.connectionInstanceId ? { connectionInstanceId: input.connectionInstanceId } : {}),\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 connectionInstanceId?: string;\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 ...(input.connectionInstanceId ? { connectionInstanceId: input.connectionInstanceId } : {}),\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 const authority = await getLiveEnrollmentConnection(db, ids.workspaceId, ids.agentId).catch(\n () => null,\n );\n if (!authority || authority.connectionInstanceId !== ids.connectionInstanceId) {\n observability?.warn?.(\"Ignored a Hello from a superseded runner instance\", {\n workspaceId: ids.workspaceId,\n agentId: ids.agentId,\n });\n return;\n }\n let workspaceRoot: string | undefined;\n if (hello.workspaceRoot.length > 0) {\n try {\n workspaceRoot = normalizeConnectedMachineWorkspaceRoot(hello.workspaceRoot, authority.os);\n } catch (error) {\n observability?.warn?.(\"Ignored an invalid Connected Machine workspace root\", {\n workspaceId: ids.workspaceId,\n agentId: ids.agentId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n try {\n await refreshEnrollmentDisplay(db, {\n workspaceId: ids.workspaceId,\n agentId: ids.agentId,\n hasDisplay: helloReportsDisplay(hello),\n desktopUnavailableReason: helloDesktopUnavailableReason(hello),\n connectionInstanceId: ids.connectionInstanceId,\n });\n await refreshEnrollmentOpStream(db, {\n workspaceId: ids.workspaceId,\n agentId: ids.agentId,\n opStream: helloReportsOpStream(hello),\n connectionInstanceId: ids.connectionInstanceId,\n });\n await setEnrollmentAgentRuntime(db, {\n accountId: authority.accountId,\n workspaceId: ids.workspaceId,\n enrollmentId: ids.agentId,\n connectionInstanceId: ids.connectionInstanceId,\n agentVersion: hello.agentVersion.trim() || null,\n binarySha256: /^[0-9a-f]{64}$/.test(hello.binarySha256) ? hello.binarySha256 : null,\n updateChannel:\n hello.updateChannel === \"stable\" || hello.updateChannel === \"beta\"\n ? hello.updateChannel\n : null,\n capabilities: helloRuntimeCapabilities(hello),\n ...(workspaceRoot !== undefined ? { workspaceRoot } : {}),\n completedUpdate: helloCompletedUpdate(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 // Screen control allowed while this machine was offline (or before its agent\n // could renew on request) applies now. Detached: it waits for the agent to\n // subscribe and must not hold up Hello ingestion.\n void reconcileScreenControlOnHello(\n { bus, observability },\n {\n authority,\n hello,\n target: {\n workspaceId: ids.workspaceId,\n enrollmentId: ids.agentId,\n connectionInstanceId: ids.connectionInstanceId,\n },\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 { cleared } = await clearEnrollmentWentOffline(db, {\n accountId: authority.accountId,\n workspaceId: ids.workspaceId,\n enrollmentId: ids.agentId,\n connectionInstanceId: ids.connectionInstanceId,\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 } 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 exact process hellos 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","import {\n claimMemorySlackPublication,\n completeMemorySlackPublication,\n currentMemorySlackConfigurationMatches,\n deferMemorySlackPublication,\n failMemorySlackPublication,\n type ClaimedMemorySlackPublication,\n} from \"@opengeni/db\";\nimport { sanitizeSlackPublicationText, type ApiRouteDeps } from \"@opengeni/core\";\nimport {\n createOpenGeniSlackBotInteractionClient,\n SlackBotProviderError,\n} from \"./integrations/slack-bot\";\n\nconst DELIVERY_LEASE_MS = 30_000;\nconst MAX_DELIVERY_ATTEMPTS = 8;\nconst MAX_DELIVERY_RETRY_MS = 5 * 60_000;\nconst MAX_SLACK_MESSAGE_CHARS = 3_500;\n\nexport async function drainMemorySlackPublicationsOnce(deps: ApiRouteDeps): Promise<boolean> {\n const claimHolderId = crypto.randomUUID();\n const publication = await claimMemorySlackPublication(deps.db, claimHolderId, DELIVERY_LEASE_MS);\n if (!publication) return false;\n\n try {\n if (!(await currentMemorySlackConfigurationMatches(deps.db, publication))) {\n await failMemorySlackPublication(deps.db, {\n publication,\n claimHolderId,\n errorCode: \"configuration_changed\",\n cancelled: true,\n });\n return true;\n }\n const client = await createOpenGeniSlackBotInteractionClient(deps, {\n accountId: publication.accountId,\n workspaceId: publication.workspaceId,\n connectionId: publication.connectionId,\n subjectId: publication.initiatorSubjectId,\n sessionId: publication.sessionId,\n });\n const result = await client.postMessage({\n operationId: publication.operationId,\n channelId: publication.slackChannelId,\n text: formatMemorySlackPublicationMessage(deps, publication),\n requireActiveNonSharedChannel: true,\n });\n const completed = await completeMemorySlackPublication(deps.db, {\n publication,\n claimHolderId,\n slackChannelId: result.channelId,\n slackMessageTimestamp: result.timestamp,\n });\n if (!completed) throw new Error(\"Memory Slack publication lost its durable claim\");\n } catch (error) {\n const errorCode = deliveryErrorCode(error);\n if (memorySlackDestinationDrift(error)) {\n await failMemorySlackPublication(deps.db, {\n publication,\n claimHolderId,\n errorCode,\n cancelled: true,\n }).catch(() => undefined);\n } else if (publication.attemptCount >= MAX_DELIVERY_ATTEMPTS || permanentDeliveryError(error)) {\n await failMemorySlackPublication(deps.db, {\n publication,\n claimHolderId,\n errorCode,\n }).catch(() => undefined);\n } else {\n await deferMemorySlackPublication(deps.db, {\n publication,\n claimHolderId,\n errorCode,\n retryAt: new Date(Date.now() + deliveryRetryMs(error, publication.attemptCount)),\n }).catch(() => undefined);\n }\n }\n return true;\n}\n\nexport function startMemorySlackPublicationPump(\n deps: ApiRouteDeps,\n options: { intervalMs?: number; maxPerTick?: number } = {},\n): () => Promise<void> {\n let stopped = false;\n let running: Promise<void> | undefined;\n const intervalMs = Math.max(250, options.intervalMs ?? 1_000);\n const maxPerTick = Math.max(1, Math.min(50, options.maxPerTick ?? 10));\n const tick = () => {\n if (stopped || running) return;\n running = (async () => {\n for (let index = 0; index < maxPerTick; index += 1) {\n if (!(await drainMemorySlackPublicationsOnce(deps))) break;\n }\n })()\n .catch((error) => {\n deps.observability?.error(\"Memory Slack publication claim failed\", {\n errorClass: error instanceof Error ? error.name : \"MemorySlackPublicationPumpError\",\n errorCode: deliveryErrorCode(error),\n origin: \"api\",\n });\n })\n .finally(() => {\n running = undefined;\n });\n };\n const timer = setInterval(tick, intervalMs);\n queueMicrotask(tick);\n return async () => {\n stopped = true;\n clearInterval(timer);\n await running;\n };\n}\n\nexport function formatMemorySlackPublicationMessage(\n deps: Pick<ApiRouteDeps, \"settings\">,\n publication: ClaimedMemorySlackPublication,\n): string {\n const projection = publication.projection;\n const summary = boundedProjectionString(projection[\"summary\"], 512) || \"Important change\";\n const owner = boundedProjectionString(projection[\"ownerLabel\"], 96);\n const occurredAt = boundedProjectionString(projection[\"occurredAt\"], 64);\n const changeKind = boundedProjectionString(projection[\"changeKind\"], 32);\n const destination = boundedProjectionString(projection[\"destination\"], 64);\n const outcome = boundedProjectionString(projection[\"outcome\"], 64);\n const heading =\n publication.sourceType === \"workspace_memory\"\n ? `Workspace Memory ${changeKind || \"change\"}`\n : `Governed learning ${outcome || \"change\"}`;\n const details = [\n `Importance: ${publication.importance}`,\n ...(destination ? [`Surface: ${destination}`] : []),\n ...(owner ? [`Owner: ${owner}`] : []),\n ...(occurredAt ? [`Recorded: ${occurredAt}`] : []),\n ];\n const path =\n publication.sourceType === \"workspace_memory\"\n ? `/workspaces/${publication.workspaceId}/memory?memoryId=${encodeURIComponent(publication.sourceId)}`\n : `/workspaces/${publication.workspaceId}/workspace-state`;\n const base = deps.settings.webBaseUrl ?? deps.settings.publicBaseUrl;\n const link = base ? new URL(path, base).toString() : null;\n const text = `*${heading}*\\n${summary}\\n\\n${details.join(\" · \")}${link ? `\\n${link}` : \"\"}`;\n return text.length <= MAX_SLACK_MESSAGE_CHARS\n ? text\n : `${text.slice(0, MAX_SLACK_MESSAGE_CHARS - 20)}\\n… message truncated`;\n}\n\nconst PERMANENT_DELIVERY_CODES = new Set([\n \"account_inactive\",\n \"channel_not_found\",\n \"invalid_auth\",\n \"is_archived\",\n \"not_authed\",\n \"not_in_channel\",\n \"token_expired\",\n \"token_revoked\",\n]);\n\nconst MEMORY_SLACK_DESTINATION_DRIFT_CODES = new Set([\n \"channel_not_found\",\n \"is_archived\",\n \"not_in_channel\",\n \"slack_connect_unsupported\",\n]);\n\nexport function memorySlackDestinationDrift(error: unknown) {\n return (\n error instanceof SlackBotProviderError && MEMORY_SLACK_DESTINATION_DRIFT_CODES.has(error.code)\n );\n}\n\nfunction permanentDeliveryError(error: unknown) {\n if (!(error instanceof SlackBotProviderError)) return false;\n if (PERMANENT_DELIVERY_CODES.has(error.code)) return true;\n const status = /^http_(\\d{3})$/.exec(error.code)?.[1];\n return status\n ? Number(status) >= 400 && Number(status) < 500 && status !== \"408\" && status !== \"429\"\n : false;\n}\n\nfunction deliveryRetryMs(error: unknown, attemptCount: number) {\n if (error instanceof SlackBotProviderError && error.retryAfterMs) {\n return Math.min(Math.max(error.retryAfterMs, 1_000), MAX_DELIVERY_RETRY_MS);\n }\n return Math.min(1_000 * 2 ** Math.max(0, attemptCount - 1), MAX_DELIVERY_RETRY_MS);\n}\n\nfunction deliveryErrorCode(error: unknown) {\n if (error instanceof SlackBotProviderError) return error.code.slice(0, 128);\n const raw = error instanceof Error ? error.name : \"memory_slack_delivery_error\";\n return (\n raw\n .toLowerCase()\n .replace(/[^a-z0-9_-]/g, \"_\")\n .slice(0, 128) || \"error\"\n );\n}\n\nfunction boundedProjectionString(value: unknown, maxChars: number) {\n return typeof value === \"string\"\n ? escapeSlackText(sanitizeSlackPublicationText(value).slice(0, maxChars))\n : \"\";\n}\n\nfunction escapeSlackText(value: string) {\n return value.replaceAll(\"&\", \"&amp;\").replaceAll(\"<\", \"&lt;\").replaceAll(\">\", \"&gt;\");\n}\n","import {\n acknowledgeScheduledTaskScheduleReconciliation,\n deferScheduledTaskScheduleReconciliation,\n listExhaustedScheduledTasks,\n listScheduledTaskScheduleReconciliations,\n retireExhaustedScheduledTask,\n type Database,\n} from \"@opengeni/db\";\nimport type { ScheduledTask } from \"@opengeni/contracts\";\nimport type { EventBus } from \"@opengeni/events\";\nimport type { Observability } from \"@opengeni/observability\";\nimport { reviewScheduledTaskBlockerInventory } from \"./scheduled-task-blockers\";\n\ntype Dependencies = {\n db: Database;\n sync(task: Pick<ScheduledTask, \"id\" | \"workspaceId\" | \"temporalScheduleId\">): Promise<void>;\n /** Enables blocked-schedule review: self-pause and the owner notice it posts. */\n bus?: EventBus;\n observability?: Pick<Observability, \"error\">;\n};\n\nexport async function reconcileExhaustedScheduledTasks(deps: Dependencies): Promise<void> {\n for (const candidate of await listExhaustedScheduledTasks(deps.db)) {\n await retireExhaustedScheduledTask(deps.db, candidate.workspace_id, candidate.id);\n }\n // Before Temporal reconciliation, so a schedule that paused itself stops\n // firing in the same pass.\n if (deps.bus) {\n await reviewScheduledTaskBlockerInventory({\n db: deps.db,\n bus: deps.bus,\n observability: deps.observability,\n });\n }\n for (const pending of await listScheduledTaskScheduleReconciliations(deps.db)) {\n try {\n // The synchronizer takes the shared external-write lock and rereads the\n // current task, including edits/deletion committed since retirement.\n await deps.sync({\n id: pending.task_id,\n workspaceId: pending.workspace_id,\n temporalScheduleId: pending.temporal_schedule_id,\n });\n await acknowledgeScheduledTaskScheduleReconciliation(\n deps.db,\n pending.workspace_id,\n pending.id,\n );\n } catch (error) {\n await deferScheduledTaskScheduleReconciliation(deps.db, pending.workspace_id, pending.id);\n deps.observability?.error(\"Exhausted schedule reconciliation will retry\", {\n taskId: pending.task_id,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n}\n\nexport function startScheduledTaskLifecyclePump(\n deps: Dependencies,\n intervalMs = 30_000,\n): () => Promise<void> {\n let stopped = false;\n let running: Promise<void> | undefined;\n const tick = () => {\n if (stopped || running) return;\n running = reconcileExhaustedScheduledTasks(deps)\n .catch((error: unknown) => {\n deps.observability?.error(\"Exhausted schedule inventory failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n })\n .finally(() => {\n running = undefined;\n });\n };\n const timer = setInterval(tick, intervalMs);\n queueMicrotask(tick);\n return async () => {\n stopped = true;\n clearInterval(timer);\n await running;\n };\n}\n","import {\n NOTIFICATION_SUBTITLE_MAX_CHARS,\n SessionNotificationPostedPayload,\n SessionNotificationWithdrawnPayload,\n} from \"@opengeni/contracts\";\nimport {\n getPendingScheduledTaskBlockerNotice,\n listScheduledTaskBlockerReviews,\n reviewScheduledTaskBlockers,\n settleScheduledTaskBlockerNotice,\n type Database,\n type ScheduledTaskBlockerDecision,\n type ScheduledTaskBlockerFacts,\n type ScheduledTaskBlockerRun,\n} from \"@opengeni/db\";\nimport { appendAndPublishEvents, type EventBus } from \"@opengeni/events\";\nimport type { Observability } from \"@opengeni/observability\";\n\n/**\n * A schedule must never stay stuck without its owner knowing. After each\n * settled scheduled run:\n *\n * - When the platform knows no later run can start until a person acts (its\n * chat is paused or gone, a pinned account or other resource it needs is\n * unavailable, or it was refused as non-retryable), the schedule pauses\n * itself with that reason and its owner is told once.\n * - When runs keep failing or being skipped for a reason that may clear by\n * itself, the owner is told once, after {@link SCHEDULED_TASK_BLOCKER_STREAK}\n * in a row; the schedule keeps running. A single skip or failure is normal.\n *\n * The notice is withdrawn when a later run succeeds or a person resumes,\n * pauses or deletes the schedule. Only scheduled (not manual) runs count, and\n * only runs since the schedule was last edited or resumed.\n */\nexport const SCHEDULED_TASK_BLOCKER_STREAK = 3;\n\nconst SETTLED = new Set([\"succeeded\", \"failed\", \"skipped\"]);\n\ntype Blocker = { reason: string; text: string };\n\nconst RESUME = \"then resume the schedule.\";\n\nconst NON_RETRYABLE_REFUSAL_TEXT: Record<string, string> = {\n scheduled_authority_unavailable: `The access it was set up with is no longer valid. Refresh the schedule's access, ${RESUME}`,\n machine_target_unavailable: `The machine it runs on is no longer available. Choose another machine or reconnect this one, ${RESUME}`,\n machine_enrollment_inactive: `The machine it runs on is disconnected from Opengeni. Reconnect the machine, ${RESUME}`,\n variable_set_unavailable: `A variable set it uses no longer exists or can't be used. Edit the schedule, ${RESUME}`,\n rig_version_unavailable: `Its rig has no usable version. Publish a rig version or edit the schedule, ${RESUME}`,\n scheduled_model_unavailable: `Its model is no longer available. Edit the schedule to choose another model, ${RESUME}`,\n};\n\nconst RETRYABLE_REFUSAL_TEXT: Record<string, string> = {\n machine_enrollment_inactive: \"the machine it runs on is disconnected\",\n insufficient_credits: \"the workspace is out of credits\",\n allowance_exhausted: \"the usage allowance is used up\",\n monthly_model_cost_limit: \"the monthly model cost limit was reached\",\n monthly_agent_run_limit: \"the monthly run limit was reached\",\n session_usage_limit: \"the schedule reached its usage limit\",\n};\n\n/** A blocker no later run can get past until a person acts, or null. */\nexport function scheduledRunHardBlocker(\n task: Pick<ScheduledTaskBlockerFacts[\"task\"], \"runMode\">,\n run: ScheduledTaskBlockerRun,\n): Blocker | null {\n if (run.admissionDiagnostic) {\n return {\n reason: \"connection_account_unavailable\",\n text: `A connected account it needs can no longer be used. Reconnect that account or refresh the schedule's access, ${RESUME}`,\n };\n }\n if (run.admissionRefusal && !run.admissionRefusal.retryable) {\n const reason = run.admissionRefusal.reason;\n return {\n reason,\n text:\n NON_RETRYABLE_REFUSAL_TEXT[reason] ??\n `Every run is refused before it starts (${reason}). Fix that, ${RESUME}`,\n };\n }\n switch (run.error) {\n case \"scheduled_session_paused\":\n return {\n reason: run.error,\n text: `Its chat is paused, so no run can start there. Resume the chat, ${RESUME}`,\n };\n case \"session_cancelled\":\n // A run that starts a new chat each time is not blocked by one ended chat.\n return task.runMode === \"new_session_per_run\"\n ? null\n : {\n reason: run.error,\n text: `The chat it runs in has ended, so no run can start there. Point the schedule at another chat or let it start a new chat each run, ${RESUME}`,\n };\n case \"scheduled_target_session_unavailable\":\n return {\n reason: run.error,\n text: `The chat it runs in no longer exists. Point the schedule at another chat or let it start a new chat each run, ${RESUME}`,\n };\n case \"scheduled_model_unavailable\":\n return { reason: run.error, text: NON_RETRYABLE_REFUSAL_TEXT.scheduled_model_unavailable! };\n default:\n return null;\n }\n}\n\nfunction streakBlocker(streak: readonly ScheduledTaskBlockerRun[]): Blocker {\n const count = streak.length;\n if (streak.every((run) => run.error === \"scheduled_session_not_idle\")) {\n return {\n reason: \"scheduled_session_not_idle\",\n text: `The last ${count} scheduled runs were skipped because its chat was still busy with earlier work. Check whether that chat is stuck. The schedule keeps trying.`,\n };\n }\n const refusal = streak[0]?.admissionRefusal;\n if (\n refusal?.retryable &&\n streak.every(\n (run) => run.admissionRefusal?.retryable && run.admissionRefusal.reason === refusal.reason,\n )\n ) {\n return {\n reason: refusal.reason,\n text: `The last ${count} scheduled runs were skipped because ${\n RETRYABLE_REFUSAL_TEXT[refusal.reason] ?? `they were refused (${refusal.reason})`\n }. Runs start again once that clears.`,\n };\n }\n const latest = streak[0]!;\n return {\n reason: latest.error ?? latest.status,\n text: `The last ${count} scheduled runs failed or were skipped. Open the latest run to see why. The schedule keeps trying.`,\n };\n}\n\nexport function scheduledTaskBlockerNoticeKey(taskId: string): string {\n return `schedule-${taskId}`;\n}\n\nfunction clip(text: string, max: number): string {\n return text.length <= max ? text : `${text.slice(0, max - 1).trimEnd()}…`;\n}\n\nfunction notice(\n facts: ScheduledTaskBlockerFacts,\n run: ScheduledTaskBlockerRun,\n state: \"notified\" | \"paused\",\n blocker: Blocker,\n): Extract<ScheduledTaskBlockerDecision, { kind: \"block\" }>[\"notice\"] {\n // The chat the owner opens from the notice: the blocked run's own, else the\n // chat the schedule runs in, else the most recent run's.\n const sessionId =\n run.sessionId ??\n facts.task.reusableSessionId ??\n facts.runs.find((candidate) => candidate.sessionId !== null)?.sessionId ??\n null;\n if (!sessionId) return null;\n const key = scheduledTaskBlockerNoticeKey(facts.task.id);\n const payload = SessionNotificationPostedPayload.parse({\n key,\n title: state === \"paused\" ? \"Schedule paused itself\" : \"Schedule needs attention\",\n subtitle: clip(facts.task.name.trim() || \"Scheduled task\", NOTIFICATION_SUBTITLE_MAX_CHARS),\n body:\n state === \"paused\"\n ? `${blocker.text} It stays paused until someone resumes it.`\n : blocker.text,\n urgency: \"normal\",\n replaced: false,\n });\n return { sessionId, key, payload };\n}\n\n/** The pure review of one schedule's newest settled scheduled run. */\nexport function decideScheduledTaskBlocker(\n facts: ScheduledTaskBlockerFacts,\n): ScheduledTaskBlockerDecision {\n const { task, review, runs } = facts;\n const blocked = review !== null && review.state !== \"clear\";\n // A person acted: resumed a self-paused schedule, or paused or deleted one\n // they were told about. Keep the reviewed run; a new one is reviewed next.\n if (task.deleted) return blocked ? { kind: \"clear\", reviewedRunId: null } : none(null);\n if (review?.state === \"paused\" && task.status === \"active\") {\n return { kind: \"clear\", reviewedRunId: null };\n }\n if (review?.state === \"notified\" && task.status !== \"active\") {\n return { kind: \"clear\", reviewedRunId: null };\n }\n if (task.status !== \"active\") return none(null);\n const latest = runs[0];\n if (!latest || !SETTLED.has(latest.status) || latest.id === review?.reviewedRunId) {\n return none(null);\n }\n if (latest.status === \"succeeded\") {\n return review?.state === \"notified\"\n ? { kind: \"clear\", reviewedRunId: latest.id }\n : none(latest.id);\n }\n // Runs before the last edit or resume say nothing about the schedule now.\n const current = (run: ScheduledTaskBlockerRun) => run.createdAt >= task.updatedAt;\n const hard = current(latest) ? scheduledRunHardBlocker(task, latest) : null;\n if (hard) {\n return {\n kind: \"block\",\n state: \"paused\",\n reason: hard.reason,\n message: hard.text,\n blockedRunId: latest.id,\n blockedSince: latest.createdAt,\n reviewedRunId: latest.id,\n notice: notice(facts, latest, \"paused\", hard),\n };\n }\n if (review?.state === \"notified\") return none(latest.id);\n const streak: ScheduledTaskBlockerRun[] = [];\n for (const run of runs) {\n if (!SETTLED.has(run.status) || run.status === \"succeeded\" || !current(run)) break;\n streak.push(run);\n }\n if (streak.length < SCHEDULED_TASK_BLOCKER_STREAK) return none(latest.id);\n const soft = streakBlocker(streak);\n const first = streak.at(-1)!;\n return {\n kind: \"block\",\n state: \"notified\",\n reason: soft.reason,\n message: soft.text,\n blockedRunId: first.id,\n blockedSince: first.createdAt,\n reviewedRunId: latest.id,\n notice: notice(facts, latest, \"notified\", soft),\n };\n}\n\nfunction none(reviewedRunId: string | null): ScheduledTaskBlockerDecision {\n return { kind: \"none\", reviewedRunId };\n}\n\ntype Dependencies = {\n db: Database;\n bus: EventBus;\n observability?: Pick<Observability, \"error\"> | undefined;\n};\n\nfunction sessionMissing(error: unknown): boolean {\n return error instanceof Error && /^Session not found: /u.test(error.message);\n}\n\n/** Post or withdraw the owner notice a review left pending. */\nexport async function deliverScheduledTaskBlockerNotice(\n deps: Dependencies,\n workspaceId: string,\n taskId: string,\n): Promise<void> {\n const pending = await getPendingScheduledTaskBlockerNotice(deps.db, workspaceId, taskId);\n if (!pending) return;\n try {\n await appendAndPublishEvents(deps.db, deps.bus, workspaceId, pending.sessionId, [\n pending.pending === \"post\"\n ? {\n type: \"session.notification.posted\",\n payload: SessionNotificationPostedPayload.parse(pending.payload),\n }\n : {\n type: \"session.notification.withdrawn\",\n payload: SessionNotificationWithdrawnPayload.parse({ key: pending.key }),\n },\n ] as Parameters<typeof appendAndPublishEvents>[4]);\n } catch (error) {\n // A deleted chat cannot carry the notice; the schedule page still shows why.\n if (!sessionMissing(error)) throw error;\n }\n await settleScheduledTaskBlockerNotice(deps.db, workspaceId, taskId, pending);\n}\n\n/** One bounded pass over schedules with a run to review or a notice to deliver. */\nexport async function reviewScheduledTaskBlockerInventory(deps: Dependencies): Promise<void> {\n for (const candidate of await listScheduledTaskBlockerReviews(deps.db)) {\n try {\n await reviewScheduledTaskBlockers(\n deps.db,\n candidate.workspace_id,\n candidate.id,\n decideScheduledTaskBlocker,\n );\n await deliverScheduledTaskBlockerNotice(deps, candidate.workspace_id, candidate.id);\n } catch (error) {\n deps.observability?.error(\"Scheduled task blocker review will retry\", {\n taskId: candidate.id,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n}\n","import type { ScheduledTask } from \"@opengeni/contracts\";\nimport { getScheduledTaskIncludingDeleted, type Database } from \"@opengeni/db\";\nimport { sql } from \"drizzle-orm\";\n\nconst LOCK_TIMEOUT = \"5s\";\nconst WRITE_TIMEOUT_MS = 5_000;\n\ntype TemporalScheduleSyncDependencies = {\n db: Database;\n withDeadline<T>(deadline: number, work: () => Promise<T>): Promise<T>;\n upsert(task: ScheduledTask): Promise<void>;\n /** Idempotent: an absent Temporal schedule is already removed. */\n remove(temporalScheduleId: string): Promise<void>;\n};\n\n/**\n * Serialize external writes across API replicas, independently of task edits.\n * A queued sync rereads the newest committed row after acquiring this lock;\n * input snapshots never become desired state. Cleanup uses the same key, so\n * an in-flight upsert finishes before its tombstone's external deletion.\n * Failure compensation commits before releasing the lock, so a queued writer\n * cannot read the row being restored and then publish that failed edit.\n *\n * Deadlines bound both lock admission and network occupancy. A thrown network\n * error retains its unknown-outcome semantics; this is not durable recovery\n * for a process crash or a lost Temporal acknowledgement.\n */\nexport function createTemporalScheduleSynchronizer(deps: TemporalScheduleSyncDependencies) {\n const write = async <T>(\n temporalScheduleId: string,\n work: (tx: Database) => Promise<T>,\n ): Promise<T> =>\n deps.db.transaction(async (tx) => {\n await tx.execute(sql`select set_config('lock_timeout', ${LOCK_TIMEOUT}, true)`);\n await tx.execute(sql`select pg_advisory_xact_lock(\n hashtextextended(${`scheduled-task-temporal:${temporalScheduleId}`}, 0)\n )`);\n return await work(tx);\n });\n\n return {\n async sync(\n task: Pick<ScheduledTask, \"id\" | \"workspaceId\" | \"temporalScheduleId\">,\n onFailure?: (tx: Database, error: unknown) => Promise<Error>,\n ) {\n const result = await write(task.temporalScheduleId, async (tx) => {\n try {\n await deps.withDeadline(Date.now() + WRITE_TIMEOUT_MS, async () => {\n const current = await getScheduledTaskIncludingDeleted(tx, task.workspaceId, task.id);\n if (current && current.temporalScheduleId !== task.temporalScheduleId)\n throw new Error(\"Scheduled task Temporal identity changed\");\n if (!current || current.deletedAt !== null || current.schedule.type === \"manual\") {\n await deps.remove(task.temporalScheduleId);\n return;\n }\n const { deletedAt: _deletedAt, ...latest } = current;\n await deps.upsert(latest);\n });\n return { ok: true as const };\n } catch (error) {\n return { ok: false as const, error: onFailure ? await onFailure(tx, error) : error };\n }\n });\n // Throw after commit: throwing inside the transaction would also undo a\n // successful compensation. A failed commit cannot claim that receipt.\n if (!result.ok) throw result.error;\n },\n async remove(temporalScheduleId: string) {\n await write(temporalScheduleId, async () =>\n deps.withDeadline(Date.now() + WRITE_TIMEOUT_MS, () => deps.remove(temporalScheduleId)),\n );\n },\n };\n}\n","import { createSign, randomUUID } from \"node:crypto\";\nimport { connect, type ClientHttp2Session } from \"node:http2\";\nimport type { Settings } from \"@opengeni/config\";\nimport {\n claimNativePushDeliveries,\n listSessionHumanInputRequests,\n pruneNativePushDeliveries,\n settleNativePushDelivery,\n type ClaimedNativePushDelivery,\n type Database,\n type NativePushOutcome,\n} from \"@opengeni/db\";\nimport type { Observability } from \"@opengeni/observability\";\n\n// Sends queued native app pushes (0638) through APNs (token auth over HTTP/2)\n// and FCM HTTP v1. At-least-once: a delivery is settled only after the\n// provider answered; an unknown token removes the registration.\n\nconst POLL_INTERVAL_MS = 1_000;\nconst CLAIM_SECONDS = 60;\nconst MAX_ATTEMPTS = 6;\nconst PRUNE_EVERY_TICKS = 600;\n\nexport type NativePushSendResult = { outcome: NativePushOutcome; error?: string };\n\nexport type NativePushSender = (\n delivery: ClaimedNativePushDelivery,\n) => Promise<NativePushSendResult>;\n\n/** A claimed payload, marked when its question asks for a secret. */\nexport type NativePushPayload = ClaimedNativePushDelivery[\"payload\"] & { secretQuestion?: boolean };\n\nconst SECRET_QUESTION_PUSH_BODY = \"Open Opengeni to answer. The answer is saved to a vault.\";\n\n/**\n * Mark question pushes whose pending request asks for a secret, so they carry\n * no inline answer action and point to the app instead.\n */\nasync function markSecretQuestionDeliveries(\n db: Database,\n deliveries: ClaimedNativePushDelivery[],\n): Promise<ClaimedNativePushDelivery[]> {\n const secretSessions = new Map<string, Promise<boolean>>();\n return await Promise.all(\n deliveries.map(async (delivery) => {\n if (delivery.payload.eventType !== \"session.humanInput.requested\") return delivery;\n const key = `${delivery.payload.workspaceId}:${delivery.payload.sessionId}`;\n let lookup = secretSessions.get(key);\n if (!lookup) {\n lookup = listSessionHumanInputRequests(\n db,\n delivery.payload.workspaceId,\n delivery.payload.sessionId,\n { status: \"pending\", limit: 20 },\n )\n .then((requests) =>\n requests.some((request) =>\n request.questions.some((question) => question.kind === \"secret\"),\n ),\n )\n .catch(() => false);\n secretSessions.set(key, lookup);\n }\n if (!(await lookup)) return delivery;\n const payload: NativePushPayload = { ...delivery.payload, secretQuestion: true };\n return { ...delivery, payload };\n }),\n );\n}\n\nexport type NativePushDispatchDeps = {\n db: Database;\n settings: Settings;\n observability?: Pick<Observability, \"info\" | \"warn\" | \"error\">;\n senders?: Partial<Record<\"ios\" | \"android\", NativePushSender>>;\n};\n\n/**\n * A notification message as plain text for the lock screen: links keep their\n * text, emphasis and code marks go, and \"- \" bullets become \"•\".\n */\nexport function plainNotificationText(markdown: string): string {\n return markdown\n .replace(/\\[([^\\]]+)\\]\\((?:[^)]+)\\)/gu, \"$1\")\n .replace(/(\\*\\*|__)(.+?)\\1/gu, \"$2\")\n .replace(/`([^`]+)`/gu, \"$1\")\n .replace(/^[ \\t]*[-*][ \\t]+/gmu, \"• \")\n .replace(/\\n{3,}/gu, \"\\n\\n\")\n .trim();\n}\n\n/** The visible text of a push: title, optional subtitle, and the message with its facts. */\nexport function nativePushAlert(payload: NativePushPayload): {\n title: string;\n subtitle?: string;\n body?: string;\n} {\n if (payload.secretQuestion) {\n // A secret is answered only in the app's secure card (AC-5): no inline reply.\n return { title: payload.title ?? \"The agent needs a secret\", body: SECRET_QUESTION_PUSH_BODY };\n }\n const fallback =\n payload.rule === \"needs_input\"\n ? \"The agent needs you\"\n : payload.rule === \"failed\"\n ? \"A turn failed\"\n : payload.rule === \"reply_ready\"\n ? \"Reply ready\"\n : \"Opengeni\";\n const facts = (payload.facts ?? [])\n .slice(0, 4)\n .map((fact) => `${fact.label}: ${fact.value}`)\n .join(\"\\n\");\n const message = payload.body ? plainNotificationText(payload.body) : \"\";\n // A notification with no message of its own carries its title as the body;\n // show the title once.\n const lines = [message === payload.title ? \"\" : message, facts].filter(Boolean);\n const body = lines.join(\"\\n\\n\");\n return {\n title: payload.title ?? fallback,\n ...(payload.subtitle ? { subtitle: payload.subtitle } : {}),\n ...(body || payload.rule !== \"agent\" ? { body: body || fallback } : {}),\n };\n}\n\n/**\n * What breaks through Focus: an agent notification the agent marked\n * time-sensitive, and questions and approvals for a person who asked for them\n * to (their setting puts the urgency on the delivery). Everything else, and\n * replies and failures always, arrive as ordinary alerts, so Focus and the\n * person's own notification settings decide when they show.\n */\nexport function nativePushInterruptionLevel(\n payload: ClaimedNativePushDelivery[\"payload\"],\n): \"time-sensitive\" | \"active\" {\n if (\n (payload.rule === \"agent\" || payload.rule === \"needs_input\") &&\n payload.urgency === \"time_sensitive\"\n ) {\n return \"time-sensitive\";\n }\n return \"active\";\n}\n\n/** What the app reads on tap: enough to open the session in the right account. */\nexport function nativePushData(payload: ClaimedNativePushDelivery[\"payload\"]) {\n return {\n sessionId: payload.sessionId,\n workspaceId: payload.workspaceId,\n subjectId: payload.subjectId,\n rule: payload.rule,\n ...(payload.eventType ? { eventType: payload.eventType } : {}),\n ...(payload.sequence ? { sequence: payload.sequence } : {}),\n };\n}\n\n/**\n * The notification category the app registers actions for: an approval can be\n * approved (behind device unlock) or denied, a question answered inline.\n */\nexport function nativePushCategory(\n payload: NativePushPayload,\n): \"og.approval\" | \"og.question\" | undefined {\n if (payload.secretQuestion) return undefined;\n if (payload.eventType === \"session.requiresAction\") return \"og.approval\";\n if (payload.eventType === \"session.humanInput.requested\") return \"og.question\";\n return undefined;\n}\n\nfunction base64Url(input: Buffer | string): string {\n return Buffer.from(input).toString(\"base64url\");\n}\n\nfunction signJwt(\n header: Record<string, string>,\n claims: Record<string, unknown>,\n privateKey: string,\n algorithm: \"ES256\" | \"RS256\",\n): string {\n const unsigned = `${base64Url(JSON.stringify(header))}.${base64Url(JSON.stringify(claims))}`;\n const signer = createSign(\"SHA256\");\n signer.update(unsigned);\n const signature =\n algorithm === \"ES256\"\n ? signer.sign({ key: privateKey, dsaEncoding: \"ieee-p1363\" })\n : signer.sign(privateKey);\n return `${unsigned}.${base64Url(signature)}`;\n}\n\nfunction pem(value: string): string {\n return value.includes(\"\\\\n\") ? value.replace(/\\\\n/gu, \"\\n\") : value;\n}\n\n/** APNs with a token-based (.p8) key; one HTTP/2 connection per environment. */\nexport function createApnsSender(input: {\n keyId: string;\n teamId: string;\n privateKey: string;\n}): NativePushSender {\n const key = pem(input.privateKey);\n let token: { value: string; issuedAt: number } | null = null;\n const sessions = new Map<string, ClientHttp2Session>();\n const bearer = () => {\n const now = Math.floor(Date.now() / 1000);\n // Apple accepts a provider token for an hour and rejects refreshes more\n // often than every 20 minutes.\n if (!token || now - token.issuedAt > 40 * 60) {\n token = {\n value: signJwt(\n { alg: \"ES256\", kid: input.keyId },\n { iss: input.teamId, iat: now },\n key,\n \"ES256\",\n ),\n issuedAt: now,\n };\n }\n return token.value;\n };\n const session = (host: string) => {\n const existing = sessions.get(host);\n if (existing && !existing.closed && !existing.destroyed) return existing;\n const created = connect(`https://${host}`);\n created.on(\"error\", () => sessions.delete(host));\n created.on(\"close\", () => sessions.delete(host));\n sessions.set(host, created);\n return created;\n };\n return async (delivery) => {\n const host =\n delivery.environment === \"development\" ? \"api.sandbox.push.apple.com\" : \"api.push.apple.com\";\n const alert = nativePushAlert(delivery.payload);\n const category = nativePushCategory(delivery.payload);\n const body = JSON.stringify({\n aps: {\n alert,\n sound: \"default\",\n \"thread-id\": delivery.payload.sessionId,\n \"interruption-level\": nativePushInterruptionLevel(delivery.payload),\n ...(category ? { category } : {}),\n },\n body: nativePushData(delivery.payload),\n });\n return await new Promise<NativePushSendResult>((resolve) => {\n const request = session(host).request({\n \":method\": \"POST\",\n \":path\": `/3/device/${delivery.token}`,\n authorization: `bearer ${bearer()}`,\n \"apns-topic\": delivery.appId,\n \"apns-push-type\": \"alert\",\n \"apns-priority\": \"10\",\n \"apns-collapse-id\": `${delivery.payload.sessionId}:${delivery.payload.rule}`.slice(0, 64),\n \"content-type\": \"application/json\",\n });\n let status = 0;\n let text = \"\";\n request.setTimeout(10_000, () => request.close());\n request.on(\"response\", (headers) => {\n status = Number(headers[\":status\"] ?? 0);\n });\n request.on(\"data\", (chunk: Buffer) => {\n text += chunk.toString(\"utf8\");\n });\n request.on(\"error\", (error) => resolve({ outcome: \"retry\", error: String(error) }));\n request.on(\"close\", () => {\n if (status === 200) return resolve({ outcome: \"delivered\" });\n const reason = (() => {\n try {\n return (JSON.parse(text) as { reason?: string }).reason ?? text;\n } catch {\n return text || `status ${status}`;\n }\n })();\n if (status === 410 || reason === \"BadDeviceToken\" || reason === \"Unregistered\") {\n return resolve({ outcome: \"unregistered\", error: `${status} ${reason}` });\n }\n resolve({\n outcome: status === 429 || status >= 500 || status === 0 ? \"retry\" : \"failed\",\n error: `${status} ${reason}`,\n });\n });\n request.end(body);\n });\n };\n}\n\n/** FCM HTTP v1 with a service account; data-only, so the app presents it. */\nexport function createFcmSender(input: {\n serviceAccountJson: string;\n fetch?: typeof fetch;\n}): NativePushSender {\n const account = JSON.parse(input.serviceAccountJson) as {\n project_id: string;\n client_email: string;\n private_key: string;\n token_uri?: string;\n };\n const http = input.fetch ?? fetch;\n let access: { token: string; expiresAt: number } | null = null;\n const accessToken = async () => {\n if (access && access.expiresAt - 60_000 > Date.now()) return access.token;\n const now = Math.floor(Date.now() / 1000);\n const tokenUri = account.token_uri ?? \"https://oauth2.googleapis.com/token\";\n const assertion = signJwt(\n { alg: \"RS256\", typ: \"JWT\" },\n {\n iss: account.client_email,\n scope: \"https://www.googleapis.com/auth/firebase.messaging\",\n aud: tokenUri,\n iat: now,\n exp: now + 3600,\n },\n pem(account.private_key),\n \"RS256\",\n );\n const response = await http(tokenUri, {\n method: \"POST\",\n headers: { \"content-type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grant_type: \"urn:ietf:params:oauth:grant-type:jwt-bearer\",\n assertion,\n }),\n });\n if (!response.ok) throw new Error(`FCM token exchange failed: ${response.status}`);\n const json = (await response.json()) as { access_token: string; expires_in: number };\n access = { token: json.access_token, expiresAt: Date.now() + json.expires_in * 1000 };\n return access.token;\n };\n return async (delivery) => {\n try {\n const alert = nativePushAlert(delivery.payload);\n const response = await http(\n `https://fcm.googleapis.com/v1/projects/${account.project_id}/messages:send`,\n {\n method: \"POST\",\n headers: {\n authorization: `Bearer ${await accessToken()}`,\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n message: {\n token: delivery.token,\n android: { priority: \"HIGH\", collapse_key: delivery.payload.sessionId },\n data: {\n title: alert.title,\n message: [alert.subtitle, alert.body].filter(Boolean).join(\"\\n\") || alert.title,\n body: JSON.stringify(nativePushData(delivery.payload)),\n },\n },\n }),\n signal: AbortSignal.timeout(10_000),\n },\n );\n if (response.ok) return { outcome: \"delivered\" };\n const text = await response.text();\n if (response.status === 404 || text.includes(\"UNREGISTERED\")) {\n return { outcome: \"unregistered\", error: `${response.status} ${text.slice(0, 200)}` };\n }\n return {\n outcome: response.status === 429 || response.status >= 500 ? \"retry\" : \"failed\",\n error: `${response.status} ${text.slice(0, 200)}`,\n };\n } catch (error) {\n return { outcome: \"retry\", error: String(error).slice(0, 300) };\n }\n };\n}\n\n/** The senders this deployment has credentials for. */\nexport function configuredNativePushSenders(\n settings: Settings,\n): Partial<Record<\"ios\" | \"android\", NativePushSender>> {\n const senders: Partial<Record<\"ios\" | \"android\", NativePushSender>> = {};\n if (settings.apnsKeyId && settings.apnsTeamId && settings.apnsPrivateKey) {\n senders.ios = createApnsSender({\n keyId: settings.apnsKeyId,\n teamId: settings.apnsTeamId,\n privateKey: settings.apnsPrivateKey,\n });\n }\n if (settings.fcmServiceAccountJson) {\n senders.android = createFcmSender({ serviceAccountJson: settings.fcmServiceAccountJson });\n }\n return senders;\n}\n\nexport async function drainNativePushDeliveries(\n deps: NativePushDispatchDeps,\n): Promise<{ claimed: number; delivered: number }> {\n const senders = deps.senders ?? configuredNativePushSenders(deps.settings);\n const claimId = randomUUID();\n const claimed = await markSecretQuestionDeliveries(\n deps.db,\n await claimNativePushDeliveries(deps.db, {\n claimId,\n limit: 32,\n claimSeconds: CLAIM_SECONDS,\n }),\n );\n let delivered = 0;\n await Promise.all(\n claimed.map(async (delivery) => {\n const sender = senders[delivery.platform];\n const result: NativePushSendResult = sender\n ? await sender(delivery).catch((error: unknown) => ({\n outcome: \"retry\" as const,\n error: String(error),\n }))\n : { outcome: \"failed\", error: `No ${delivery.platform} push credentials configured` };\n const outcome =\n result.outcome === \"retry\" && delivery.attempts >= MAX_ATTEMPTS ? \"failed\" : result.outcome;\n if (outcome === \"delivered\") delivered += 1;\n else\n deps.observability?.warn(\"Native push not delivered\", {\n platform: delivery.platform,\n outcome,\n error: result.error,\n });\n await settleNativePushDelivery(deps.db, {\n claimId,\n deliveryId: delivery.deliveryId,\n outcome,\n error: result.error ?? null,\n retrySeconds: Math.min(3600, 5 * 2 ** delivery.attempts),\n });\n }),\n );\n return { claimed: claimed.length, delivered };\n}\n\nexport function startNativePushDispatchPump(deps: NativePushDispatchDeps): () => Promise<void> {\n const senders = deps.senders ?? configuredNativePushSenders(deps.settings);\n let stopped = false;\n let ticks = 0;\n let running: Promise<void> | null = null;\n const tick = async () => {\n ticks += 1;\n try {\n const { claimed } = await drainNativePushDeliveries({ ...deps, senders });\n if (claimed > 0) deps.observability?.info(\"Native push batch\", { claimed });\n if (ticks % PRUNE_EVERY_TICKS === 0) await pruneNativePushDeliveries(deps.db);\n } catch (error) {\n deps.observability?.error(\"Native push dispatch failed\", { error: String(error) });\n }\n };\n const timer = setInterval(() => {\n if (stopped || running) return;\n running = tick().finally(() => {\n running = null;\n });\n }, POLL_INTERVAL_MS);\n return async () => {\n stopped = true;\n clearInterval(timer);\n await running;\n };\n}\n","import { randomUUID } from \"node:crypto\";\nimport { environmentsEncryptionKeyBytes, type Settings } from \"@opengeni/config\";\nimport {\n OPENGENI_DELIVERY_ID_HEADER,\n OPENGENI_EVENT_ID_HEADER,\n OPENGENI_SIGNATURE_HEADER,\n signOpenGeniPayload,\n} from \"@opengeni/contracts\";\nimport {\n claimWorkspaceWebhookDeliveries,\n claimOrganizationWebhookDeliveries,\n decryptEnvironmentValue,\n maintainSessionUsageLimits,\n maintainWorkspaceAllowances,\n pruneOrganizationWebhookDeliveries,\n pruneWorkspaceWebhookDeliveries,\n settleOrganizationWebhookDelivery,\n settleWorkspaceWebhookDelivery,\n type ClaimedWorkspaceWebhookDelivery,\n type Database,\n} from \"@opengeni/db\";\nimport { pinnedFetch } from \"@opengeni/network\";\nimport type { Observability } from \"@opengeni/observability\";\nimport { recordSessionUsageLimitEvent } from \"@opengeni/core\";\n\nexport const WORKSPACE_WEBHOOK_DISPATCH_BATCH_SIZE = 32;\nconst CLAIM_SECONDS = 60;\nconst POLL_INTERVAL_MS = 2_000;\nconst DELIVERY_TIMEOUT_MS = 10_000;\nconst PRUNE_EVERY_TICKS = 300;\n\nexport type WorkspaceWebhookDispatchDeps = {\n db: Database;\n settings: Settings;\n observability?: Pick<Observability, \"info\" | \"warn\" | \"error\"> &\n Partial<Pick<Observability, \"incrementCounter\">>;\n fetch?: typeof pinnedFetch;\n};\n\nexport type WorkspaceWebhookBatchResult = { claimed: number; delivered: number; failed: number };\n\nfunction errorText(error: unknown): string {\n if (error instanceof Error) {\n if (error.name === \"TimeoutError\" || error.name === \"AbortError\") return \"timeout\";\n return `${error.name}: ${error.message}`.slice(0, 500);\n }\n return String(error).slice(0, 500);\n}\n\nasync function deliverOne(\n deps: WorkspaceWebhookDispatchDeps,\n key: Uint8Array,\n claimId: string,\n delivery: ClaimedWorkspaceWebhookDelivery,\n organization = false,\n): Promise<\"delivered\" | \"failed\"> {\n let status: number | null = null;\n let error: string | null = null;\n try {\n const body = JSON.stringify(delivery.payload);\n const secret = decryptEnvironmentValue(key, delivery.secretEncrypted);\n const response = await (deps.fetch ?? pinnedFetch)(\n delivery.url,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"user-agent\": \"OpenGeni-Webhooks/1\",\n [OPENGENI_SIGNATURE_HEADER]: await signOpenGeniPayload(secret, body),\n [OPENGENI_EVENT_ID_HEADER]: delivery.eventId,\n [OPENGENI_DELIVERY_ID_HEADER]: delivery.deliveryId,\n },\n body,\n signal: AbortSignal.timeout(DELIVERY_TIMEOUT_MS),\n },\n deps.settings,\n {\n label: organization ? \"Organization webhook\" : \"Workspace webhook\",\n requireHttpsOutsideLocalTest: true,\n },\n );\n status = response.status;\n await response.body?.cancel().catch(() => undefined);\n if (status < 200 || status >= 300) error = `HTTP ${status}`;\n } catch (caught) {\n error = errorText(caught);\n }\n await (organization ? settleOrganizationWebhookDelivery : settleWorkspaceWebhookDelivery)(\n deps.db,\n {\n deliveryId: delivery.deliveryId,\n claimId,\n status,\n error,\n },\n );\n return error === null ? \"delivered\" : \"failed\";\n}\n\n/**\n * One bounded, resumable page of the per-task usage limit legacy import.\n * Roots created before the feature stay `preparing` (never shown or\n * admitted as $0 for a write) until this converges them. A failure is retried\n * on a later tick (per-root exponential backoff with its SQLSTATE kept) and\n * never blocks webhook delivery. The same pass discloses lost single-call\n * custody markers as unpriced so a crashed process cannot block a task forever.\n */\nasync function importLegacySessionUsage(deps: WorkspaceWebhookDispatchDeps): Promise<void> {\n const sink = deps.observability?.incrementCounter ? deps.observability : null;\n const metrics = sink as Pick<Observability, \"incrementCounter\"> | null;\n try {\n const result = await maintainSessionUsageLimits(deps.db);\n recordSessionUsageLimitEvent(metrics, \"import\", \"imported\", result.processed);\n recordSessionUsageLimitEvent(metrics, \"import\", \"import_failed\", result.failed);\n recordSessionUsageLimitEvent(metrics, \"single_call\", \"lost_resolved\", result.resolvedLost);\n if (result.failed > 0) {\n deps.observability?.warn(\"Session usage limit import pages failed\", {\n failed: result.failed,\n sqlstates: JSON.stringify(result.errors),\n });\n }\n } catch (error) {\n recordSessionUsageLimitEvent(metrics, \"import\", \"import_failed\");\n deps.observability?.warn(\"Session usage limit import failed\", { error: errorText(error) });\n }\n}\n\n/** Claim and deliver one globally bounded batch. At-least-once: receivers dedupe on event id. */\nexport async function drainWorkspaceWebhookDeliveries(\n deps: WorkspaceWebhookDispatchDeps,\n): Promise<WorkspaceWebhookBatchResult> {\n // Usage-limit maintenance contains its own failures, so it runs first: a\n // failing allowance pass cannot keep lost custody markers (and the tasks\n // they park) unresolved.\n await importLegacySessionUsage(deps);\n // Allowance rollover/expiry does not depend on webhook secrets, usage\n // readers, inference or having any pending delivery.\n await maintainWorkspaceAllowances(deps.db);\n const key = environmentsEncryptionKeyBytes(deps.settings);\n if (!key) return { claimed: 0, delivered: 0, failed: 0 };\n const claimId = randomUUID();\n const claims = await claimWorkspaceWebhookDeliveries(deps.db, {\n claimId,\n limit: WORKSPACE_WEBHOOK_DISPATCH_BATCH_SIZE,\n claimSeconds: CLAIM_SECONDS,\n });\n // Each lane is bounded; the shared pump does not starve organization queues\n // behind a sustained workspace backlog.\n const organizationClaims = await claimOrganizationWebhookDeliveries(deps.db, {\n claimId,\n limit: WORKSPACE_WEBHOOK_DISPATCH_BATCH_SIZE,\n claimSeconds: CLAIM_SECONDS,\n });\n const outcomes = await Promise.all(\n [\n ...claims.map((delivery) => ({ delivery, organization: false })),\n ...organizationClaims.map((delivery) => ({ delivery, organization: true })),\n ].map(async ({ delivery, organization }) => {\n try {\n return await deliverOne(deps, key, claimId, delivery, organization);\n } catch (error) {\n deps.observability?.warn(\"Workspace webhook settlement failed\", {\n deliveryId: delivery.deliveryId,\n error: errorText(error),\n });\n return \"failed\" as const;\n }\n }),\n );\n return {\n claimed: claims.length + organizationClaims.length,\n delivered: outcomes.filter((outcome) => outcome === \"delivered\").length,\n failed: outcomes.filter((outcome) => outcome === \"failed\").length,\n };\n}\n\n/**\n * One non-overlapping loop per API replica. PostgreSQL claims coordinate\n * replicas; a crash only delays a delivery until its claim expires.\n */\nexport function startWorkspaceWebhookDispatchPump(\n deps: WorkspaceWebhookDispatchDeps,\n options: {\n intervalMs?: number;\n drain?: (deps: WorkspaceWebhookDispatchDeps) => Promise<WorkspaceWebhookBatchResult>;\n } = {},\n): () => Promise<void> {\n const intervalMs = Math.max(100, options.intervalMs ?? POLL_INTERVAL_MS);\n const drain = options.drain ?? drainWorkspaceWebhookDeliveries;\n let stopped = false;\n let running: Promise<void> | undefined;\n let ticks = 0;\n\n const tick = (): void => {\n if (stopped || running) return;\n ticks += 1;\n // A full batch means a backlog: drain it now instead of one batch per interval.\n let backlog = false;\n running = (async () => {\n const result = await drain(deps);\n backlog = result.claimed >= WORKSPACE_WEBHOOK_DISPATCH_BATCH_SIZE;\n if (result.claimed > 0) deps.observability?.info(\"Workspace webhook batch settled\", result);\n if (ticks % PRUNE_EVERY_TICKS === 0) {\n await pruneWorkspaceWebhookDeliveries(deps.db);\n await pruneOrganizationWebhookDeliveries(deps.db);\n }\n })()\n .catch((error: unknown) => {\n deps.observability?.error(\"Workspace webhook dispatch failed\", { error: errorText(error) });\n })\n .finally(() => {\n running = undefined;\n if (backlog && !stopped) queueMicrotask(tick);\n });\n };\n\n const timer = setInterval(tick, intervalMs);\n queueMicrotask(tick);\n\n return async () => {\n stopped = true;\n clearInterval(timer);\n await running;\n };\n}\n","import {\n EditableArtifactDomainError,\n EditableArtifactLiveError,\n decodeEditableArtifactLiveClientWireFrame,\n encodeEditableArtifactLiveServerWireFrame,\n type EditableArtifactApplicationPort,\n type EditableArtifactLiveClose,\n type EditableArtifactLiveServerFrame,\n type EditableArtifactLiveSession,\n type EditableArtifactLiveSinkPort,\n type OpenEditableArtifactLiveInput,\n} from \"@opengeni/core\";\nimport type {\n ApiWebSocketConnection,\n ApiWebSocketLike,\n ApiWebSocketUpgradeServer,\n} from \"./api-websocket\";\n\nexport const EDITABLE_ARTIFACT_LIVE_WEBSOCKET_PATH = \"/v1/editable-artifacts/live\";\nexport const EDITABLE_ARTIFACT_LIVE_WEBSOCKET_PROTOCOL = \"opengeni-artifact-v2\";\nexport const EDITABLE_ARTIFACT_LIVE_WEBSOCKET_MAX_MESSAGE_BYTES = 8 * 1024 * 1024 + 64 * 1024;\n\nconst MAX_QUEUED_MESSAGES = 64;\nconst MAX_QUEUED_BYTES = 12 * 1024 * 1024;\n\nexport type EditableArtifactWebSocketLike = ApiWebSocketLike;\n\nexport type EditableArtifactWebSocketUpgradeServer = ApiWebSocketUpgradeServer;\n\nexport type EditableArtifactWebSocketHandler = Readonly<{\n open(socket: EditableArtifactWebSocketLike): void;\n message(socket: EditableArtifactWebSocketLike, message: string | Uint8Array | ArrayBuffer): void;\n close(socket: EditableArtifactWebSocketLike): void;\n}>;\n\nexport class EditableArtifactWebSocketTransport {\n readonly websocket: EditableArtifactWebSocketHandler;\n\n constructor(\n private readonly application: EditableArtifactApplicationPort | undefined,\n private readonly authorizeSourceSession?: OpenEditableArtifactLiveInput[\"authorizeSourceSession\"],\n ) {\n this.websocket = Object.freeze({\n open: (socket) => socket.data.attach(socket),\n message: (socket, message) => socket.data.receive(message),\n close: (socket) => socket.data.transportClosed(),\n });\n }\n\n handles(request: Request): boolean {\n return new URL(request.url).pathname === EDITABLE_ARTIFACT_LIVE_WEBSOCKET_PATH;\n }\n\n upgrade(request: Request, server: EditableArtifactWebSocketUpgradeServer): Response | undefined {\n const url = new URL(request.url);\n if (url.pathname !== EDITABLE_ARTIFACT_LIVE_WEBSOCKET_PATH) return undefined;\n if (request.method !== \"GET\") {\n return new Response(\"Method Not Allowed\", {\n status: 405,\n headers: { allow: \"GET\" },\n });\n }\n if (!this.application) return new Response(\"Service Unavailable\", { status: 503 });\n if (!offeredProtocol(request.headers.get(\"sec-websocket-protocol\"))) {\n return new Response(\"WebSocket protocol required\", { status: 426 });\n }\n const connection = new EditableArtifactWebSocketConnection(\n this.application,\n this.authorizeSourceSession,\n );\n const upgraded = server.upgrade(request, {\n data: connection,\n headers: {\n \"sec-websocket-protocol\": EDITABLE_ARTIFACT_LIVE_WEBSOCKET_PROTOCOL,\n },\n });\n return upgraded ? undefined : new Response(\"Bad Request\", { status: 400 });\n }\n}\n\n/** One socket, one consumed ticket, one stream epoch. */\nexport class EditableArtifactWebSocketConnection\n implements EditableArtifactLiveSinkPort, ApiWebSocketConnection\n{\n private socket: EditableArtifactWebSocketLike | null = null;\n private session: EditableArtifactLiveSession | null = null;\n private work: Promise<void> = Promise.resolve();\n private queuedMessages = 0;\n private queuedBytes = 0;\n private terminal = false;\n\n constructor(\n private readonly application: EditableArtifactApplicationPort,\n private readonly authorizeSourceSession?: OpenEditableArtifactLiveInput[\"authorizeSourceSession\"],\n ) {}\n\n attach(socket: EditableArtifactWebSocketLike): void {\n if (this.socket || this.terminal) {\n socket.close(4400, \"invalid connection state\");\n return;\n }\n this.socket = socket;\n }\n\n receive(message: string | Uint8Array | ArrayBuffer): void {\n if (this.terminal) return;\n if (typeof message === \"string\") {\n void this.fail(\"invalid_frame\");\n return;\n }\n const byteLength = message.byteLength;\n if (\n byteLength === 0 ||\n byteLength > EDITABLE_ARTIFACT_LIVE_WEBSOCKET_MAX_MESSAGE_BYTES ||\n this.queuedMessages + 1 > MAX_QUEUED_MESSAGES ||\n this.queuedBytes + byteLength > MAX_QUEUED_BYTES\n ) {\n void this.fail(\n byteLength > EDITABLE_ARTIFACT_LIVE_WEBSOCKET_MAX_MESSAGE_BYTES\n ? \"oversized_frame\"\n : \"slow_client\",\n );\n return;\n }\n const bytes =\n message instanceof Uint8Array ? Uint8Array.from(message) : new Uint8Array(message).slice();\n this.queuedMessages += 1;\n this.queuedBytes += bytes.byteLength;\n const run = this.work.then(async () => {\n try {\n await this.process(bytes);\n } finally {\n this.queuedMessages -= 1;\n this.queuedBytes -= bytes.byteLength;\n }\n });\n this.work = run.catch(async (error: unknown) => {\n await this.handleFailure(error);\n });\n }\n\n async send(frame: EditableArtifactLiveServerFrame): Promise<void> {\n if (this.terminal || !this.socket) {\n throw new EditableArtifactLiveError(\"closed\", \"Editable artifact socket is closed\");\n }\n const bytes = encodeEditableArtifactLiveServerWireFrame(frame);\n if (bytes.byteLength > EDITABLE_ARTIFACT_LIVE_WEBSOCKET_MAX_MESSAGE_BYTES) {\n throw new EditableArtifactLiveError(\n \"oversized_frame\",\n \"Editable artifact server frame exceeds socket limit\",\n { requiresSnapshot: true },\n );\n }\n const accepted = this.socket.send(bytes, false);\n if (!Number.isSafeInteger(accepted) || accepted <= 0) {\n throw new EditableArtifactLiveError(\"closed\", \"Editable artifact socket rejected frame\");\n }\n }\n\n bufferedBytes(): number {\n const buffered = this.socket?.getBufferedAmount?.() ?? this.socket?.bufferedAmount ?? 0;\n return Number.isSafeInteger(buffered) && buffered >= 0 ? buffered : Number.MAX_SAFE_INTEGER;\n }\n\n close(close: EditableArtifactLiveClose): void {\n if (this.terminal) return;\n this.terminal = true;\n this.socket?.close(closeCode(close.reason), close.reason);\n }\n\n transportClosed(): void {\n if (this.terminal) return;\n this.terminal = true;\n void this.session?.close(\"transport_error\");\n }\n\n private async process(bytes: Uint8Array): Promise<void> {\n if (this.terminal) return;\n const frame = decodeEditableArtifactLiveClientWireFrame(bytes);\n if (!this.session) {\n if (frame.type !== \"open\") {\n throw new EditableArtifactLiveError(\"invalid_frame\", \"First socket frame must be open\");\n }\n const session = await this.application.openLive({\n token: frame.token,\n artifactId: frame.artifactId,\n protocolVersion: frame.protocolVersion,\n resume: frame.resume,\n sink: this,\n ...(this.authorizeSourceSession\n ? { authorizeSourceSession: this.authorizeSourceSession }\n : {}),\n });\n if (this.terminal) {\n await session.close(\"transport_error\");\n return;\n }\n this.session = session;\n void session.closed.then(() => {\n if (!this.terminal)\n this.close({\n reason: \"closed\",\n retryable: false,\n requiresSnapshot: false,\n });\n });\n return;\n }\n if (frame.type === \"open\") {\n throw new EditableArtifactLiveError(\"invalid_frame\", \"Socket is already open\");\n }\n if (\n frame.artifactId !== this.session.artifactId ||\n frame.streamEpoch !== this.session.streamEpoch\n ) {\n throw new EditableArtifactLiveError(\"stale_epoch\", \"Socket frame belongs to another stream\");\n }\n if (frame.type === \"applied\") {\n await this.session.acknowledge(frame);\n return;\n }\n let receipt: Awaited<ReturnType<EditableArtifactLiveSession[\"submitIntent\"]>>;\n try {\n receipt = await this.session.submitIntent(frame);\n } catch (error) {\n await this.send({\n type: \"mutationRejected\",\n protocolVersion: frame.protocolVersion,\n artifactId: frame.artifactId,\n streamEpoch: frame.streamEpoch,\n requestHash: frame.requestHash,\n ...mutationFailure(error),\n });\n return;\n }\n // Always return the exact durable canonical transaction evidence (OGACO\n // or OGAST) on this request's socket, including idempotent unknown-outcome\n // retries whose original fanout was already replayed and ACKed. Transaction\n // first, mapping second: acceptance is never exposed without settle bytes.\n await this.send({\n type: \"transaction\",\n protocolVersion: frame.protocolVersion,\n artifactId: frame.artifactId,\n streamEpoch: frame.streamEpoch,\n transaction: receipt.transaction,\n });\n await this.send({\n type: \"mutationAccepted\",\n protocolVersion: frame.protocolVersion,\n artifactId: frame.artifactId,\n streamEpoch: frame.streamEpoch,\n requestHash: receipt.requestHash,\n clientTransactionId: receipt.clientTransactionId,\n transactionId: receipt.transaction.transactionId,\n startSequence: receipt.transaction.startSequence,\n endSequence: receipt.transaction.endSequence,\n stateHash: receipt.transaction.stateHash,\n });\n }\n\n private async handleFailure(error: unknown): Promise<void> {\n if (this.terminal) return;\n if (error instanceof EditableArtifactLiveError) {\n await this.fail(error.code === \"invalid_ticket\" ? \"transport_error\" : error.code);\n return;\n }\n await this.fail(\"transport_error\");\n }\n\n private async fail(reason: Parameters<EditableArtifactLiveSession[\"close\"]>[0]): Promise<void> {\n if (this.terminal) return;\n this.terminal = true;\n await this.session?.close(reason).catch(() => undefined);\n this.socket?.close(closeCode(reason ?? \"transport_error\"), reason ?? \"transport_error\");\n }\n}\n\nfunction mutationFailure(error: unknown): Readonly<{\n code: \"invalid_request\" | \"forbidden\" | \"conflict\" | \"unsupported\" | \"unavailable\";\n retryable: boolean;\n}> {\n if (error instanceof EditableArtifactDomainError) {\n if (error.code === \"forbidden\") return { code: \"forbidden\", retryable: false };\n if ([\"invalid_request\", \"request_hash_mismatch\", \"invalid_undo_target\"].includes(error.code)) {\n return { code: \"invalid_request\", retryable: false };\n }\n if (error.code === \"kernel_contract_violation\") {\n return { code: \"unsupported\", retryable: false };\n }\n if ([\"retryable_conflict\", \"outbox_lease_conflict\"].includes(error.code)) {\n return { code: \"conflict\", retryable: true };\n }\n return { code: \"conflict\", retryable: false };\n }\n if (error instanceof EditableArtifactLiveError && error.code === \"permission_changed\") {\n return { code: \"forbidden\", retryable: false };\n }\n return { code: \"unavailable\", retryable: true };\n}\n\nfunction offeredProtocol(value: string | null): boolean {\n return (\n value\n ?.split(\",\")\n .map((part) => part.trim())\n .includes(EDITABLE_ARTIFACT_LIVE_WEBSOCKET_PROTOCOL) ?? false\n );\n}\n\nfunction closeCode(reason: string): number {\n if (reason === \"permission_changed\") return 4403;\n if (reason === \"ticket_expired\" || reason === \"ticket_replayed\") return 4401;\n if (reason === \"protocol_mismatch\") return 4406;\n if (reason === \"slow_client\" || reason === \"oversized_frame\") return 4409;\n if (reason === \"closed\") return 1000;\n return 4400;\n}\n","import {\n hasPermission,\n requireExternalContinuationAuthority,\n requireSessionAuthorization,\n type ApiRouteDeps,\n type OpenEditableArtifactLiveInput,\n} from \"@opengeni/core\";\nimport {\n findActiveWorkspaceApiKeyById,\n getSession,\n getWorkspaceGrant,\n hasEditableArtifactSessionLink,\n lockExternalWorkspaceMembershipLifecycle,\n withRlsContext,\n} from \"@opengeni/db\";\nimport { withAccessGrantSessionRlsContext } from \"./access-grant-rls\";\nimport { sql } from \"drizzle-orm\";\n\n/** Supplied by the API adapter, so mounted hosts use their canonical live port. */\nexport function editableArtifactSourceSessionAuthorizer(\n deps: ApiRouteDeps,\n): NonNullable<OpenEditableArtifactLiveInput[\"authorizeSourceSession\"]> {\n return async (ticket, permission, transaction, signal) => {\n signal?.throwIfAborted();\n const authority = ticket.sourceSessionAuthority;\n if (!authority) return true;\n const { grant } = authority;\n const required = permission === \"edit\" ? \"artifacts:publish\" : \"artifacts:read\";\n if (\n !hasPermission(grant.permissions, required) ||\n !hasPermission(grant.permissions, \"sessions:read\")\n ) {\n return false;\n }\n // An external audit shape without the verified continuation is not authority.\n if (grant.metadata?.externalActor && !authority.externalContinuation) return false;\n try {\n const scopedDeps = transaction ? { ...deps, db: transaction } : deps;\n // Source-bound stores invoke us before their tenancy/aggregate locks.\n // Match lifecycle writers' organization -> tenancy -> session prefix.\n if (transaction) {\n await lockExternalWorkspaceMembershipLifecycle(transaction, ticket.scope.accountId);\n signal?.throwIfAborted();\n // Tenancy writers acquire this fence before source session rows.\n await transaction.execute(sql`select pg_advisory_xact_lock_shared(\n hashtextextended(${`session-tenancy:${ticket.scope.workspaceId}`}, 0))`);\n signal?.throwIfAborted();\n }\n return await withAccessGrantSessionRlsContext(scopedDeps, grant, async () => {\n return await withRlsContext(scopedDeps.db, ticket.scope, async (tx) => {\n if (authority.externalContinuation) {\n await requireExternalContinuationAuthority(\n tx,\n authority.externalContinuation,\n { ...ticket.scope, subjectId: grant.subjectId },\n [\"sessions:read\", required],\n );\n signal?.throwIfAborted();\n } else if (transaction) {\n // The authenticated ticket grant is a ceiling, not proof that\n // source-read permission still exists at the commit boundary.\n const actor = ticket.actor;\n if (\n actor.kind === \"human\" ||\n (actor.kind === \"service\" && actor.service === \"configured_key\")\n ) {\n await tx.execute(sql`select subject_id from workspace_memberships\n where account_id = ${ticket.scope.accountId}::uuid\n and workspace_id = ${ticket.scope.workspaceId}::uuid\n and subject_id = ${grant.subjectId} for share`);\n const live = await getWorkspaceGrant(tx, grant.subjectId, ticket.scope.workspaceId);\n if (!live || !hasPermission(live.permissions, \"sessions:read\")) return false;\n } else if (actor.kind === \"service\" && actor.service === \"api_key\") {\n await tx.execute(sql`select id from api_keys\n where account_id = ${ticket.scope.accountId}::uuid\n and id::text = ${grant.subjectId.slice(\"api_key:\".length)}\n for share`);\n const live = await findActiveWorkspaceApiKeyById(tx, {\n ...ticket.scope,\n apiKeyId: grant.subjectId.slice(\"api_key:\".length),\n });\n if (!live || !hasPermission(live.permissions, \"sessions:read\")) return false;\n } else if (actor.kind === \"agent\") {\n const live = await getSession(tx, ticket.scope.workspaceId, actor.sessionId);\n if (\n !live ||\n (live.firstPartyMcpPermissions !== null &&\n !hasPermission(live.firstPartyMcpPermissions, \"sessions:read\"))\n ) {\n return false;\n }\n } else {\n return false;\n }\n signal?.throwIfAborted();\n }\n // Locks protect visibility and removal of the exact association\n // until the enclosing mutation transaction commits.\n const linked = await hasEditableArtifactSessionLink(\n tx,\n ticket.scope,\n authority.sessionId,\n ticket.artifactId,\n { lockForCommit: transaction !== undefined },\n );\n signal?.throwIfAborted();\n if (!linked) return false;\n await requireSessionAuthorization({ ...scopedDeps, db: tx }, grant, {\n sessionId: authority.sessionId,\n operation: \"session.read\",\n surface: \"http\",\n });\n signal?.throwIfAborted();\n return true;\n });\n });\n } catch {\n // Denial or an unavailable authority must stop data/writes, never fall\n // back to artifact-only scope. The live loop closes denied readers.\n return false;\n }\n };\n}\n","import { localBrowserBoundaryResponse, type LocalBrowserBoundary } from \"./local-browser-boundary\";\n\nexport type ApiWebSocketUpgradeRoute<Server> = {\n handles(request: Request): boolean;\n upgrade(request: Request, server: Server): Response | undefined;\n};\n\nexport type ApiWebSocketUpgradeDispatch =\n | { handled: false }\n | { handled: true; response: Response | undefined };\n\n/**\n * WebSocket upgrades bypass the Hono app, so the local-mode browser boundary\n * (./local-browser-boundary.ts) is applied here before a transport upgrades.\n * Returns `{ handled: false }` when no transport claims the request, so the\n * caller dispatches it to the app, where the boundary runs as middleware.\n */\nexport function dispatchApiWebSocketUpgrade<Server>(\n request: Request,\n server: Server,\n routes: ReadonlyArray<ApiWebSocketUpgradeRoute<Server>>,\n localBrowserBoundary: LocalBrowserBoundary | null,\n): ApiWebSocketUpgradeDispatch {\n const route = routes.find((candidate) => candidate.handles(request));\n if (!route) return { handled: false };\n const rejection = localBrowserBoundary?.rejection(request);\n if (rejection) return { handled: true, response: localBrowserBoundaryResponse(rejection) };\n return { handled: true, response: route.upgrade(request, server) };\n}\n","import { createHash, randomUUID } from \"node:crypto\";\nimport {\n editableArtifactMaterializerCapabilitiesForRuntime,\n type EditableArtifactNativeMaterializerCapabilities,\n} from \"@opengeni/artifact-tool/runtime/materializer\";\nimport {\n EditableArtifactDurableExportService,\n EditableArtifactAgentApplication,\n EDITABLE_ARTIFACT_EXPORT_FORMATS,\n EDITABLE_ARTIFACT_EXPORT_MAX_DOWNLOAD_BYTES,\n EditableArtifactCompactionPipeline,\n EditableArtifactGenesisPipeline,\n EditableArtifactService,\n MAX_EDITABLE_ARTIFACT_SNAPSHOT_BYTES,\n ProductionEditableArtifactSnapshotVerifier,\n SystemEditableArtifactClock,\n editableArtifactLiveReadPortFromPostgres,\n editableArtifactLiveTicketStorePortFromPostgres,\n editableArtifactStorePortFromPostgres,\n editableArtifactDurableExportStorePortFromPostgres,\n ogatxEditableArtifactMutationIntentCodec,\n editableArtifactId,\n type EditableArtifactAuthorizationDecision,\n type EditableArtifactAuthorizationPort,\n type EditableArtifactAuthorizationRequest,\n type EditableArtifactStableIdFactoryPort,\n type EditableArtifactStableIdKind,\n type EditableArtifactDurableExportIdFactoryPort,\n type EditableArtifactExactSnapshotPort,\n type EditableArtifactAgentAssociationPort,\n type EditableArtifactMaterializationProfilePort,\n} from \"@opengeni/core/editable-artifacts\";\nimport {\n EditableArtifactApplication,\n EditableArtifactCompatibilityError,\n EditableArtifactLiveServer,\n SystemEditableArtifactLiveClock,\n SystemEditableArtifactLiveScheduler,\n WebCryptoEditableArtifactLiveTokens,\n type EditableArtifactApplicationPort,\n type EditableArtifactLiveAuthorizationInvalidationPort,\n type EditableArtifactLiveCompatibilityPort,\n} from \"@opengeni/core/editable-artifact-live\";\nimport { currentEditableArtifactCompatibility } from \"@opengeni/contracts/editable-artifacts\";\nimport {\n PostgresEditableArtifactLiveReadStore,\n PostgresEditableArtifactLiveTicketStore,\n PostgresEditableArtifactStore,\n listEditableArtifactIdsForSession,\n touchEditableArtifactSessionLink,\n recordNativeDocumentInspection,\n dbSql,\n withRlsContext,\n type Database,\n type PersistedEditableArtifactSnapshotBytesPort,\n type PersistedEditableArtifactSnapshotMetadata,\n} from \"@opengeni/db\";\nimport { PostgresEditableArtifactDurableExportStore } from \"@opengeni/db/editable-artifact-durable-export\";\nimport type { EventBus } from \"@opengeni/events\";\nimport {\n MAX_BOUNDED_OBJECT_CHUNK_BYTES,\n createObjectStorageBoundedPorts,\n type BoundedObjectReadPort,\n type ObjectStorage,\n} from \"@opengeni/storage\";\nimport { EventBusEditableArtifactLiveHints } from \"./editable-artifact-live-hints\";\nimport {\n NativeEditableArtifactKernelAdapter,\n loadVerifiedNativeArtifactRuntimeBinding,\n} from \"./editable-artifact-native-kernel\";\nimport { EditableArtifactOfficeImportAdapter } from \"./editable-artifact-office-import\";\nimport { EditableArtifactWorkspaceFileAdapter } from \"./editable-artifact-workspace-files\";\n\nconst INVALIDATION_POLL_MS = 1_000;\nconst TICKET_CLEANUP_MS = 30_000;\n\nexport type StandaloneEditableArtifactApplication = Readonly<{\n application: EditableArtifactApplicationPort;\n durableExports: EditableArtifactDurableExportService;\n agent: EditableArtifactAgentApplication;\n officeImports: EditableArtifactOfficeImportAdapter;\n kernelVersion: string;\n close(): void;\n}>;\n\n/**\n * Standalone production composition. Every authority is durable: PostgreSQL\n * owns admission/authorization/history, object storage owns immutable model\n * bytes, and NATS carries wake-up hints only.\n */\nexport async function createStandaloneEditableArtifactApplication(input: {\n db: Database;\n bus: EventBus;\n objectStorage: ObjectStorage;\n}): Promise<StandaloneEditableArtifactApplication> {\n const boundedObjects = createObjectStorageBoundedPorts(input.objectStorage);\n const materializationObjects = createObjectStorageBoundedPorts(input.objectStorage, {\n keyPrefix: \"editable-artifacts/materializations/v1/sha256/\",\n });\n const importSourceObjects = createObjectStorageBoundedPorts(input.objectStorage, {\n keyPrefix: \"editable-artifacts/imports/v1/sha256/\",\n });\n const runtimeBinding = await loadVerifiedNativeArtifactRuntimeBinding();\n const runtime = runtimeBinding.runtime;\n const kernel = new NativeEditableArtifactKernelAdapter(runtime, boundedObjects.read);\n const persistedStore = new PostgresEditableArtifactStore(input.db);\n const store = editableArtifactStorePortFromPostgres(persistedStore);\n const authorization = new PostgresEditableArtifactAuthorization(input.db);\n const ids = new RandomEditableArtifactStableIds();\n const clock = new SystemEditableArtifactClock();\n const snapshotVerifier = new ProductionEditableArtifactSnapshotVerifier({\n objects: boundedObjects.read,\n kernel,\n });\n const genesis = new EditableArtifactGenesisPipeline({\n kernel,\n objects: boundedObjects.write,\n now: () => clock.now(),\n });\n const compaction = new EditableArtifactCompactionPipeline({\n kernel,\n objects: boundedObjects.write,\n now: () => clock.now(),\n });\n const domain = new EditableArtifactService({\n authorization,\n kernel,\n store,\n intentCodec: ogatxEditableArtifactMutationIntentCodec,\n clock,\n ids,\n snapshotVerifier,\n genesis,\n compaction,\n });\n const materializerCapabilities = editableArtifactMaterializerCapabilitiesForRuntime(\n runtime,\n runtimeBinding.location.artifactTool.packageVersion,\n );\n const durableExports = new EditableArtifactDurableExportService({\n authorization,\n exactSnapshots: Object.freeze({\n ensure: async (request: Parameters<EditableArtifactExactSnapshotPort[\"ensure\"]>[0]) =>\n await domain.compactCurrentHead(request),\n }),\n store: editableArtifactDurableExportStorePortFromPostgres(\n new PostgresEditableArtifactDurableExportStore(input.db),\n ),\n ids: new RandomEditableArtifactDurableExportIds(),\n profiles: materializationProfiles(materializerCapabilities),\n materializationObjects: materializationObjects.read,\n });\n const officeImports = new EditableArtifactOfficeImportAdapter({\n db: input.db,\n objectStorage: input.objectStorage,\n runtime: runtimeBinding,\n sourceObjects: importSourceObjects.write,\n snapshotObjects: boundedObjects.write,\n });\n const agent = new EditableArtifactAgentApplication({\n domain,\n exports: durableExports,\n associations: Object.freeze({\n listArtifactIds: async ({ scope, sessionId, limit }) =>\n (await listEditableArtifactIdsForSession(input.db, scope, sessionId, limit)).map(\n editableArtifactId,\n ),\n touch: async ({ scope, sessionId, artifactId }) =>\n await touchEditableArtifactSessionLink(input.db, scope, sessionId, artifactId),\n } satisfies EditableArtifactAgentAssociationPort),\n inspector: kernel,\n recordInspection: async (inspection) => {\n if (inspection.actor.kind !== \"agent\")\n throw new Error(\"Inspection proof requires an agent attempt\");\n return recordNativeDocumentInspection(input.db, { ...inspection, actor: inspection.actor });\n },\n officeImports,\n workspaceFiles: new EditableArtifactWorkspaceFileAdapter({\n db: input.db,\n objectStorage: input.objectStorage,\n durableExports,\n }),\n });\n const ticketStore = new PostgresEditableArtifactLiveTicketStore(input.db);\n const liveRead = new PostgresEditableArtifactLiveReadStore(input.db, {\n snapshotBytes: snapshotBytesPort(boundedObjects.read),\n });\n const invalidations = new PollingEditableArtifactAuthorizationInvalidations(authorization);\n const live = new EditableArtifactLiveServer({\n authorization,\n domain,\n tickets: editableArtifactLiveTicketStorePortFromPostgres(ticketStore),\n tokens: new WebCryptoEditableArtifactLiveTokens(),\n clock: new SystemEditableArtifactLiveClock(),\n scheduler: new SystemEditableArtifactLiveScheduler(),\n read: editableArtifactLiveReadPortFromPostgres(liveRead),\n hints: new EventBusEditableArtifactLiveHints(input.bus),\n invalidations,\n });\n const compatibility: EditableArtifactLiveCompatibilityPort = Object.freeze({\n assertCompatible(\n request: Parameters<EditableArtifactLiveCompatibilityPort[\"assertCompatible\"]>[0],\n ) {\n const current = currentEditableArtifactCompatibility(request.artifact.modality);\n if (\n request.modality !== request.artifact.modality ||\n request.liveProtocolVersion !== current.liveProtocolVersion ||\n request.modelSchemaVersion !== current.modelSchemaVersion ||\n request.snapshotVersion !== current.snapshotVersion ||\n request.commandProtocolVersion !== current.commandProtocolVersion ||\n request.committedTransactionProtocolVersion !== current.committedTransactionProtocolVersion\n ) {\n throw new EditableArtifactCompatibilityError();\n }\n },\n });\n const application = new EditableArtifactApplication({\n domain,\n live,\n compatibility,\n });\n const cleanup = setInterval(() => {\n void ticketStore.cleanupExpired().catch(() => undefined);\n }, TICKET_CLEANUP_MS);\n cleanup.unref?.();\n return Object.freeze({\n application,\n durableExports,\n agent,\n officeImports,\n kernelVersion: runtime.buildIdentity,\n close() {\n clearInterval(cleanup);\n invalidations.close();\n },\n });\n}\n\nexport class PostgresEditableArtifactAuthorization implements EditableArtifactAuthorizationPort {\n constructor(private readonly db: Database) {}\n\n async authorize(\n request: EditableArtifactAuthorizationRequest,\n ): Promise<EditableArtifactAuthorizationDecision> {\n const actor = request.actor;\n const rows = await withRlsContext(this.db, request.scope, async (tx) =>\n rawRows<{ allowed: boolean; authorization_revision: number | string | bigint }>(\n await tx.execute(dbSql`select *\n from opengeni_private.authorize_editable_artifact_actor(\n ${request.scope.accountId}::uuid,\n ${request.scope.workspaceId}::uuid,\n ${request.artifactId},\n ${actor.kind},\n ${actor.subjectId},\n ${actor.kind === \"agent\" ? actor.sessionId : null},\n ${actor.kind === \"agent\" ? actor.turnId : null},\n ${actor.kind === \"agent\" ? actor.attemptId : null},\n ${actor.kind === \"agent\" ? actor.generation : null},\n ${actor.kind === \"service\" ? actor.service : null},\n ${request.permission},\n current_schema()\n )`),\n ),\n );\n if (rows.length !== 1) throw new Error(\"Editable artifact authorization returned no decision\");\n const revision = Number(rows[0]!.authorization_revision);\n if (!Number.isSafeInteger(revision) || revision < 1) {\n throw new Error(\"Editable artifact authorization returned an invalid revision\");\n }\n return Object.freeze({ allowed: rows[0]!.allowed === true, revision });\n }\n}\n\nclass PollingEditableArtifactAuthorizationInvalidations implements EditableArtifactLiveAuthorizationInvalidationPort {\n private readonly stops = new Set<() => void>();\n\n constructor(private readonly authorization: EditableArtifactAuthorizationPort) {}\n\n async subscribe(\n input: Parameters<EditableArtifactLiveAuthorizationInvalidationPort[\"subscribe\"]>[0],\n ): Promise<() => void> {\n let active = true;\n let polling = false;\n let baseline = await this.read(input);\n const timer = setInterval(() => {\n if (!active || polling) return;\n polling = true;\n void this.read(input)\n .then((next) => {\n if (!active) return;\n if (next !== baseline) {\n baseline = next;\n input.onInvalidated();\n }\n })\n .catch(() => {\n if (active) input.onInvalidated();\n })\n .finally(() => {\n polling = false;\n });\n }, INVALIDATION_POLL_MS);\n timer.unref?.();\n const stop = () => {\n if (!active) return;\n active = false;\n clearInterval(timer);\n this.stops.delete(stop);\n };\n this.stops.add(stop);\n return stop;\n }\n\n close(): void {\n for (const stop of [...this.stops]) stop();\n }\n\n private async read(\n input: Parameters<EditableArtifactLiveAuthorizationInvalidationPort[\"subscribe\"]>[0],\n ): Promise<string> {\n const decision = await this.authorization.authorize({\n scope: input.scope,\n artifactId: input.artifactId,\n actor: input.actor,\n permission: \"read\",\n });\n return `${decision.allowed ? 1 : 0}:${decision.revision}`;\n }\n}\n\nclass RandomEditableArtifactStableIds implements EditableArtifactStableIdFactoryPort {\n next(_kind: EditableArtifactStableIdKind) {\n return randomUUID().replaceAll(\"-\", \"\") as ReturnType<\n EditableArtifactStableIdFactoryPort[\"next\"]\n >;\n }\n}\n\nclass RandomEditableArtifactDurableExportIds implements EditableArtifactDurableExportIdFactoryPort {\n next(_kind: \"version\" | \"materialization_job\" | \"receipt\"): string {\n return randomUUID().replaceAll(\"-\", \"\");\n }\n}\n\nfunction materializationProfiles(\n capabilities: EditableArtifactNativeMaterializerCapabilities,\n): EditableArtifactMaterializationProfilePort {\n const spreadsheetCompatibility = currentEditableArtifactCompatibility(\"spreadsheet\");\n if (\n capabilities.protocol !== \"OGAMC001\" ||\n capabilities.runtimeKind !== \"native\" ||\n capabilities.maxOutputBytes !== EDITABLE_ARTIFACT_EXPORT_MAX_DOWNLOAD_BYTES ||\n capabilities.codecVersions[\"opengeni.xlsx\"] === undefined ||\n capabilities.supportedModelSchemaVersions[0] !== spreadsheetCompatibility.modelSchemaVersion ||\n capabilities.supportedOperationProtocolVersions[0] !==\n spreadsheetCompatibility.committedTransactionProtocolVersion ||\n capabilities.supportedSnapshotProtocolVersions[0] !== spreadsheetCompatibility.snapshotVersion\n ) {\n throw new Error(\"Verified artifact materializer profile is incompatible\");\n }\n const codecVersion = capabilities.codecVersions[\"opengeni.xlsx\"];\n return Object.freeze({\n supportedFormats: EDITABLE_ARTIFACT_EXPORT_FORMATS,\n async resolve(input: Parameters<EditableArtifactMaterializationProfilePort[\"resolve\"]>[0]) {\n // EDITABLE_ARTIFACT_EXPORT_FORMATS is what agents are told exists.\n if (\n input.modality !== \"spreadsheet\" ||\n input.format !== \"xlsx\" ||\n !EDITABLE_ARTIFACT_EXPORT_FORMATS[input.modality].includes(input.format) ||\n Object.keys(input.options).length !== 0\n ) {\n return null;\n }\n return Object.freeze({\n modality: \"spreadsheet\" as const,\n format: \"xlsx\" as const,\n codecId: \"opengeni.xlsx\",\n codecVersion,\n kernelVersion: capabilities.kernelVersion,\n fontRegistryHash: capabilities.fontRegistryHash,\n policyHash: capabilities.policyHash,\n normalizedOptions: \"{}\",\n });\n },\n });\n}\n\nfunction snapshotBytesPort(\n objects: BoundedObjectReadPort,\n): PersistedEditableArtifactSnapshotBytesPort {\n return Object.freeze({\n async readSnapshotBytes(snapshot: PersistedEditableArtifactSnapshotMetadata) {\n const object = await objects.open({\n opaqueReference: snapshot.blobReference,\n maxBytes: MAX_EDITABLE_ARTIFACT_SNAPSHOT_BYTES,\n expectedByteSize: snapshot.byteSize,\n });\n try {\n if (object.contentType !== undefined && object.contentType !== snapshot.mimeType) {\n throw new Error(\"Editable artifact snapshot content type mismatch\");\n }\n const bytes = new Uint8Array(snapshot.byteSize);\n const digest = createHash(\"sha256\");\n let offset = 0;\n for await (const chunk of object.chunks({\n chunkBytes: MAX_BOUNDED_OBJECT_CHUNK_BYTES,\n })) {\n if (offset + chunk.byteLength > bytes.byteLength) {\n throw new Error(\"Editable artifact snapshot exceeds its declared size\");\n }\n bytes.set(chunk, offset);\n digest.update(chunk);\n offset += chunk.byteLength;\n }\n if (\n offset !== bytes.byteLength ||\n `sha256:${digest.digest(\"hex\")}` !== snapshot.contentHash\n ) {\n throw new Error(\"Editable artifact snapshot digest or size mismatch\");\n }\n await object.assertUnchanged();\n return bytes;\n } finally {\n await object.close();\n }\n },\n });\n}\n\nfunction rawRows<T extends Record<string, unknown>>(result: unknown): T[] {\n if (Array.isArray(result)) return result as T[];\n const rows = (result as { rows?: unknown } | null)?.rows;\n if (Array.isArray(rows)) return rows as T[];\n throw new Error(\"Unsupported database execute result shape\");\n}\n","import {\n decodeEditableArtifactBrokerHint,\n editableArtifactLiveHintSubject,\n type EditableArtifactLiveHintPort,\n} from \"@opengeni/core\";\nimport type { EventBus, OpStreamConnection } from \"@opengeni/events\";\n\n/**\n * Uses the API's existing resilient NATS connection. Hints carry no operation\n * bytes; every callback causes a durable DB head read and contiguous gap-fill.\n */\nexport class EventBusEditableArtifactLiveHints implements EditableArtifactLiveHintPort {\n constructor(private readonly bus: Pick<EventBus, \"getOpStreamConnection\">) {}\n\n async subscribe(\n input: Parameters<EditableArtifactLiveHintPort[\"subscribe\"]>[0],\n ): Promise<() => void> {\n const connection = this.bus.getOpStreamConnection?.();\n if (!connection) throw new Error(\"Event bus has no artifact hint subscription transport\");\n const subject = editableArtifactLiveHintSubject(input.scope, input.artifactId);\n const subscription = connection.subscribe(subject);\n let active = true;\n try {\n await requireFlushBarrier(connection);\n } catch (error) {\n subscription.unsubscribe();\n throw error;\n }\n void (async () => {\n try {\n for await (const message of subscription) {\n if (!active) return;\n try {\n const hint = decodeEditableArtifactBrokerHint(message.data, {\n scope: input.scope,\n artifactId: input.artifactId,\n });\n input.onHint({\n artifactId: input.artifactId,\n headSequence: hint.headSequence,\n });\n } catch {\n // Broker input is advisory and untrusted. Drop poison; periodic\n // durable reconciliation remains authoritative.\n }\n }\n } catch {\n if (active) input.onReconnect();\n }\n })();\n return () => {\n if (!active) return;\n active = false;\n subscription.unsubscribe();\n };\n }\n}\n\nasync function requireFlushBarrier(connection: OpStreamConnection): Promise<void> {\n if (!connection.flush) {\n throw new Error(\"Artifact hint subscription transport lacks a flush barrier\");\n }\n await connection.flush();\n}\n","import { createHash } from \"node:crypto\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n createNativeArtifactSession,\n openNativeArtifactSession,\n type NativeArtifactSession,\n type NativeSpreadsheetSession,\n} from \"@opengeni/artifact-tool/native\";\nimport type { ArtifactKernelRuntime } from \"@opengeni/artifact-tool/runtime\";\nimport {\n doctorConfiguredArtifactRuntime,\n type ConfiguredArtifactRuntimeLocation,\n} from \"@opengeni/artifact-tool/runtime/development\";\nimport {\n decodeEditableArtifactCausalFrontier,\n encodeEditableArtifactCausalFrontier,\n} from \"@opengeni/contracts/editable-artifact-causal-frontier\";\nimport { decodeEditableArtifactSerializedCommit } from \"@opengeni/contracts/editable-artifact-serialized-commit\";\nimport { decodeEditableArtifactMutationIntent } from \"@opengeni/contracts/editable-artifacts\";\nimport {\n COMMITTED_TRANSACTION_PROTOCOL_VERSION,\n DOCUMENT_ARTIFACT_MODEL_SCHEMA_VERSION,\n PRESENTATION_ARTIFACT_MODEL_SCHEMA_VERSION,\n SPREADSHEET_ARTIFACT_MODEL_SCHEMA_VERSION,\n SPREADSHEET_COLLABORATION_SNAPSHOT_VERSION,\n} from \"@opengeni/contracts/editable-artifact-versions\";\nimport {\n MAX_EDITABLE_ARTIFACT_SNAPSHOT_BYTES,\n causalFrontiersEqual,\n editableArtifactCausalFrontier,\n editableArtifactContentHash,\n editableArtifactReplicaId,\n editableArtifactStateHash,\n type ApplyAuthoritativeEditableArtifactKernelRequest,\n type ApplyAuthoritativeEditableArtifactKernelResult,\n type AuthoritativeEditableArtifactCompactionKernelPort,\n type AuthoritativeEditableArtifactCompactionKernelResult,\n type AuthoritativeEditableArtifactGenesisKernelPort,\n type AuthoritativeEditableArtifactGenesisKernelResult,\n type AuthoritativeEditableArtifactKernelPort,\n type EditableArtifactAgentInspectionKernelPort,\n type EditableArtifactKernelState,\n type EditableArtifactSnapshotReplayPlan,\n type IsolatedEditableArtifactSnapshotKernelPort,\n type IsolatedEditableArtifactSnapshotKernelResult,\n} from \"@opengeni/core\";\nimport type { BoundedObjectReadPort } from \"@opengeni/storage\";\n\nconst SNAPSHOT_CHUNK_BYTES = 1024 * 1024;\n\ntype RuntimeFacadeModule = Readonly<{\n getConfiguredArtifactRuntime?: () => unknown;\n}> &\n Readonly<Record<string, unknown>>;\n\nexport type VerifiedNativeArtifactRuntimeBinding = Readonly<{\n runtime: ArtifactKernelRuntime;\n location: ConfiguredArtifactRuntimeLocation;\n facade: RuntimeFacadeModule;\n}>;\n\n/** Loads only the manifest-pinned, byte-verified native runtime. */\nexport async function loadVerifiedNativeArtifactRuntime(): Promise<ArtifactKernelRuntime> {\n return (await loadVerifiedNativeArtifactRuntimeBinding()).runtime;\n}\n\n/** Same verified load plus the pinned package identity used by export profiles. */\nexport async function loadVerifiedNativeArtifactRuntimeBinding(): Promise<VerifiedNativeArtifactRuntimeBinding> {\n const location = await doctorConfiguredArtifactRuntime();\n const module = (await import(\n /* @vite-ignore */ pathToFileURL(location.skillFacadeEntrypoint).href\n )) as RuntimeFacadeModule;\n const candidate = module.getConfiguredArtifactRuntime?.();\n assertRuntime(candidate, location);\n return Object.freeze({ runtime: candidate, location, facade: module });\n}\n\n/** Exact native authority shared by mutation, genesis, and snapshot verification. */\nexport class NativeEditableArtifactKernelAdapter\n implements\n AuthoritativeEditableArtifactKernelPort,\n AuthoritativeEditableArtifactGenesisKernelPort,\n AuthoritativeEditableArtifactCompactionKernelPort,\n IsolatedEditableArtifactSnapshotKernelPort,\n EditableArtifactAgentInspectionKernelPort\n{\n constructor(\n readonly runtime: ArtifactKernelRuntime,\n private readonly objects: BoundedObjectReadPort,\n ) {\n if (runtime.kind !== \"native\" || runtime.target === \"wasm-web\") {\n throw new Error(\"Editable artifact authority requires a native kernel\");\n }\n }\n\n async applyTransaction(\n request: ApplyAuthoritativeEditableArtifactKernelRequest,\n ): Promise<ApplyAuthoritativeEditableArtifactKernelResult> {\n const session = await this.openCurrentState(request.state);\n try {\n if (request.modality === \"spreadsheet\") {\n if (session.modality !== \"spreadsheet\") throw new Error(\"Native modality mismatch\");\n const committedTransactionBytes = session.authorTransaction(\n request.intentBytes,\n encodeEditableArtifactCausalFrontier(request.resolvedCausalBase),\n );\n return Object.freeze({\n modality: \"spreadsheet\" as const,\n committedTransactionBytes,\n kernelVersion: this.runtime.buildIdentity,\n modelSchemaVersion: SPREADSHEET_ARTIFACT_MODEL_SCHEMA_VERSION,\n });\n }\n if (session.modality !== request.modality) {\n throw new Error(\"Native modality mismatch\");\n }\n const nativeReceiptBytes = session.applyCommands(request.intent.commandBytes);\n return Object.freeze({\n modality: request.modality,\n nativeReceiptBytes,\n resultingStateHash: editableArtifactStateHash(session.stateHash()),\n kernelVersion: this.runtime.buildIdentity,\n modelSchemaVersion: modelSchemaVersionFor(request.modality),\n });\n } finally {\n session.dispose();\n }\n }\n\n async query(\n input: Parameters<EditableArtifactAgentInspectionKernelPort[\"query\"]>[0],\n ): ReturnType<EditableArtifactAgentInspectionKernelPort[\"query\"]> {\n const session = await this.openCurrentState(input.state);\n try {\n return Uint8Array.from(session.query(input.queryBytes));\n } finally {\n session.dispose();\n }\n }\n\n private async openCurrentState(\n state: EditableArtifactKernelState,\n ): Promise<NativeArtifactSession> {\n const snapshot = state.snapshot;\n if (!snapshot) throw new Error(\"Editable artifact has no verified replay snapshot\");\n const snapshotBytes = await readVerifiedSnapshot(this.objects, snapshot);\n const session = openNativeArtifactSession(this.runtime, {\n modality: state.modality,\n snapshot: snapshotBytes,\n });\n try {\n verifySnapshotBoundary(session, state);\n replayKernelTail(session, state);\n verifyDurableHead(session, state);\n return session;\n } catch (error) {\n session.dispose();\n throw error;\n }\n }\n\n async createCanonicalEmptySnapshot(input: {\n scope: Parameters<\n AuthoritativeEditableArtifactGenesisKernelPort[\"createCanonicalEmptySnapshot\"]\n >[0][\"scope\"];\n artifactId: Parameters<\n AuthoritativeEditableArtifactGenesisKernelPort[\"createCanonicalEmptySnapshot\"]\n >[0][\"artifactId\"];\n modality: Parameters<\n AuthoritativeEditableArtifactGenesisKernelPort[\"createCanonicalEmptySnapshot\"]\n >[0][\"modality\"];\n signal?: AbortSignal;\n }): Promise<AuthoritativeEditableArtifactGenesisKernelResult> {\n throwIfAborted(input.signal);\n const session = createNativeArtifactSession(this.runtime, {\n modality: input.modality,\n replicaNamespace: namespaceForArtifact(input.artifactId),\n });\n try {\n const snapshot = session.snapshot();\n throwIfAborted(input.signal);\n const revision = safeRevision(session.revision());\n if (revision !== 0) throw new Error(\"Native genesis revision is not zero\");\n const common = {\n scope: input.scope,\n artifactId: input.artifactId,\n modality: input.modality,\n canonicalChunks: fixedChunks(snapshot, input.signal),\n canonicalByteSize: snapshot.byteLength,\n canonicalContentHash: editableArtifactContentHash(\n `sha256:${createHash(\"sha256\").update(snapshot).digest(\"hex\")}`,\n ),\n stateHash: editableArtifactStateHash(session.stateHash()),\n coveredHeadSequence: 0 as const,\n modelSchemaVersion: modelSchemaVersionFor(input.modality),\n kernelVersion: this.runtime.buildIdentity,\n };\n if (session.modality === \"spreadsheet\") {\n return Object.freeze({\n ...common,\n modality: \"spreadsheet\" as const,\n coveredCausalFrontier: domainFrontier(session.frontier()),\n operationProtocolVersion: COMMITTED_TRANSACTION_PROTOCOL_VERSION,\n crdtStateVersion: SPREADSHEET_COLLABORATION_SNAPSHOT_VERSION,\n });\n }\n return Object.freeze({\n ...common,\n modality: session.modality,\n nativeRevision: 0 as const,\n });\n } finally {\n session.dispose();\n }\n }\n\n async createCanonicalSnapshot(input: {\n state: EditableArtifactKernelState;\n signal?: AbortSignal;\n }): Promise<AuthoritativeEditableArtifactCompactionKernelResult> {\n throwIfAborted(input.signal);\n const snapshot = input.state.snapshot;\n if (!snapshot) throw new Error(\"Editable artifact has no verified replay snapshot\");\n const snapshotBytes = await readVerifiedSnapshot(this.objects, snapshot, input.signal);\n const session = openNativeArtifactSession(this.runtime, {\n modality: input.state.modality,\n snapshot: snapshotBytes,\n });\n try {\n verifySnapshotBoundary(session, input.state);\n replayKernelTail(session, input.state);\n verifyDurableHead(session, input.state);\n throwIfAborted(input.signal);\n const canonical = session.snapshot();\n const common = {\n scope: input.state.artifact.scope,\n artifactId: input.state.artifact.id,\n modality: input.state.modality,\n canonicalChunks: fixedChunks(canonical, input.signal),\n canonicalByteSize: canonical.byteLength,\n canonicalContentHash: editableArtifactContentHash(\n `sha256:${createHash(\"sha256\").update(canonical).digest(\"hex\")}`,\n ),\n stateHash: editableArtifactStateHash(session.stateHash()),\n coveredHeadSequence: input.state.artifact.headSequence,\n modelSchemaVersion: modelSchemaVersionFor(input.state.modality),\n kernelVersion: this.runtime.buildIdentity,\n } as const;\n if (session.modality === \"spreadsheet\") {\n if (input.state.modality !== \"spreadsheet\") throw new Error(\"Native modality mismatch\");\n return Object.freeze({\n ...common,\n modality: session.modality,\n coveredCausalFrontier: domainFrontier(session.frontier()),\n operationProtocolVersion: COMMITTED_TRANSACTION_PROTOCOL_VERSION,\n crdtStateVersion: SPREADSHEET_COLLABORATION_SNAPSHOT_VERSION,\n });\n }\n if (session.modality !== input.state.modality) throw new Error(\"Native modality mismatch\");\n return Object.freeze({\n ...common,\n modality: session.modality,\n nativeRevision: safeRevision(session.revision()),\n });\n } finally {\n session.dispose();\n }\n }\n\n async verifyAndReconstruct(\n input: Parameters<IsolatedEditableArtifactSnapshotKernelPort[\"verifyAndReconstruct\"]>[0],\n ): Promise<IsolatedEditableArtifactSnapshotKernelResult> {\n throwIfAborted(input.signal);\n const bytes = await collectExact(\n input.snapshotChunks,\n input.expectedSnapshotByteSize,\n input.signal,\n );\n const session = openNativeArtifactSession(this.runtime, {\n modality: input.modality,\n snapshot: bytes,\n });\n try {\n const canonical = session.snapshot();\n if (!equalBytes(canonical, bytes)) throw new Error(\"Native snapshot is not canonical\");\n const expected = input.expectedSnapshot;\n if (expected.modality !== session.modality) throw new Error(\"Snapshot modality mismatch\");\n const coveredHeadSequence = expected.coveredHeadSequence;\n const stateHash = editableArtifactStateHash(session.stateHash());\n if (stateHash !== expected.stateHash) throw new Error(\"Snapshot state hash mismatch\");\n const canonicalContentHash = editableArtifactContentHash(\n `sha256:${createHash(\"sha256\").update(canonical).digest(\"hex\")}`,\n );\n if (session.modality === \"spreadsheet\") {\n const coveredCausalFrontier = domainFrontier(session.frontier());\n if (\n expected.modality !== \"spreadsheet\" ||\n !causalFrontiersEqual(coveredCausalFrontier, expected.coveredCausalFrontier)\n ) {\n throw new Error(\"Snapshot causal coverage mismatch\");\n }\n if (input.replayPlan && input.replayPlan.modality !== \"spreadsheet\") {\n throw new Error(\"Replay modality mismatch\");\n }\n const replayedTarget = input.replayPlan\n ? await replaySpreadsheetPlan(session, input.replayPlan, input.signal)\n : undefined;\n return Object.freeze({\n modality: \"spreadsheet\" as const,\n canonicalReencodeVerified: true as const,\n scope: input.scope,\n artifactId: input.artifactId,\n canonicalByteSize: canonical.byteLength,\n canonicalContentHash,\n coveredHeadSequence,\n stateHash,\n modelSchemaVersion: SPREADSHEET_ARTIFACT_MODEL_SCHEMA_VERSION,\n kernelVersion: this.runtime.buildIdentity,\n fullCrdtStateVerified: true as const,\n coveredCausalFrontier,\n operationProtocolVersion: COMMITTED_TRANSACTION_PROTOCOL_VERSION,\n crdtStateVersion: SPREADSHEET_COLLABORATION_SNAPSHOT_VERSION,\n ...(replayedTarget ? { replayedTarget } : {}),\n });\n }\n if (expected.modality === \"spreadsheet\") throw new Error(\"Snapshot modality mismatch\");\n const nativeRevision = safeRevision(session.revision());\n if (nativeRevision !== expected.nativeRevision) {\n throw new Error(\"Snapshot native revision mismatch\");\n }\n if (input.replayPlan && input.replayPlan.modality === \"spreadsheet\") {\n throw new Error(\"Replay modality mismatch\");\n }\n const replayedTarget = input.replayPlan\n ? await replaySerializedPlan(session, input.replayPlan, input.signal)\n : undefined;\n return Object.freeze({\n modality: session.modality,\n canonicalReencodeVerified: true as const,\n scope: input.scope,\n artifactId: input.artifactId,\n canonicalByteSize: canonical.byteLength,\n canonicalContentHash,\n coveredHeadSequence,\n stateHash,\n modelSchemaVersion: modelSchemaVersionFor(session.modality),\n kernelVersion: this.runtime.buildIdentity,\n nativeRevision,\n ...(replayedTarget ? { replayedTarget } : {}),\n });\n } finally {\n session.dispose();\n }\n }\n}\n\nfunction modelSchemaVersionFor(modality: \"spreadsheet\" | \"document\" | \"presentation\"): 1 | 2 {\n if (modality === \"spreadsheet\") return SPREADSHEET_ARTIFACT_MODEL_SCHEMA_VERSION;\n return modality === \"document\"\n ? DOCUMENT_ARTIFACT_MODEL_SCHEMA_VERSION\n : PRESENTATION_ARTIFACT_MODEL_SCHEMA_VERSION;\n}\n\nfunction assertRuntime(\n candidate: unknown,\n location: ConfiguredArtifactRuntimeLocation,\n): asserts candidate is ArtifactKernelRuntime {\n if (typeof candidate !== \"object\" || candidate === null) {\n throw new Error(\"Verified artifact facade returned no runtime\");\n }\n const runtime = candidate as Partial<ArtifactKernelRuntime>;\n if (\n runtime.kind !== \"native\" ||\n runtime.target === \"wasm-web\" ||\n runtime.target !== location.target ||\n runtime.buildIdentity !== location.kernel.buildIdentity ||\n typeof runtime.createCollaborationSession !== \"function\" ||\n typeof runtime.openCollaborationSession !== \"function\" ||\n typeof runtime.createDocumentSession !== \"function\" ||\n typeof runtime.openDocumentSession !== \"function\" ||\n typeof runtime.createPresentationSession !== \"function\" ||\n typeof runtime.openPresentationSession !== \"function\"\n ) {\n throw new Error(\"Verified artifact facade returned an incompatible runtime\");\n }\n}\n\nfunction verifySnapshotBoundary(\n session: NativeArtifactSession,\n state: EditableArtifactKernelState,\n): void {\n const snapshot = state.snapshot;\n if (!snapshot || session.modality !== state.modality)\n throw new Error(\"Snapshot modality mismatch\");\n if (session.stateHash() !== snapshot.stateHash) {\n throw new Error(\"Native snapshot boundary does not match durable metadata\");\n }\n if (state.modality === \"spreadsheet\") {\n if (\n session.modality !== \"spreadsheet\" ||\n snapshot.modality !== \"spreadsheet\" ||\n !causalFrontiersEqual(domainFrontier(session.frontier()), snapshot.coveredCausalFrontier)\n ) {\n throw new Error(\"Native snapshot frontier does not match durable metadata\");\n }\n } else if (\n session.modality === \"spreadsheet\" ||\n snapshot.modality === \"spreadsheet\" ||\n safeRevision(session.revision()) !== snapshot.nativeRevision ||\n state.baseNativeRevision !== snapshot.nativeRevision\n ) {\n throw new Error(\"Native snapshot revision does not match durable metadata\");\n }\n}\n\nfunction replayKernelTail(\n session: NativeArtifactSession,\n state: EditableArtifactKernelState,\n): void {\n if (state.modality === \"spreadsheet\") {\n if (session.modality !== \"spreadsheet\") throw new Error(\"Native modality mismatch\");\n for (const transaction of state.committedTransactionTail) {\n const priorNativeRevision = safeRevision(session.revision());\n if (session.stateHash() !== transaction.priorStateHash) {\n throw new Error(\"Spreadsheet replay prior state mismatch\");\n }\n session.applyCommitted(transaction.committedTransactionBytes);\n if (\n safeRevision(session.revision()) !== priorNativeRevision + 1 ||\n session.stateHash() !== transaction.stateHash ||\n !causalFrontiersEqual(\n domainFrontier(session.frontier()),\n transaction.resultingCausalFrontier,\n )\n ) {\n throw new Error(\"Spreadsheet replay result mismatch\");\n }\n }\n return;\n }\n if (session.modality !== state.modality) {\n throw new Error(\"Native modality mismatch\");\n }\n for (const transaction of state.committedTransactionTail) {\n if (\n session.stateHash() !== transaction.priorStateHash ||\n safeRevision(session.revision()) !== transaction.priorNativeRevision\n ) {\n throw new Error(\"Serialized replay prior state mismatch\");\n }\n const commit = decodeEditableArtifactSerializedCommit(\n transaction.committedTransactionBytes,\n state.modality,\n );\n const intent = decodeEditableArtifactMutationIntent(commit.intentBytes);\n const receipt = session.applyCommands(intent.commandBytes);\n if (\n !equalBytes(receipt, commit.nativeReceiptBytes) ||\n !equalBytes(receipt, transaction.nativeReceiptBytes) ||\n safeRevision(session.revision()) !== transaction.nativeRevision ||\n session.stateHash() !== transaction.stateHash\n ) {\n throw new Error(\"Serialized replay result mismatch\");\n }\n }\n}\n\nfunction verifyDurableHead(\n session: NativeArtifactSession,\n state: EditableArtifactKernelState,\n): void {\n const snapshot = state.snapshot;\n if (!snapshot) throw new Error(\"Editable artifact has no replay snapshot\");\n let durableSequence = snapshot.coveredHeadSequence;\n for (const transaction of state.committedTransactionTail) {\n if (transaction.sequenceStart !== durableSequence + 1) {\n throw new Error(\"Durable transaction tail contains a sequence gap\");\n }\n durableSequence = transaction.sequenceEnd;\n }\n if (\n session.modality !== state.modality ||\n durableSequence !== state.artifact.headSequence ||\n session.stateHash() !== state.artifact.stateHash\n ) {\n throw new Error(\"Reconstructed native state does not match the durable head\");\n }\n if (\n state.modality === \"spreadsheet\" &&\n (session.modality !== \"spreadsheet\" ||\n !causalFrontiersEqual(domainFrontier(session.frontier()), state.artifact.causalFrontier))\n ) {\n throw new Error(\"Reconstructed native frontier does not match the durable head\");\n }\n if (state.modality !== \"spreadsheet\") {\n const expectedNativeRevision =\n state.committedTransactionTail.at(-1)?.nativeRevision ?? state.baseNativeRevision;\n if (safeRevision(session.revision()) !== expectedNativeRevision) {\n throw new Error(\"Reconstructed native revision does not match the serialized tail\");\n }\n }\n}\n\nasync function replaySpreadsheetPlan(\n session: NativeSpreadsheetSession,\n plan: Extract<EditableArtifactSnapshotReplayPlan, { modality: \"spreadsheet\" }>,\n signal: AbortSignal | undefined,\n): Promise<\n Readonly<{\n headSequence: number;\n causalFrontier: ReturnType<typeof editableArtifactCausalFrontier>;\n stateHash: ReturnType<typeof editableArtifactStateHash>;\n }>\n> {\n let sequence = plan.baseHeadSequence;\n for await (const segment of plan.segments) {\n throwIfAborted(signal);\n if (segment.sequenceStart !== sequence + 1) throw new Error(\"Replay sequence gap\");\n if (segment.modality !== \"spreadsheet\") throw new Error(\"Replay segment modality mismatch\");\n session.applyCommitted(segment.bytes);\n sequence = segment.sequenceEnd;\n }\n if (sequence !== plan.targetHeadSequence || session.stateHash() !== plan.targetStateHash) {\n throw new Error(\"Replay target mismatch\");\n }\n const causalFrontier = domainFrontier(session.frontier());\n if (!causalFrontiersEqual(causalFrontier, plan.targetCausalFrontier)) {\n throw new Error(\"Replay frontier mismatch\");\n }\n return Object.freeze({\n headSequence: sequence,\n causalFrontier,\n stateHash: editableArtifactStateHash(session.stateHash()),\n });\n}\n\nasync function replaySerializedPlan(\n session: Exclude<NativeArtifactSession, NativeSpreadsheetSession>,\n plan: Exclude<EditableArtifactSnapshotReplayPlan, { modality: \"spreadsheet\" }>,\n signal: AbortSignal | undefined,\n): Promise<\n Readonly<{\n headSequence: number;\n nativeRevision: number;\n stateHash: ReturnType<typeof editableArtifactStateHash>;\n }>\n> {\n if (session.modality !== plan.modality) throw new Error(\"Replay modality mismatch\");\n let sequence = plan.baseHeadSequence;\n for await (const segment of plan.segments) {\n throwIfAborted(signal);\n if (segment.sequenceStart !== sequence + 1 || segment.modality !== session.modality) {\n throw new Error(\"Replay sequence or modality mismatch\");\n }\n const commit = decodeEditableArtifactSerializedCommit(segment.bytes, session.modality);\n const intent = decodeEditableArtifactMutationIntent(commit.intentBytes);\n const receipt = session.applyCommands(intent.commandBytes);\n if (!equalBytes(receipt, commit.nativeReceiptBytes)) throw new Error(\"Replay receipt mismatch\");\n sequence = segment.sequenceEnd;\n }\n if (sequence !== plan.targetHeadSequence || session.stateHash() !== plan.targetStateHash) {\n throw new Error(\"Replay target mismatch\");\n }\n if (safeRevision(session.revision()) !== plan.targetNativeRevision) {\n throw new Error(\"Replay native revision mismatch\");\n }\n return Object.freeze({\n headSequence: sequence,\n nativeRevision: plan.targetNativeRevision,\n stateHash: editableArtifactStateHash(session.stateHash()),\n });\n}\n\nfunction domainFrontier(bytes: Uint8Array): ReturnType<typeof editableArtifactCausalFrontier> {\n return editableArtifactCausalFrontier(\n decodeEditableArtifactCausalFrontier(bytes).map((entry) => ({\n replicaId: editableArtifactReplicaId(entry.replicaId),\n counter: entry.counter,\n })),\n );\n}\n\nasync function readVerifiedSnapshot(\n objects: BoundedObjectReadPort,\n snapshot: NonNullable<EditableArtifactKernelState[\"snapshot\"]>,\n signal?: AbortSignal,\n): Promise<Uint8Array> {\n const object = await objects.open({\n opaqueReference: snapshot.blobReference,\n maxBytes: MAX_EDITABLE_ARTIFACT_SNAPSHOT_BYTES,\n expectedByteSize: snapshot.byteSize,\n ...(signal ? { signal } : {}),\n });\n try {\n if (object.contentType !== undefined && object.contentType !== snapshot.mimeType) {\n throw new Error(\"Snapshot content type mismatch\");\n }\n const bytes = await collectExact(\n object.chunks(signal ? { signal } : {}),\n snapshot.byteSize,\n signal,\n );\n const contentHash = `sha256:${createHash(\"sha256\").update(bytes).digest(\"hex\")}`;\n if (contentHash !== snapshot.contentHash) throw new Error(\"Snapshot content hash mismatch\");\n await object.assertUnchanged(signal);\n return bytes;\n } finally {\n await object.close();\n }\n}\n\nasync function collectExact(\n chunks: AsyncIterable<Uint8Array>,\n expectedBytes: number,\n signal?: AbortSignal,\n): Promise<Uint8Array> {\n if (!Number.isSafeInteger(expectedBytes) || expectedBytes <= 0) {\n throw new Error(\"Snapshot byte size is invalid\");\n }\n const result = new Uint8Array(expectedBytes);\n let offset = 0;\n for await (const chunk of chunks) {\n throwIfAborted(signal);\n if (!(chunk instanceof Uint8Array) || chunk.byteLength === 0) {\n throw new Error(\"Snapshot stream is truncated\");\n }\n if (offset + chunk.byteLength > result.byteLength) {\n throw new Error(\"Snapshot stream exceeds its declared size\");\n }\n result.set(chunk, offset);\n offset += chunk.byteLength;\n }\n throwIfAborted(signal);\n if (offset !== result.byteLength) throw new Error(\"Snapshot stream is truncated\");\n return result;\n}\n\nasync function* fixedChunks(bytes: Uint8Array, signal?: AbortSignal): AsyncIterable<Uint8Array> {\n for (let offset = 0; offset < bytes.byteLength; offset += SNAPSHOT_CHUNK_BYTES) {\n throwIfAborted(signal);\n yield bytes.subarray(offset, Math.min(bytes.byteLength, offset + SNAPSHOT_CHUNK_BYTES));\n }\n}\n\nfunction namespaceForArtifact(artifactId: string): bigint {\n const digest = createHash(\"sha256\").update(artifactId).digest();\n let value = 0n;\n for (let index = 0; index < 8; index += 1) value = (value << 8n) | BigInt(digest[index]!);\n return value === 0n ? 1n : value;\n}\n\nfunction safeRevision(value: bigint): number {\n if (value < 0n || value > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new Error(\"Native revision exceeds the safe integer range\");\n }\n return Number(value);\n}\n\nfunction equalBytes(left: Uint8Array, right: Uint8Array): boolean {\n if (left.byteLength !== right.byteLength) return false;\n let difference = 0;\n for (let index = 0; index < left.byteLength; index += 1) {\n difference |= left[index]! ^ right[index]!;\n }\n return difference === 0;\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) throw new Error(\"Editable artifact native operation was cancelled\");\n}\n","import { createHash } from \"node:crypto\";\nimport {\n ArtifactOfficeSourceUnsupportedError,\n prepareArtifactOfficeImport,\n type ArtifactOfficeMimeType,\n} from \"@opengeni/artifact-tool/office-import\";\nimport {\n MAX_EDITABLE_ARTIFACT_SNAPSHOT_BYTES,\n EDITABLE_ARTIFACT_ORIGINAL_IMPORT_MAX_BYTES,\n editableArtifactCausalFrontier,\n editableArtifactContentHash,\n editableArtifactReplicaId,\n editableArtifactStateHash,\n EditableArtifactOfficeImportError,\n type EditableArtifactActor,\n type EditableArtifactOfficeImportPort,\n type EditableArtifactModality,\n type EditableArtifactScope,\n} from \"@opengeni/core/editable-artifacts\";\nimport { requireLiveAgentAttemptAuthorization } from \"@opengeni/core\";\nimport { getFilesForSubject } from \"@opengeni/db\";\nimport {\n MAX_BOUNDED_OBJECT_CHUNK_BYTES,\n type BoundedImmutableObjectWritePort,\n retryWhileMissing,\n type ObjectStorage,\n} from \"@opengeni/storage\";\nimport type { Database } from \"@opengeni/db\";\nimport type { VerifiedNativeArtifactRuntimeBinding } from \"./editable-artifact-native-kernel\";\n\nconst SNAPSHOT_MIME = \"application/vnd.opengeni.editable-artifact-snapshot\" as const;\n\nexport type EditableArtifactOfficeImportAdapterDependencies = Readonly<{\n db: Database;\n objectStorage: ObjectStorage;\n runtime: VerifiedNativeArtifactRuntimeBinding;\n sourceObjects: BoundedImmutableObjectWritePort;\n snapshotObjects: BoundedImmutableObjectWritePort;\n readFiles?: typeof getFilesForSubject;\n resolveFileAuthoritySubjectId?: typeof editableArtifactFileAuthoritySubjectId;\n prepareOffice?: typeof prepareArtifactOfficeImport;\n}>;\n\n/** Trusted import boundary from one ready workspace file into native sequence-zero state. */\nexport class EditableArtifactOfficeImportAdapter implements EditableArtifactOfficeImportPort {\n private readonly readFiles: typeof getFilesForSubject;\n private readonly resolveFileAuthoritySubjectId: typeof editableArtifactFileAuthoritySubjectId;\n\n constructor(private readonly dependencies: EditableArtifactOfficeImportAdapterDependencies) {\n this.readFiles = dependencies.readFiles ?? getFilesForSubject;\n this.resolveFileAuthoritySubjectId =\n dependencies.resolveFileAuthoritySubjectId ?? editableArtifactFileAuthoritySubjectId;\n }\n\n async prepare(\n input: Parameters<EditableArtifactOfficeImportPort[\"prepare\"]>[0],\n ): ReturnType<EditableArtifactOfficeImportPort[\"prepare\"]> {\n throwIfAborted(input.signal);\n const subjectId = await this.resolveFileAuthoritySubjectId(\n this.dependencies.db,\n input.scope,\n input.actor,\n );\n const [file] = await this.readFiles(this.dependencies.db, {\n accountId: input.scope.accountId,\n workspaceId: input.scope.workspaceId,\n subjectId,\n fileIds: [input.fileId],\n });\n if (!file || file.status !== \"ready\") {\n throw new EditableArtifactOfficeImportError(\"invalid_source\");\n }\n const expectedMimeType = officeMimeType(input.modality);\n if (\n file.contentType !== expectedMimeType ||\n !officeFilenameMatches(file.filename, input.modality) ||\n !Number.isSafeInteger(file.sizeBytes) ||\n file.sizeBytes < 1 ||\n file.sizeBytes > EDITABLE_ARTIFACT_ORIGINAL_IMPORT_MAX_BYTES ||\n typeof file.sha256 !== \"string\" ||\n !/^[0-9a-f]{64}$/u.test(file.sha256)\n ) {\n throw new EditableArtifactOfficeImportError(\"invalid_source\");\n }\n const sourceBytes = await readVerifiedWorkspaceFile(\n this.dependencies.objectStorage,\n file,\n input.signal,\n );\n const prepared = await prepareOfficeImport({\n runtime: this.dependencies.runtime,\n modality: input.modality,\n filename: file.filename,\n mimeType: expectedMimeType,\n bytes: sourceBytes,\n prepare: this.dependencies.prepareOffice ?? prepareArtifactOfficeImport,\n });\n const retainedSource = await this.dependencies.sourceObjects.write({\n chunks: byteChunks(sourceBytes),\n contentType: expectedMimeType,\n maxBytes: EDITABLE_ARTIFACT_ORIGINAL_IMPORT_MAX_BYTES,\n expectedByteSize: prepared.source.byteSize,\n expectedContentHash: prepared.source.contentHash,\n ...(input.signal ? { signal: input.signal } : {}),\n });\n const retainedSnapshot = await this.dependencies.snapshotObjects.write({\n chunks: byteChunks(prepared.snapshot.bytes),\n contentType: SNAPSHOT_MIME,\n maxBytes: MAX_EDITABLE_ARTIFACT_SNAPSHOT_BYTES,\n expectedByteSize: prepared.snapshot.byteSize,\n expectedContentHash: prepared.snapshot.contentHash,\n ...(input.signal ? { signal: input.signal } : {}),\n });\n const common = {\n modality: prepared.snapshot.modality,\n blobReference: retainedSnapshot.opaqueReference,\n byteSize: prepared.snapshot.byteSize,\n contentHash: editableArtifactContentHash(prepared.snapshot.contentHash),\n mimeType: SNAPSHOT_MIME,\n coveredHeadSequence: 0 as const,\n stateHash: editableArtifactStateHash(prepared.snapshot.stateHash),\n modelSchemaVersion: prepared.snapshot.modelSchemaVersion,\n kernelVersion: prepared.snapshot.kernelVersion,\n };\n return Object.freeze({\n originalImport: Object.freeze({\n fileId: file.id,\n blobReference: retainedSource.opaqueReference,\n byteSize: prepared.source.byteSize,\n contentHash: editableArtifactContentHash(prepared.source.contentHash),\n mimeType: expectedMimeType,\n }),\n snapshot:\n prepared.snapshot.modality === \"spreadsheet\"\n ? Object.freeze({\n ...common,\n modality: \"spreadsheet\" as const,\n coveredCausalFrontier: editableArtifactCausalFrontier(\n prepared.snapshot.coveredCausalFrontier.map((entry) => ({\n replicaId: editableArtifactReplicaId(entry.replicaId),\n counter: entry.counter,\n })),\n ),\n operationProtocolVersion: prepared.snapshot.operationProtocolVersion,\n crdtStateVersion: prepared.snapshot.crdtStateVersion,\n })\n : Object.freeze({\n ...common,\n modality: prepared.snapshot.modality,\n nativeRevision: prepared.snapshot.nativeRevision,\n }),\n });\n }\n}\n\nasync function prepareOfficeImport(input: {\n runtime: VerifiedNativeArtifactRuntimeBinding;\n modality: EditableArtifactModality;\n filename: string;\n mimeType: ArtifactOfficeMimeType;\n bytes: Uint8Array;\n prepare: typeof prepareArtifactOfficeImport;\n}) {\n try {\n return await input.prepare({\n facade: input.runtime.facade,\n modality: input.modality,\n filename: input.filename,\n mimeType: input.mimeType,\n bytes: input.bytes,\n expectedRuntimeTarget: input.runtime.location.target,\n expectedKernelVersion: input.runtime.runtime.buildIdentity,\n });\n } catch (error) {\n if (error instanceof ArtifactOfficeSourceUnsupportedError) {\n throw new EditableArtifactOfficeImportError(\"unsupported_content\");\n }\n throw error;\n }\n}\n\nfunction officeMimeType(modality: EditableArtifactModality): ArtifactOfficeMimeType {\n if (modality === \"spreadsheet\") {\n return \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\";\n }\n if (modality === \"document\") {\n return \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\";\n }\n return \"application/vnd.openxmlformats-officedocument.presentationml.presentation\";\n}\n\nfunction officeFilenameMatches(filename: string, modality: EditableArtifactModality): boolean {\n const extension =\n modality === \"spreadsheet\" ? \".xlsx\" : modality === \"document\" ? \".docx\" : \".pptx\";\n return filename.toLowerCase().endsWith(extension);\n}\n\nasync function readVerifiedWorkspaceFile(\n storage: ObjectStorage,\n file: NonNullable<Awaited<ReturnType<typeof getFilesForSubject>>>[number],\n signal?: AbortSignal,\n): Promise<Uint8Array> {\n throwIfAborted(signal);\n const before = await retryWhileMissing(async () => {\n try {\n return await storage.headFile(file);\n } catch (error) {\n if (typeof storage.fileExists === \"function\" && !(await storage.fileExists(file))) {\n return null;\n }\n throw error;\n }\n });\n if (!before) {\n throw new EditableArtifactOfficeImportError(\"source_changed\");\n }\n if (\n before.ContentLength !== file.sizeBytes ||\n before.ContentType !== file.contentType ||\n before.Metadata?.sha256 !== file.sha256 ||\n typeof before.VersionToken !== \"string\" ||\n before.VersionToken.length < 1\n ) {\n throw new EditableArtifactOfficeImportError(\"source_changed\");\n }\n const bytes = new Uint8Array(file.sizeBytes);\n const digest = createHash(\"sha256\");\n for (let start = 0; start < file.sizeBytes; start += MAX_BOUNDED_OBJECT_CHUNK_BYTES) {\n throwIfAborted(signal);\n const end = Math.min(file.sizeBytes, start + MAX_BOUNDED_OBJECT_CHUNK_BYTES) - 1;\n const chunk = await retryWhileMissing(async () => storage.getFileRange(file, { start, end }));\n if (!chunk || chunk.byteLength !== end - start + 1) {\n throw new EditableArtifactOfficeImportError(\"source_changed\");\n }\n bytes.set(chunk, start);\n digest.update(chunk);\n }\n const after = await retryWhileMissing(async () => {\n try {\n return await storage.headFile(file);\n } catch (error) {\n if (typeof storage.fileExists === \"function\" && !(await storage.fileExists(file))) {\n return null;\n }\n throw error;\n }\n });\n if (!after) {\n throw new EditableArtifactOfficeImportError(\"source_changed\");\n }\n const sha256 = digest.digest(\"hex\");\n if (\n after.ContentLength !== before.ContentLength ||\n after.ContentType !== before.ContentType ||\n after.Metadata?.sha256 !== before.Metadata?.sha256 ||\n after.VersionToken !== before.VersionToken ||\n sha256 !== file.sha256\n ) {\n throw new EditableArtifactOfficeImportError(\"source_changed\");\n }\n return bytes;\n}\n\nexport async function editableArtifactFileAuthoritySubjectId(\n db: Database,\n scope: EditableArtifactScope,\n actor: EditableArtifactActor,\n): Promise<string | null> {\n if (actor.kind !== \"agent\") return actor.subjectId;\n const authorization = await requireLiveAgentAttemptAuthorization(\n db,\n {\n accountId: scope.accountId,\n workspaceId: scope.workspaceId,\n subjectId: actor.subjectId,\n permissions: [],\n principalKind: \"agent_attempt\",\n metadata: {\n sessionId: actor.sessionId,\n turnId: actor.turnId,\n attemptId: actor.attemptId,\n executionGeneration: actor.generation,\n },\n },\n actor.sessionId,\n );\n return authorization.initiatingHumanSubjectId;\n}\n\nasync function* byteChunks(bytes: Uint8Array): AsyncIterable<Uint8Array> {\n for (let offset = 0; offset < bytes.byteLength; offset += MAX_BOUNDED_OBJECT_CHUNK_BYTES) {\n yield bytes.subarray(offset, offset + MAX_BOUNDED_OBJECT_CHUNK_BYTES);\n }\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) throw signal.reason ?? new Error(\"Artifact import aborted\");\n}\n","import { createHash } from \"node:crypto\";\n\nimport {\n type EditableArtifactAgentWorkspaceFilePort,\n type EditableArtifactDurableExportService,\n} from \"@opengeni/core/editable-artifacts\";\nimport { completeFileUpload, prepareGeneratedWorkspaceFile, type Database } from \"@opengeni/db\";\nimport { retryWhileMissing, type ObjectHead, type ObjectStorage } from \"@opengeni/storage\";\n\nconst UPLOAD_INTENT_TTL_MS = 60 * 60_000;\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;\n\nexport type EditableArtifactWorkspaceFileAdapterDependencies = Readonly<{\n db: Database;\n objectStorage: ObjectStorage;\n durableExports: EditableArtifactDurableExportService;\n now?: () => Date;\n prepareFile?: typeof prepareGeneratedWorkspaceFile;\n completeFile?: typeof completeFileUpload;\n}>;\n\n/**\n * Promotes one immutable materialization into the normal workspace-file domain.\n * The returned file ID is the only artifact export handle exposed to agents.\n */\nexport class EditableArtifactWorkspaceFileAdapter implements EditableArtifactAgentWorkspaceFilePort {\n private readonly now: () => Date;\n private readonly prepareFile: typeof prepareGeneratedWorkspaceFile;\n private readonly completeFile: typeof completeFileUpload;\n\n constructor(private readonly dependencies: EditableArtifactWorkspaceFileAdapterDependencies) {\n this.now = dependencies.now ?? (() => new Date());\n this.prepareFile = dependencies.prepareFile ?? prepareGeneratedWorkspaceFile;\n this.completeFile = dependencies.completeFile ?? completeFileUpload;\n }\n\n async ensureMaterializationFile(\n input: Parameters<EditableArtifactAgentWorkspaceFilePort[\"ensureMaterializationFile\"]>[0],\n ): ReturnType<EditableArtifactAgentWorkspaceFilePort[\"ensureMaterializationFile\"]> {\n throwIfAborted(input.signal);\n const storage = this.dependencies.objectStorage;\n if (!storage.headObject || !storage.putObjectStreamIfAbsent) {\n throw new Error(\"Object storage lacks immutable streaming upload support\");\n }\n const download = await this.dependencies.durableExports.openMaterializationDownload({\n scope: input.scope,\n actor: input.actor,\n artifactId: input.artifact.id,\n jobId: input.jobId,\n ...(input.signal ? { signal: input.signal } : {}),\n });\n try {\n const sha256 = plainSha256(download.contentHash);\n const filename = exportFilename(input.filename, download.format);\n const fileId = deterministicUuid(\n `editable-artifact-export:file:${input.scope.workspaceId}:${input.artifact.id}:${input.versionId}:${input.jobId}`,\n );\n const uploadId = deterministicUuid(\n `editable-artifact-export:upload:${input.scope.workspaceId}:${input.artifact.id}:${input.versionId}:${input.jobId}`,\n );\n const safeFilename = `artifact-${input.artifact.id}-${input.jobId}.${download.format}`;\n const objectKey = `workspaces/${input.scope.workspaceId}/files/${fileId}/artifact-exports/${safeFilename}`;\n const prepared = await this.prepareFile(this.dependencies.db, {\n accountId: input.scope.accountId,\n workspaceId: input.scope.workspaceId,\n fileId,\n uploadId,\n filename,\n safeFilename,\n contentType: download.mimeType,\n sizeBytes: download.byteSize,\n sha256,\n bucket: storage.bucket,\n objectKey,\n expiresAt: new Date(this.now().getTime() + UPLOAD_INTENT_TTL_MS),\n });\n\n let file = prepared.file;\n if (file.status !== \"ready\") {\n const existing = await storage.headObject(objectKey);\n if (existing) {\n assertStoredExport(existing, download.byteSize, download.mimeType, sha256);\n } else {\n const created = await storage.putObjectStreamIfAbsent({\n key: objectKey,\n contentType: download.mimeType,\n chunks: download.chunks(input.signal ? { signal: input.signal } : {}),\n byteSize: download.byteSize,\n sha256,\n ...(input.signal ? { signal: input.signal } : {}),\n });\n if (!created) {\n await assertVisibleExport(\n storage,\n objectKey,\n download.byteSize,\n download.mimeType,\n sha256,\n input.signal,\n );\n }\n }\n await download.assertUnchanged(input.signal);\n throwIfAborted(input.signal);\n file = await this.completeFile(this.dependencies.db, input.scope.workspaceId, uploadId);\n } else {\n await assertVisibleExport(\n storage,\n objectKey,\n download.byteSize,\n download.mimeType,\n sha256,\n input.signal,\n );\n await download.assertUnchanged(input.signal);\n }\n if (\n file.id !== fileId ||\n file.status !== \"ready\" ||\n file.filename !== filename ||\n file.contentType !== download.mimeType ||\n file.sizeBytes !== download.byteSize ||\n file.sha256 !== sha256\n ) {\n throw new Error(\"Generated workspace file differs from its immutable export\");\n }\n\n return Object.freeze({\n fileId: file.id,\n filename: file.filename,\n contentType: file.contentType,\n sizeBytes: file.sizeBytes,\n sha256,\n artifactId: input.artifact.id,\n versionId: input.versionId,\n materializationJobId: input.jobId,\n sourceHeadSequence: input.sourceHeadSequence,\n sourceStateHash: input.sourceStateHash,\n });\n } finally {\n await download.close();\n }\n }\n}\n\nasync function assertVisibleExport(\n storage: ObjectStorage,\n objectKey: string,\n byteSize: number,\n contentType: string,\n sha256: string,\n signal?: AbortSignal,\n): Promise<void> {\n const head = await retryWhileMissing(\n async () => await storage.headObject!(objectKey),\n signal ? { signal } : {},\n );\n assertStoredExport(head, byteSize, contentType, sha256);\n}\n\nfunction assertStoredExport(\n head: ObjectHead | null,\n byteSize: number,\n contentType: string,\n sha256: string,\n): void {\n if (\n !head ||\n head.ContentLength !== byteSize ||\n head.ContentType !== contentType ||\n head.Metadata?.sha256 !== sha256 ||\n typeof head.VersionToken !== \"string\" ||\n head.VersionToken.length < 1\n ) {\n throw new Error(\"Workspace export object differs from its durable materialization\");\n }\n}\n\nfunction exportFilename(value: string, format: string): string {\n const expectedExtension = `.${format}`;\n const normalized = value\n .normalize(\"NFKC\")\n .replace(/[\\\\/:*?\"<>|\\u0000-\\u001f\\u007f]+/gu, \"-\")\n .replace(/\\s+/gu, \" \")\n .trim()\n .slice(0, 200);\n const stem = normalized.toLowerCase().endsWith(expectedExtension)\n ? normalized.slice(0, -expectedExtension.length)\n : normalized;\n return `${stem.replace(/[. ]+$/u, \"\").slice(0, 190) || \"artifact\"}${expectedExtension}`;\n}\n\nfunction plainSha256(value: string): string {\n const match = /^sha256:([0-9a-f]{64})$/u.exec(value);\n if (!match) throw new Error(\"Materialized artifact content hash is invalid\");\n return match[1]!;\n}\n\nfunction deterministicUuid(seed: string): string {\n const bytes = createHash(\"sha256\").update(seed, \"utf8\").digest().subarray(0, 16);\n bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x50;\n bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;\n const hex = bytes.toString(\"hex\");\n const value = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n if (!UUID_PATTERN.test(value)) throw new Error(\"Generated workspace file identity is invalid\");\n return value;\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) throw signal.reason ?? new Error(\"Artifact export aborted\");\n}\n","import { randomUUID } from \"node:crypto\";\nimport { isDatabaseConnectionLoss } from \"@opengeni/db\";\nimport type { Attributes, Observability, Span } from \"@opengeni/observability\";\n\nexport type ApiFatalEvent = \"startup_failure\" | \"unhandled_rejection\" | \"uncaught_exception\";\nexport type ApiFatalPhase = \"startup\" | \"running\";\nexport type ApiFatalReasonKind =\n | \"bigint\"\n | \"boolean\"\n | \"error\"\n | \"function\"\n | \"null\"\n | \"number\"\n | \"object\"\n | \"string\"\n | \"symbol\"\n | \"undefined\";\n\ntype ApiFatalObservability = Pick<Observability, \"error\" | \"flush\" | \"startSpan\"> &\n Partial<Pick<Observability, \"recordFailureDiagnostic\" | \"warn\" | \"incrementCounter\">>;\n\ntype ApiFatalProcess = {\n on: (\n event: \"unhandledRejection\" | \"uncaughtException\",\n listener: (reason: unknown) => void,\n ) => void;\n off: (\n event: \"unhandledRejection\" | \"uncaughtException\",\n listener: (reason: unknown) => void,\n ) => void;\n exit: (code: number) => void;\n};\n\nexport type ApiFatalProcessBoundaryOptions = {\n process?: ApiFatalProcess;\n observability?: ApiFatalObservability;\n flushTimeoutMs?: number;\n correlationId?: () => string;\n fallbackLog?: (message: string) => void;\n /**\n * Classifies an unhandled rejection that leaves no process state behind and\n * is therefore survivable once the API is serving. Defaults to a lost\n * database connection (deploy drain, failover, restart): the rejected query\n * held only a pooled connection the driver has already discarded, and every\n * durable loop retries its claim on the next tick.\n */\n isRecoverableRejection?: (reason: unknown) => boolean;\n};\n\nexport type ApiFatalProcessBoundary = {\n attachObservability: (observability: ApiFatalObservability) => void;\n markRunning: () => void;\n reportStartupFailure: (reason: unknown) => Promise<void>;\n dispose: () => void;\n};\n\nconst API_FATAL_FLUSH_TIMEOUT_MS = 1_000;\nconst API_FATAL_CORRELATION_ID_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;\n\nconst FATAL_ERROR_CODES = {\n startup_failure: \"api_startup_failed\",\n unhandled_rejection: \"api_unhandled_rejection\",\n uncaught_exception: \"api_uncaught_exception\",\n} as const;\n\nexport function installApiFatalProcessBoundary(\n options: ApiFatalProcessBoundaryOptions = {},\n): ApiFatalProcessBoundary {\n const runtimeProcess = options.process ?? defaultProcessBoundary();\n const flushTimeoutMs = options.flushTimeoutMs ?? API_FATAL_FLUSH_TIMEOUT_MS;\n const correlationId = options.correlationId ?? (() => `api-fatal.${randomUUID()}`);\n const fallbackLog = options.fallbackLog ?? ((message: string) => console.error(message));\n const isRecoverableRejection = options.isRecoverableRejection ?? isDatabaseConnectionLoss;\n let observability = options.observability;\n let phase: ApiFatalPhase = \"startup\";\n let reporting = false;\n\n const recover = (reason: unknown): boolean => {\n if (phase !== \"running\" || reporting) return false;\n let recoverable = false;\n try {\n recoverable = isRecoverableRejection(reason);\n } catch {\n return false;\n }\n if (!recoverable) return false;\n const attributes = {\n errorClass: \"ApiRecoveredRejection\",\n errorCode: \"api_unhandled_database_connection_loss\",\n origin: \"api\",\n reasonKind: apiFatalReasonKind(reason),\n };\n try {\n if (observability?.warn) {\n observability.warn(\n \"Opengeni API recovered an unhandled database connection loss\",\n attributes,\n );\n } else {\n safeFallbackLog(\n fallbackLog,\n \"Opengeni API recovered an unhandled database connection loss (api_unhandled_database_connection_loss)\",\n );\n }\n observability?.incrementCounter?.({\n name: \"opengeni_api_recovered_rejections_total\",\n help: \"Unhandled rejections the API survived because they only reported a lost database connection.\",\n labels: { code: \"api_unhandled_database_connection_loss\" },\n });\n } catch {\n // Recovery never depends on the observer.\n }\n return true;\n };\n\n const report = async (event: ApiFatalEvent, reason: unknown): Promise<void> => {\n if (reporting) return;\n reporting = true;\n\n const diagnostic = apiFatalDiagnostic(event, phase, reason, correlationId);\n let message = apiFatalMessage(diagnostic);\n const activeObservability = observability;\n try {\n if (activeObservability) {\n try {\n const diagnosticId = activeObservability.recordFailureDiagnostic?.({\n code: FATAL_ERROR_CODES[event],\n stage: phase,\n retryDecision: \"not_retryable\",\n error: reason,\n });\n if (diagnosticId) {\n diagnostic.correlationId = diagnosticId;\n message = apiFatalMessage(diagnostic);\n }\n } catch {\n // Never replace the required fatal exit with an observer failure.\n }\n let logged = false;\n try {\n activeObservability.error(message, diagnostic);\n logged = true;\n } catch {\n // The fatal boundary must still report and terminate if logging is unhealthy.\n }\n if (!logged) {\n safeFallbackLog(fallbackLog, message);\n }\n try {\n const span: Span = activeObservability.startSpan(\"api.process.fatal\", diagnostic);\n span.end({ error: true });\n } catch {\n // The synchronous log remains authoritative when span creation fails.\n }\n await flushWithin(activeObservability, flushTimeoutMs);\n } else {\n safeFallbackLog(fallbackLog, message);\n }\n } finally {\n runtimeProcess.exit(1);\n }\n };\n\n const onUnhandledRejection = (reason: unknown): void => {\n if (recover(reason)) return;\n void report(\"unhandled_rejection\", reason);\n };\n const onUncaughtException = (reason: unknown): void => {\n void report(\"uncaught_exception\", reason);\n };\n runtimeProcess.on(\"unhandledRejection\", onUnhandledRejection);\n runtimeProcess.on(\"uncaughtException\", onUncaughtException);\n\n return {\n attachObservability: (value) => {\n observability = value;\n },\n markRunning: () => {\n phase = \"running\";\n },\n reportStartupFailure: async (reason) => {\n await report(\"startup_failure\", reason);\n },\n dispose: () => {\n runtimeProcess.off(\"unhandledRejection\", onUnhandledRejection);\n runtimeProcess.off(\"uncaughtException\", onUncaughtException);\n },\n };\n}\n\nfunction apiFatalDiagnostic(\n event: ApiFatalEvent,\n phase: ApiFatalPhase,\n reason: unknown,\n correlationId: () => string,\n): Attributes & {\n errorClass: \"ApiFatalOperationError\";\n errorCode: (typeof FATAL_ERROR_CODES)[ApiFatalEvent];\n origin: \"api\";\n phase: ApiFatalPhase;\n reasonKind: ApiFatalReasonKind;\n correlationId: string;\n} {\n let safeCorrelationId = \"api-fatal.fallback\";\n try {\n const candidate = correlationId();\n if (API_FATAL_CORRELATION_ID_PATTERN.test(candidate)) {\n safeCorrelationId = candidate;\n }\n } catch {\n // A fixed valid fallback preserves the fatal report and nonzero exit.\n }\n return {\n errorClass: \"ApiFatalOperationError\",\n errorCode: FATAL_ERROR_CODES[event],\n origin: \"api\",\n phase,\n reasonKind: apiFatalReasonKind(reason),\n correlationId: safeCorrelationId,\n };\n}\n\nfunction apiFatalReasonKind(reason: unknown): ApiFatalReasonKind {\n if (reason === null) return \"null\";\n const kind = typeof reason;\n if (kind !== \"object\") return kind;\n try {\n return reason instanceof Error ? \"error\" : \"object\";\n } catch {\n return \"object\";\n }\n}\n\nfunction apiFatalMessage(diagnostic: ReturnType<typeof apiFatalDiagnostic>): string {\n return (\n `Opengeni API fatal process failure (${diagnostic.errorCode}; ` +\n `phase=${diagnostic.phase}; reason_kind=${diagnostic.reasonKind}; ` +\n `correlation_id=${diagnostic.correlationId})`\n );\n}\n\nasync function flushWithin(\n observability: Pick<Observability, \"flush\">,\n timeoutMs: number,\n): Promise<void> {\n let flush: Promise<void>;\n try {\n flush = Promise.resolve(observability.flush()).catch(() => undefined);\n } catch {\n return;\n }\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return;\n\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n flush,\n new Promise<void>((resolve) => {\n timeout = setTimeout(resolve, timeoutMs);\n }),\n ]);\n } finally {\n if (timeout !== undefined) clearTimeout(timeout);\n }\n}\n\nfunction safeFallbackLog(fallbackLog: (message: string) => void, message: string): void {\n try {\n fallbackLog(message);\n } catch {\n // Process termination remains mandatory even when every diagnostic sink fails.\n }\n}\n\nfunction defaultProcessBoundary(): ApiFatalProcess {\n return {\n on: (event, listener) => {\n if (event === \"unhandledRejection\") {\n process.on(\"unhandledRejection\", listener);\n } else {\n process.on(\"uncaughtException\", listener);\n }\n },\n off: (event, listener) => {\n if (event === \"unhandledRejection\") {\n process.off(\"unhandledRejection\", listener);\n } else {\n process.off(\"uncaughtException\", listener);\n }\n },\n exit: (code) => {\n process.exit(code);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,SAAS,oCAAoC;AAC7C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,0BAAoD;AAC7D;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,2BAA2B;AACpC,SAAS,mCAAmC;AAC5C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA,UAAU;AAAA,EACV;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;AC5CP;AAAA,EACE;AAAA,OAGK;AAIA,SAAS,6BACd,eAC8D;AAC9D,SAAO;AAAA,IACL,QAAQ,yBAAyB,aAAa;AAAA,IAC9C,0BAA0B,mCAAmC,aAAa;AAAA,EAC5E;AACF;AAEO,SAAS,yBAAyB,eAA2C;AAClF,SAAO;AAAA,IACL,OAAO,CAAC,SAAS,eAAe,cAAc,MAAM,SAAS,gBAAgB,UAAU,CAAC;AAAA,IACxF,MAAM,CAAC,SAAS,eAAe,cAAc,KAAK,SAAS,gBAAgB,UAAU,CAAC;AAAA,EACxF;AACF;AAEA,SAAS,gBAAgB,YAAyE;AAChG,MAAI,CAAC,YAAY;AACf,WAAO;AAAA,EACT;AACA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AA,MACJ,WAAW,KAAK;AAAA,MAChB,aAAa,KAAK;AAAA,MAClB,iBAAiB,KAAK;AAAA,MACtB,MAAM,KAAK;AAAA,IACb;AAAA,EACF;AACF;AAEA,SAAS,+BAA+B,MAA8B;AACpE,MAAI,KAAK,WAAW,SAAU,QAAO;AACrC,MAAI,CAAC,6BAA6B,IAAI,EAAG,QAAO;AAChD,QAAM,UAAU,KAAK,SAAS;AAC9B,MAAI,CAAC,WAAW,OAAO,YAAY,SAAU,QAAO;AACpD,QAAM,SAAS;AACf,SAAO,OAAO,kBAAkB,SAAS,OAAO,qBAAqB;AACvE;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","getEnrollment","enrollment","appendAndPublishEvents","randomUUID","CLAIM_SECONDS","POLL_INTERVAL_MS","PRUNE_EVERY_TICKS","createHash","randomUUID","MAX_EDITABLE_ARTIFACT_SNAPSHOT_BYTES","withRlsContext","MAX_BOUNDED_OBJECT_CHUNK_BYTES","createHash","createHash","replayedTarget","createHash","MAX_EDITABLE_ARTIFACT_SNAPSHOT_BYTES","editableArtifactCausalFrontier","editableArtifactContentHash","editableArtifactReplicaId","editableArtifactStateHash","throwIfAborted","createHash","retryWhileMissing","throwIfAborted","withRlsContext","randomUUID","MAX_EDITABLE_ARTIFACT_SNAPSHOT_BYTES","createHash","MAX_BOUNDED_OBJECT_CHUNK_BYTES","randomUUID"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/observability.ts","../src/sandbox/auth-callout.ts","../src/sandbox/connection-authority.ts","../src/sandbox/metrics-ingestion.ts","../src/memory-slack-delivery.ts","../src/scheduled-task-lifecycle.ts","../src/scheduled-task-blockers.ts","../src/temporal-schedule-sync.ts","../src/native-push-dispatch.ts","../src/workspace-webhook-dispatch.ts","../src/editable-artifact-websocket.ts","../src/editable-artifact-source-session.ts","../src/http/websocket-upgrade-dispatch.ts","../src/editable-artifact-production.ts","../src/editable-artifact-live-hints.ts","../src/editable-artifact-native-kernel.ts","../src/editable-artifact-office-import.ts","../src/editable-artifact-workspace-files.ts","../src/fatal-process-boundary.ts","../src/shutdown.ts"],"sourcesContent":["import { scheduledTaskKnowledgeSource } from \"@opengeni/contracts\";\nimport {\n dbSearchPath,\n getSettings,\n resolveFirstPartyDelegationSecret,\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 isRetryableRuntimeDatabaseStartupError,\n createDb,\n markSessionWorkflowWakeDelivered,\n runtimeDatabaseReadyCheck,\n type Database,\n} from \"@opengeni/db\";\nimport { createNatsEventBus, type ResponderConnection } from \"@opengeni/events\";\nimport {\n createObservability,\n logStartupDependencyRetry,\n type Observability,\n} from \"@opengeni/observability\";\nimport { createObjectStorage } from \"@opengeni/storage\";\nimport { isArtifactRuntimeConfigured } from \"@opengeni/artifact-tool/runtime/development\";\nimport {\n resolveCatalogSettings,\n SESSION_WORKFLOW_WAKE_DISPATCH_REQUESTED_SIGNAL,\n SESSION_WORKFLOW_WAKE_DISPATCHER_WORKFLOW_ID,\n SESSION_WORKFLOW_WAKE_DISPATCHER_WORKFLOW_TYPE,\n} 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 { observabilityEventBusOptions } from \"./observability\";\nimport { startAuthCalloutResponder } from \"./sandbox/auth-callout\";\nimport { startHelloIngestion, startMetricsIngestion } from \"./sandbox/metrics-ingestion\";\nimport { createAutomaticAgentUpdater } from \"./sandbox/agent-update\";\nimport { startSlackInteractionPump } from \"./integrations/slack-interactions\";\nimport { startMemorySlackPublicationPump } from \"./memory-slack-delivery\";\nimport { startTemporalScheduleCleanupPump } from \"./temporal-schedule-cleanup\";\nimport { closeNativeExternalVaultProviders } from \"./integrations/external-vault-providers\";\nimport { startScheduledTaskLifecyclePump } from \"./scheduled-task-lifecycle\";\nimport { createTemporalScheduleSynchronizer } from \"./temporal-schedule-sync\";\nimport { startNativePushDispatchPump } from \"./native-push-dispatch\";\nimport { startWorkspaceWebhookDispatchPump } from \"./workspace-webhook-dispatch\";\nimport { cleanupScheduledTaskConnectorAuthorization } from \"./scheduled-task-deletion\";\nimport {\n EDITABLE_ARTIFACT_LIVE_WEBSOCKET_MAX_MESSAGE_BYTES,\n EditableArtifactWebSocketTransport,\n} from \"./editable-artifact-websocket\";\nimport { editableArtifactSourceSessionAuthorizer } from \"./editable-artifact-source-session\";\nimport type { ApiWebSocketConnection } from \"./api-websocket\";\nimport { InteractionFrameProxyTransport } from \"./interaction-frame-proxy\";\nimport { apiRequestBindingsForTransportPeer } from \"./http/request-source\";\nimport { startApiMetricsListener } from \"./http/metrics-listener\";\nimport { createLocalBrowserBoundary } from \"./http/local-browser-boundary\";\nimport { dispatchApiWebSocketUpgrade } from \"./http/websocket-upgrade-dispatch\";\nimport {\n createStandaloneEditableArtifactApplication,\n type StandaloneEditableArtifactApplication,\n} from \"./editable-artifact-production\";\nimport { installApiFatalProcessBoundary } from \"./fatal-process-boundary\";\nimport { installApiShutdownHandlers } from \"./shutdown\";\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 scheduledTasks = createTemporalScheduleSynchronizer({\n db,\n withDeadline: (deadline, work) => temporal.withDeadline(deadline, work),\n upsert: async (task) => {\n const options = temporalScheduleOptions(task, settings.temporalTaskQueue);\n try {\n await temporal.schedule\n .getHandle(task.temporalScheduleId)\n .update(() => temporalScheduleUpdateOptions(options));\n } catch (error) {\n if (!shouldCreateScheduleAfterUpdateError(error)) throw error;\n await temporal.schedule.create(options);\n }\n },\n remove: async (temporalScheduleId) => {\n try {\n await temporal.schedule.getHandle(temporalScheduleId).delete();\n } catch (error) {\n if (!(error instanceof ScheduleNotFoundError)) throw error;\n }\n },\n });\n const client: SessionWorkflowClient = {\n triggerAutomationRun: async ({ accountId, workspaceId, runId }) => {\n try {\n await temporal.workflow.start(\"automationRunWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId: `automation-run:${runId}`,\n workflowIdReusePolicy: \"REJECT_DUPLICATE\",\n args: [{ accountId, workspaceId, runId }],\n });\n } catch (error) {\n if (isWorkflowAlreadyStarted(error)) return;\n throw error;\n }\n },\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 onSignalAccepted,\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 onSignalAccepted?.();\n return await markSessionWorkflowWakeDelivered(db, {\n accountId,\n workspaceId,\n sessionId,\n temporalWorkflowId: workflowId,\n wakeRevision,\n });\n },\n requestSessionWorkflowWakeDispatch: async () => {\n await temporal.workflow.signalWithStart(SESSION_WORKFLOW_WAKE_DISPATCHER_WORKFLOW_TYPE, {\n taskQueue: settings.temporalTaskQueue,\n workflowId: SESSION_WORKFLOW_WAKE_DISPATCHER_WORKFLOW_ID,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [],\n signal: SESSION_WORKFLOW_WAKE_DISPATCH_REQUESTED_SIGNAL,\n });\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, onFailure }) => scheduledTasks.sync(task, onFailure),\n deleteScheduledTaskSchedule: async ({ temporalScheduleId }) =>\n scheduledTasks.remove(temporalScheduleId),\n triggerScheduledTask: async ({\n task,\n agentRunUsageIdempotencyKey,\n triggerWorkflowId,\n initiator,\n credentialRestriction,\n triggerType = \"manual\",\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,\n agentRunUsageIdempotencyKey,\n initiator,\n ...(credentialRestriction ? { credentialRestriction } : {}),\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(\"sandbox environment verification requires changeId or versionId\");\n }\n try {\n await temporal.workflow.start(\"rigVerificationWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId: workflowId ?? `rig-verification-${targetId}-${crypto.randomUUID()}`,\n workflowIdReusePolicy: \"REJECT_DUPLICATE\",\n args: [\n {\n workspaceId,\n ...(changeId ? { changeId } : {}),\n ...(versionId ? { versionId } : {}),\n },\n ],\n });\n } catch (error) {\n // A lost start acknowledgement is indistinguishable from a retry. The\n // caller-owned workflow id makes both cases the same successful start.\n if (isWorkflowAlreadyStarted(error)) return;\n throw error;\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 options: {\n settings?: ReturnType<typeof getSettings>;\n observability?: Observability;\n } = {},\n) {\n const settings = options.settings ?? getSettings();\n const observability =\n options.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 max: settings.apiDatabasePoolMax,\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 exact generation-fenced agent RPC subjects. Null in local dev\n // (anonymous connect — the bus default).\n const controlPlaneAuth = resolveNatsControlPlaneAuth(settings);\n try {\n // Browser, Computer, Terminal, and Files can cold-create the home sandbox\n // directly from this API process. Resolve the same private-registry Modal\n // image before the API becomes reachable so the first human interaction\n // does not pay the provider import/build latency. This mirrors the turn\n // worker's startup boundary and is a no-op for provider-native image IDs,\n // public images, and non-Modal backends.\n const { ensureModalRegistryImage } = await import(\"@opengeni/runtime/sandbox\");\n await retryStartupDependency(\n \"Modal private-registry image\",\n () => ensureModalRegistryImage(settings),\n { ...retryOptions, onRetry },\n );\n await retryStartupDependency(\n \"PostgreSQL runtime posture\",\n () => assertRuntimeDatabasePosture(dbClient.db, databasePosture),\n { ...retryOptions, onRetry, shouldRetry: isRetryableRuntimeDatabaseStartupError },\n );\n const resolvedCatalog = await retryStartupDependency(\n \"model catalog\",\n () => resolveCatalogSettings(dbClient.db, settings),\n { ...retryOptions, onRetry },\n );\n observability.info(\"Opengeni model catalog resolved\", {\n catalogSource: resolvedCatalog.source,\n catalogVersion: resolvedCatalog.version,\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 observabilityEventBusOptions(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 objectStorage = createObjectStorage(settings);\n let editableArtifactComposition: StandaloneEditableArtifactApplication | undefined;\n if (objectStorage && isArtifactRuntimeConfigured()) {\n try {\n editableArtifactComposition = await createStandaloneEditableArtifactApplication({\n db: dbClient.db,\n bus,\n objectStorage,\n });\n } catch (error) {\n await Promise.allSettled([bus.close(), workflowClient.close(), dbClient.close()]);\n throw error;\n }\n }\n const { app, routeDeps } = createAppComposition({\n settings,\n db: dbClient.db,\n bus,\n workflowClient: workflowClient.client,\n documentIndexer: workflowClient.documentIndexer,\n objectStorage,\n ...(editableArtifactComposition\n ? {\n editableArtifacts: editableArtifactComposition.application,\n editableArtifactExports: editableArtifactComposition.durableExports,\n editableArtifactAgent: editableArtifactComposition.agent,\n editableArtifactOfficeImports: editableArtifactComposition.officeImports,\n }\n : {}),\n observability,\n readinessChecks: {\n db: runtimeDatabaseReadyCheck(dbClient.db, databasePosture),\n },\n });\n if (!routeDeps.editableArtifacts) {\n observability.warn(\"editable artifact engine is not composed\", {\n subsystem: \"editable_artifacts\",\n behavior: \"http_and_websocket_fail_closed\",\n });\n }\n const artifactWebSockets = new EditableArtifactWebSocketTransport(\n routeDeps.editableArtifacts,\n editableArtifactSourceSessionAuthorizer(routeDeps),\n );\n const interactionFrameProxies = new InteractionFrameProxyTransport(\n resolveFirstPartyDelegationSecret(settings),\n );\n // WebSocket upgrades bypass the Hono app, so the local-mode browser boundary\n // (http/local-browser-boundary.ts) is applied to them in the dispatcher;\n // every other request meets it in the Hono middleware.\n const localBrowserBoundary = createLocalBrowserBoundary(settings, {\n warn: (message, attributes) => observability.warn(message, attributes),\n });\n const webSocketUpgrades = [interactionFrameProxies, artifactWebSockets];\n const server = Bun.serve<ApiWebSocketConnection>({\n hostname: settings.apiHost,\n port: settings.apiPort,\n idleTimeout: 255,\n fetch: (request, bunServer) => {\n const upgrade = dispatchApiWebSocketUpgrade(\n request,\n bunServer,\n webSocketUpgrades,\n localBrowserBoundary,\n );\n if (upgrade.handled) return upgrade.response;\n return app.fetch(\n request,\n apiRequestBindingsForTransportPeer(bunServer.requestIP(request)?.address),\n );\n },\n websocket: {\n maxPayloadLength: EDITABLE_ARTIFACT_LIVE_WEBSOCKET_MAX_MESSAGE_BYTES,\n backpressureLimit: 16 * 1024 * 1024,\n closeOnBackpressureLimit: true,\n open: (socket) => socket.data.attach(socket),\n message: (socket, message) => socket.data.receive(message),\n close: (socket) => socket.data.transportClosed(),\n },\n });\n const metricsServer = startApiMetricsListener(settings, observability);\n const stopSlackInteractionPump = settings.slackSigningSecret\n ? startSlackInteractionPump(routeDeps)\n : undefined;\n const stopMemorySlackPublicationPump = startMemorySlackPublicationPump(routeDeps);\n const stopWorkspaceWebhookDispatchPump = startWorkspaceWebhookDispatchPump({\n db: dbClient.db,\n settings,\n observability,\n });\n const stopNativePushDispatchPump = startNativePushDispatchPump({\n db: dbClient.db,\n settings,\n observability,\n });\n const stopTemporalScheduleCleanupPump = startTemporalScheduleCleanupPump({\n db: dbClient.db,\n cleanupConnectorAuthorization: async (claim) =>\n await cleanupScheduledTaskConnectorAuthorization(routeDeps, claim),\n deleteSchedule: async (temporalScheduleId) => {\n await workflowClient.client.deleteScheduledTaskSchedule({ temporalScheduleId });\n },\n observability,\n });\n const stopScheduledTaskLifecyclePump = startScheduledTaskLifecyclePump({\n db: dbClient.db,\n sync: (task) => workflowClient.client.syncScheduledTask({ task }),\n bus,\n observability,\n });\n // M10 — start the metrics-ingestion consumer (agent heartbeats → DB last-sample\n // + downsampled series), gated on the selfhosted flag. A no-op when disabled.\n let stopMetricsIngestion: (() => void) | undefined;\n // Reconcile enrollments.has_display to the LIVE capability the agent reports in\n // its connect Hello (has_display was frozen at the enroll-time snapshot). Gated\n // on the same selfhosted flag.\n let stopHelloIngestion: (() => void) | undefined;\n // M-AUTH — start the NATS auth-callout responder (the tenancy boundary): it\n // validates an agent's enrollment bearer presented at NATS connect and mints a\n // workspace-scoped user JWT. Gated on the selfhosted flag + a resolvable callout\n // config; without the callout plane it never starts (selfhosted agents simply\n // cannot connect — graceful). It runs on its OWN connection (the callout auth\n // user), separate from the privileged control-plane bus.\n let authCalloutResponder: ResponderConnection | undefined;\n if (settings.sandboxSelfhostedEnabled) {\n stopMetricsIngestion = startMetricsIngestion({\n db: dbClient.db,\n bus,\n observability,\n agentUpdates: createAutomaticAgentUpdater({\n db: dbClient.db,\n bus,\n settings,\n observability,\n }),\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 ...(metricsServer ? { metricsPort: settings.apiMetricsPort } : {}),\n });\n return {\n server,\n close: async () => {\n server.stop(true);\n // Start private CLI session cleanup even if another service's drain stalls.\n const vaultProvidersClosed = closeNativeExternalVaultProviders().catch(() => undefined);\n metricsServer?.stop(true);\n stopSlackInteractionPump?.();\n await stopMemorySlackPublicationPump();\n stopMetricsIngestion?.();\n stopHelloIngestion?.();\n await stopTemporalScheduleCleanupPump();\n await stopScheduledTaskLifecyclePump();\n await stopWorkspaceWebhookDispatchPump();\n await stopNativePushDispatchPump();\n // Write queued presence before the database pool closes.\n await routeDeps.userPresence?.close().catch(() => undefined);\n await Promise.allSettled([\n vaultProvidersClosed,\n Promise.resolve(editableArtifactComposition?.close()),\n authCalloutResponder?.close(),\n bus.close(),\n workflowClient.close(),\n dbClient.close(),\n ]);\n },\n };\n}\n\nif (import.meta.main) {\n const fatalBoundary = installApiFatalProcessBoundary();\n try {\n const settings = getSettings();\n const observability = createObservability(settings, { component: \"api\" });\n fatalBoundary.attachObservability(observability);\n const api = await startApi({ settings, observability });\n installApiShutdownHandlers({\n close: api.close,\n onFailure: () =>\n observability.warn(\"Opengeni API shutdown did not finish cleanly\", {\n errorCode: \"api_shutdown_failed\",\n }),\n });\n fatalBoundary.markRunning();\n } catch (error) {\n await fatalBoundary.reportStartupFailure(error);\n }\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 === \"manual\") {\n throw new Error(\"manual scheduled tasks do not have a Temporal Schedule spec\");\n }\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: scheduledTaskEffectivelyPaused(task),\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 scheduledTaskEffectivelyPaused(task: ScheduledTask): boolean {\n if (task.status === \"paused\") return true;\n if (!scheduledTaskKnowledgeSource(task)) return false;\n const control = task.metadata.knowledgeSourceSync;\n if (!control || typeof control !== \"object\") return false;\n const record = control as Record<string, unknown>;\n return record.sourceEnabled === false || record.connectionPaused === true;\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 {\n natsSubscriptionTerminationCounter,\n type EventBusOptions,\n type EventLogger,\n} from \"@opengeni/events\";\nimport type { Attributes, AttributeValue, Observability } from \"@opengeni/observability\";\n\n/** Logger plus the closed-label subscription-termination counter for NATS connections. */\nexport function observabilityEventBusOptions(\n observability: Observability,\n): Pick<EventBusOptions, \"logger\" | \"onSubscriptionTerminated\"> {\n return {\n logger: observabilityEventLogger(observability),\n onSubscriptionTerminated: natsSubscriptionTerminationCounter(observability),\n };\n}\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. atomically claims the daemon instance named in CONNECT;\n// 5. signs a NATS user JWT granting pub/sub ONLY that exact process subtree +\n// `_INBOX.>` (deny-all-else by an allow-list) and returns it inside a signed\n// authorization-response JWT.\n//\n// That exact scope is both the tenancy boundary and routing fence: workspace A\n// cannot reach B, and an old/duplicate process cannot subscribe to its successor's\n// work. nats-server enforces the signed permission set; the boundary does not rely\n// on naming alone.\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 { createHash } from \"node:crypto\";\nimport { createLogThrottle, type LogThrottle } from \"@opengeni/observability\";\nimport {\n resolveEnrollmentSigningSecret,\n type NatsCalloutConfig,\n type Settings,\n} from \"@opengeni/config\";\nimport { verifyEnrollmentBearer } from \"@opengeni/contracts\";\nimport { claimEnrollmentConnection, getEnrollment, type Database } from \"@opengeni/db\";\nimport {\n createResponderConnection,\n decodeAuthRequest,\n mintAuthResponse,\n mintUserJwt,\n parseAgentConnectionName,\n workspaceAgentPermissions,\n type ResponderConnection,\n} from \"@opengeni/events\";\nimport type { Observability } from \"@opengeni/observability\";\nimport { observabilityEventBusOptions } from \"../observability\";\nimport { AGENT_CONNECTION_LEASE_MS } from \"./connection-authority\";\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;\nexport interface AuthCalloutDeps {\n db: Database;\n settings: Settings;\n callout: NatsCalloutConfig;\n observability?: Observability;\n /** Bounds repeated denial warnings; defaults to one process-wide throttle. */\n denialWarningThrottle?: LogThrottle;\n}\n\n/** A stale or revoked machine re-dials on its reconnect backoff forever, so an\n * unthrottled denial warning repeats every few seconds per machine. Log each\n * distinct machine's first denial, then at most once per interval with the\n * count of denials it hid. The denial decision itself is never throttled. */\nexport const AUTH_CALLOUT_DENIAL_WARNING_INTERVAL_MS = 60_000;\nconst processDenialWarningThrottle = createLogThrottle({\n intervalMs: AUTH_CALLOUT_DENIAL_WARNING_INTERVAL_MS,\n maxKeys: 1_024,\n});\n\n/** Closed denial vocabulary. The public log projection drops identifiers, so\n * `reason` is what tells an operator which throttle key a count belongs to. */\ntype AuthCalloutDenialReason = \"invalid_bearer\" | \"inactive_enrollment\" | \"duplicate_runner\";\n\nfunction warnDenial(\n deps: AuthCalloutDeps,\n key: string,\n reason: AuthCalloutDenialReason,\n message: string,\n attributes: Record<string, string | number> = {},\n): void {\n const admission = (deps.denialWarningThrottle ?? processDenialWarningThrottle).admit(key);\n if (!admission) return;\n deps.observability?.warn?.(message, {\n ...attributes,\n reason,\n ...(admission.suppressedCount > 0 ? { suppressedCount: admission.suppressedCount } : {}),\n });\n}\n\n/** Closed reasons a Connected Machine agent's NATS connect is refused. */\ntype MachineConnectDenialReason =\n | \"undecodable\"\n | \"missing_bearer\"\n | \"plane_disabled\"\n | \"invalid_bearer\"\n | \"inactive_enrollment\"\n | \"identity_mismatch\"\n | \"generation_mismatch\"\n | \"invalid_instance\"\n | \"duplicate_runner\";\n\n/** Count every machine connect decision; identifiers never become labels. */\nfunction recordMachineConnect(\n deps: AuthCalloutDeps,\n outcome: \"granted\" | \"denied\",\n reason: MachineConnectDenialReason | \"none\",\n): void {\n try {\n deps.observability?.incrementCounter({\n name: \"opengeni_machine_connect_total\",\n help: \"Connected Machine agent NATS connect decisions (auth callout) by outcome and closed denial reason.\",\n labels: { outcome, reason },\n });\n } catch {\n // Telemetry never changes the signed connect decision.\n }\n}\n\n/** A process-local dedupe key for a rejected bearer. The digest is never\n * logged, and the bearer value never leaves this function. */\nfunction rejectedBearerKey(bearer: string): string {\n return `invalid-bearer:${createHash(\"sha256\").update(bearer).digest(\"hex\").slice(0, 32)}`;\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 recordMachineConnect(deps, \"denied\", \"undecodable\");\n throw new Error(\"undecodable authorization request\");\n }\n\n const deny = (code: MachineConnectDenialReason, reason: string): Uint8Array => {\n recordMachineConnect(deps, \"denied\", code);\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_bearer\", \"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(\"plane_disabled\", \"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 warnDenial(\n deps,\n rejectedBearerKey(bearer),\n \"invalid_bearer\",\n \"auth-callout: rejected an invalid enrollment bearer\",\n );\n return deny(\"invalid_bearer\", \"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 warnDenial(\n deps,\n `inactive:${claims.workspaceId}:${claims.agentId}`,\n \"inactive_enrollment\",\n \"auth-callout: denied a revoked or unknown enrollment\",\n { workspaceId: claims.workspaceId, agentId: claims.agentId },\n );\n return deny(\"inactive_enrollment\", \"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(\"identity_mismatch\", \"enrollment identity mismatch\");\n }\n if (enrollment.credentialGeneration !== claims.credentialGeneration) {\n return deny(\"generation_mismatch\", \"enrollment credential generation mismatch\");\n }\n\n const connectionInstanceId = parseAgentConnectionName(decoded.name);\n if (!connectionInstanceId) {\n return deny(\"invalid_instance\", \"missing or invalid agent connection instance\");\n }\n const claim = await claimEnrollmentConnection(deps.db, {\n workspaceId: claims.workspaceId,\n enrollmentId: claims.enrollmentId,\n credentialGeneration: claims.credentialGeneration,\n connectionInstanceId,\n leaseMs: AGENT_CONNECTION_LEASE_MS,\n });\n if (!claim.claimed) {\n warnDenial(\n deps,\n `duplicate:${claims.workspaceId}:${claims.agentId}`,\n \"duplicate_runner\",\n \"auth-callout: denied a duplicate live runner\",\n { workspaceId: claims.workspaceId, agentId: claims.agentId },\n );\n return deny(\"duplicate_runner\", \"another runner instance currently owns this enrollment\");\n }\n\n // GRANT: the operational subject includes the exact claimed process instance.\n // A previous socket may remain open until its short JWT expires, but no control\n // request is routed to its old subject after a successor claims authority.\n const permissions = workspaceAgentPermissions(\n claims.workspaceId,\n claims.agentId,\n connectionInstanceId,\n );\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 recordMachineConnect(deps, \"granted\", \"none\");\n deps.observability?.info?.(\"auth-callout: granted a workspace-scoped NATS credential\", {\n workspaceId: claims.workspaceId,\n agentId: claims.agentId,\n connectionGeneration: claim.connectionGeneration,\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 ? observabilityEventBusOptions(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","/** Five-second heartbeats get four missed intervals before another daemon may\n * claim the enrollment. Server time is authoritative. */\nexport const AGENT_CONNECTION_LEASE_MS = 20_000;\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 the exact process events subject) and publishes a\n// `Hello` (its live self-description) on the exact process hello subject on every connect\n// /reconnect. This module owns the two agent→control-plane inbound consumers:\n//\n// `agent.*.*.connection.*.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.*.*.connection.*.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. Exec is unavailable unless the runner\n// 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. Event ingestion drains the NATS\n// subscription immediately into exact-subject queues: different runner connections\n// progress concurrently, one runner's ordering is preserved, and consecutive queued\n// heartbeats collapse latest-wins. A delayed heartbeat backlog therefore cannot keep\n// renewing a dead runner's short connection lease one stale message at a time.\n\nimport {\n clearEnrollmentWentOffline,\n disconnectAttachedBrowserDevices,\n advanceEnrollmentAgentUpdate,\n enrollmentMacPermissionCapabilities,\n enrollmentMacPermissions,\n getEnrollment,\n getLiveEnrollmentConnection,\n ingestMachineMetricsSample,\n reconcileAttachedBrowserInventory,\n releaseEnrollmentConnection,\n renewEnrollmentConnection,\n sessionsWithActiveOpOnEnrollment,\n setEnrollmentDisplayState,\n setEnrollmentAgentRuntime,\n setEnrollmentOpStreamState,\n type AppendEventInput,\n type Database,\n type EnrollmentMacPermissions,\n type MachineMetricsSample,\n} from \"@opengeni/db\";\nimport {\n AttachedBrowserConnectionEnd as AttachedBrowserConnectionEndContract,\n AttachedBrowserInventorySnapshot as AttachedBrowserInventoryContract,\n type AttachedBrowserInventorySnapshot as AttachedBrowserInventoryContractValue,\n type AttachedBrowserConnectionEnd as AttachedBrowserConnectionEndValue,\n} from \"@opengeni/contracts\";\nimport { appendAndPublishEvents, type EventBus } from \"@opengeni/events\";\nimport type { Observability } from \"@opengeni/observability\";\nimport { normalizeConnectedMachineWorkspaceRoot } from \"@opengeni/runtime/sandbox\";\nimport type { AutomaticAgentUpdater } from \"./agent-update\";\nimport {\n AgentEvent,\n AgentUpdateStage,\n Arch,\n AttachedBrowserConnectionEndReason as WireConnectionEndReason,\n GoingOfflineReason,\n Hello,\n Os,\n goingOfflineReasonToJSON,\n type AttachedBrowserConnectionEnd as WireAttachedBrowserConnectionEnd,\n type AttachedBrowserInventorySnapshot as WireAttachedBrowserInventorySnapshot,\n type MetricsSample,\n} from \"@opengeni/agent-proto\";\nimport { AGENT_CONNECTION_LEASE_MS } from \"./connection-authority\";\nimport { reconcileScreenControlOnHello } from \"./screen-control\";\n\n/** The wildcard subject the agent event plane publishes heartbeats on. */\nexport const AGENT_EVENTS_SUBJECT = \"agent.*.*.connection.*.events\";\n\n/** The wildcard subject the agent publishes its connect Hello on. */\nexport const AGENT_HELLO_SUBJECT = \"agent.*.*.connection.*.hello\";\n\ntype QueuedAgentEvent = {\n payload: Uint8Array;\n subject: string;\n heartbeat: boolean;\n};\n\ntype AgentEventQueueState = {\n scheduled: boolean;\n pending: QueuedAgentEvent[];\n};\n\ntype ScheduledAgentEventQueue = {\n subject: string;\n state: AgentEventQueueState;\n};\n\nexport type AgentEventIngestionScheduler = {\n enqueue: (payload: Uint8Array, subject: string) => void;\n whenIdle: () => Promise<void>;\n close: () => void;\n};\n\nfunction payloadIsHeartbeat(payload: Uint8Array): boolean {\n try {\n return AgentEvent.decode(payload).event?.$case === \"heartbeat\";\n } catch {\n // Preserve the normal decoder/logging path for malformed events. They are\n // barriers rather than heartbeat-coalescing candidates.\n return false;\n }\n}\n\n/**\n * Drain agent events without making every Connected Machine wait behind one\n * deployment-wide serial DB queue. Each exact process subject retains FIFO order;\n * separate subjects drain concurrently. Consecutive pending heartbeats for one\n * subject are latest-wins because they are point-in-time liveness/metrics samples,\n * while GoingOffline and update-progress events remain ordered barriers.\n */\nexport function createAgentEventIngestionScheduler(\n handler: (payload: Uint8Array, subject: string) => void | Promise<void>,\n options: { maxConcurrentSubjects?: number; onHeartbeatCoalesced?: () => void } = {},\n): AgentEventIngestionScheduler {\n const maxConcurrentSubjects = options.maxConcurrentSubjects ?? 32;\n if (!Number.isSafeInteger(maxConcurrentSubjects) || maxConcurrentSubjects <= 0) {\n throw new RangeError(\"maxConcurrentSubjects must be a positive safe integer\");\n }\n\n const states = new Map<string, AgentEventQueueState>();\n const readySubjects: ScheduledAgentEventQueue[] = [];\n const idleWaiters = new Set<() => void>();\n let accepting = true;\n let activeSubjects = 0;\n\n const resolveIdleWaiters = (): void => {\n if (states.size !== 0) return;\n for (const resolve of idleWaiters) resolve();\n idleWaiters.clear();\n };\n\n async function drain(subject: string, state: AgentEventQueueState): Promise<void> {\n while (true) {\n const event = state.pending.shift();\n if (!event) break;\n try {\n await handler(event.payload, event.subject);\n } catch {\n // Agent-event ingestion is best-effort. One bad event must not strand the\n // exact-subject queue or prevent later heartbeats from restoring liveness.\n }\n }\n\n activeSubjects -= 1;\n state.scheduled = false;\n if (state.pending.length > 0) {\n schedule(subject, state);\n } else {\n if (states.get(subject) === state) states.delete(subject);\n resolveIdleWaiters();\n }\n pump();\n }\n\n function pump(): void {\n while (activeSubjects < maxConcurrentSubjects) {\n const next = readySubjects.shift();\n if (!next) return;\n if (states.get(next.subject) !== next.state || !next.state.scheduled) continue;\n activeSubjects += 1;\n void drain(next.subject, next.state);\n }\n }\n\n function schedule(subject: string, state: AgentEventQueueState): void {\n if (state.scheduled) return;\n state.scheduled = true;\n readySubjects.push({ subject, state });\n pump();\n }\n\n return {\n enqueue(payload, subject) {\n if (!accepting) return;\n const heartbeat = payloadIsHeartbeat(payload);\n let state = states.get(subject);\n if (!state) {\n state = { scheduled: false, pending: [] };\n states.set(subject, state);\n }\n\n const queued = { payload, subject, heartbeat };\n const lastIndex = state.pending.length - 1;\n if (heartbeat && lastIndex >= 0 && state.pending[lastIndex]!.heartbeat) {\n state.pending[lastIndex] = queued;\n options.onHeartbeatCoalesced?.();\n } else {\n state.pending.push(queued);\n }\n\n schedule(subject, state);\n },\n async whenIdle() {\n if (states.size === 0) return;\n await new Promise<void>((resolve) => idleWaiters.add(resolve));\n },\n close() {\n accepting = false;\n for (const state of states.values()) {\n state.pending.length = 0;\n }\n resolveIdleWaiters();\n },\n };\n}\n\n/**\n * Parse `agent.<ws>.<id>.connection.<instance>.<tail>` into its exact authority,\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; connectionInstanceId: string } | null {\n const parts = subject.split(\".\");\n if (\n parts.length !== 6 ||\n parts[0] !== \"agent\" ||\n parts[3] !== \"connection\" ||\n !parts[4] ||\n parts[5] !== tail\n ) {\n return null;\n }\n return {\n workspaceId: parts[1]!,\n agentId: parts[2]!,\n connectionInstanceId: parts[4]!,\n };\n}\n\n/** Parse the exact process events subject (heartbeat plane). */\nexport function parseAgentEventSubject(\n subject: string,\n): { workspaceId: string; agentId: string; connectionInstanceId: string } | null {\n return parseAgentSubject(subject, \"events\");\n}\n\n/** Parse the exact process hello subject (connect plane). */\nexport function parseAgentHelloSubject(\n subject: string,\n): { workspaceId: string; agentId: string; connectionInstanceId: 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/** Validate and project one wire inventory before it reaches durable browser\n * discovery. Unknown enum values and unsafe uint64 counters reject the whole\n * authoritative snapshot instead of partially disconnecting good endpoints. */\nexport function wireAttachedBrowserInventoryToContract(\n wire: WireAttachedBrowserInventorySnapshot,\n): AttachedBrowserInventoryContractValue {\n return AttachedBrowserInventoryContract.parse({\n bridgeGeneration: wire.bridgeGeneration,\n revision: safeWireInteger(wire.revision, \"browser inventory revision\"),\n devices: wire.devices.map((device) => ({\n id: device.id,\n name: device.name,\n profileLabel: device.profileLabel.trim() || null,\n browserName: device.browserName,\n browserVersion: device.browserVersion,\n extensionVersion: device.extensionVersion,\n platform: wireBrowserPlatform(device.platform),\n architecture: wireBrowserArchitecture(device.arch),\n connectionGeneration: device.connectionGeneration,\n inventoryRevision: safeWireInteger(\n device.inventoryRevision,\n \"attached browser inventory revision\",\n ),\n tabCount: safeWireInteger(device.tabCount, \"attached browser tab count\"),\n capabilities: device.capabilities,\n })),\n connectionEnds: (wire.connectionEnds ?? []).flatMap(wireConnectionEndToContract),\n });\n}\n\nconst WIRE_CONNECTION_END_REASONS = new Map<\n WireConnectionEndReason,\n AttachedBrowserConnectionEndValue[\"reason\"]\n>([\n [\n WireConnectionEndReason.ATTACHED_BROWSER_CONNECTION_END_REASON_BROWSER_CLOSED_PORT,\n \"browser_closed_port\",\n ],\n [\n WireConnectionEndReason.ATTACHED_BROWSER_CONNECTION_END_REASON_BROWSER_MESSAGE_INVALID,\n \"browser_message_invalid\",\n ],\n [\n WireConnectionEndReason.ATTACHED_BROWSER_CONNECTION_END_REASON_BROWSER_OUTPUT_FAILED,\n \"browser_output_failed\",\n ],\n [\n WireConnectionEndReason.ATTACHED_BROWSER_CONNECTION_END_REASON_NATIVE_HOST_LOST,\n \"native_host_lost\",\n ],\n [WireConnectionEndReason.ATTACHED_BROWSER_CONNECTION_END_REASON_AGENT_REJECTED, \"agent_rejected\"],\n]);\n\n/** Connection ends are diagnostics. One the contract cannot hold (a future\n * reason, or the generation of a hello the bridge rejected as malformed) is\n * dropped instead of rejecting the authoritative device inventory. */\nfunction wireConnectionEndToContract(\n wire: WireAttachedBrowserConnectionEnd,\n): AttachedBrowserConnectionEndValue[] {\n const reason = WIRE_CONNECTION_END_REASONS.get(wire.reason);\n const endedAtMs = Number(wire.endedAtUnixMs);\n if (!reason || !Number.isSafeInteger(endedAtMs) || endedAtMs <= 0) return [];\n const parsed = AttachedBrowserConnectionEndContract.safeParse({\n deviceId: wire.deviceId,\n connectionGeneration: wire.connectionGeneration,\n reason,\n detail: wire.detail.slice(0, 512) || null,\n endedAt: new Date(endedAtMs).toISOString(),\n connectedMs: Math.min(Number(wire.connectedMs) || 0, Number.MAX_SAFE_INTEGER),\n });\n return parsed.success ? [parsed.data] : [];\n}\n\nfunction safeWireInteger(value: string | number, label: string): number {\n let parsed: bigint;\n try {\n parsed = BigInt(value);\n } catch {\n throw new Error(`${label} is not an integer`);\n }\n if (parsed < 0n || parsed > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new Error(`${label} is outside the safe integer range`);\n }\n return Number(parsed);\n}\n\nfunction wireBrowserPlatform(platform: Os): \"linux\" | \"macos\" | \"windows\" {\n switch (platform) {\n case Os.OS_LINUX:\n return \"linux\";\n case Os.OS_MACOS:\n return \"macos\";\n case Os.OS_WINDOWS:\n return \"windows\";\n default:\n throw new Error(\"attached browser platform is unspecified or unsupported\");\n }\n}\n\nfunction wireBrowserArchitecture(architecture: Arch): \"x64\" | \"arm64\" {\n switch (architecture) {\n case Arch.ARCH_X86_64:\n return \"x64\";\n case Arch.ARCH_AARCH64:\n return \"arm64\";\n default:\n throw new Error(\"attached browser architecture is unspecified or unsupported\");\n }\n}\n\nasync function ingestAttachedBrowserInventory(\n db: Database,\n input: {\n workspaceId: string;\n agentId: string;\n inventory: WireAttachedBrowserInventorySnapshot;\n },\n): Promise<void> {\n const enrollment = await getEnrollment(db, input.workspaceId, input.agentId);\n if (!enrollment) return;\n await reconcileAttachedBrowserInventory(db, {\n accountId: enrollment.accountId,\n workspaceId: input.workspaceId,\n enrollmentId: input.agentId,\n snapshot: wireAttachedBrowserInventoryToContract(input.inventory),\n });\n}\n\n/**\n * Ingest the OPTIONAL metrics sample carried by an already-authorized heartbeat.\n * Connection renewal is deliberately owned by the outer event handler and runs\n * before optional telemetry/inventory work, so telemetry absence or failure can\n * never make a healthy runner lose authority.\n */\nasync function ingestHeartbeatMetrics(\n db: Database,\n input: {\n accountId: string;\n workspaceId: string;\n agentId: string;\n sample: MetricsSample;\n },\n): Promise<{ ingested: boolean; seriesAppended: boolean }> {\n const sample = wireSampleToDbSample(input.sample);\n const result = await ingestMachineMetricsSample(db, {\n accountId: input.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 agentUpdates?: AutomaticAgentUpdater | null,\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 const released = await releaseEnrollmentConnection(db, {\n accountId: enrollment.accountId,\n workspaceId: ids.workspaceId,\n enrollmentId: ids.agentId,\n connectionInstanceId: ids.connectionInstanceId,\n reason,\n });\n // A late goodbye from a superseded process is not the current machine\n // going offline. It must not disconnect browsers or fan out link loss.\n if (!released.released) return;\n try {\n await disconnectAttachedBrowserDevices(db, {\n accountId: enrollment.accountId,\n workspaceId: ids.workspaceId,\n enrollmentId: ids.agentId,\n });\n } catch (error) {\n observability?.warn?.(\"Failed to disconnect attached browsers with their machine\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\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 === \"agentUpdateProgress\") {\n const enrollment = await getEnrollment(db, ids.workspaceId, ids.agentId).catch(() => null);\n if (!enrollment || enrollment.connectionInstanceId !== ids.connectionInstanceId) return;\n const progress = event.event.agentUpdateProgress;\n const status = (() => {\n switch (progress.stage) {\n case AgentUpdateStage.AGENT_UPDATE_STAGE_ACCEPTED:\n return \"accepted\" as const;\n case AgentUpdateStage.AGENT_UPDATE_STAGE_WAITING_FOR_IDLE:\n return \"waiting_for_idle\" as const;\n case AgentUpdateStage.AGENT_UPDATE_STAGE_DOWNLOADING:\n return \"downloading\" as const;\n case AgentUpdateStage.AGENT_UPDATE_STAGE_VERIFYING:\n return \"verifying\" as const;\n case AgentUpdateStage.AGENT_UPDATE_STAGE_APPLYING:\n return \"applying\" as const;\n case AgentUpdateStage.AGENT_UPDATE_STAGE_RESTARTING:\n return \"restarting\" as const;\n case AgentUpdateStage.AGENT_UPDATE_STAGE_FAILED:\n return \"failed\" as const;\n default:\n return null;\n }\n })();\n if (!status) return;\n try {\n await advanceEnrollmentAgentUpdate(db, {\n accountId: enrollment.accountId,\n workspaceId: ids.workspaceId,\n enrollmentId: ids.agentId,\n connectionInstanceId: ids.connectionInstanceId,\n connectionGeneration: enrollment.connectionGeneration,\n operationId: progress.operationId,\n status,\n expectedBinarySha256: /^[0-9a-f]{64}$/.test(progress.expectedBinarySha256)\n ? progress.expectedBinarySha256\n : null,\n errorCode: progress.errorCode || null,\n retryable: progress.retryable,\n rolledBack: progress.rolledBack,\n });\n } catch (error) {\n observability?.warn?.(\"Failed to ingest a machine self-update progress event\", {\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 heartbeat = event.event.heartbeat;\n const enrollment = await getEnrollment(db, ids.workspaceId, ids.agentId).catch(() => null);\n if (!enrollment || enrollment.connectionInstanceId !== ids.connectionInstanceId) return;\n try {\n const renewed = await renewEnrollmentConnection(db, {\n accountId: enrollment.accountId,\n workspaceId: ids.workspaceId,\n enrollmentId: ids.agentId,\n connectionInstanceId: ids.connectionInstanceId,\n leaseMs: AGENT_CONNECTION_LEASE_MS,\n });\n if (!renewed.renewed) return;\n } catch (error) {\n observability?.warn?.(\"Failed to renew a machine connection heartbeat\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n // A live machine behind its promoted build is asked to update; the decision\n // reads only this enrollment, and a request never blocks heartbeat ingestion.\n agentUpdates?.consider(enrollment);\n if (heartbeat.attachedBrowserInventory) {\n try {\n await ingestAttachedBrowserInventory(db, {\n workspaceId: ids.workspaceId,\n agentId: ids.agentId,\n inventory: heartbeat.attachedBrowserInventory,\n });\n } catch (error) {\n observability?.warn?.(\"Failed to ingest an attached-browser inventory\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n if (heartbeat.desktopStatus) {\n try {\n const status = heartbeat.desktopStatus;\n const available = status.available && !status.unavailableReason;\n const reason = status.unavailableReason || null;\n const macPermissions = status.macPermissions;\n const stored = enrollmentMacPermissions(enrollment.agentCapabilities);\n // The heartbeat already read the exact enrollment. Steady state adds no\n // extra query; the change path re-reads and fences its eventual write.\n if (\n enrollment.hasDisplay !== available ||\n (enrollment.desktopUnavailableReason ?? null) !== reason ||\n enrollment.agentCapabilities?.desktop !== available ||\n (macPermissions !== undefined &&\n (stored?.screenRecording !== macPermissions.screenRecording ||\n stored?.accessibility !== macPermissions.accessibility ||\n stored?.inputMonitoring !== macPermissions.inputMonitoring))\n ) {\n await refreshEnrollmentDisplay(db, {\n workspaceId: ids.workspaceId,\n agentId: ids.agentId,\n hasDisplay: available,\n desktopUnavailableReason: reason,\n runtimeDesktop: available,\n ...(macPermissions ? { macPermissions } : {}),\n connectionInstanceId: ids.connectionInstanceId,\n });\n }\n } catch (error) {\n observability?.warn?.(\"Failed to refresh a machine desktop heartbeat\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n const metrics = heartbeat.metrics;\n if (!metrics) return;\n try {\n await ingestHeartbeatMetrics(db, {\n accountId: enrollment.accountId,\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 exact process 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 agentUpdates?: AutomaticAgentUpdater | null;\n}): () => void {\n const scheduler = createAgentEventIngestionScheduler(\n (payload, subject) =>\n handleAgentEventPayload(\n deps.db,\n deps.observability,\n payload,\n subject,\n deps.bus,\n deps.agentUpdates,\n ),\n {\n onHeartbeatCoalesced: () =>\n deps.observability?.incrementCounter({\n name: \"opengeni_machine_heartbeat_coalesced_total\",\n help: \"Connected Machine heartbeats collapsed while an exact runner event queue was busy.\",\n }),\n },\n );\n const unsubscribe = deps.bus.subscribeAgentEvents(AGENT_EVENTS_SUBJECT, (payload, subject) => {\n scheduler.enqueue(payload, subject);\n });\n return () => {\n unsubscribe();\n scheduler.close();\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\nexport function helloRuntimeCapabilities(hello: Hello): Record<string, boolean> {\n const caps = hello.capabilities;\n // Absence is an older-agent/unknown signal, not a fabricated set of false claims.\n // Keep the durable cursor empty so reconnects from legacy agents remain a\n // no-op and future capability additions do not get silently fabricated.\n if (!caps) return {};\n return {\n exec: caps.exec === true,\n filesystem: caps.filesystem === true,\n git: caps.git === true,\n pty: caps.pty === true,\n desktop: caps.desktop === true,\n opStream: caps.opStream === true,\n browserBridge: caps.browserBridge === true,\n operationResourcePolicy: caps.operationResourcePolicy === true,\n operationCpuQuota: caps.operationCpuQuota === true,\n transactionalFsWrite: caps.transactionalFsWrite === true,\n credentialRenew: caps.credentialRenew === true,\n screenControl: caps.consentedScreenControl === true,\n ...(caps.macPermissions ? enrollmentMacPermissionCapabilities(caps.macPermissions) : {}),\n };\n}\n\nfunction helloCompletedUpdate(hello: Hello): {\n operationId: string;\n targetVersion: string;\n binarySha256: string;\n} | null {\n if (\n !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(\n hello.completedUpdateOperationId,\n ) ||\n !/^(?:v)?\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/.test(hello.completedUpdateTargetVersion) ||\n !/^[0-9a-f]{64}$/.test(hello.completedUpdateBinarySha256)\n ) {\n return null;\n }\n return {\n operationId: hello.completedUpdateOperationId,\n targetVersion: hello.completedUpdateTargetVersion,\n binarySha256: hello.completedUpdateBinarySha256,\n };\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 runtimeDesktop?: boolean;\n macPermissions?: EnrollmentMacPermissions;\n connectionInstanceId?: string;\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 (input.runtimeDesktop === undefined ||\n enrollment.agentCapabilities?.desktop === input.runtimeDesktop) &&\n (input.macPermissions === undefined ||\n JSON.stringify(enrollmentMacPermissions(enrollment.agentCapabilities)) ===\n JSON.stringify({\n screenRecording: input.macPermissions.screenRecording,\n accessibility: input.macPermissions.accessibility,\n inputMonitoring: input.macPermissions.inputMonitoring,\n }))\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 ...(input.runtimeDesktop !== undefined ? { runtimeDesktop: input.runtimeDesktop } : {}),\n ...(input.macPermissions ? { macPermissions: input.macPermissions } : {}),\n ...(input.connectionInstanceId ? { connectionInstanceId: input.connectionInstanceId } : {}),\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 connectionInstanceId?: string;\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 ...(input.connectionInstanceId ? { connectionInstanceId: input.connectionInstanceId } : {}),\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 const authority = await getLiveEnrollmentConnection(db, ids.workspaceId, ids.agentId).catch(\n () => null,\n );\n if (!authority || authority.connectionInstanceId !== ids.connectionInstanceId) {\n observability?.warn?.(\"Ignored a Hello from a superseded runner instance\", {\n workspaceId: ids.workspaceId,\n agentId: ids.agentId,\n });\n return;\n }\n let workspaceRoot: string | undefined;\n if (hello.workspaceRoot.length > 0) {\n try {\n workspaceRoot = normalizeConnectedMachineWorkspaceRoot(hello.workspaceRoot, authority.os);\n } catch (error) {\n observability?.warn?.(\"Ignored an invalid Connected Machine workspace root\", {\n workspaceId: ids.workspaceId,\n agentId: ids.agentId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n try {\n await refreshEnrollmentDisplay(db, {\n workspaceId: ids.workspaceId,\n agentId: ids.agentId,\n hasDisplay: helloReportsDisplay(hello),\n desktopUnavailableReason: helloDesktopUnavailableReason(hello),\n connectionInstanceId: ids.connectionInstanceId,\n });\n await refreshEnrollmentOpStream(db, {\n workspaceId: ids.workspaceId,\n agentId: ids.agentId,\n opStream: helloReportsOpStream(hello),\n connectionInstanceId: ids.connectionInstanceId,\n });\n await setEnrollmentAgentRuntime(db, {\n accountId: authority.accountId,\n workspaceId: ids.workspaceId,\n enrollmentId: ids.agentId,\n connectionInstanceId: ids.connectionInstanceId,\n agentVersion: hello.agentVersion.trim() || null,\n binarySha256: /^[0-9a-f]{64}$/.test(hello.binarySha256) ? hello.binarySha256 : null,\n updateChannel:\n hello.updateChannel === \"stable\" || hello.updateChannel === \"beta\"\n ? hello.updateChannel\n : null,\n capabilities: helloRuntimeCapabilities(hello),\n ...(workspaceRoot !== undefined ? { workspaceRoot } : {}),\n completedUpdate: helloCompletedUpdate(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 // Screen control allowed while this machine was offline (or before its agent\n // could renew on request) applies now. Detached: it waits for the agent to\n // subscribe and must not hold up Hello ingestion.\n void reconcileScreenControlOnHello(\n { bus, observability },\n {\n authority,\n hello,\n target: {\n workspaceId: ids.workspaceId,\n enrollmentId: ids.agentId,\n connectionInstanceId: ids.connectionInstanceId,\n },\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 { cleared } = await clearEnrollmentWentOffline(db, {\n accountId: authority.accountId,\n workspaceId: ids.workspaceId,\n enrollmentId: ids.agentId,\n connectionInstanceId: ids.connectionInstanceId,\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 } 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 exact process hellos 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","import {\n claimMemorySlackPublication,\n completeMemorySlackPublication,\n currentMemorySlackConfigurationMatches,\n deferMemorySlackPublication,\n failMemorySlackPublication,\n type ClaimedMemorySlackPublication,\n} from \"@opengeni/db\";\nimport { sanitizeSlackPublicationText, type ApiRouteDeps } from \"@opengeni/core\";\nimport {\n createOpenGeniSlackBotInteractionClient,\n SlackBotProviderError,\n} from \"./integrations/slack-bot\";\n\nconst DELIVERY_LEASE_MS = 30_000;\nconst MAX_DELIVERY_ATTEMPTS = 8;\nconst MAX_DELIVERY_RETRY_MS = 5 * 60_000;\nconst MAX_SLACK_MESSAGE_CHARS = 3_500;\n\nexport async function drainMemorySlackPublicationsOnce(deps: ApiRouteDeps): Promise<boolean> {\n const claimHolderId = crypto.randomUUID();\n const publication = await claimMemorySlackPublication(deps.db, claimHolderId, DELIVERY_LEASE_MS);\n if (!publication) return false;\n\n try {\n if (!(await currentMemorySlackConfigurationMatches(deps.db, publication))) {\n await failMemorySlackPublication(deps.db, {\n publication,\n claimHolderId,\n errorCode: \"configuration_changed\",\n cancelled: true,\n });\n return true;\n }\n const client = await createOpenGeniSlackBotInteractionClient(deps, {\n accountId: publication.accountId,\n workspaceId: publication.workspaceId,\n connectionId: publication.connectionId,\n subjectId: publication.initiatorSubjectId,\n sessionId: publication.sessionId,\n });\n const result = await client.postMessage({\n operationId: publication.operationId,\n channelId: publication.slackChannelId,\n text: formatMemorySlackPublicationMessage(deps, publication),\n requireActiveNonSharedChannel: true,\n });\n const completed = await completeMemorySlackPublication(deps.db, {\n publication,\n claimHolderId,\n slackChannelId: result.channelId,\n slackMessageTimestamp: result.timestamp,\n });\n if (!completed) throw new Error(\"Memory Slack publication lost its durable claim\");\n } catch (error) {\n const errorCode = deliveryErrorCode(error);\n if (memorySlackDestinationDrift(error)) {\n await failMemorySlackPublication(deps.db, {\n publication,\n claimHolderId,\n errorCode,\n cancelled: true,\n }).catch(() => undefined);\n } else if (publication.attemptCount >= MAX_DELIVERY_ATTEMPTS || permanentDeliveryError(error)) {\n await failMemorySlackPublication(deps.db, {\n publication,\n claimHolderId,\n errorCode,\n }).catch(() => undefined);\n } else {\n await deferMemorySlackPublication(deps.db, {\n publication,\n claimHolderId,\n errorCode,\n retryAt: new Date(Date.now() + deliveryRetryMs(error, publication.attemptCount)),\n }).catch(() => undefined);\n }\n }\n return true;\n}\n\nexport function startMemorySlackPublicationPump(\n deps: ApiRouteDeps,\n options: { intervalMs?: number; maxPerTick?: number } = {},\n): () => Promise<void> {\n let stopped = false;\n let running: Promise<void> | undefined;\n const intervalMs = Math.max(250, options.intervalMs ?? 1_000);\n const maxPerTick = Math.max(1, Math.min(50, options.maxPerTick ?? 10));\n const tick = () => {\n if (stopped || running) return;\n running = (async () => {\n for (let index = 0; index < maxPerTick; index += 1) {\n if (!(await drainMemorySlackPublicationsOnce(deps))) break;\n }\n })()\n .catch((error) => {\n deps.observability?.error(\"Memory Slack publication claim failed\", {\n errorClass: error instanceof Error ? error.name : \"MemorySlackPublicationPumpError\",\n errorCode: deliveryErrorCode(error),\n origin: \"api\",\n });\n })\n .finally(() => {\n running = undefined;\n });\n };\n const timer = setInterval(tick, intervalMs);\n queueMicrotask(tick);\n return async () => {\n stopped = true;\n clearInterval(timer);\n await running;\n };\n}\n\nexport function formatMemorySlackPublicationMessage(\n deps: Pick<ApiRouteDeps, \"settings\">,\n publication: ClaimedMemorySlackPublication,\n): string {\n const projection = publication.projection;\n const summary = boundedProjectionString(projection[\"summary\"], 512) || \"Important change\";\n const owner = boundedProjectionString(projection[\"ownerLabel\"], 96);\n const occurredAt = boundedProjectionString(projection[\"occurredAt\"], 64);\n const changeKind = boundedProjectionString(projection[\"changeKind\"], 32);\n const destination = boundedProjectionString(projection[\"destination\"], 64);\n const outcome = boundedProjectionString(projection[\"outcome\"], 64);\n const heading =\n publication.sourceType === \"workspace_memory\"\n ? `Workspace Memory ${changeKind || \"change\"}`\n : `Governed learning ${outcome || \"change\"}`;\n const details = [\n `Importance: ${publication.importance}`,\n ...(destination ? [`Surface: ${destination}`] : []),\n ...(owner ? [`Owner: ${owner}`] : []),\n ...(occurredAt ? [`Recorded: ${occurredAt}`] : []),\n ];\n const path =\n publication.sourceType === \"workspace_memory\"\n ? `/workspaces/${publication.workspaceId}/memory?memoryId=${encodeURIComponent(publication.sourceId)}`\n : `/workspaces/${publication.workspaceId}/workspace-state`;\n const base = deps.settings.webBaseUrl ?? deps.settings.publicBaseUrl;\n const link = base ? new URL(path, base).toString() : null;\n const text = `*${heading}*\\n${summary}\\n\\n${details.join(\" · \")}${link ? `\\n${link}` : \"\"}`;\n return text.length <= MAX_SLACK_MESSAGE_CHARS\n ? text\n : `${text.slice(0, MAX_SLACK_MESSAGE_CHARS - 20)}\\n… message truncated`;\n}\n\nconst PERMANENT_DELIVERY_CODES = new Set([\n \"account_inactive\",\n \"channel_not_found\",\n \"invalid_auth\",\n \"is_archived\",\n \"not_authed\",\n \"not_in_channel\",\n \"token_expired\",\n \"token_revoked\",\n]);\n\nconst MEMORY_SLACK_DESTINATION_DRIFT_CODES = new Set([\n \"channel_not_found\",\n \"is_archived\",\n \"not_in_channel\",\n \"slack_connect_unsupported\",\n]);\n\nexport function memorySlackDestinationDrift(error: unknown) {\n return (\n error instanceof SlackBotProviderError && MEMORY_SLACK_DESTINATION_DRIFT_CODES.has(error.code)\n );\n}\n\nfunction permanentDeliveryError(error: unknown) {\n if (!(error instanceof SlackBotProviderError)) return false;\n if (PERMANENT_DELIVERY_CODES.has(error.code)) return true;\n const status = /^http_(\\d{3})$/.exec(error.code)?.[1];\n return status\n ? Number(status) >= 400 && Number(status) < 500 && status !== \"408\" && status !== \"429\"\n : false;\n}\n\nfunction deliveryRetryMs(error: unknown, attemptCount: number) {\n if (error instanceof SlackBotProviderError && error.retryAfterMs) {\n return Math.min(Math.max(error.retryAfterMs, 1_000), MAX_DELIVERY_RETRY_MS);\n }\n return Math.min(1_000 * 2 ** Math.max(0, attemptCount - 1), MAX_DELIVERY_RETRY_MS);\n}\n\nfunction deliveryErrorCode(error: unknown) {\n if (error instanceof SlackBotProviderError) return error.code.slice(0, 128);\n const raw = error instanceof Error ? error.name : \"memory_slack_delivery_error\";\n return (\n raw\n .toLowerCase()\n .replace(/[^a-z0-9_-]/g, \"_\")\n .slice(0, 128) || \"error\"\n );\n}\n\nfunction boundedProjectionString(value: unknown, maxChars: number) {\n return typeof value === \"string\"\n ? escapeSlackText(sanitizeSlackPublicationText(value).slice(0, maxChars))\n : \"\";\n}\n\nfunction escapeSlackText(value: string) {\n return value.replaceAll(\"&\", \"&amp;\").replaceAll(\"<\", \"&lt;\").replaceAll(\">\", \"&gt;\");\n}\n","import {\n acknowledgeScheduledTaskScheduleReconciliation,\n deferScheduledTaskScheduleReconciliation,\n listExhaustedScheduledTasks,\n listScheduledTaskScheduleReconciliations,\n retireExhaustedScheduledTask,\n type Database,\n} from \"@opengeni/db\";\nimport type { ScheduledTask } from \"@opengeni/contracts\";\nimport type { EventBus } from \"@opengeni/events\";\nimport type { Observability } from \"@opengeni/observability\";\nimport { reviewScheduledTaskBlockerInventory } from \"./scheduled-task-blockers\";\n\ntype Dependencies = {\n db: Database;\n sync(task: Pick<ScheduledTask, \"id\" | \"workspaceId\" | \"temporalScheduleId\">): Promise<void>;\n /** Enables blocked-schedule review: self-pause and the owner notice it posts. */\n bus?: EventBus;\n observability?: Pick<Observability, \"error\">;\n};\n\nexport async function reconcileExhaustedScheduledTasks(deps: Dependencies): Promise<void> {\n for (const candidate of await listExhaustedScheduledTasks(deps.db)) {\n await retireExhaustedScheduledTask(deps.db, candidate.workspace_id, candidate.id);\n }\n // Before Temporal reconciliation, so a schedule that paused itself stops\n // firing in the same pass.\n if (deps.bus) {\n await reviewScheduledTaskBlockerInventory({\n db: deps.db,\n bus: deps.bus,\n observability: deps.observability,\n });\n }\n for (const pending of await listScheduledTaskScheduleReconciliations(deps.db)) {\n try {\n // The synchronizer takes the shared external-write lock and rereads the\n // current task, including edits/deletion committed since retirement.\n await deps.sync({\n id: pending.task_id,\n workspaceId: pending.workspace_id,\n temporalScheduleId: pending.temporal_schedule_id,\n });\n await acknowledgeScheduledTaskScheduleReconciliation(\n deps.db,\n pending.workspace_id,\n pending.id,\n );\n } catch (error) {\n await deferScheduledTaskScheduleReconciliation(deps.db, pending.workspace_id, pending.id);\n deps.observability?.error(\"Exhausted schedule reconciliation will retry\", {\n taskId: pending.task_id,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n}\n\nexport function startScheduledTaskLifecyclePump(\n deps: Dependencies,\n intervalMs = 30_000,\n): () => Promise<void> {\n let stopped = false;\n let running: Promise<void> | undefined;\n const tick = () => {\n if (stopped || running) return;\n running = reconcileExhaustedScheduledTasks(deps)\n .catch((error: unknown) => {\n deps.observability?.error(\"Exhausted schedule inventory failed\", {\n error: error instanceof Error ? error.message : String(error),\n });\n })\n .finally(() => {\n running = undefined;\n });\n };\n const timer = setInterval(tick, intervalMs);\n queueMicrotask(tick);\n return async () => {\n stopped = true;\n clearInterval(timer);\n await running;\n };\n}\n","import {\n NOTIFICATION_SUBTITLE_MAX_CHARS,\n SessionNotificationPostedPayload,\n SessionNotificationWithdrawnPayload,\n} from \"@opengeni/contracts\";\nimport {\n getPendingScheduledTaskBlockerNotice,\n listScheduledTaskBlockerReviews,\n reviewScheduledTaskBlockers,\n settleScheduledTaskBlockerNotice,\n type Database,\n type ScheduledTaskBlockerDecision,\n type ScheduledTaskBlockerFacts,\n type ScheduledTaskBlockerRun,\n} from \"@opengeni/db\";\nimport { appendAndPublishEvents, type EventBus } from \"@opengeni/events\";\nimport type { Observability } from \"@opengeni/observability\";\n\n/**\n * A schedule must never stay stuck without its owner knowing. After each\n * settled scheduled run:\n *\n * - When the platform knows no later run can start until a person acts (its\n * chat is paused or gone, a pinned account or other resource it needs is\n * unavailable, or it was refused as non-retryable), the schedule pauses\n * itself with that reason and its owner is told once.\n * - When runs keep failing or being skipped for a reason that may clear by\n * itself, the owner is told once, after {@link SCHEDULED_TASK_BLOCKER_STREAK}\n * in a row; the schedule keeps running. A single skip or failure is normal.\n *\n * The notice is withdrawn when a later run succeeds or a person resumes,\n * pauses or deletes the schedule. Only scheduled (not manual) runs count, and\n * only runs since the schedule was last edited or resumed.\n */\nexport const SCHEDULED_TASK_BLOCKER_STREAK = 3;\n\nconst SETTLED = new Set([\"succeeded\", \"failed\", \"skipped\"]);\n\ntype Blocker = { reason: string; text: string };\n\nconst RESUME = \"then resume the schedule.\";\n\nconst NON_RETRYABLE_REFUSAL_TEXT: Record<string, string> = {\n scheduled_authority_unavailable: `The access it was set up with is no longer valid. Refresh the schedule's access, ${RESUME}`,\n machine_target_unavailable: `The machine it runs on is no longer available. Choose another machine or reconnect this one, ${RESUME}`,\n machine_enrollment_inactive: `The machine it runs on is disconnected from Opengeni. Reconnect the machine, ${RESUME}`,\n variable_set_unavailable: `A variable set it uses no longer exists or can't be used. Edit the schedule, ${RESUME}`,\n rig_version_unavailable: `Its rig has no usable version. Publish a rig version or edit the schedule, ${RESUME}`,\n scheduled_model_unavailable: `Its model is no longer available. Edit the schedule to choose another model, ${RESUME}`,\n};\n\nconst RETRYABLE_REFUSAL_TEXT: Record<string, string> = {\n machine_enrollment_inactive: \"the machine it runs on is disconnected\",\n insufficient_credits: \"the workspace is out of credits\",\n allowance_exhausted: \"the usage allowance is used up\",\n monthly_model_cost_limit: \"the monthly model cost limit was reached\",\n monthly_agent_run_limit: \"the monthly run limit was reached\",\n session_usage_limit: \"the schedule reached its usage limit\",\n};\n\n/** A blocker no later run can get past until a person acts, or null. */\nexport function scheduledRunHardBlocker(\n task: Pick<ScheduledTaskBlockerFacts[\"task\"], \"runMode\">,\n run: ScheduledTaskBlockerRun,\n): Blocker | null {\n if (run.admissionDiagnostic) {\n return {\n reason: \"connection_account_unavailable\",\n text: `A connected account it needs can no longer be used. Reconnect that account or refresh the schedule's access, ${RESUME}`,\n };\n }\n if (run.admissionRefusal && !run.admissionRefusal.retryable) {\n const reason = run.admissionRefusal.reason;\n return {\n reason,\n text:\n NON_RETRYABLE_REFUSAL_TEXT[reason] ??\n `Every run is refused before it starts (${reason}). Fix that, ${RESUME}`,\n };\n }\n switch (run.error) {\n case \"scheduled_session_paused\":\n return {\n reason: run.error,\n text: `Its chat is paused, so no run can start there. Resume the chat, ${RESUME}`,\n };\n case \"session_cancelled\":\n // A run that starts a new chat each time is not blocked by one ended chat.\n return task.runMode === \"new_session_per_run\"\n ? null\n : {\n reason: run.error,\n text: `The chat it runs in has ended, so no run can start there. Point the schedule at another chat or let it start a new chat each run, ${RESUME}`,\n };\n case \"scheduled_target_session_unavailable\":\n return {\n reason: run.error,\n text: `The chat it runs in no longer exists. Point the schedule at another chat or let it start a new chat each run, ${RESUME}`,\n };\n case \"scheduled_model_unavailable\":\n return { reason: run.error, text: NON_RETRYABLE_REFUSAL_TEXT.scheduled_model_unavailable! };\n default:\n return null;\n }\n}\n\nfunction streakBlocker(streak: readonly ScheduledTaskBlockerRun[]): Blocker {\n const count = streak.length;\n if (streak.every((run) => run.error === \"scheduled_session_not_idle\")) {\n return {\n reason: \"scheduled_session_not_idle\",\n text: `The last ${count} scheduled runs were skipped because its chat was still busy with earlier work. Check whether that chat is stuck. The schedule keeps trying.`,\n };\n }\n const refusal = streak[0]?.admissionRefusal;\n if (\n refusal?.retryable &&\n streak.every(\n (run) => run.admissionRefusal?.retryable && run.admissionRefusal.reason === refusal.reason,\n )\n ) {\n return {\n reason: refusal.reason,\n text: `The last ${count} scheduled runs were skipped because ${\n RETRYABLE_REFUSAL_TEXT[refusal.reason] ?? `they were refused (${refusal.reason})`\n }. Runs start again once that clears.`,\n };\n }\n const latest = streak[0]!;\n return {\n reason: latest.error ?? latest.status,\n text: `The last ${count} scheduled runs failed or were skipped. Open the latest run to see why. The schedule keeps trying.`,\n };\n}\n\nexport function scheduledTaskBlockerNoticeKey(taskId: string): string {\n return `schedule-${taskId}`;\n}\n\nfunction clip(text: string, max: number): string {\n return text.length <= max ? text : `${text.slice(0, max - 1).trimEnd()}…`;\n}\n\nfunction notice(\n facts: ScheduledTaskBlockerFacts,\n run: ScheduledTaskBlockerRun,\n state: \"notified\" | \"paused\",\n blocker: Blocker,\n): Extract<ScheduledTaskBlockerDecision, { kind: \"block\" }>[\"notice\"] {\n // The chat the owner opens from the notice: the blocked run's own, else the\n // chat the schedule runs in, else the most recent run's.\n const sessionId =\n run.sessionId ??\n facts.task.reusableSessionId ??\n facts.runs.find((candidate) => candidate.sessionId !== null)?.sessionId ??\n null;\n if (!sessionId) return null;\n const key = scheduledTaskBlockerNoticeKey(facts.task.id);\n const payload = SessionNotificationPostedPayload.parse({\n key,\n title: state === \"paused\" ? \"Schedule paused itself\" : \"Schedule needs attention\",\n subtitle: clip(facts.task.name.trim() || \"Scheduled task\", NOTIFICATION_SUBTITLE_MAX_CHARS),\n body:\n state === \"paused\"\n ? `${blocker.text} It stays paused until someone resumes it.`\n : blocker.text,\n urgency: \"normal\",\n replaced: false,\n });\n return { sessionId, key, payload };\n}\n\n/** The pure review of one schedule's newest settled scheduled run. */\nexport function decideScheduledTaskBlocker(\n facts: ScheduledTaskBlockerFacts,\n): ScheduledTaskBlockerDecision {\n const { task, review, runs } = facts;\n const blocked = review !== null && review.state !== \"clear\";\n // A person acted: resumed a self-paused schedule, or paused or deleted one\n // they were told about. Keep the reviewed run; a new one is reviewed next.\n if (task.deleted) return blocked ? { kind: \"clear\", reviewedRunId: null } : none(null);\n if (review?.state === \"paused\" && task.status === \"active\") {\n return { kind: \"clear\", reviewedRunId: null };\n }\n if (review?.state === \"notified\" && task.status !== \"active\") {\n return { kind: \"clear\", reviewedRunId: null };\n }\n if (task.status !== \"active\") return none(null);\n const latest = runs[0];\n if (!latest || !SETTLED.has(latest.status) || latest.id === review?.reviewedRunId) {\n return none(null);\n }\n if (latest.status === \"succeeded\") {\n return review?.state === \"notified\"\n ? { kind: \"clear\", reviewedRunId: latest.id }\n : none(latest.id);\n }\n // Runs before the last edit or resume say nothing about the schedule now.\n const current = (run: ScheduledTaskBlockerRun) => run.createdAt >= task.updatedAt;\n const hard = current(latest) ? scheduledRunHardBlocker(task, latest) : null;\n if (hard) {\n return {\n kind: \"block\",\n state: \"paused\",\n reason: hard.reason,\n message: hard.text,\n blockedRunId: latest.id,\n blockedSince: latest.createdAt,\n reviewedRunId: latest.id,\n notice: notice(facts, latest, \"paused\", hard),\n };\n }\n if (review?.state === \"notified\") return none(latest.id);\n const streak: ScheduledTaskBlockerRun[] = [];\n for (const run of runs) {\n if (!SETTLED.has(run.status) || run.status === \"succeeded\" || !current(run)) break;\n streak.push(run);\n }\n if (streak.length < SCHEDULED_TASK_BLOCKER_STREAK) return none(latest.id);\n const soft = streakBlocker(streak);\n const first = streak.at(-1)!;\n return {\n kind: \"block\",\n state: \"notified\",\n reason: soft.reason,\n message: soft.text,\n blockedRunId: first.id,\n blockedSince: first.createdAt,\n reviewedRunId: latest.id,\n notice: notice(facts, latest, \"notified\", soft),\n };\n}\n\nfunction none(reviewedRunId: string | null): ScheduledTaskBlockerDecision {\n return { kind: \"none\", reviewedRunId };\n}\n\ntype Dependencies = {\n db: Database;\n bus: EventBus;\n observability?: Pick<Observability, \"error\"> | undefined;\n};\n\nfunction sessionMissing(error: unknown): boolean {\n return error instanceof Error && /^Session not found: /u.test(error.message);\n}\n\n/** Post or withdraw the owner notice a review left pending. */\nexport async function deliverScheduledTaskBlockerNotice(\n deps: Dependencies,\n workspaceId: string,\n taskId: string,\n): Promise<void> {\n const pending = await getPendingScheduledTaskBlockerNotice(deps.db, workspaceId, taskId);\n if (!pending) return;\n try {\n await appendAndPublishEvents(deps.db, deps.bus, workspaceId, pending.sessionId, [\n pending.pending === \"post\"\n ? {\n type: \"session.notification.posted\",\n payload: SessionNotificationPostedPayload.parse(pending.payload),\n }\n : {\n type: \"session.notification.withdrawn\",\n payload: SessionNotificationWithdrawnPayload.parse({ key: pending.key }),\n },\n ] as Parameters<typeof appendAndPublishEvents>[4]);\n } catch (error) {\n // A deleted chat cannot carry the notice; the schedule page still shows why.\n if (!sessionMissing(error)) throw error;\n }\n await settleScheduledTaskBlockerNotice(deps.db, workspaceId, taskId, pending);\n}\n\n/** One bounded pass over schedules with a run to review or a notice to deliver. */\nexport async function reviewScheduledTaskBlockerInventory(deps: Dependencies): Promise<void> {\n for (const candidate of await listScheduledTaskBlockerReviews(deps.db)) {\n try {\n await reviewScheduledTaskBlockers(\n deps.db,\n candidate.workspace_id,\n candidate.id,\n decideScheduledTaskBlocker,\n );\n await deliverScheduledTaskBlockerNotice(deps, candidate.workspace_id, candidate.id);\n } catch (error) {\n deps.observability?.error(\"Scheduled task blocker review will retry\", {\n taskId: candidate.id,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n}\n","import type { ScheduledTask } from \"@opengeni/contracts\";\nimport { getScheduledTaskIncludingDeleted, type Database } from \"@opengeni/db\";\nimport { sql } from \"drizzle-orm\";\n\nconst LOCK_TIMEOUT = \"5s\";\nconst WRITE_TIMEOUT_MS = 5_000;\n\ntype TemporalScheduleSyncDependencies = {\n db: Database;\n withDeadline<T>(deadline: number, work: () => Promise<T>): Promise<T>;\n upsert(task: ScheduledTask): Promise<void>;\n /** Idempotent: an absent Temporal schedule is already removed. */\n remove(temporalScheduleId: string): Promise<void>;\n};\n\n/**\n * Serialize external writes across API replicas, independently of task edits.\n * A queued sync rereads the newest committed row after acquiring this lock;\n * input snapshots never become desired state. Cleanup uses the same key, so\n * an in-flight upsert finishes before its tombstone's external deletion.\n * Failure compensation commits before releasing the lock, so a queued writer\n * cannot read the row being restored and then publish that failed edit.\n *\n * Deadlines bound both lock admission and network occupancy. A thrown network\n * error retains its unknown-outcome semantics; this is not durable recovery\n * for a process crash or a lost Temporal acknowledgement.\n */\nexport function createTemporalScheduleSynchronizer(deps: TemporalScheduleSyncDependencies) {\n const write = async <T>(\n temporalScheduleId: string,\n work: (tx: Database) => Promise<T>,\n ): Promise<T> =>\n deps.db.transaction(async (tx) => {\n await tx.execute(sql`select set_config('lock_timeout', ${LOCK_TIMEOUT}, true)`);\n await tx.execute(sql`select pg_advisory_xact_lock(\n hashtextextended(${`scheduled-task-temporal:${temporalScheduleId}`}, 0)\n )`);\n return await work(tx);\n });\n\n return {\n async sync(\n task: Pick<ScheduledTask, \"id\" | \"workspaceId\" | \"temporalScheduleId\">,\n onFailure?: (tx: Database, error: unknown) => Promise<Error>,\n ) {\n const result = await write(task.temporalScheduleId, async (tx) => {\n try {\n await deps.withDeadline(Date.now() + WRITE_TIMEOUT_MS, async () => {\n const current = await getScheduledTaskIncludingDeleted(tx, task.workspaceId, task.id);\n if (current && current.temporalScheduleId !== task.temporalScheduleId)\n throw new Error(\"Scheduled task Temporal identity changed\");\n if (!current || current.deletedAt !== null || current.schedule.type === \"manual\") {\n await deps.remove(task.temporalScheduleId);\n return;\n }\n const { deletedAt: _deletedAt, ...latest } = current;\n await deps.upsert(latest);\n });\n return { ok: true as const };\n } catch (error) {\n return { ok: false as const, error: onFailure ? await onFailure(tx, error) : error };\n }\n });\n // Throw after commit: throwing inside the transaction would also undo a\n // successful compensation. A failed commit cannot claim that receipt.\n if (!result.ok) throw result.error;\n },\n async remove(temporalScheduleId: string) {\n await write(temporalScheduleId, async () =>\n deps.withDeadline(Date.now() + WRITE_TIMEOUT_MS, () => deps.remove(temporalScheduleId)),\n );\n },\n };\n}\n","import { createSign, randomUUID } from \"node:crypto\";\nimport { connect, type ClientHttp2Session } from \"node:http2\";\nimport type { Settings } from \"@opengeni/config\";\nimport {\n claimNativePushDeliveries,\n listSessionHumanInputRequests,\n pruneNativePushDeliveries,\n settleNativePushDelivery,\n type ClaimedNativePushDelivery,\n type Database,\n type NativePushOutcome,\n} from \"@opengeni/db\";\nimport type { Observability } from \"@opengeni/observability\";\n\n// Sends queued native app pushes (0638) through APNs (token auth over HTTP/2)\n// and FCM HTTP v1. At-least-once: a delivery is settled only after the\n// provider answered; an unknown token removes the registration.\n\nconst POLL_INTERVAL_MS = 1_000;\nconst CLAIM_SECONDS = 60;\nconst MAX_ATTEMPTS = 6;\nconst PRUNE_EVERY_TICKS = 600;\n\nexport type NativePushSendResult = { outcome: NativePushOutcome; error?: string };\n\nexport type NativePushSender = (\n delivery: ClaimedNativePushDelivery,\n) => Promise<NativePushSendResult>;\n\n/** A claimed payload, marked when its question asks for a secret. */\nexport type NativePushPayload = ClaimedNativePushDelivery[\"payload\"] & { secretQuestion?: boolean };\n\nconst SECRET_QUESTION_PUSH_BODY = \"Open Opengeni to answer. The answer is saved to a vault.\";\n\n/**\n * Mark question pushes whose pending request asks for a secret, so they carry\n * no inline answer action and point to the app instead.\n */\nasync function markSecretQuestionDeliveries(\n db: Database,\n deliveries: ClaimedNativePushDelivery[],\n): Promise<ClaimedNativePushDelivery[]> {\n const secretSessions = new Map<string, Promise<boolean>>();\n return await Promise.all(\n deliveries.map(async (delivery) => {\n if (delivery.payload.eventType !== \"session.humanInput.requested\") return delivery;\n const key = `${delivery.payload.workspaceId}:${delivery.payload.sessionId}`;\n let lookup = secretSessions.get(key);\n if (!lookup) {\n lookup = listSessionHumanInputRequests(\n db,\n delivery.payload.workspaceId,\n delivery.payload.sessionId,\n { status: \"pending\", limit: 20 },\n )\n .then((requests) =>\n requests.some((request) =>\n request.questions.some((question) => question.kind === \"secret\"),\n ),\n )\n .catch(() => false);\n secretSessions.set(key, lookup);\n }\n if (!(await lookup)) return delivery;\n const payload: NativePushPayload = { ...delivery.payload, secretQuestion: true };\n return { ...delivery, payload };\n }),\n );\n}\n\nexport type NativePushDispatchDeps = {\n db: Database;\n settings: Settings;\n observability?: Pick<Observability, \"info\" | \"warn\" | \"error\">;\n senders?: Partial<Record<\"ios\" | \"android\", NativePushSender>>;\n};\n\n/**\n * A notification message as plain text for the lock screen: links keep their\n * text, emphasis and code marks go, and \"- \" bullets become \"•\".\n */\nexport function plainNotificationText(markdown: string): string {\n return markdown\n .replace(/\\[([^\\]]+)\\]\\((?:[^)]+)\\)/gu, \"$1\")\n .replace(/(\\*\\*|__)(.+?)\\1/gu, \"$2\")\n .replace(/`([^`]+)`/gu, \"$1\")\n .replace(/^[ \\t]*[-*][ \\t]+/gmu, \"• \")\n .replace(/\\n{3,}/gu, \"\\n\\n\")\n .trim();\n}\n\n/** The visible text of a push: title, optional subtitle, and the message with its facts. */\nexport function nativePushAlert(payload: NativePushPayload): {\n title: string;\n subtitle?: string;\n body?: string;\n} {\n if (payload.secretQuestion) {\n // A secret is answered only in the app's secure card (AC-5): no inline reply.\n return { title: payload.title ?? \"The agent needs a secret\", body: SECRET_QUESTION_PUSH_BODY };\n }\n const fallback =\n payload.rule === \"needs_input\"\n ? \"The agent needs you\"\n : payload.rule === \"failed\"\n ? \"A turn failed\"\n : payload.rule === \"reply_ready\"\n ? \"Reply ready\"\n : \"Opengeni\";\n const facts = (payload.facts ?? [])\n .slice(0, 4)\n .map((fact) => `${fact.label}: ${fact.value}`)\n .join(\"\\n\");\n const message = payload.body ? plainNotificationText(payload.body) : \"\";\n // A notification with no message of its own carries its title as the body;\n // show the title once.\n const lines = [message === payload.title ? \"\" : message, facts].filter(Boolean);\n const body = lines.join(\"\\n\\n\");\n return {\n title: payload.title ?? fallback,\n ...(payload.subtitle ? { subtitle: payload.subtitle } : {}),\n ...(body || payload.rule !== \"agent\" ? { body: body || fallback } : {}),\n };\n}\n\n/**\n * What breaks through Focus: an agent notification the agent marked\n * time-sensitive, and questions and approvals for a person who asked for them\n * to (their setting puts the urgency on the delivery). Everything else, and\n * replies and failures always, arrive as ordinary alerts, so Focus and the\n * person's own notification settings decide when they show.\n */\nexport function nativePushInterruptionLevel(\n payload: ClaimedNativePushDelivery[\"payload\"],\n): \"time-sensitive\" | \"active\" {\n if (\n (payload.rule === \"agent\" || payload.rule === \"needs_input\") &&\n payload.urgency === \"time_sensitive\"\n ) {\n return \"time-sensitive\";\n }\n return \"active\";\n}\n\n/** What the app reads on tap: enough to open the session in the right account. */\nexport function nativePushData(payload: ClaimedNativePushDelivery[\"payload\"]) {\n return {\n sessionId: payload.sessionId,\n workspaceId: payload.workspaceId,\n subjectId: payload.subjectId,\n rule: payload.rule,\n ...(payload.eventType ? { eventType: payload.eventType } : {}),\n ...(payload.sequence ? { sequence: payload.sequence } : {}),\n };\n}\n\n/**\n * The notification category the app registers actions for: an approval can be\n * approved (behind device unlock) or denied, a question answered inline.\n */\nexport function nativePushCategory(\n payload: NativePushPayload,\n): \"og.approval\" | \"og.question\" | undefined {\n if (payload.secretQuestion) return undefined;\n if (payload.eventType === \"session.requiresAction\") return \"og.approval\";\n if (payload.eventType === \"session.humanInput.requested\") return \"og.question\";\n return undefined;\n}\n\nfunction base64Url(input: Buffer | string): string {\n return Buffer.from(input).toString(\"base64url\");\n}\n\nfunction signJwt(\n header: Record<string, string>,\n claims: Record<string, unknown>,\n privateKey: string,\n algorithm: \"ES256\" | \"RS256\",\n): string {\n const unsigned = `${base64Url(JSON.stringify(header))}.${base64Url(JSON.stringify(claims))}`;\n const signer = createSign(\"SHA256\");\n signer.update(unsigned);\n const signature =\n algorithm === \"ES256\"\n ? signer.sign({ key: privateKey, dsaEncoding: \"ieee-p1363\" })\n : signer.sign(privateKey);\n return `${unsigned}.${base64Url(signature)}`;\n}\n\nfunction pem(value: string): string {\n return value.includes(\"\\\\n\") ? value.replace(/\\\\n/gu, \"\\n\") : value;\n}\n\n/** APNs with a token-based (.p8) key; one HTTP/2 connection per environment. */\nexport function createApnsSender(input: {\n keyId: string;\n teamId: string;\n privateKey: string;\n}): NativePushSender {\n const key = pem(input.privateKey);\n let token: { value: string; issuedAt: number } | null = null;\n const sessions = new Map<string, ClientHttp2Session>();\n const bearer = () => {\n const now = Math.floor(Date.now() / 1000);\n // Apple accepts a provider token for an hour and rejects refreshes more\n // often than every 20 minutes.\n if (!token || now - token.issuedAt > 40 * 60) {\n token = {\n value: signJwt(\n { alg: \"ES256\", kid: input.keyId },\n { iss: input.teamId, iat: now },\n key,\n \"ES256\",\n ),\n issuedAt: now,\n };\n }\n return token.value;\n };\n const session = (host: string) => {\n const existing = sessions.get(host);\n if (existing && !existing.closed && !existing.destroyed) return existing;\n const created = connect(`https://${host}`);\n created.on(\"error\", () => sessions.delete(host));\n created.on(\"close\", () => sessions.delete(host));\n sessions.set(host, created);\n return created;\n };\n return async (delivery) => {\n const host =\n delivery.environment === \"development\" ? \"api.sandbox.push.apple.com\" : \"api.push.apple.com\";\n const alert = nativePushAlert(delivery.payload);\n const category = nativePushCategory(delivery.payload);\n const body = JSON.stringify({\n aps: {\n alert,\n sound: \"default\",\n \"thread-id\": delivery.payload.sessionId,\n \"interruption-level\": nativePushInterruptionLevel(delivery.payload),\n ...(category ? { category } : {}),\n },\n body: nativePushData(delivery.payload),\n });\n return await new Promise<NativePushSendResult>((resolve) => {\n const request = session(host).request({\n \":method\": \"POST\",\n \":path\": `/3/device/${delivery.token}`,\n authorization: `bearer ${bearer()}`,\n \"apns-topic\": delivery.appId,\n \"apns-push-type\": \"alert\",\n \"apns-priority\": \"10\",\n \"apns-collapse-id\": `${delivery.payload.sessionId}:${delivery.payload.rule}`.slice(0, 64),\n \"content-type\": \"application/json\",\n });\n let status = 0;\n let text = \"\";\n request.setTimeout(10_000, () => request.close());\n request.on(\"response\", (headers) => {\n status = Number(headers[\":status\"] ?? 0);\n });\n request.on(\"data\", (chunk: Buffer) => {\n text += chunk.toString(\"utf8\");\n });\n request.on(\"error\", (error) => resolve({ outcome: \"retry\", error: String(error) }));\n request.on(\"close\", () => {\n if (status === 200) return resolve({ outcome: \"delivered\" });\n const reason = (() => {\n try {\n return (JSON.parse(text) as { reason?: string }).reason ?? text;\n } catch {\n return text || `status ${status}`;\n }\n })();\n if (status === 410 || reason === \"BadDeviceToken\" || reason === \"Unregistered\") {\n return resolve({ outcome: \"unregistered\", error: `${status} ${reason}` });\n }\n resolve({\n outcome: status === 429 || status >= 500 || status === 0 ? \"retry\" : \"failed\",\n error: `${status} ${reason}`,\n });\n });\n request.end(body);\n });\n };\n}\n\n/** FCM HTTP v1 with a service account; data-only, so the app presents it. */\nexport function createFcmSender(input: {\n serviceAccountJson: string;\n fetch?: typeof fetch;\n}): NativePushSender {\n const account = JSON.parse(input.serviceAccountJson) as {\n project_id: string;\n client_email: string;\n private_key: string;\n token_uri?: string;\n };\n const http = input.fetch ?? fetch;\n let access: { token: string; expiresAt: number } | null = null;\n const accessToken = async () => {\n if (access && access.expiresAt - 60_000 > Date.now()) return access.token;\n const now = Math.floor(Date.now() / 1000);\n const tokenUri = account.token_uri ?? \"https://oauth2.googleapis.com/token\";\n const assertion = signJwt(\n { alg: \"RS256\", typ: \"JWT\" },\n {\n iss: account.client_email,\n scope: \"https://www.googleapis.com/auth/firebase.messaging\",\n aud: tokenUri,\n iat: now,\n exp: now + 3600,\n },\n pem(account.private_key),\n \"RS256\",\n );\n const response = await http(tokenUri, {\n method: \"POST\",\n headers: { \"content-type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grant_type: \"urn:ietf:params:oauth:grant-type:jwt-bearer\",\n assertion,\n }),\n });\n if (!response.ok) throw new Error(`FCM token exchange failed: ${response.status}`);\n const json = (await response.json()) as { access_token: string; expires_in: number };\n access = { token: json.access_token, expiresAt: Date.now() + json.expires_in * 1000 };\n return access.token;\n };\n return async (delivery) => {\n try {\n const alert = nativePushAlert(delivery.payload);\n const response = await http(\n `https://fcm.googleapis.com/v1/projects/${account.project_id}/messages:send`,\n {\n method: \"POST\",\n headers: {\n authorization: `Bearer ${await accessToken()}`,\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n message: {\n token: delivery.token,\n android: { priority: \"HIGH\", collapse_key: delivery.payload.sessionId },\n data: {\n title: alert.title,\n message: [alert.subtitle, alert.body].filter(Boolean).join(\"\\n\") || alert.title,\n body: JSON.stringify(nativePushData(delivery.payload)),\n },\n },\n }),\n signal: AbortSignal.timeout(10_000),\n },\n );\n if (response.ok) return { outcome: \"delivered\" };\n const text = await response.text();\n if (response.status === 404 || text.includes(\"UNREGISTERED\")) {\n return { outcome: \"unregistered\", error: `${response.status} ${text.slice(0, 200)}` };\n }\n return {\n outcome: response.status === 429 || response.status >= 500 ? \"retry\" : \"failed\",\n error: `${response.status} ${text.slice(0, 200)}`,\n };\n } catch (error) {\n return { outcome: \"retry\", error: String(error).slice(0, 300) };\n }\n };\n}\n\n/** The senders this deployment has credentials for. */\nexport function configuredNativePushSenders(\n settings: Settings,\n): Partial<Record<\"ios\" | \"android\", NativePushSender>> {\n const senders: Partial<Record<\"ios\" | \"android\", NativePushSender>> = {};\n if (settings.apnsKeyId && settings.apnsTeamId && settings.apnsPrivateKey) {\n senders.ios = createApnsSender({\n keyId: settings.apnsKeyId,\n teamId: settings.apnsTeamId,\n privateKey: settings.apnsPrivateKey,\n });\n }\n if (settings.fcmServiceAccountJson) {\n senders.android = createFcmSender({ serviceAccountJson: settings.fcmServiceAccountJson });\n }\n return senders;\n}\n\nexport async function drainNativePushDeliveries(\n deps: NativePushDispatchDeps,\n): Promise<{ claimed: number; delivered: number }> {\n const senders = deps.senders ?? configuredNativePushSenders(deps.settings);\n const claimId = randomUUID();\n const claimed = await markSecretQuestionDeliveries(\n deps.db,\n await claimNativePushDeliveries(deps.db, {\n claimId,\n limit: 32,\n claimSeconds: CLAIM_SECONDS,\n }),\n );\n let delivered = 0;\n await Promise.all(\n claimed.map(async (delivery) => {\n const sender = senders[delivery.platform];\n const result: NativePushSendResult = sender\n ? await sender(delivery).catch((error: unknown) => ({\n outcome: \"retry\" as const,\n error: String(error),\n }))\n : { outcome: \"failed\", error: `No ${delivery.platform} push credentials configured` };\n const outcome =\n result.outcome === \"retry\" && delivery.attempts >= MAX_ATTEMPTS ? \"failed\" : result.outcome;\n if (outcome === \"delivered\") delivered += 1;\n else\n deps.observability?.warn(\"Native push not delivered\", {\n platform: delivery.platform,\n outcome,\n error: result.error,\n });\n await settleNativePushDelivery(deps.db, {\n claimId,\n deliveryId: delivery.deliveryId,\n outcome,\n error: result.error ?? null,\n retrySeconds: Math.min(3600, 5 * 2 ** delivery.attempts),\n });\n }),\n );\n return { claimed: claimed.length, delivered };\n}\n\nexport function startNativePushDispatchPump(deps: NativePushDispatchDeps): () => Promise<void> {\n const senders = deps.senders ?? configuredNativePushSenders(deps.settings);\n let stopped = false;\n let ticks = 0;\n let running: Promise<void> | null = null;\n const tick = async () => {\n ticks += 1;\n try {\n const { claimed } = await drainNativePushDeliveries({ ...deps, senders });\n if (claimed > 0) deps.observability?.info(\"Native push batch\", { claimed });\n if (ticks % PRUNE_EVERY_TICKS === 0) await pruneNativePushDeliveries(deps.db);\n } catch (error) {\n deps.observability?.error(\"Native push dispatch failed\", { error: String(error) });\n }\n };\n const timer = setInterval(() => {\n if (stopped || running) return;\n running = tick().finally(() => {\n running = null;\n });\n }, POLL_INTERVAL_MS);\n return async () => {\n stopped = true;\n clearInterval(timer);\n await running;\n };\n}\n","import { randomUUID } from \"node:crypto\";\nimport { environmentsEncryptionKeyBytes, type Settings } from \"@opengeni/config\";\nimport {\n OPENGENI_DELIVERY_ID_HEADER,\n OPENGENI_EVENT_ID_HEADER,\n OPENGENI_SIGNATURE_HEADER,\n signOpenGeniPayload,\n} from \"@opengeni/contracts\";\nimport {\n claimWorkspaceWebhookDeliveries,\n claimOrganizationWebhookDeliveries,\n decryptEnvironmentValue,\n maintainSessionUsageLimits,\n maintainWorkspaceAllowances,\n pruneOrganizationWebhookDeliveries,\n pruneWorkspaceWebhookDeliveries,\n settleOrganizationWebhookDelivery,\n settleWorkspaceWebhookDelivery,\n type ClaimedWorkspaceWebhookDelivery,\n type Database,\n} from \"@opengeni/db\";\nimport { pinnedFetch } from \"@opengeni/network\";\nimport type { Observability } from \"@opengeni/observability\";\nimport { recordSessionUsageLimitEvent } from \"@opengeni/core\";\n\nexport const WORKSPACE_WEBHOOK_DISPATCH_BATCH_SIZE = 32;\nconst CLAIM_SECONDS = 60;\nconst POLL_INTERVAL_MS = 2_000;\nconst DELIVERY_TIMEOUT_MS = 10_000;\nconst PRUNE_EVERY_TICKS = 300;\n\nexport type WorkspaceWebhookDispatchDeps = {\n db: Database;\n settings: Settings;\n observability?: Pick<Observability, \"info\" | \"warn\" | \"error\"> &\n Partial<Pick<Observability, \"incrementCounter\">>;\n fetch?: typeof pinnedFetch;\n};\n\nexport type WorkspaceWebhookBatchResult = { claimed: number; delivered: number; failed: number };\n\nfunction errorText(error: unknown): string {\n if (error instanceof Error) {\n if (error.name === \"TimeoutError\" || error.name === \"AbortError\") return \"timeout\";\n return `${error.name}: ${error.message}`.slice(0, 500);\n }\n return String(error).slice(0, 500);\n}\n\nasync function deliverOne(\n deps: WorkspaceWebhookDispatchDeps,\n key: Uint8Array,\n claimId: string,\n delivery: ClaimedWorkspaceWebhookDelivery,\n organization = false,\n): Promise<\"delivered\" | \"failed\"> {\n let status: number | null = null;\n let error: string | null = null;\n try {\n const body = JSON.stringify(delivery.payload);\n const secret = decryptEnvironmentValue(key, delivery.secretEncrypted);\n const response = await (deps.fetch ?? pinnedFetch)(\n delivery.url,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"user-agent\": \"OpenGeni-Webhooks/1\",\n [OPENGENI_SIGNATURE_HEADER]: await signOpenGeniPayload(secret, body),\n [OPENGENI_EVENT_ID_HEADER]: delivery.eventId,\n [OPENGENI_DELIVERY_ID_HEADER]: delivery.deliveryId,\n },\n body,\n signal: AbortSignal.timeout(DELIVERY_TIMEOUT_MS),\n },\n deps.settings,\n {\n label: organization ? \"Organization webhook\" : \"Workspace webhook\",\n requireHttpsOutsideLocalTest: true,\n },\n );\n status = response.status;\n await response.body?.cancel().catch(() => undefined);\n if (status < 200 || status >= 300) error = `HTTP ${status}`;\n } catch (caught) {\n error = errorText(caught);\n }\n await (organization ? settleOrganizationWebhookDelivery : settleWorkspaceWebhookDelivery)(\n deps.db,\n {\n deliveryId: delivery.deliveryId,\n claimId,\n status,\n error,\n },\n );\n return error === null ? \"delivered\" : \"failed\";\n}\n\n/**\n * One bounded, resumable page of the per-task usage limit legacy import.\n * Roots created before the feature stay `preparing` (never shown or\n * admitted as $0 for a write) until this converges them. A failure is retried\n * on a later tick (per-root exponential backoff with its SQLSTATE kept) and\n * never blocks webhook delivery. The same pass discloses lost single-call\n * custody markers as unpriced so a crashed process cannot block a task forever.\n */\nasync function importLegacySessionUsage(deps: WorkspaceWebhookDispatchDeps): Promise<void> {\n const sink = deps.observability?.incrementCounter ? deps.observability : null;\n const metrics = sink as Pick<Observability, \"incrementCounter\"> | null;\n try {\n const result = await maintainSessionUsageLimits(deps.db);\n recordSessionUsageLimitEvent(metrics, \"import\", \"imported\", result.processed);\n recordSessionUsageLimitEvent(metrics, \"import\", \"import_failed\", result.failed);\n recordSessionUsageLimitEvent(metrics, \"single_call\", \"lost_resolved\", result.resolvedLost);\n if (result.failed > 0) {\n deps.observability?.warn(\"Session usage limit import pages failed\", {\n failed: result.failed,\n sqlstates: JSON.stringify(result.errors),\n });\n }\n } catch (error) {\n recordSessionUsageLimitEvent(metrics, \"import\", \"import_failed\");\n deps.observability?.warn(\"Session usage limit import failed\", { error: errorText(error) });\n }\n}\n\n/** Claim and deliver one globally bounded batch. At-least-once: receivers dedupe on event id. */\nexport async function drainWorkspaceWebhookDeliveries(\n deps: WorkspaceWebhookDispatchDeps,\n): Promise<WorkspaceWebhookBatchResult> {\n // Usage-limit maintenance contains its own failures, so it runs first: a\n // failing allowance pass cannot keep lost custody markers (and the tasks\n // they park) unresolved.\n await importLegacySessionUsage(deps);\n // Allowance rollover/expiry does not depend on webhook secrets, usage\n // readers, inference or having any pending delivery.\n await maintainWorkspaceAllowances(deps.db);\n const key = environmentsEncryptionKeyBytes(deps.settings);\n if (!key) return { claimed: 0, delivered: 0, failed: 0 };\n const claimId = randomUUID();\n const claims = await claimWorkspaceWebhookDeliveries(deps.db, {\n claimId,\n limit: WORKSPACE_WEBHOOK_DISPATCH_BATCH_SIZE,\n claimSeconds: CLAIM_SECONDS,\n });\n // Each lane is bounded; the shared pump does not starve organization queues\n // behind a sustained workspace backlog.\n const organizationClaims = await claimOrganizationWebhookDeliveries(deps.db, {\n claimId,\n limit: WORKSPACE_WEBHOOK_DISPATCH_BATCH_SIZE,\n claimSeconds: CLAIM_SECONDS,\n });\n const outcomes = await Promise.all(\n [\n ...claims.map((delivery) => ({ delivery, organization: false })),\n ...organizationClaims.map((delivery) => ({ delivery, organization: true })),\n ].map(async ({ delivery, organization }) => {\n try {\n return await deliverOne(deps, key, claimId, delivery, organization);\n } catch (error) {\n deps.observability?.warn(\"Workspace webhook settlement failed\", {\n deliveryId: delivery.deliveryId,\n error: errorText(error),\n });\n return \"failed\" as const;\n }\n }),\n );\n return {\n claimed: claims.length + organizationClaims.length,\n delivered: outcomes.filter((outcome) => outcome === \"delivered\").length,\n failed: outcomes.filter((outcome) => outcome === \"failed\").length,\n };\n}\n\n/**\n * One non-overlapping loop per API replica. PostgreSQL claims coordinate\n * replicas; a crash only delays a delivery until its claim expires.\n */\nexport function startWorkspaceWebhookDispatchPump(\n deps: WorkspaceWebhookDispatchDeps,\n options: {\n intervalMs?: number;\n drain?: (deps: WorkspaceWebhookDispatchDeps) => Promise<WorkspaceWebhookBatchResult>;\n } = {},\n): () => Promise<void> {\n const intervalMs = Math.max(100, options.intervalMs ?? POLL_INTERVAL_MS);\n const drain = options.drain ?? drainWorkspaceWebhookDeliveries;\n let stopped = false;\n let running: Promise<void> | undefined;\n let ticks = 0;\n\n const tick = (): void => {\n if (stopped || running) return;\n ticks += 1;\n // A full batch means a backlog: drain it now instead of one batch per interval.\n let backlog = false;\n running = (async () => {\n const result = await drain(deps);\n backlog = result.claimed >= WORKSPACE_WEBHOOK_DISPATCH_BATCH_SIZE;\n if (result.claimed > 0) deps.observability?.info(\"Workspace webhook batch settled\", result);\n if (ticks % PRUNE_EVERY_TICKS === 0) {\n await pruneWorkspaceWebhookDeliveries(deps.db);\n await pruneOrganizationWebhookDeliveries(deps.db);\n }\n })()\n .catch((error: unknown) => {\n deps.observability?.error(\"Workspace webhook dispatch failed\", { error: errorText(error) });\n })\n .finally(() => {\n running = undefined;\n if (backlog && !stopped) queueMicrotask(tick);\n });\n };\n\n const timer = setInterval(tick, intervalMs);\n queueMicrotask(tick);\n\n return async () => {\n stopped = true;\n clearInterval(timer);\n await running;\n };\n}\n","import {\n EditableArtifactDomainError,\n EditableArtifactLiveError,\n decodeEditableArtifactLiveClientWireFrame,\n encodeEditableArtifactLiveServerWireFrame,\n type EditableArtifactApplicationPort,\n type EditableArtifactLiveClose,\n type EditableArtifactLiveServerFrame,\n type EditableArtifactLiveSession,\n type EditableArtifactLiveSinkPort,\n type OpenEditableArtifactLiveInput,\n} from \"@opengeni/core\";\nimport type {\n ApiWebSocketConnection,\n ApiWebSocketLike,\n ApiWebSocketUpgradeServer,\n} from \"./api-websocket\";\n\nexport const EDITABLE_ARTIFACT_LIVE_WEBSOCKET_PATH = \"/v1/editable-artifacts/live\";\nexport const EDITABLE_ARTIFACT_LIVE_WEBSOCKET_PROTOCOL = \"opengeni-artifact-v2\";\nexport const EDITABLE_ARTIFACT_LIVE_WEBSOCKET_MAX_MESSAGE_BYTES = 8 * 1024 * 1024 + 64 * 1024;\n\nconst MAX_QUEUED_MESSAGES = 64;\nconst MAX_QUEUED_BYTES = 12 * 1024 * 1024;\n\nexport type EditableArtifactWebSocketLike = ApiWebSocketLike;\n\nexport type EditableArtifactWebSocketUpgradeServer = ApiWebSocketUpgradeServer;\n\nexport type EditableArtifactWebSocketHandler = Readonly<{\n open(socket: EditableArtifactWebSocketLike): void;\n message(socket: EditableArtifactWebSocketLike, message: string | Uint8Array | ArrayBuffer): void;\n close(socket: EditableArtifactWebSocketLike): void;\n}>;\n\nexport class EditableArtifactWebSocketTransport {\n readonly websocket: EditableArtifactWebSocketHandler;\n\n constructor(\n private readonly application: EditableArtifactApplicationPort | undefined,\n private readonly authorizeSourceSession?: OpenEditableArtifactLiveInput[\"authorizeSourceSession\"],\n ) {\n this.websocket = Object.freeze({\n open: (socket) => socket.data.attach(socket),\n message: (socket, message) => socket.data.receive(message),\n close: (socket) => socket.data.transportClosed(),\n });\n }\n\n handles(request: Request): boolean {\n return new URL(request.url).pathname === EDITABLE_ARTIFACT_LIVE_WEBSOCKET_PATH;\n }\n\n upgrade(request: Request, server: EditableArtifactWebSocketUpgradeServer): Response | undefined {\n const url = new URL(request.url);\n if (url.pathname !== EDITABLE_ARTIFACT_LIVE_WEBSOCKET_PATH) return undefined;\n if (request.method !== \"GET\") {\n return new Response(\"Method Not Allowed\", {\n status: 405,\n headers: { allow: \"GET\" },\n });\n }\n if (!this.application) return new Response(\"Service Unavailable\", { status: 503 });\n if (!offeredProtocol(request.headers.get(\"sec-websocket-protocol\"))) {\n return new Response(\"WebSocket protocol required\", { status: 426 });\n }\n const connection = new EditableArtifactWebSocketConnection(\n this.application,\n this.authorizeSourceSession,\n );\n const upgraded = server.upgrade(request, {\n data: connection,\n headers: {\n \"sec-websocket-protocol\": EDITABLE_ARTIFACT_LIVE_WEBSOCKET_PROTOCOL,\n },\n });\n return upgraded ? undefined : new Response(\"Bad Request\", { status: 400 });\n }\n}\n\n/** One socket, one consumed ticket, one stream epoch. */\nexport class EditableArtifactWebSocketConnection\n implements EditableArtifactLiveSinkPort, ApiWebSocketConnection\n{\n private socket: EditableArtifactWebSocketLike | null = null;\n private session: EditableArtifactLiveSession | null = null;\n private work: Promise<void> = Promise.resolve();\n private queuedMessages = 0;\n private queuedBytes = 0;\n private terminal = false;\n\n constructor(\n private readonly application: EditableArtifactApplicationPort,\n private readonly authorizeSourceSession?: OpenEditableArtifactLiveInput[\"authorizeSourceSession\"],\n ) {}\n\n attach(socket: EditableArtifactWebSocketLike): void {\n if (this.socket || this.terminal) {\n socket.close(4400, \"invalid connection state\");\n return;\n }\n this.socket = socket;\n }\n\n receive(message: string | Uint8Array | ArrayBuffer): void {\n if (this.terminal) return;\n if (typeof message === \"string\") {\n void this.fail(\"invalid_frame\");\n return;\n }\n const byteLength = message.byteLength;\n if (\n byteLength === 0 ||\n byteLength > EDITABLE_ARTIFACT_LIVE_WEBSOCKET_MAX_MESSAGE_BYTES ||\n this.queuedMessages + 1 > MAX_QUEUED_MESSAGES ||\n this.queuedBytes + byteLength > MAX_QUEUED_BYTES\n ) {\n void this.fail(\n byteLength > EDITABLE_ARTIFACT_LIVE_WEBSOCKET_MAX_MESSAGE_BYTES\n ? \"oversized_frame\"\n : \"slow_client\",\n );\n return;\n }\n const bytes =\n message instanceof Uint8Array ? Uint8Array.from(message) : new Uint8Array(message).slice();\n this.queuedMessages += 1;\n this.queuedBytes += bytes.byteLength;\n const run = this.work.then(async () => {\n try {\n await this.process(bytes);\n } finally {\n this.queuedMessages -= 1;\n this.queuedBytes -= bytes.byteLength;\n }\n });\n this.work = run.catch(async (error: unknown) => {\n await this.handleFailure(error);\n });\n }\n\n async send(frame: EditableArtifactLiveServerFrame): Promise<void> {\n if (this.terminal || !this.socket) {\n throw new EditableArtifactLiveError(\"closed\", \"Editable artifact socket is closed\");\n }\n const bytes = encodeEditableArtifactLiveServerWireFrame(frame);\n if (bytes.byteLength > EDITABLE_ARTIFACT_LIVE_WEBSOCKET_MAX_MESSAGE_BYTES) {\n throw new EditableArtifactLiveError(\n \"oversized_frame\",\n \"Editable artifact server frame exceeds socket limit\",\n { requiresSnapshot: true },\n );\n }\n const accepted = this.socket.send(bytes, false);\n if (!Number.isSafeInteger(accepted) || accepted <= 0) {\n throw new EditableArtifactLiveError(\"closed\", \"Editable artifact socket rejected frame\");\n }\n }\n\n bufferedBytes(): number {\n const buffered = this.socket?.getBufferedAmount?.() ?? this.socket?.bufferedAmount ?? 0;\n return Number.isSafeInteger(buffered) && buffered >= 0 ? buffered : Number.MAX_SAFE_INTEGER;\n }\n\n close(close: EditableArtifactLiveClose): void {\n if (this.terminal) return;\n this.terminal = true;\n this.socket?.close(closeCode(close.reason), close.reason);\n }\n\n transportClosed(): void {\n if (this.terminal) return;\n this.terminal = true;\n void this.session?.close(\"transport_error\");\n }\n\n private async process(bytes: Uint8Array): Promise<void> {\n if (this.terminal) return;\n const frame = decodeEditableArtifactLiveClientWireFrame(bytes);\n if (!this.session) {\n if (frame.type !== \"open\") {\n throw new EditableArtifactLiveError(\"invalid_frame\", \"First socket frame must be open\");\n }\n const session = await this.application.openLive({\n token: frame.token,\n artifactId: frame.artifactId,\n protocolVersion: frame.protocolVersion,\n resume: frame.resume,\n sink: this,\n ...(this.authorizeSourceSession\n ? { authorizeSourceSession: this.authorizeSourceSession }\n : {}),\n });\n if (this.terminal) {\n await session.close(\"transport_error\");\n return;\n }\n this.session = session;\n void session.closed.then(() => {\n if (!this.terminal)\n this.close({\n reason: \"closed\",\n retryable: false,\n requiresSnapshot: false,\n });\n });\n return;\n }\n if (frame.type === \"open\") {\n throw new EditableArtifactLiveError(\"invalid_frame\", \"Socket is already open\");\n }\n if (\n frame.artifactId !== this.session.artifactId ||\n frame.streamEpoch !== this.session.streamEpoch\n ) {\n throw new EditableArtifactLiveError(\"stale_epoch\", \"Socket frame belongs to another stream\");\n }\n if (frame.type === \"applied\") {\n await this.session.acknowledge(frame);\n return;\n }\n let receipt: Awaited<ReturnType<EditableArtifactLiveSession[\"submitIntent\"]>>;\n try {\n receipt = await this.session.submitIntent(frame);\n } catch (error) {\n await this.send({\n type: \"mutationRejected\",\n protocolVersion: frame.protocolVersion,\n artifactId: frame.artifactId,\n streamEpoch: frame.streamEpoch,\n requestHash: frame.requestHash,\n ...mutationFailure(error),\n });\n return;\n }\n // Always return the exact durable canonical transaction evidence (OGACO\n // or OGAST) on this request's socket, including idempotent unknown-outcome\n // retries whose original fanout was already replayed and ACKed. Transaction\n // first, mapping second: acceptance is never exposed without settle bytes.\n await this.send({\n type: \"transaction\",\n protocolVersion: frame.protocolVersion,\n artifactId: frame.artifactId,\n streamEpoch: frame.streamEpoch,\n transaction: receipt.transaction,\n });\n await this.send({\n type: \"mutationAccepted\",\n protocolVersion: frame.protocolVersion,\n artifactId: frame.artifactId,\n streamEpoch: frame.streamEpoch,\n requestHash: receipt.requestHash,\n clientTransactionId: receipt.clientTransactionId,\n transactionId: receipt.transaction.transactionId,\n startSequence: receipt.transaction.startSequence,\n endSequence: receipt.transaction.endSequence,\n stateHash: receipt.transaction.stateHash,\n });\n }\n\n private async handleFailure(error: unknown): Promise<void> {\n if (this.terminal) return;\n if (error instanceof EditableArtifactLiveError) {\n await this.fail(error.code === \"invalid_ticket\" ? \"transport_error\" : error.code);\n return;\n }\n await this.fail(\"transport_error\");\n }\n\n private async fail(reason: Parameters<EditableArtifactLiveSession[\"close\"]>[0]): Promise<void> {\n if (this.terminal) return;\n this.terminal = true;\n await this.session?.close(reason).catch(() => undefined);\n this.socket?.close(closeCode(reason ?? \"transport_error\"), reason ?? \"transport_error\");\n }\n}\n\nfunction mutationFailure(error: unknown): Readonly<{\n code: \"invalid_request\" | \"forbidden\" | \"conflict\" | \"unsupported\" | \"unavailable\";\n retryable: boolean;\n}> {\n if (error instanceof EditableArtifactDomainError) {\n if (error.code === \"forbidden\") return { code: \"forbidden\", retryable: false };\n if ([\"invalid_request\", \"request_hash_mismatch\", \"invalid_undo_target\"].includes(error.code)) {\n return { code: \"invalid_request\", retryable: false };\n }\n if (error.code === \"kernel_contract_violation\") {\n return { code: \"unsupported\", retryable: false };\n }\n if ([\"retryable_conflict\", \"outbox_lease_conflict\"].includes(error.code)) {\n return { code: \"conflict\", retryable: true };\n }\n return { code: \"conflict\", retryable: false };\n }\n if (error instanceof EditableArtifactLiveError && error.code === \"permission_changed\") {\n return { code: \"forbidden\", retryable: false };\n }\n return { code: \"unavailable\", retryable: true };\n}\n\nfunction offeredProtocol(value: string | null): boolean {\n return (\n value\n ?.split(\",\")\n .map((part) => part.trim())\n .includes(EDITABLE_ARTIFACT_LIVE_WEBSOCKET_PROTOCOL) ?? false\n );\n}\n\nfunction closeCode(reason: string): number {\n if (reason === \"permission_changed\") return 4403;\n if (reason === \"ticket_expired\" || reason === \"ticket_replayed\") return 4401;\n if (reason === \"protocol_mismatch\") return 4406;\n if (reason === \"slow_client\" || reason === \"oversized_frame\") return 4409;\n if (reason === \"closed\") return 1000;\n return 4400;\n}\n","import {\n hasPermission,\n requireExternalContinuationAuthority,\n requireSessionAuthorization,\n type ApiRouteDeps,\n type OpenEditableArtifactLiveInput,\n} from \"@opengeni/core\";\nimport {\n findActiveWorkspaceApiKeyById,\n getSession,\n getWorkspaceGrant,\n hasEditableArtifactSessionLink,\n lockExternalWorkspaceMembershipLifecycle,\n withRlsContext,\n} from \"@opengeni/db\";\nimport { withAccessGrantSessionRlsContext } from \"./access-grant-rls\";\nimport { sql } from \"drizzle-orm\";\n\n/** Supplied by the API adapter, so mounted hosts use their canonical live port. */\nexport function editableArtifactSourceSessionAuthorizer(\n deps: ApiRouteDeps,\n): NonNullable<OpenEditableArtifactLiveInput[\"authorizeSourceSession\"]> {\n return async (ticket, permission, transaction, signal) => {\n signal?.throwIfAborted();\n const authority = ticket.sourceSessionAuthority;\n if (!authority) return true;\n const { grant } = authority;\n const required = permission === \"edit\" ? \"artifacts:publish\" : \"artifacts:read\";\n if (\n !hasPermission(grant.permissions, required) ||\n !hasPermission(grant.permissions, \"sessions:read\")\n ) {\n return false;\n }\n // An external audit shape without the verified continuation is not authority.\n if (grant.metadata?.externalActor && !authority.externalContinuation) return false;\n try {\n const scopedDeps = transaction ? { ...deps, db: transaction } : deps;\n // Source-bound stores invoke us before their tenancy/aggregate locks.\n // Match lifecycle writers' organization -> tenancy -> session prefix.\n if (transaction) {\n await lockExternalWorkspaceMembershipLifecycle(transaction, ticket.scope.accountId);\n signal?.throwIfAborted();\n // Tenancy writers acquire this fence before source session rows.\n await transaction.execute(sql`select pg_advisory_xact_lock_shared(\n hashtextextended(${`session-tenancy:${ticket.scope.workspaceId}`}, 0))`);\n signal?.throwIfAborted();\n }\n return await withAccessGrantSessionRlsContext(scopedDeps, grant, async () => {\n return await withRlsContext(scopedDeps.db, ticket.scope, async (tx) => {\n if (authority.externalContinuation) {\n await requireExternalContinuationAuthority(\n tx,\n authority.externalContinuation,\n { ...ticket.scope, subjectId: grant.subjectId },\n [\"sessions:read\", required],\n );\n signal?.throwIfAborted();\n } else if (transaction) {\n // The authenticated ticket grant is a ceiling, not proof that\n // source-read permission still exists at the commit boundary.\n const actor = ticket.actor;\n if (\n actor.kind === \"human\" ||\n (actor.kind === \"service\" && actor.service === \"configured_key\")\n ) {\n await tx.execute(sql`select subject_id from workspace_memberships\n where account_id = ${ticket.scope.accountId}::uuid\n and workspace_id = ${ticket.scope.workspaceId}::uuid\n and subject_id = ${grant.subjectId} for share`);\n const live = await getWorkspaceGrant(tx, grant.subjectId, ticket.scope.workspaceId);\n if (!live || !hasPermission(live.permissions, \"sessions:read\")) return false;\n } else if (actor.kind === \"service\" && actor.service === \"api_key\") {\n await tx.execute(sql`select id from api_keys\n where account_id = ${ticket.scope.accountId}::uuid\n and id::text = ${grant.subjectId.slice(\"api_key:\".length)}\n for share`);\n const live = await findActiveWorkspaceApiKeyById(tx, {\n ...ticket.scope,\n apiKeyId: grant.subjectId.slice(\"api_key:\".length),\n });\n if (!live || !hasPermission(live.permissions, \"sessions:read\")) return false;\n } else if (actor.kind === \"agent\") {\n const live = await getSession(tx, ticket.scope.workspaceId, actor.sessionId);\n if (\n !live ||\n (live.firstPartyMcpPermissions !== null &&\n !hasPermission(live.firstPartyMcpPermissions, \"sessions:read\"))\n ) {\n return false;\n }\n } else {\n return false;\n }\n signal?.throwIfAborted();\n }\n // Locks protect visibility and removal of the exact association\n // until the enclosing mutation transaction commits.\n const linked = await hasEditableArtifactSessionLink(\n tx,\n ticket.scope,\n authority.sessionId,\n ticket.artifactId,\n { lockForCommit: transaction !== undefined },\n );\n signal?.throwIfAborted();\n if (!linked) return false;\n await requireSessionAuthorization({ ...scopedDeps, db: tx }, grant, {\n sessionId: authority.sessionId,\n operation: \"session.read\",\n surface: \"http\",\n });\n signal?.throwIfAborted();\n return true;\n });\n });\n } catch {\n // Denial or an unavailable authority must stop data/writes, never fall\n // back to artifact-only scope. The live loop closes denied readers.\n return false;\n }\n };\n}\n","import { localBrowserBoundaryResponse, type LocalBrowserBoundary } from \"./local-browser-boundary\";\n\nexport type ApiWebSocketUpgradeRoute<Server> = {\n handles(request: Request): boolean;\n upgrade(request: Request, server: Server): Response | undefined;\n};\n\nexport type ApiWebSocketUpgradeDispatch =\n | { handled: false }\n | { handled: true; response: Response | undefined };\n\n/**\n * WebSocket upgrades bypass the Hono app, so the local-mode browser boundary\n * (./local-browser-boundary.ts) is applied here before a transport upgrades.\n * Returns `{ handled: false }` when no transport claims the request, so the\n * caller dispatches it to the app, where the boundary runs as middleware.\n */\nexport function dispatchApiWebSocketUpgrade<Server>(\n request: Request,\n server: Server,\n routes: ReadonlyArray<ApiWebSocketUpgradeRoute<Server>>,\n localBrowserBoundary: LocalBrowserBoundary | null,\n): ApiWebSocketUpgradeDispatch {\n const route = routes.find((candidate) => candidate.handles(request));\n if (!route) return { handled: false };\n const rejection = localBrowserBoundary?.rejection(request);\n if (rejection) return { handled: true, response: localBrowserBoundaryResponse(rejection) };\n return { handled: true, response: route.upgrade(request, server) };\n}\n","import { createHash, randomUUID } from \"node:crypto\";\nimport {\n editableArtifactMaterializerCapabilitiesForRuntime,\n type EditableArtifactNativeMaterializerCapabilities,\n} from \"@opengeni/artifact-tool/runtime/materializer\";\nimport {\n EditableArtifactDurableExportService,\n EditableArtifactAgentApplication,\n EDITABLE_ARTIFACT_EXPORT_FORMATS,\n EDITABLE_ARTIFACT_EXPORT_MAX_DOWNLOAD_BYTES,\n EditableArtifactCompactionPipeline,\n EditableArtifactGenesisPipeline,\n EditableArtifactService,\n MAX_EDITABLE_ARTIFACT_SNAPSHOT_BYTES,\n ProductionEditableArtifactSnapshotVerifier,\n SystemEditableArtifactClock,\n editableArtifactLiveReadPortFromPostgres,\n editableArtifactLiveTicketStorePortFromPostgres,\n editableArtifactStorePortFromPostgres,\n editableArtifactDurableExportStorePortFromPostgres,\n ogatxEditableArtifactMutationIntentCodec,\n editableArtifactId,\n type EditableArtifactAuthorizationDecision,\n type EditableArtifactAuthorizationPort,\n type EditableArtifactAuthorizationRequest,\n type EditableArtifactStableIdFactoryPort,\n type EditableArtifactStableIdKind,\n type EditableArtifactDurableExportIdFactoryPort,\n type EditableArtifactExactSnapshotPort,\n type EditableArtifactAgentAssociationPort,\n type EditableArtifactMaterializationProfilePort,\n} from \"@opengeni/core/editable-artifacts\";\nimport {\n EditableArtifactApplication,\n EditableArtifactCompatibilityError,\n EditableArtifactLiveServer,\n SystemEditableArtifactLiveClock,\n SystemEditableArtifactLiveScheduler,\n WebCryptoEditableArtifactLiveTokens,\n type EditableArtifactApplicationPort,\n type EditableArtifactLiveAuthorizationInvalidationPort,\n type EditableArtifactLiveCompatibilityPort,\n} from \"@opengeni/core/editable-artifact-live\";\nimport { currentEditableArtifactCompatibility } from \"@opengeni/contracts/editable-artifacts\";\nimport {\n PostgresEditableArtifactLiveReadStore,\n PostgresEditableArtifactLiveTicketStore,\n PostgresEditableArtifactStore,\n listEditableArtifactIdsForSession,\n touchEditableArtifactSessionLink,\n recordNativeDocumentInspection,\n dbSql,\n withRlsContext,\n type Database,\n type PersistedEditableArtifactSnapshotBytesPort,\n type PersistedEditableArtifactSnapshotMetadata,\n} from \"@opengeni/db\";\nimport { PostgresEditableArtifactDurableExportStore } from \"@opengeni/db/editable-artifact-durable-export\";\nimport type { EventBus } from \"@opengeni/events\";\nimport {\n MAX_BOUNDED_OBJECT_CHUNK_BYTES,\n createObjectStorageBoundedPorts,\n type BoundedObjectReadPort,\n type ObjectStorage,\n} from \"@opengeni/storage\";\nimport { EventBusEditableArtifactLiveHints } from \"./editable-artifact-live-hints\";\nimport {\n NativeEditableArtifactKernelAdapter,\n loadVerifiedNativeArtifactRuntimeBinding,\n} from \"./editable-artifact-native-kernel\";\nimport { EditableArtifactOfficeImportAdapter } from \"./editable-artifact-office-import\";\nimport { EditableArtifactWorkspaceFileAdapter } from \"./editable-artifact-workspace-files\";\n\nconst INVALIDATION_POLL_MS = 1_000;\nconst TICKET_CLEANUP_MS = 30_000;\n\nexport type StandaloneEditableArtifactApplication = Readonly<{\n application: EditableArtifactApplicationPort;\n durableExports: EditableArtifactDurableExportService;\n agent: EditableArtifactAgentApplication;\n officeImports: EditableArtifactOfficeImportAdapter;\n kernelVersion: string;\n close(): void;\n}>;\n\n/**\n * Standalone production composition. Every authority is durable: PostgreSQL\n * owns admission/authorization/history, object storage owns immutable model\n * bytes, and NATS carries wake-up hints only.\n */\nexport async function createStandaloneEditableArtifactApplication(input: {\n db: Database;\n bus: EventBus;\n objectStorage: ObjectStorage;\n}): Promise<StandaloneEditableArtifactApplication> {\n const boundedObjects = createObjectStorageBoundedPorts(input.objectStorage);\n const materializationObjects = createObjectStorageBoundedPorts(input.objectStorage, {\n keyPrefix: \"editable-artifacts/materializations/v1/sha256/\",\n });\n const importSourceObjects = createObjectStorageBoundedPorts(input.objectStorage, {\n keyPrefix: \"editable-artifacts/imports/v1/sha256/\",\n });\n const runtimeBinding = await loadVerifiedNativeArtifactRuntimeBinding();\n const runtime = runtimeBinding.runtime;\n const kernel = new NativeEditableArtifactKernelAdapter(runtime, boundedObjects.read);\n const persistedStore = new PostgresEditableArtifactStore(input.db);\n const store = editableArtifactStorePortFromPostgres(persistedStore);\n const authorization = new PostgresEditableArtifactAuthorization(input.db);\n const ids = new RandomEditableArtifactStableIds();\n const clock = new SystemEditableArtifactClock();\n const snapshotVerifier = new ProductionEditableArtifactSnapshotVerifier({\n objects: boundedObjects.read,\n kernel,\n });\n const genesis = new EditableArtifactGenesisPipeline({\n kernel,\n objects: boundedObjects.write,\n now: () => clock.now(),\n });\n const compaction = new EditableArtifactCompactionPipeline({\n kernel,\n objects: boundedObjects.write,\n now: () => clock.now(),\n });\n const domain = new EditableArtifactService({\n authorization,\n kernel,\n store,\n intentCodec: ogatxEditableArtifactMutationIntentCodec,\n clock,\n ids,\n snapshotVerifier,\n genesis,\n compaction,\n });\n const materializerCapabilities = editableArtifactMaterializerCapabilitiesForRuntime(\n runtime,\n runtimeBinding.location.artifactTool.packageVersion,\n );\n const durableExports = new EditableArtifactDurableExportService({\n authorization,\n exactSnapshots: Object.freeze({\n ensure: async (request: Parameters<EditableArtifactExactSnapshotPort[\"ensure\"]>[0]) =>\n await domain.compactCurrentHead(request),\n }),\n store: editableArtifactDurableExportStorePortFromPostgres(\n new PostgresEditableArtifactDurableExportStore(input.db),\n ),\n ids: new RandomEditableArtifactDurableExportIds(),\n profiles: materializationProfiles(materializerCapabilities),\n materializationObjects: materializationObjects.read,\n });\n const officeImports = new EditableArtifactOfficeImportAdapter({\n db: input.db,\n objectStorage: input.objectStorage,\n runtime: runtimeBinding,\n sourceObjects: importSourceObjects.write,\n snapshotObjects: boundedObjects.write,\n });\n const agent = new EditableArtifactAgentApplication({\n domain,\n exports: durableExports,\n associations: Object.freeze({\n listArtifactIds: async ({ scope, sessionId, limit }) =>\n (await listEditableArtifactIdsForSession(input.db, scope, sessionId, limit)).map(\n editableArtifactId,\n ),\n touch: async ({ scope, sessionId, artifactId }) =>\n await touchEditableArtifactSessionLink(input.db, scope, sessionId, artifactId),\n } satisfies EditableArtifactAgentAssociationPort),\n inspector: kernel,\n recordInspection: async (inspection) => {\n if (inspection.actor.kind !== \"agent\")\n throw new Error(\"Inspection proof requires an agent attempt\");\n return recordNativeDocumentInspection(input.db, { ...inspection, actor: inspection.actor });\n },\n officeImports,\n workspaceFiles: new EditableArtifactWorkspaceFileAdapter({\n db: input.db,\n objectStorage: input.objectStorage,\n durableExports,\n }),\n });\n const ticketStore = new PostgresEditableArtifactLiveTicketStore(input.db);\n const liveRead = new PostgresEditableArtifactLiveReadStore(input.db, {\n snapshotBytes: snapshotBytesPort(boundedObjects.read),\n });\n const invalidations = new PollingEditableArtifactAuthorizationInvalidations(authorization);\n const live = new EditableArtifactLiveServer({\n authorization,\n domain,\n tickets: editableArtifactLiveTicketStorePortFromPostgres(ticketStore),\n tokens: new WebCryptoEditableArtifactLiveTokens(),\n clock: new SystemEditableArtifactLiveClock(),\n scheduler: new SystemEditableArtifactLiveScheduler(),\n read: editableArtifactLiveReadPortFromPostgres(liveRead),\n hints: new EventBusEditableArtifactLiveHints(input.bus),\n invalidations,\n });\n const compatibility: EditableArtifactLiveCompatibilityPort = Object.freeze({\n assertCompatible(\n request: Parameters<EditableArtifactLiveCompatibilityPort[\"assertCompatible\"]>[0],\n ) {\n const current = currentEditableArtifactCompatibility(request.artifact.modality);\n if (\n request.modality !== request.artifact.modality ||\n request.liveProtocolVersion !== current.liveProtocolVersion ||\n request.modelSchemaVersion !== current.modelSchemaVersion ||\n request.snapshotVersion !== current.snapshotVersion ||\n request.commandProtocolVersion !== current.commandProtocolVersion ||\n request.committedTransactionProtocolVersion !== current.committedTransactionProtocolVersion\n ) {\n throw new EditableArtifactCompatibilityError();\n }\n },\n });\n const application = new EditableArtifactApplication({\n domain,\n live,\n compatibility,\n });\n const cleanup = setInterval(() => {\n void ticketStore.cleanupExpired().catch(() => undefined);\n }, TICKET_CLEANUP_MS);\n cleanup.unref?.();\n return Object.freeze({\n application,\n durableExports,\n agent,\n officeImports,\n kernelVersion: runtime.buildIdentity,\n close() {\n clearInterval(cleanup);\n invalidations.close();\n },\n });\n}\n\nexport class PostgresEditableArtifactAuthorization implements EditableArtifactAuthorizationPort {\n constructor(private readonly db: Database) {}\n\n async authorize(\n request: EditableArtifactAuthorizationRequest,\n ): Promise<EditableArtifactAuthorizationDecision> {\n const actor = request.actor;\n const rows = await withRlsContext(this.db, request.scope, async (tx) =>\n rawRows<{ allowed: boolean; authorization_revision: number | string | bigint }>(\n await tx.execute(dbSql`select *\n from opengeni_private.authorize_editable_artifact_actor(\n ${request.scope.accountId}::uuid,\n ${request.scope.workspaceId}::uuid,\n ${request.artifactId},\n ${actor.kind},\n ${actor.subjectId},\n ${actor.kind === \"agent\" ? actor.sessionId : null},\n ${actor.kind === \"agent\" ? actor.turnId : null},\n ${actor.kind === \"agent\" ? actor.attemptId : null},\n ${actor.kind === \"agent\" ? actor.generation : null},\n ${actor.kind === \"service\" ? actor.service : null},\n ${request.permission},\n current_schema()\n )`),\n ),\n );\n if (rows.length !== 1) throw new Error(\"Editable artifact authorization returned no decision\");\n const revision = Number(rows[0]!.authorization_revision);\n if (!Number.isSafeInteger(revision) || revision < 1) {\n throw new Error(\"Editable artifact authorization returned an invalid revision\");\n }\n return Object.freeze({ allowed: rows[0]!.allowed === true, revision });\n }\n}\n\nclass PollingEditableArtifactAuthorizationInvalidations implements EditableArtifactLiveAuthorizationInvalidationPort {\n private readonly stops = new Set<() => void>();\n\n constructor(private readonly authorization: EditableArtifactAuthorizationPort) {}\n\n async subscribe(\n input: Parameters<EditableArtifactLiveAuthorizationInvalidationPort[\"subscribe\"]>[0],\n ): Promise<() => void> {\n let active = true;\n let polling = false;\n let baseline = await this.read(input);\n const timer = setInterval(() => {\n if (!active || polling) return;\n polling = true;\n void this.read(input)\n .then((next) => {\n if (!active) return;\n if (next !== baseline) {\n baseline = next;\n input.onInvalidated();\n }\n })\n .catch(() => {\n if (active) input.onInvalidated();\n })\n .finally(() => {\n polling = false;\n });\n }, INVALIDATION_POLL_MS);\n timer.unref?.();\n const stop = () => {\n if (!active) return;\n active = false;\n clearInterval(timer);\n this.stops.delete(stop);\n };\n this.stops.add(stop);\n return stop;\n }\n\n close(): void {\n for (const stop of [...this.stops]) stop();\n }\n\n private async read(\n input: Parameters<EditableArtifactLiveAuthorizationInvalidationPort[\"subscribe\"]>[0],\n ): Promise<string> {\n const decision = await this.authorization.authorize({\n scope: input.scope,\n artifactId: input.artifactId,\n actor: input.actor,\n permission: \"read\",\n });\n return `${decision.allowed ? 1 : 0}:${decision.revision}`;\n }\n}\n\nclass RandomEditableArtifactStableIds implements EditableArtifactStableIdFactoryPort {\n next(_kind: EditableArtifactStableIdKind) {\n return randomUUID().replaceAll(\"-\", \"\") as ReturnType<\n EditableArtifactStableIdFactoryPort[\"next\"]\n >;\n }\n}\n\nclass RandomEditableArtifactDurableExportIds implements EditableArtifactDurableExportIdFactoryPort {\n next(_kind: \"version\" | \"materialization_job\" | \"receipt\"): string {\n return randomUUID().replaceAll(\"-\", \"\");\n }\n}\n\nfunction materializationProfiles(\n capabilities: EditableArtifactNativeMaterializerCapabilities,\n): EditableArtifactMaterializationProfilePort {\n const spreadsheetCompatibility = currentEditableArtifactCompatibility(\"spreadsheet\");\n if (\n capabilities.protocol !== \"OGAMC001\" ||\n capabilities.runtimeKind !== \"native\" ||\n capabilities.maxOutputBytes !== EDITABLE_ARTIFACT_EXPORT_MAX_DOWNLOAD_BYTES ||\n capabilities.codecVersions[\"opengeni.xlsx\"] === undefined ||\n capabilities.supportedModelSchemaVersions[0] !== spreadsheetCompatibility.modelSchemaVersion ||\n capabilities.supportedOperationProtocolVersions[0] !==\n spreadsheetCompatibility.committedTransactionProtocolVersion ||\n capabilities.supportedSnapshotProtocolVersions[0] !== spreadsheetCompatibility.snapshotVersion\n ) {\n throw new Error(\"Verified artifact materializer profile is incompatible\");\n }\n const codecVersion = capabilities.codecVersions[\"opengeni.xlsx\"];\n return Object.freeze({\n supportedFormats: EDITABLE_ARTIFACT_EXPORT_FORMATS,\n async resolve(input: Parameters<EditableArtifactMaterializationProfilePort[\"resolve\"]>[0]) {\n // EDITABLE_ARTIFACT_EXPORT_FORMATS is what agents are told exists.\n if (\n input.modality !== \"spreadsheet\" ||\n input.format !== \"xlsx\" ||\n !EDITABLE_ARTIFACT_EXPORT_FORMATS[input.modality].includes(input.format) ||\n Object.keys(input.options).length !== 0\n ) {\n return null;\n }\n return Object.freeze({\n modality: \"spreadsheet\" as const,\n format: \"xlsx\" as const,\n codecId: \"opengeni.xlsx\",\n codecVersion,\n kernelVersion: capabilities.kernelVersion,\n fontRegistryHash: capabilities.fontRegistryHash,\n policyHash: capabilities.policyHash,\n normalizedOptions: \"{}\",\n });\n },\n });\n}\n\nfunction snapshotBytesPort(\n objects: BoundedObjectReadPort,\n): PersistedEditableArtifactSnapshotBytesPort {\n return Object.freeze({\n async readSnapshotBytes(snapshot: PersistedEditableArtifactSnapshotMetadata) {\n const object = await objects.open({\n opaqueReference: snapshot.blobReference,\n maxBytes: MAX_EDITABLE_ARTIFACT_SNAPSHOT_BYTES,\n expectedByteSize: snapshot.byteSize,\n });\n try {\n if (object.contentType !== undefined && object.contentType !== snapshot.mimeType) {\n throw new Error(\"Editable artifact snapshot content type mismatch\");\n }\n const bytes = new Uint8Array(snapshot.byteSize);\n const digest = createHash(\"sha256\");\n let offset = 0;\n for await (const chunk of object.chunks({\n chunkBytes: MAX_BOUNDED_OBJECT_CHUNK_BYTES,\n })) {\n if (offset + chunk.byteLength > bytes.byteLength) {\n throw new Error(\"Editable artifact snapshot exceeds its declared size\");\n }\n bytes.set(chunk, offset);\n digest.update(chunk);\n offset += chunk.byteLength;\n }\n if (\n offset !== bytes.byteLength ||\n `sha256:${digest.digest(\"hex\")}` !== snapshot.contentHash\n ) {\n throw new Error(\"Editable artifact snapshot digest or size mismatch\");\n }\n await object.assertUnchanged();\n return bytes;\n } finally {\n await object.close();\n }\n },\n });\n}\n\nfunction rawRows<T extends Record<string, unknown>>(result: unknown): T[] {\n if (Array.isArray(result)) return result as T[];\n const rows = (result as { rows?: unknown } | null)?.rows;\n if (Array.isArray(rows)) return rows as T[];\n throw new Error(\"Unsupported database execute result shape\");\n}\n","import {\n decodeEditableArtifactBrokerHint,\n editableArtifactLiveHintSubject,\n type EditableArtifactLiveHintPort,\n} from \"@opengeni/core\";\nimport type { EventBus, OpStreamConnection } from \"@opengeni/events\";\n\n/**\n * Uses the API's existing resilient NATS connection. Hints carry no operation\n * bytes; every callback causes a durable DB head read and contiguous gap-fill.\n */\nexport class EventBusEditableArtifactLiveHints implements EditableArtifactLiveHintPort {\n constructor(private readonly bus: Pick<EventBus, \"getOpStreamConnection\">) {}\n\n async subscribe(\n input: Parameters<EditableArtifactLiveHintPort[\"subscribe\"]>[0],\n ): Promise<() => void> {\n const connection = this.bus.getOpStreamConnection?.();\n if (!connection) throw new Error(\"Event bus has no artifact hint subscription transport\");\n const subject = editableArtifactLiveHintSubject(input.scope, input.artifactId);\n const subscription = connection.subscribe(subject);\n let active = true;\n try {\n await requireFlushBarrier(connection);\n } catch (error) {\n subscription.unsubscribe();\n throw error;\n }\n void (async () => {\n try {\n for await (const message of subscription) {\n if (!active) return;\n try {\n const hint = decodeEditableArtifactBrokerHint(message.data, {\n scope: input.scope,\n artifactId: input.artifactId,\n });\n input.onHint({\n artifactId: input.artifactId,\n headSequence: hint.headSequence,\n });\n } catch {\n // Broker input is advisory and untrusted. Drop poison; periodic\n // durable reconciliation remains authoritative.\n }\n }\n } catch {\n if (active) input.onReconnect();\n }\n })();\n return () => {\n if (!active) return;\n active = false;\n subscription.unsubscribe();\n };\n }\n}\n\nasync function requireFlushBarrier(connection: OpStreamConnection): Promise<void> {\n if (!connection.flush) {\n throw new Error(\"Artifact hint subscription transport lacks a flush barrier\");\n }\n await connection.flush();\n}\n","import { createHash } from \"node:crypto\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n createNativeArtifactSession,\n openNativeArtifactSession,\n type NativeArtifactSession,\n type NativeSpreadsheetSession,\n} from \"@opengeni/artifact-tool/native\";\nimport type { ArtifactKernelRuntime } from \"@opengeni/artifact-tool/runtime\";\nimport {\n doctorConfiguredArtifactRuntime,\n type ConfiguredArtifactRuntimeLocation,\n} from \"@opengeni/artifact-tool/runtime/development\";\nimport {\n decodeEditableArtifactCausalFrontier,\n encodeEditableArtifactCausalFrontier,\n} from \"@opengeni/contracts/editable-artifact-causal-frontier\";\nimport { decodeEditableArtifactSerializedCommit } from \"@opengeni/contracts/editable-artifact-serialized-commit\";\nimport { decodeEditableArtifactMutationIntent } from \"@opengeni/contracts/editable-artifacts\";\nimport {\n COMMITTED_TRANSACTION_PROTOCOL_VERSION,\n DOCUMENT_ARTIFACT_MODEL_SCHEMA_VERSION,\n PRESENTATION_ARTIFACT_MODEL_SCHEMA_VERSION,\n SPREADSHEET_ARTIFACT_MODEL_SCHEMA_VERSION,\n SPREADSHEET_COLLABORATION_SNAPSHOT_VERSION,\n} from \"@opengeni/contracts/editable-artifact-versions\";\nimport {\n MAX_EDITABLE_ARTIFACT_SNAPSHOT_BYTES,\n causalFrontiersEqual,\n editableArtifactCausalFrontier,\n editableArtifactContentHash,\n editableArtifactReplicaId,\n editableArtifactStateHash,\n type ApplyAuthoritativeEditableArtifactKernelRequest,\n type ApplyAuthoritativeEditableArtifactKernelResult,\n type AuthoritativeEditableArtifactCompactionKernelPort,\n type AuthoritativeEditableArtifactCompactionKernelResult,\n type AuthoritativeEditableArtifactGenesisKernelPort,\n type AuthoritativeEditableArtifactGenesisKernelResult,\n type AuthoritativeEditableArtifactKernelPort,\n type EditableArtifactAgentInspectionKernelPort,\n type EditableArtifactKernelState,\n type EditableArtifactSnapshotReplayPlan,\n type IsolatedEditableArtifactSnapshotKernelPort,\n type IsolatedEditableArtifactSnapshotKernelResult,\n} from \"@opengeni/core\";\nimport type { BoundedObjectReadPort } from \"@opengeni/storage\";\n\nconst SNAPSHOT_CHUNK_BYTES = 1024 * 1024;\n\ntype RuntimeFacadeModule = Readonly<{\n getConfiguredArtifactRuntime?: () => unknown;\n}> &\n Readonly<Record<string, unknown>>;\n\nexport type VerifiedNativeArtifactRuntimeBinding = Readonly<{\n runtime: ArtifactKernelRuntime;\n location: ConfiguredArtifactRuntimeLocation;\n facade: RuntimeFacadeModule;\n}>;\n\n/** Loads only the manifest-pinned, byte-verified native runtime. */\nexport async function loadVerifiedNativeArtifactRuntime(): Promise<ArtifactKernelRuntime> {\n return (await loadVerifiedNativeArtifactRuntimeBinding()).runtime;\n}\n\n/** Same verified load plus the pinned package identity used by export profiles. */\nexport async function loadVerifiedNativeArtifactRuntimeBinding(): Promise<VerifiedNativeArtifactRuntimeBinding> {\n const location = await doctorConfiguredArtifactRuntime();\n const module = (await import(\n /* @vite-ignore */ pathToFileURL(location.skillFacadeEntrypoint).href\n )) as RuntimeFacadeModule;\n const candidate = module.getConfiguredArtifactRuntime?.();\n assertRuntime(candidate, location);\n return Object.freeze({ runtime: candidate, location, facade: module });\n}\n\n/** Exact native authority shared by mutation, genesis, and snapshot verification. */\nexport class NativeEditableArtifactKernelAdapter\n implements\n AuthoritativeEditableArtifactKernelPort,\n AuthoritativeEditableArtifactGenesisKernelPort,\n AuthoritativeEditableArtifactCompactionKernelPort,\n IsolatedEditableArtifactSnapshotKernelPort,\n EditableArtifactAgentInspectionKernelPort\n{\n constructor(\n readonly runtime: ArtifactKernelRuntime,\n private readonly objects: BoundedObjectReadPort,\n ) {\n if (runtime.kind !== \"native\" || runtime.target === \"wasm-web\") {\n throw new Error(\"Editable artifact authority requires a native kernel\");\n }\n }\n\n async applyTransaction(\n request: ApplyAuthoritativeEditableArtifactKernelRequest,\n ): Promise<ApplyAuthoritativeEditableArtifactKernelResult> {\n const session = await this.openCurrentState(request.state);\n try {\n if (request.modality === \"spreadsheet\") {\n if (session.modality !== \"spreadsheet\") throw new Error(\"Native modality mismatch\");\n const committedTransactionBytes = session.authorTransaction(\n request.intentBytes,\n encodeEditableArtifactCausalFrontier(request.resolvedCausalBase),\n );\n return Object.freeze({\n modality: \"spreadsheet\" as const,\n committedTransactionBytes,\n kernelVersion: this.runtime.buildIdentity,\n modelSchemaVersion: SPREADSHEET_ARTIFACT_MODEL_SCHEMA_VERSION,\n });\n }\n if (session.modality !== request.modality) {\n throw new Error(\"Native modality mismatch\");\n }\n const nativeReceiptBytes = session.applyCommands(request.intent.commandBytes);\n return Object.freeze({\n modality: request.modality,\n nativeReceiptBytes,\n resultingStateHash: editableArtifactStateHash(session.stateHash()),\n kernelVersion: this.runtime.buildIdentity,\n modelSchemaVersion: modelSchemaVersionFor(request.modality),\n });\n } finally {\n session.dispose();\n }\n }\n\n async query(\n input: Parameters<EditableArtifactAgentInspectionKernelPort[\"query\"]>[0],\n ): ReturnType<EditableArtifactAgentInspectionKernelPort[\"query\"]> {\n const session = await this.openCurrentState(input.state);\n try {\n return Uint8Array.from(session.query(input.queryBytes));\n } finally {\n session.dispose();\n }\n }\n\n private async openCurrentState(\n state: EditableArtifactKernelState,\n ): Promise<NativeArtifactSession> {\n const snapshot = state.snapshot;\n if (!snapshot) throw new Error(\"Editable artifact has no verified replay snapshot\");\n const snapshotBytes = await readVerifiedSnapshot(this.objects, snapshot);\n const session = openNativeArtifactSession(this.runtime, {\n modality: state.modality,\n snapshot: snapshotBytes,\n });\n try {\n verifySnapshotBoundary(session, state);\n replayKernelTail(session, state);\n verifyDurableHead(session, state);\n return session;\n } catch (error) {\n session.dispose();\n throw error;\n }\n }\n\n async createCanonicalEmptySnapshot(input: {\n scope: Parameters<\n AuthoritativeEditableArtifactGenesisKernelPort[\"createCanonicalEmptySnapshot\"]\n >[0][\"scope\"];\n artifactId: Parameters<\n AuthoritativeEditableArtifactGenesisKernelPort[\"createCanonicalEmptySnapshot\"]\n >[0][\"artifactId\"];\n modality: Parameters<\n AuthoritativeEditableArtifactGenesisKernelPort[\"createCanonicalEmptySnapshot\"]\n >[0][\"modality\"];\n signal?: AbortSignal;\n }): Promise<AuthoritativeEditableArtifactGenesisKernelResult> {\n throwIfAborted(input.signal);\n const session = createNativeArtifactSession(this.runtime, {\n modality: input.modality,\n replicaNamespace: namespaceForArtifact(input.artifactId),\n });\n try {\n const snapshot = session.snapshot();\n throwIfAborted(input.signal);\n const revision = safeRevision(session.revision());\n if (revision !== 0) throw new Error(\"Native genesis revision is not zero\");\n const common = {\n scope: input.scope,\n artifactId: input.artifactId,\n modality: input.modality,\n canonicalChunks: fixedChunks(snapshot, input.signal),\n canonicalByteSize: snapshot.byteLength,\n canonicalContentHash: editableArtifactContentHash(\n `sha256:${createHash(\"sha256\").update(snapshot).digest(\"hex\")}`,\n ),\n stateHash: editableArtifactStateHash(session.stateHash()),\n coveredHeadSequence: 0 as const,\n modelSchemaVersion: modelSchemaVersionFor(input.modality),\n kernelVersion: this.runtime.buildIdentity,\n };\n if (session.modality === \"spreadsheet\") {\n return Object.freeze({\n ...common,\n modality: \"spreadsheet\" as const,\n coveredCausalFrontier: domainFrontier(session.frontier()),\n operationProtocolVersion: COMMITTED_TRANSACTION_PROTOCOL_VERSION,\n crdtStateVersion: SPREADSHEET_COLLABORATION_SNAPSHOT_VERSION,\n });\n }\n return Object.freeze({\n ...common,\n modality: session.modality,\n nativeRevision: 0 as const,\n });\n } finally {\n session.dispose();\n }\n }\n\n async createCanonicalSnapshot(input: {\n state: EditableArtifactKernelState;\n signal?: AbortSignal;\n }): Promise<AuthoritativeEditableArtifactCompactionKernelResult> {\n throwIfAborted(input.signal);\n const snapshot = input.state.snapshot;\n if (!snapshot) throw new Error(\"Editable artifact has no verified replay snapshot\");\n const snapshotBytes = await readVerifiedSnapshot(this.objects, snapshot, input.signal);\n const session = openNativeArtifactSession(this.runtime, {\n modality: input.state.modality,\n snapshot: snapshotBytes,\n });\n try {\n verifySnapshotBoundary(session, input.state);\n replayKernelTail(session, input.state);\n verifyDurableHead(session, input.state);\n throwIfAborted(input.signal);\n const canonical = session.snapshot();\n const common = {\n scope: input.state.artifact.scope,\n artifactId: input.state.artifact.id,\n modality: input.state.modality,\n canonicalChunks: fixedChunks(canonical, input.signal),\n canonicalByteSize: canonical.byteLength,\n canonicalContentHash: editableArtifactContentHash(\n `sha256:${createHash(\"sha256\").update(canonical).digest(\"hex\")}`,\n ),\n stateHash: editableArtifactStateHash(session.stateHash()),\n coveredHeadSequence: input.state.artifact.headSequence,\n modelSchemaVersion: modelSchemaVersionFor(input.state.modality),\n kernelVersion: this.runtime.buildIdentity,\n } as const;\n if (session.modality === \"spreadsheet\") {\n if (input.state.modality !== \"spreadsheet\") throw new Error(\"Native modality mismatch\");\n return Object.freeze({\n ...common,\n modality: session.modality,\n coveredCausalFrontier: domainFrontier(session.frontier()),\n operationProtocolVersion: COMMITTED_TRANSACTION_PROTOCOL_VERSION,\n crdtStateVersion: SPREADSHEET_COLLABORATION_SNAPSHOT_VERSION,\n });\n }\n if (session.modality !== input.state.modality) throw new Error(\"Native modality mismatch\");\n return Object.freeze({\n ...common,\n modality: session.modality,\n nativeRevision: safeRevision(session.revision()),\n });\n } finally {\n session.dispose();\n }\n }\n\n async verifyAndReconstruct(\n input: Parameters<IsolatedEditableArtifactSnapshotKernelPort[\"verifyAndReconstruct\"]>[0],\n ): Promise<IsolatedEditableArtifactSnapshotKernelResult> {\n throwIfAborted(input.signal);\n const bytes = await collectExact(\n input.snapshotChunks,\n input.expectedSnapshotByteSize,\n input.signal,\n );\n const session = openNativeArtifactSession(this.runtime, {\n modality: input.modality,\n snapshot: bytes,\n });\n try {\n const canonical = session.snapshot();\n if (!equalBytes(canonical, bytes)) throw new Error(\"Native snapshot is not canonical\");\n const expected = input.expectedSnapshot;\n if (expected.modality !== session.modality) throw new Error(\"Snapshot modality mismatch\");\n const coveredHeadSequence = expected.coveredHeadSequence;\n const stateHash = editableArtifactStateHash(session.stateHash());\n if (stateHash !== expected.stateHash) throw new Error(\"Snapshot state hash mismatch\");\n const canonicalContentHash = editableArtifactContentHash(\n `sha256:${createHash(\"sha256\").update(canonical).digest(\"hex\")}`,\n );\n if (session.modality === \"spreadsheet\") {\n const coveredCausalFrontier = domainFrontier(session.frontier());\n if (\n expected.modality !== \"spreadsheet\" ||\n !causalFrontiersEqual(coveredCausalFrontier, expected.coveredCausalFrontier)\n ) {\n throw new Error(\"Snapshot causal coverage mismatch\");\n }\n if (input.replayPlan && input.replayPlan.modality !== \"spreadsheet\") {\n throw new Error(\"Replay modality mismatch\");\n }\n const replayedTarget = input.replayPlan\n ? await replaySpreadsheetPlan(session, input.replayPlan, input.signal)\n : undefined;\n return Object.freeze({\n modality: \"spreadsheet\" as const,\n canonicalReencodeVerified: true as const,\n scope: input.scope,\n artifactId: input.artifactId,\n canonicalByteSize: canonical.byteLength,\n canonicalContentHash,\n coveredHeadSequence,\n stateHash,\n modelSchemaVersion: SPREADSHEET_ARTIFACT_MODEL_SCHEMA_VERSION,\n kernelVersion: this.runtime.buildIdentity,\n fullCrdtStateVerified: true as const,\n coveredCausalFrontier,\n operationProtocolVersion: COMMITTED_TRANSACTION_PROTOCOL_VERSION,\n crdtStateVersion: SPREADSHEET_COLLABORATION_SNAPSHOT_VERSION,\n ...(replayedTarget ? { replayedTarget } : {}),\n });\n }\n if (expected.modality === \"spreadsheet\") throw new Error(\"Snapshot modality mismatch\");\n const nativeRevision = safeRevision(session.revision());\n if (nativeRevision !== expected.nativeRevision) {\n throw new Error(\"Snapshot native revision mismatch\");\n }\n if (input.replayPlan && input.replayPlan.modality === \"spreadsheet\") {\n throw new Error(\"Replay modality mismatch\");\n }\n const replayedTarget = input.replayPlan\n ? await replaySerializedPlan(session, input.replayPlan, input.signal)\n : undefined;\n return Object.freeze({\n modality: session.modality,\n canonicalReencodeVerified: true as const,\n scope: input.scope,\n artifactId: input.artifactId,\n canonicalByteSize: canonical.byteLength,\n canonicalContentHash,\n coveredHeadSequence,\n stateHash,\n modelSchemaVersion: modelSchemaVersionFor(session.modality),\n kernelVersion: this.runtime.buildIdentity,\n nativeRevision,\n ...(replayedTarget ? { replayedTarget } : {}),\n });\n } finally {\n session.dispose();\n }\n }\n}\n\nfunction modelSchemaVersionFor(modality: \"spreadsheet\" | \"document\" | \"presentation\"): 1 | 2 {\n if (modality === \"spreadsheet\") return SPREADSHEET_ARTIFACT_MODEL_SCHEMA_VERSION;\n return modality === \"document\"\n ? DOCUMENT_ARTIFACT_MODEL_SCHEMA_VERSION\n : PRESENTATION_ARTIFACT_MODEL_SCHEMA_VERSION;\n}\n\nfunction assertRuntime(\n candidate: unknown,\n location: ConfiguredArtifactRuntimeLocation,\n): asserts candidate is ArtifactKernelRuntime {\n if (typeof candidate !== \"object\" || candidate === null) {\n throw new Error(\"Verified artifact facade returned no runtime\");\n }\n const runtime = candidate as Partial<ArtifactKernelRuntime>;\n if (\n runtime.kind !== \"native\" ||\n runtime.target === \"wasm-web\" ||\n runtime.target !== location.target ||\n runtime.buildIdentity !== location.kernel.buildIdentity ||\n typeof runtime.createCollaborationSession !== \"function\" ||\n typeof runtime.openCollaborationSession !== \"function\" ||\n typeof runtime.createDocumentSession !== \"function\" ||\n typeof runtime.openDocumentSession !== \"function\" ||\n typeof runtime.createPresentationSession !== \"function\" ||\n typeof runtime.openPresentationSession !== \"function\"\n ) {\n throw new Error(\"Verified artifact facade returned an incompatible runtime\");\n }\n}\n\nfunction verifySnapshotBoundary(\n session: NativeArtifactSession,\n state: EditableArtifactKernelState,\n): void {\n const snapshot = state.snapshot;\n if (!snapshot || session.modality !== state.modality)\n throw new Error(\"Snapshot modality mismatch\");\n if (session.stateHash() !== snapshot.stateHash) {\n throw new Error(\"Native snapshot boundary does not match durable metadata\");\n }\n if (state.modality === \"spreadsheet\") {\n if (\n session.modality !== \"spreadsheet\" ||\n snapshot.modality !== \"spreadsheet\" ||\n !causalFrontiersEqual(domainFrontier(session.frontier()), snapshot.coveredCausalFrontier)\n ) {\n throw new Error(\"Native snapshot frontier does not match durable metadata\");\n }\n } else if (\n session.modality === \"spreadsheet\" ||\n snapshot.modality === \"spreadsheet\" ||\n safeRevision(session.revision()) !== snapshot.nativeRevision ||\n state.baseNativeRevision !== snapshot.nativeRevision\n ) {\n throw new Error(\"Native snapshot revision does not match durable metadata\");\n }\n}\n\nfunction replayKernelTail(\n session: NativeArtifactSession,\n state: EditableArtifactKernelState,\n): void {\n if (state.modality === \"spreadsheet\") {\n if (session.modality !== \"spreadsheet\") throw new Error(\"Native modality mismatch\");\n for (const transaction of state.committedTransactionTail) {\n const priorNativeRevision = safeRevision(session.revision());\n if (session.stateHash() !== transaction.priorStateHash) {\n throw new Error(\"Spreadsheet replay prior state mismatch\");\n }\n session.applyCommitted(transaction.committedTransactionBytes);\n if (\n safeRevision(session.revision()) !== priorNativeRevision + 1 ||\n session.stateHash() !== transaction.stateHash ||\n !causalFrontiersEqual(\n domainFrontier(session.frontier()),\n transaction.resultingCausalFrontier,\n )\n ) {\n throw new Error(\"Spreadsheet replay result mismatch\");\n }\n }\n return;\n }\n if (session.modality !== state.modality) {\n throw new Error(\"Native modality mismatch\");\n }\n for (const transaction of state.committedTransactionTail) {\n if (\n session.stateHash() !== transaction.priorStateHash ||\n safeRevision(session.revision()) !== transaction.priorNativeRevision\n ) {\n throw new Error(\"Serialized replay prior state mismatch\");\n }\n const commit = decodeEditableArtifactSerializedCommit(\n transaction.committedTransactionBytes,\n state.modality,\n );\n const intent = decodeEditableArtifactMutationIntent(commit.intentBytes);\n const receipt = session.applyCommands(intent.commandBytes);\n if (\n !equalBytes(receipt, commit.nativeReceiptBytes) ||\n !equalBytes(receipt, transaction.nativeReceiptBytes) ||\n safeRevision(session.revision()) !== transaction.nativeRevision ||\n session.stateHash() !== transaction.stateHash\n ) {\n throw new Error(\"Serialized replay result mismatch\");\n }\n }\n}\n\nfunction verifyDurableHead(\n session: NativeArtifactSession,\n state: EditableArtifactKernelState,\n): void {\n const snapshot = state.snapshot;\n if (!snapshot) throw new Error(\"Editable artifact has no replay snapshot\");\n let durableSequence = snapshot.coveredHeadSequence;\n for (const transaction of state.committedTransactionTail) {\n if (transaction.sequenceStart !== durableSequence + 1) {\n throw new Error(\"Durable transaction tail contains a sequence gap\");\n }\n durableSequence = transaction.sequenceEnd;\n }\n if (\n session.modality !== state.modality ||\n durableSequence !== state.artifact.headSequence ||\n session.stateHash() !== state.artifact.stateHash\n ) {\n throw new Error(\"Reconstructed native state does not match the durable head\");\n }\n if (\n state.modality === \"spreadsheet\" &&\n (session.modality !== \"spreadsheet\" ||\n !causalFrontiersEqual(domainFrontier(session.frontier()), state.artifact.causalFrontier))\n ) {\n throw new Error(\"Reconstructed native frontier does not match the durable head\");\n }\n if (state.modality !== \"spreadsheet\") {\n const expectedNativeRevision =\n state.committedTransactionTail.at(-1)?.nativeRevision ?? state.baseNativeRevision;\n if (safeRevision(session.revision()) !== expectedNativeRevision) {\n throw new Error(\"Reconstructed native revision does not match the serialized tail\");\n }\n }\n}\n\nasync function replaySpreadsheetPlan(\n session: NativeSpreadsheetSession,\n plan: Extract<EditableArtifactSnapshotReplayPlan, { modality: \"spreadsheet\" }>,\n signal: AbortSignal | undefined,\n): Promise<\n Readonly<{\n headSequence: number;\n causalFrontier: ReturnType<typeof editableArtifactCausalFrontier>;\n stateHash: ReturnType<typeof editableArtifactStateHash>;\n }>\n> {\n let sequence = plan.baseHeadSequence;\n for await (const segment of plan.segments) {\n throwIfAborted(signal);\n if (segment.sequenceStart !== sequence + 1) throw new Error(\"Replay sequence gap\");\n if (segment.modality !== \"spreadsheet\") throw new Error(\"Replay segment modality mismatch\");\n session.applyCommitted(segment.bytes);\n sequence = segment.sequenceEnd;\n }\n if (sequence !== plan.targetHeadSequence || session.stateHash() !== plan.targetStateHash) {\n throw new Error(\"Replay target mismatch\");\n }\n const causalFrontier = domainFrontier(session.frontier());\n if (!causalFrontiersEqual(causalFrontier, plan.targetCausalFrontier)) {\n throw new Error(\"Replay frontier mismatch\");\n }\n return Object.freeze({\n headSequence: sequence,\n causalFrontier,\n stateHash: editableArtifactStateHash(session.stateHash()),\n });\n}\n\nasync function replaySerializedPlan(\n session: Exclude<NativeArtifactSession, NativeSpreadsheetSession>,\n plan: Exclude<EditableArtifactSnapshotReplayPlan, { modality: \"spreadsheet\" }>,\n signal: AbortSignal | undefined,\n): Promise<\n Readonly<{\n headSequence: number;\n nativeRevision: number;\n stateHash: ReturnType<typeof editableArtifactStateHash>;\n }>\n> {\n if (session.modality !== plan.modality) throw new Error(\"Replay modality mismatch\");\n let sequence = plan.baseHeadSequence;\n for await (const segment of plan.segments) {\n throwIfAborted(signal);\n if (segment.sequenceStart !== sequence + 1 || segment.modality !== session.modality) {\n throw new Error(\"Replay sequence or modality mismatch\");\n }\n const commit = decodeEditableArtifactSerializedCommit(segment.bytes, session.modality);\n const intent = decodeEditableArtifactMutationIntent(commit.intentBytes);\n const receipt = session.applyCommands(intent.commandBytes);\n if (!equalBytes(receipt, commit.nativeReceiptBytes)) throw new Error(\"Replay receipt mismatch\");\n sequence = segment.sequenceEnd;\n }\n if (sequence !== plan.targetHeadSequence || session.stateHash() !== plan.targetStateHash) {\n throw new Error(\"Replay target mismatch\");\n }\n if (safeRevision(session.revision()) !== plan.targetNativeRevision) {\n throw new Error(\"Replay native revision mismatch\");\n }\n return Object.freeze({\n headSequence: sequence,\n nativeRevision: plan.targetNativeRevision,\n stateHash: editableArtifactStateHash(session.stateHash()),\n });\n}\n\nfunction domainFrontier(bytes: Uint8Array): ReturnType<typeof editableArtifactCausalFrontier> {\n return editableArtifactCausalFrontier(\n decodeEditableArtifactCausalFrontier(bytes).map((entry) => ({\n replicaId: editableArtifactReplicaId(entry.replicaId),\n counter: entry.counter,\n })),\n );\n}\n\nasync function readVerifiedSnapshot(\n objects: BoundedObjectReadPort,\n snapshot: NonNullable<EditableArtifactKernelState[\"snapshot\"]>,\n signal?: AbortSignal,\n): Promise<Uint8Array> {\n const object = await objects.open({\n opaqueReference: snapshot.blobReference,\n maxBytes: MAX_EDITABLE_ARTIFACT_SNAPSHOT_BYTES,\n expectedByteSize: snapshot.byteSize,\n ...(signal ? { signal } : {}),\n });\n try {\n if (object.contentType !== undefined && object.contentType !== snapshot.mimeType) {\n throw new Error(\"Snapshot content type mismatch\");\n }\n const bytes = await collectExact(\n object.chunks(signal ? { signal } : {}),\n snapshot.byteSize,\n signal,\n );\n const contentHash = `sha256:${createHash(\"sha256\").update(bytes).digest(\"hex\")}`;\n if (contentHash !== snapshot.contentHash) throw new Error(\"Snapshot content hash mismatch\");\n await object.assertUnchanged(signal);\n return bytes;\n } finally {\n await object.close();\n }\n}\n\nasync function collectExact(\n chunks: AsyncIterable<Uint8Array>,\n expectedBytes: number,\n signal?: AbortSignal,\n): Promise<Uint8Array> {\n if (!Number.isSafeInteger(expectedBytes) || expectedBytes <= 0) {\n throw new Error(\"Snapshot byte size is invalid\");\n }\n const result = new Uint8Array(expectedBytes);\n let offset = 0;\n for await (const chunk of chunks) {\n throwIfAborted(signal);\n if (!(chunk instanceof Uint8Array) || chunk.byteLength === 0) {\n throw new Error(\"Snapshot stream is truncated\");\n }\n if (offset + chunk.byteLength > result.byteLength) {\n throw new Error(\"Snapshot stream exceeds its declared size\");\n }\n result.set(chunk, offset);\n offset += chunk.byteLength;\n }\n throwIfAborted(signal);\n if (offset !== result.byteLength) throw new Error(\"Snapshot stream is truncated\");\n return result;\n}\n\nasync function* fixedChunks(bytes: Uint8Array, signal?: AbortSignal): AsyncIterable<Uint8Array> {\n for (let offset = 0; offset < bytes.byteLength; offset += SNAPSHOT_CHUNK_BYTES) {\n throwIfAborted(signal);\n yield bytes.subarray(offset, Math.min(bytes.byteLength, offset + SNAPSHOT_CHUNK_BYTES));\n }\n}\n\nfunction namespaceForArtifact(artifactId: string): bigint {\n const digest = createHash(\"sha256\").update(artifactId).digest();\n let value = 0n;\n for (let index = 0; index < 8; index += 1) value = (value << 8n) | BigInt(digest[index]!);\n return value === 0n ? 1n : value;\n}\n\nfunction safeRevision(value: bigint): number {\n if (value < 0n || value > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new Error(\"Native revision exceeds the safe integer range\");\n }\n return Number(value);\n}\n\nfunction equalBytes(left: Uint8Array, right: Uint8Array): boolean {\n if (left.byteLength !== right.byteLength) return false;\n let difference = 0;\n for (let index = 0; index < left.byteLength; index += 1) {\n difference |= left[index]! ^ right[index]!;\n }\n return difference === 0;\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) throw new Error(\"Editable artifact native operation was cancelled\");\n}\n","import { createHash } from \"node:crypto\";\nimport {\n ArtifactOfficeSourceUnsupportedError,\n prepareArtifactOfficeImport,\n type ArtifactOfficeMimeType,\n} from \"@opengeni/artifact-tool/office-import\";\nimport {\n MAX_EDITABLE_ARTIFACT_SNAPSHOT_BYTES,\n EDITABLE_ARTIFACT_ORIGINAL_IMPORT_MAX_BYTES,\n editableArtifactCausalFrontier,\n editableArtifactContentHash,\n editableArtifactReplicaId,\n editableArtifactStateHash,\n EditableArtifactOfficeImportError,\n type EditableArtifactActor,\n type EditableArtifactOfficeImportPort,\n type EditableArtifactModality,\n type EditableArtifactScope,\n} from \"@opengeni/core/editable-artifacts\";\nimport { requireLiveAgentAttemptAuthorization } from \"@opengeni/core\";\nimport { getFilesForSubject } from \"@opengeni/db\";\nimport {\n MAX_BOUNDED_OBJECT_CHUNK_BYTES,\n type BoundedImmutableObjectWritePort,\n retryWhileMissing,\n type ObjectStorage,\n} from \"@opengeni/storage\";\nimport type { Database } from \"@opengeni/db\";\nimport type { VerifiedNativeArtifactRuntimeBinding } from \"./editable-artifact-native-kernel\";\n\nconst SNAPSHOT_MIME = \"application/vnd.opengeni.editable-artifact-snapshot\" as const;\n\nexport type EditableArtifactOfficeImportAdapterDependencies = Readonly<{\n db: Database;\n objectStorage: ObjectStorage;\n runtime: VerifiedNativeArtifactRuntimeBinding;\n sourceObjects: BoundedImmutableObjectWritePort;\n snapshotObjects: BoundedImmutableObjectWritePort;\n readFiles?: typeof getFilesForSubject;\n resolveFileAuthoritySubjectId?: typeof editableArtifactFileAuthoritySubjectId;\n prepareOffice?: typeof prepareArtifactOfficeImport;\n}>;\n\n/** Trusted import boundary from one ready workspace file into native sequence-zero state. */\nexport class EditableArtifactOfficeImportAdapter implements EditableArtifactOfficeImportPort {\n private readonly readFiles: typeof getFilesForSubject;\n private readonly resolveFileAuthoritySubjectId: typeof editableArtifactFileAuthoritySubjectId;\n\n constructor(private readonly dependencies: EditableArtifactOfficeImportAdapterDependencies) {\n this.readFiles = dependencies.readFiles ?? getFilesForSubject;\n this.resolveFileAuthoritySubjectId =\n dependencies.resolveFileAuthoritySubjectId ?? editableArtifactFileAuthoritySubjectId;\n }\n\n async prepare(\n input: Parameters<EditableArtifactOfficeImportPort[\"prepare\"]>[0],\n ): ReturnType<EditableArtifactOfficeImportPort[\"prepare\"]> {\n throwIfAborted(input.signal);\n const subjectId = await this.resolveFileAuthoritySubjectId(\n this.dependencies.db,\n input.scope,\n input.actor,\n );\n const [file] = await this.readFiles(this.dependencies.db, {\n accountId: input.scope.accountId,\n workspaceId: input.scope.workspaceId,\n subjectId,\n fileIds: [input.fileId],\n });\n if (!file || file.status !== \"ready\") {\n throw new EditableArtifactOfficeImportError(\"invalid_source\");\n }\n const expectedMimeType = officeMimeType(input.modality);\n if (\n file.contentType !== expectedMimeType ||\n !officeFilenameMatches(file.filename, input.modality) ||\n !Number.isSafeInteger(file.sizeBytes) ||\n file.sizeBytes < 1 ||\n file.sizeBytes > EDITABLE_ARTIFACT_ORIGINAL_IMPORT_MAX_BYTES ||\n typeof file.sha256 !== \"string\" ||\n !/^[0-9a-f]{64}$/u.test(file.sha256)\n ) {\n throw new EditableArtifactOfficeImportError(\"invalid_source\");\n }\n const sourceBytes = await readVerifiedWorkspaceFile(\n this.dependencies.objectStorage,\n file,\n input.signal,\n );\n const prepared = await prepareOfficeImport({\n runtime: this.dependencies.runtime,\n modality: input.modality,\n filename: file.filename,\n mimeType: expectedMimeType,\n bytes: sourceBytes,\n prepare: this.dependencies.prepareOffice ?? prepareArtifactOfficeImport,\n });\n const retainedSource = await this.dependencies.sourceObjects.write({\n chunks: byteChunks(sourceBytes),\n contentType: expectedMimeType,\n maxBytes: EDITABLE_ARTIFACT_ORIGINAL_IMPORT_MAX_BYTES,\n expectedByteSize: prepared.source.byteSize,\n expectedContentHash: prepared.source.contentHash,\n ...(input.signal ? { signal: input.signal } : {}),\n });\n const retainedSnapshot = await this.dependencies.snapshotObjects.write({\n chunks: byteChunks(prepared.snapshot.bytes),\n contentType: SNAPSHOT_MIME,\n maxBytes: MAX_EDITABLE_ARTIFACT_SNAPSHOT_BYTES,\n expectedByteSize: prepared.snapshot.byteSize,\n expectedContentHash: prepared.snapshot.contentHash,\n ...(input.signal ? { signal: input.signal } : {}),\n });\n const common = {\n modality: prepared.snapshot.modality,\n blobReference: retainedSnapshot.opaqueReference,\n byteSize: prepared.snapshot.byteSize,\n contentHash: editableArtifactContentHash(prepared.snapshot.contentHash),\n mimeType: SNAPSHOT_MIME,\n coveredHeadSequence: 0 as const,\n stateHash: editableArtifactStateHash(prepared.snapshot.stateHash),\n modelSchemaVersion: prepared.snapshot.modelSchemaVersion,\n kernelVersion: prepared.snapshot.kernelVersion,\n };\n return Object.freeze({\n originalImport: Object.freeze({\n fileId: file.id,\n blobReference: retainedSource.opaqueReference,\n byteSize: prepared.source.byteSize,\n contentHash: editableArtifactContentHash(prepared.source.contentHash),\n mimeType: expectedMimeType,\n }),\n snapshot:\n prepared.snapshot.modality === \"spreadsheet\"\n ? Object.freeze({\n ...common,\n modality: \"spreadsheet\" as const,\n coveredCausalFrontier: editableArtifactCausalFrontier(\n prepared.snapshot.coveredCausalFrontier.map((entry) => ({\n replicaId: editableArtifactReplicaId(entry.replicaId),\n counter: entry.counter,\n })),\n ),\n operationProtocolVersion: prepared.snapshot.operationProtocolVersion,\n crdtStateVersion: prepared.snapshot.crdtStateVersion,\n })\n : Object.freeze({\n ...common,\n modality: prepared.snapshot.modality,\n nativeRevision: prepared.snapshot.nativeRevision,\n }),\n });\n }\n}\n\nasync function prepareOfficeImport(input: {\n runtime: VerifiedNativeArtifactRuntimeBinding;\n modality: EditableArtifactModality;\n filename: string;\n mimeType: ArtifactOfficeMimeType;\n bytes: Uint8Array;\n prepare: typeof prepareArtifactOfficeImport;\n}) {\n try {\n return await input.prepare({\n facade: input.runtime.facade,\n modality: input.modality,\n filename: input.filename,\n mimeType: input.mimeType,\n bytes: input.bytes,\n expectedRuntimeTarget: input.runtime.location.target,\n expectedKernelVersion: input.runtime.runtime.buildIdentity,\n });\n } catch (error) {\n if (error instanceof ArtifactOfficeSourceUnsupportedError) {\n throw new EditableArtifactOfficeImportError(\"unsupported_content\");\n }\n throw error;\n }\n}\n\nfunction officeMimeType(modality: EditableArtifactModality): ArtifactOfficeMimeType {\n if (modality === \"spreadsheet\") {\n return \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\";\n }\n if (modality === \"document\") {\n return \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\";\n }\n return \"application/vnd.openxmlformats-officedocument.presentationml.presentation\";\n}\n\nfunction officeFilenameMatches(filename: string, modality: EditableArtifactModality): boolean {\n const extension =\n modality === \"spreadsheet\" ? \".xlsx\" : modality === \"document\" ? \".docx\" : \".pptx\";\n return filename.toLowerCase().endsWith(extension);\n}\n\nasync function readVerifiedWorkspaceFile(\n storage: ObjectStorage,\n file: NonNullable<Awaited<ReturnType<typeof getFilesForSubject>>>[number],\n signal?: AbortSignal,\n): Promise<Uint8Array> {\n throwIfAborted(signal);\n const before = await retryWhileMissing(async () => {\n try {\n return await storage.headFile(file);\n } catch (error) {\n if (typeof storage.fileExists === \"function\" && !(await storage.fileExists(file))) {\n return null;\n }\n throw error;\n }\n });\n if (!before) {\n throw new EditableArtifactOfficeImportError(\"source_changed\");\n }\n if (\n before.ContentLength !== file.sizeBytes ||\n before.ContentType !== file.contentType ||\n before.Metadata?.sha256 !== file.sha256 ||\n typeof before.VersionToken !== \"string\" ||\n before.VersionToken.length < 1\n ) {\n throw new EditableArtifactOfficeImportError(\"source_changed\");\n }\n const bytes = new Uint8Array(file.sizeBytes);\n const digest = createHash(\"sha256\");\n for (let start = 0; start < file.sizeBytes; start += MAX_BOUNDED_OBJECT_CHUNK_BYTES) {\n throwIfAborted(signal);\n const end = Math.min(file.sizeBytes, start + MAX_BOUNDED_OBJECT_CHUNK_BYTES) - 1;\n const chunk = await retryWhileMissing(async () => storage.getFileRange(file, { start, end }));\n if (!chunk || chunk.byteLength !== end - start + 1) {\n throw new EditableArtifactOfficeImportError(\"source_changed\");\n }\n bytes.set(chunk, start);\n digest.update(chunk);\n }\n const after = await retryWhileMissing(async () => {\n try {\n return await storage.headFile(file);\n } catch (error) {\n if (typeof storage.fileExists === \"function\" && !(await storage.fileExists(file))) {\n return null;\n }\n throw error;\n }\n });\n if (!after) {\n throw new EditableArtifactOfficeImportError(\"source_changed\");\n }\n const sha256 = digest.digest(\"hex\");\n if (\n after.ContentLength !== before.ContentLength ||\n after.ContentType !== before.ContentType ||\n after.Metadata?.sha256 !== before.Metadata?.sha256 ||\n after.VersionToken !== before.VersionToken ||\n sha256 !== file.sha256\n ) {\n throw new EditableArtifactOfficeImportError(\"source_changed\");\n }\n return bytes;\n}\n\nexport async function editableArtifactFileAuthoritySubjectId(\n db: Database,\n scope: EditableArtifactScope,\n actor: EditableArtifactActor,\n): Promise<string | null> {\n if (actor.kind !== \"agent\") return actor.subjectId;\n const authorization = await requireLiveAgentAttemptAuthorization(\n db,\n {\n accountId: scope.accountId,\n workspaceId: scope.workspaceId,\n subjectId: actor.subjectId,\n permissions: [],\n principalKind: \"agent_attempt\",\n metadata: {\n sessionId: actor.sessionId,\n turnId: actor.turnId,\n attemptId: actor.attemptId,\n executionGeneration: actor.generation,\n },\n },\n actor.sessionId,\n );\n return authorization.initiatingHumanSubjectId;\n}\n\nasync function* byteChunks(bytes: Uint8Array): AsyncIterable<Uint8Array> {\n for (let offset = 0; offset < bytes.byteLength; offset += MAX_BOUNDED_OBJECT_CHUNK_BYTES) {\n yield bytes.subarray(offset, offset + MAX_BOUNDED_OBJECT_CHUNK_BYTES);\n }\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) throw signal.reason ?? new Error(\"Artifact import aborted\");\n}\n","import { createHash } from \"node:crypto\";\n\nimport {\n type EditableArtifactAgentWorkspaceFilePort,\n type EditableArtifactDurableExportService,\n} from \"@opengeni/core/editable-artifacts\";\nimport { completeFileUpload, prepareGeneratedWorkspaceFile, type Database } from \"@opengeni/db\";\nimport { retryWhileMissing, type ObjectHead, type ObjectStorage } from \"@opengeni/storage\";\n\nconst UPLOAD_INTENT_TTL_MS = 60 * 60_000;\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;\n\nexport type EditableArtifactWorkspaceFileAdapterDependencies = Readonly<{\n db: Database;\n objectStorage: ObjectStorage;\n durableExports: EditableArtifactDurableExportService;\n now?: () => Date;\n prepareFile?: typeof prepareGeneratedWorkspaceFile;\n completeFile?: typeof completeFileUpload;\n}>;\n\n/**\n * Promotes one immutable materialization into the normal workspace-file domain.\n * The returned file ID is the only artifact export handle exposed to agents.\n */\nexport class EditableArtifactWorkspaceFileAdapter implements EditableArtifactAgentWorkspaceFilePort {\n private readonly now: () => Date;\n private readonly prepareFile: typeof prepareGeneratedWorkspaceFile;\n private readonly completeFile: typeof completeFileUpload;\n\n constructor(private readonly dependencies: EditableArtifactWorkspaceFileAdapterDependencies) {\n this.now = dependencies.now ?? (() => new Date());\n this.prepareFile = dependencies.prepareFile ?? prepareGeneratedWorkspaceFile;\n this.completeFile = dependencies.completeFile ?? completeFileUpload;\n }\n\n async ensureMaterializationFile(\n input: Parameters<EditableArtifactAgentWorkspaceFilePort[\"ensureMaterializationFile\"]>[0],\n ): ReturnType<EditableArtifactAgentWorkspaceFilePort[\"ensureMaterializationFile\"]> {\n throwIfAborted(input.signal);\n const storage = this.dependencies.objectStorage;\n if (!storage.headObject || !storage.putObjectStreamIfAbsent) {\n throw new Error(\"Object storage lacks immutable streaming upload support\");\n }\n const download = await this.dependencies.durableExports.openMaterializationDownload({\n scope: input.scope,\n actor: input.actor,\n artifactId: input.artifact.id,\n jobId: input.jobId,\n ...(input.signal ? { signal: input.signal } : {}),\n });\n try {\n const sha256 = plainSha256(download.contentHash);\n const filename = exportFilename(input.filename, download.format);\n const fileId = deterministicUuid(\n `editable-artifact-export:file:${input.scope.workspaceId}:${input.artifact.id}:${input.versionId}:${input.jobId}`,\n );\n const uploadId = deterministicUuid(\n `editable-artifact-export:upload:${input.scope.workspaceId}:${input.artifact.id}:${input.versionId}:${input.jobId}`,\n );\n const safeFilename = `artifact-${input.artifact.id}-${input.jobId}.${download.format}`;\n const objectKey = `workspaces/${input.scope.workspaceId}/files/${fileId}/artifact-exports/${safeFilename}`;\n const prepared = await this.prepareFile(this.dependencies.db, {\n accountId: input.scope.accountId,\n workspaceId: input.scope.workspaceId,\n fileId,\n uploadId,\n filename,\n safeFilename,\n contentType: download.mimeType,\n sizeBytes: download.byteSize,\n sha256,\n bucket: storage.bucket,\n objectKey,\n expiresAt: new Date(this.now().getTime() + UPLOAD_INTENT_TTL_MS),\n });\n\n let file = prepared.file;\n if (file.status !== \"ready\") {\n const existing = await storage.headObject(objectKey);\n if (existing) {\n assertStoredExport(existing, download.byteSize, download.mimeType, sha256);\n } else {\n const created = await storage.putObjectStreamIfAbsent({\n key: objectKey,\n contentType: download.mimeType,\n chunks: download.chunks(input.signal ? { signal: input.signal } : {}),\n byteSize: download.byteSize,\n sha256,\n ...(input.signal ? { signal: input.signal } : {}),\n });\n if (!created) {\n await assertVisibleExport(\n storage,\n objectKey,\n download.byteSize,\n download.mimeType,\n sha256,\n input.signal,\n );\n }\n }\n await download.assertUnchanged(input.signal);\n throwIfAborted(input.signal);\n file = await this.completeFile(this.dependencies.db, input.scope.workspaceId, uploadId);\n } else {\n await assertVisibleExport(\n storage,\n objectKey,\n download.byteSize,\n download.mimeType,\n sha256,\n input.signal,\n );\n await download.assertUnchanged(input.signal);\n }\n if (\n file.id !== fileId ||\n file.status !== \"ready\" ||\n file.filename !== filename ||\n file.contentType !== download.mimeType ||\n file.sizeBytes !== download.byteSize ||\n file.sha256 !== sha256\n ) {\n throw new Error(\"Generated workspace file differs from its immutable export\");\n }\n\n return Object.freeze({\n fileId: file.id,\n filename: file.filename,\n contentType: file.contentType,\n sizeBytes: file.sizeBytes,\n sha256,\n artifactId: input.artifact.id,\n versionId: input.versionId,\n materializationJobId: input.jobId,\n sourceHeadSequence: input.sourceHeadSequence,\n sourceStateHash: input.sourceStateHash,\n });\n } finally {\n await download.close();\n }\n }\n}\n\nasync function assertVisibleExport(\n storage: ObjectStorage,\n objectKey: string,\n byteSize: number,\n contentType: string,\n sha256: string,\n signal?: AbortSignal,\n): Promise<void> {\n const head = await retryWhileMissing(\n async () => await storage.headObject!(objectKey),\n signal ? { signal } : {},\n );\n assertStoredExport(head, byteSize, contentType, sha256);\n}\n\nfunction assertStoredExport(\n head: ObjectHead | null,\n byteSize: number,\n contentType: string,\n sha256: string,\n): void {\n if (\n !head ||\n head.ContentLength !== byteSize ||\n head.ContentType !== contentType ||\n head.Metadata?.sha256 !== sha256 ||\n typeof head.VersionToken !== \"string\" ||\n head.VersionToken.length < 1\n ) {\n throw new Error(\"Workspace export object differs from its durable materialization\");\n }\n}\n\nfunction exportFilename(value: string, format: string): string {\n const expectedExtension = `.${format}`;\n const normalized = value\n .normalize(\"NFKC\")\n .replace(/[\\\\/:*?\"<>|\\u0000-\\u001f\\u007f]+/gu, \"-\")\n .replace(/\\s+/gu, \" \")\n .trim()\n .slice(0, 200);\n const stem = normalized.toLowerCase().endsWith(expectedExtension)\n ? normalized.slice(0, -expectedExtension.length)\n : normalized;\n return `${stem.replace(/[. ]+$/u, \"\").slice(0, 190) || \"artifact\"}${expectedExtension}`;\n}\n\nfunction plainSha256(value: string): string {\n const match = /^sha256:([0-9a-f]{64})$/u.exec(value);\n if (!match) throw new Error(\"Materialized artifact content hash is invalid\");\n return match[1]!;\n}\n\nfunction deterministicUuid(seed: string): string {\n const bytes = createHash(\"sha256\").update(seed, \"utf8\").digest().subarray(0, 16);\n bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x50;\n bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;\n const hex = bytes.toString(\"hex\");\n const value = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n if (!UUID_PATTERN.test(value)) throw new Error(\"Generated workspace file identity is invalid\");\n return value;\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) throw signal.reason ?? new Error(\"Artifact export aborted\");\n}\n","import { randomUUID } from \"node:crypto\";\nimport { isDatabaseConnectionLoss } from \"@opengeni/db\";\nimport type { Attributes, Observability, Span } from \"@opengeni/observability\";\n\nexport type ApiFatalEvent = \"startup_failure\" | \"unhandled_rejection\" | \"uncaught_exception\";\nexport type ApiFatalPhase = \"startup\" | \"running\";\nexport type ApiFatalReasonKind =\n | \"bigint\"\n | \"boolean\"\n | \"error\"\n | \"function\"\n | \"null\"\n | \"number\"\n | \"object\"\n | \"string\"\n | \"symbol\"\n | \"undefined\";\n\ntype ApiFatalObservability = Pick<Observability, \"error\" | \"flush\" | \"startSpan\"> &\n Partial<Pick<Observability, \"recordFailureDiagnostic\" | \"warn\" | \"incrementCounter\">>;\n\ntype ApiFatalProcess = {\n on: (\n event: \"unhandledRejection\" | \"uncaughtException\",\n listener: (reason: unknown) => void,\n ) => void;\n off: (\n event: \"unhandledRejection\" | \"uncaughtException\",\n listener: (reason: unknown) => void,\n ) => void;\n exit: (code: number) => void;\n};\n\nexport type ApiFatalProcessBoundaryOptions = {\n process?: ApiFatalProcess;\n observability?: ApiFatalObservability;\n flushTimeoutMs?: number;\n correlationId?: () => string;\n fallbackLog?: (message: string) => void;\n /**\n * Classifies an unhandled rejection that leaves no process state behind and\n * is therefore survivable once the API is serving. Defaults to a lost\n * database connection (deploy drain, failover, restart): the rejected query\n * held only a pooled connection the driver has already discarded, and every\n * durable loop retries its claim on the next tick.\n */\n isRecoverableRejection?: (reason: unknown) => boolean;\n};\n\nexport type ApiFatalProcessBoundary = {\n attachObservability: (observability: ApiFatalObservability) => void;\n markRunning: () => void;\n reportStartupFailure: (reason: unknown) => Promise<void>;\n dispose: () => void;\n};\n\nconst API_FATAL_FLUSH_TIMEOUT_MS = 1_000;\nconst API_FATAL_CORRELATION_ID_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;\n\nconst FATAL_ERROR_CODES = {\n startup_failure: \"api_startup_failed\",\n unhandled_rejection: \"api_unhandled_rejection\",\n uncaught_exception: \"api_uncaught_exception\",\n} as const;\n\nexport function installApiFatalProcessBoundary(\n options: ApiFatalProcessBoundaryOptions = {},\n): ApiFatalProcessBoundary {\n const runtimeProcess = options.process ?? defaultProcessBoundary();\n const flushTimeoutMs = options.flushTimeoutMs ?? API_FATAL_FLUSH_TIMEOUT_MS;\n const correlationId = options.correlationId ?? (() => `api-fatal.${randomUUID()}`);\n const fallbackLog = options.fallbackLog ?? ((message: string) => console.error(message));\n const isRecoverableRejection = options.isRecoverableRejection ?? isDatabaseConnectionLoss;\n let observability = options.observability;\n let phase: ApiFatalPhase = \"startup\";\n let reporting = false;\n\n const recover = (reason: unknown): boolean => {\n if (phase !== \"running\" || reporting) return false;\n let recoverable = false;\n try {\n recoverable = isRecoverableRejection(reason);\n } catch {\n return false;\n }\n if (!recoverable) return false;\n const attributes = {\n errorClass: \"ApiRecoveredRejection\",\n errorCode: \"api_unhandled_database_connection_loss\",\n origin: \"api\",\n reasonKind: apiFatalReasonKind(reason),\n };\n try {\n if (observability?.warn) {\n observability.warn(\n \"Opengeni API recovered an unhandled database connection loss\",\n attributes,\n );\n } else {\n safeFallbackLog(\n fallbackLog,\n \"Opengeni API recovered an unhandled database connection loss (api_unhandled_database_connection_loss)\",\n );\n }\n observability?.incrementCounter?.({\n name: \"opengeni_api_recovered_rejections_total\",\n help: \"Unhandled rejections the API survived because they only reported a lost database connection.\",\n labels: { code: \"api_unhandled_database_connection_loss\" },\n });\n } catch {\n // Recovery never depends on the observer.\n }\n return true;\n };\n\n const report = async (event: ApiFatalEvent, reason: unknown): Promise<void> => {\n if (reporting) return;\n reporting = true;\n\n const diagnostic = apiFatalDiagnostic(event, phase, reason, correlationId);\n let message = apiFatalMessage(diagnostic);\n const activeObservability = observability;\n try {\n if (activeObservability) {\n try {\n const diagnosticId = activeObservability.recordFailureDiagnostic?.({\n code: FATAL_ERROR_CODES[event],\n stage: phase,\n retryDecision: \"not_retryable\",\n error: reason,\n });\n if (diagnosticId) {\n diagnostic.correlationId = diagnosticId;\n message = apiFatalMessage(diagnostic);\n }\n } catch {\n // Never replace the required fatal exit with an observer failure.\n }\n let logged = false;\n try {\n activeObservability.error(message, diagnostic);\n logged = true;\n } catch {\n // The fatal boundary must still report and terminate if logging is unhealthy.\n }\n if (!logged) {\n safeFallbackLog(fallbackLog, message);\n }\n try {\n const span: Span = activeObservability.startSpan(\"api.process.fatal\", diagnostic);\n span.end({ error: true });\n } catch {\n // The synchronous log remains authoritative when span creation fails.\n }\n await flushWithin(activeObservability, flushTimeoutMs);\n } else {\n safeFallbackLog(fallbackLog, message);\n }\n } finally {\n runtimeProcess.exit(1);\n }\n };\n\n const onUnhandledRejection = (reason: unknown): void => {\n if (recover(reason)) return;\n void report(\"unhandled_rejection\", reason);\n };\n const onUncaughtException = (reason: unknown): void => {\n void report(\"uncaught_exception\", reason);\n };\n runtimeProcess.on(\"unhandledRejection\", onUnhandledRejection);\n runtimeProcess.on(\"uncaughtException\", onUncaughtException);\n\n return {\n attachObservability: (value) => {\n observability = value;\n },\n markRunning: () => {\n phase = \"running\";\n },\n reportStartupFailure: async (reason) => {\n await report(\"startup_failure\", reason);\n },\n dispose: () => {\n runtimeProcess.off(\"unhandledRejection\", onUnhandledRejection);\n runtimeProcess.off(\"uncaughtException\", onUncaughtException);\n },\n };\n}\n\nfunction apiFatalDiagnostic(\n event: ApiFatalEvent,\n phase: ApiFatalPhase,\n reason: unknown,\n correlationId: () => string,\n): Attributes & {\n errorClass: \"ApiFatalOperationError\";\n errorCode: (typeof FATAL_ERROR_CODES)[ApiFatalEvent];\n origin: \"api\";\n phase: ApiFatalPhase;\n reasonKind: ApiFatalReasonKind;\n correlationId: string;\n} {\n let safeCorrelationId = \"api-fatal.fallback\";\n try {\n const candidate = correlationId();\n if (API_FATAL_CORRELATION_ID_PATTERN.test(candidate)) {\n safeCorrelationId = candidate;\n }\n } catch {\n // A fixed valid fallback preserves the fatal report and nonzero exit.\n }\n return {\n errorClass: \"ApiFatalOperationError\",\n errorCode: FATAL_ERROR_CODES[event],\n origin: \"api\",\n phase,\n reasonKind: apiFatalReasonKind(reason),\n correlationId: safeCorrelationId,\n };\n}\n\nfunction apiFatalReasonKind(reason: unknown): ApiFatalReasonKind {\n if (reason === null) return \"null\";\n const kind = typeof reason;\n if (kind !== \"object\") return kind;\n try {\n return reason instanceof Error ? \"error\" : \"object\";\n } catch {\n return \"object\";\n }\n}\n\nfunction apiFatalMessage(diagnostic: ReturnType<typeof apiFatalDiagnostic>): string {\n return (\n `Opengeni API fatal process failure (${diagnostic.errorCode}; ` +\n `phase=${diagnostic.phase}; reason_kind=${diagnostic.reasonKind}; ` +\n `correlation_id=${diagnostic.correlationId})`\n );\n}\n\nasync function flushWithin(\n observability: Pick<Observability, \"flush\">,\n timeoutMs: number,\n): Promise<void> {\n let flush: Promise<void>;\n try {\n flush = Promise.resolve(observability.flush()).catch(() => undefined);\n } catch {\n return;\n }\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return;\n\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n flush,\n new Promise<void>((resolve) => {\n timeout = setTimeout(resolve, timeoutMs);\n }),\n ]);\n } finally {\n if (timeout !== undefined) clearTimeout(timeout);\n }\n}\n\nfunction safeFallbackLog(fallbackLog: (message: string) => void, message: string): void {\n try {\n fallbackLog(message);\n } catch {\n // Process termination remains mandatory even when every diagnostic sink fails.\n }\n}\n\nfunction defaultProcessBoundary(): ApiFatalProcess {\n return {\n on: (event, listener) => {\n if (event === \"unhandledRejection\") {\n process.on(\"unhandledRejection\", listener);\n } else {\n process.on(\"uncaughtException\", listener);\n }\n },\n off: (event, listener) => {\n if (event === \"unhandledRejection\") {\n process.off(\"unhandledRejection\", listener);\n } else {\n process.off(\"uncaughtException\", listener);\n }\n },\n exit: (code) => {\n process.exit(code);\n },\n };\n}\n","type ShutdownSignal = \"SIGINT\" | \"SIGTERM\";\ntype ShutdownProcess = {\n on(signal: ShutdownSignal, handler: () => void): unknown;\n off(signal: ShutdownSignal, handler: () => void): unknown;\n exit(code: number): void;\n};\n\n/** Standalone process boundary; embedded hosts keep owning their explicit close(). */\nexport function installApiShutdownHandlers(input: {\n close: () => Promise<void>;\n process?: ShutdownProcess;\n timeoutMs?: number;\n onFailure?: () => void;\n}): () => void {\n const runtime = input.process ?? process;\n let started = false;\n let finished = false;\n let deadline: ReturnType<typeof setTimeout> | undefined;\n const dispose = () => {\n runtime.off(\"SIGINT\", shutdown);\n runtime.off(\"SIGTERM\", shutdown);\n };\n const finish = (code: number) => {\n if (finished) return;\n finished = true;\n clearTimeout(deadline);\n dispose();\n if (code !== 0) {\n try {\n input.onFailure?.();\n } catch {\n /* Observability cannot prevent exit. */\n }\n }\n runtime.exit(code);\n };\n function shutdown() {\n if (started) return;\n started = true;\n deadline = setTimeout(() => finish(1), input.timeoutMs ?? 30_000);\n deadline.unref?.();\n // Catch synchronous close failures as well. Duplicate signals never start a\n // second logout or race the connection pool's credential/session cleanup.\n void Promise.resolve()\n .then(input.close)\n .then(\n () => finish(0),\n () => finish(1),\n );\n }\n runtime.on(\"SIGINT\", shutdown);\n runtime.on(\"SIGTERM\", shutdown);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,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","getEnrollment","enrollment","appendAndPublishEvents","randomUUID","CLAIM_SECONDS","POLL_INTERVAL_MS","PRUNE_EVERY_TICKS","createHash","randomUUID","MAX_EDITABLE_ARTIFACT_SNAPSHOT_BYTES","withRlsContext","MAX_BOUNDED_OBJECT_CHUNK_BYTES","createHash","createHash","replayedTarget","createHash","MAX_EDITABLE_ARTIFACT_SNAPSHOT_BYTES","editableArtifactCausalFrontier","editableArtifactContentHash","editableArtifactReplicaId","editableArtifactStateHash","throwIfAborted","createHash","retryWhileMissing","throwIfAborted","withRlsContext","randomUUID","MAX_EDITABLE_ARTIFACT_SNAPSHOT_BYTES","createHash","MAX_BOUNDED_OBJECT_CHUNK_BYTES","randomUUID"]}