@opengeni/api-router 0.23.1 → 0.30.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app.d.ts +3 -2
- package/dist/app.js +5 -3
- package/dist/auth/canonical-human-session-admission.d.ts +27 -0
- package/dist/browser-auth-broker.d.ts +20 -0
- package/dist/browser-controller-authority.d.ts +61 -0
- package/dist/browser-network-route.d.ts +8 -0
- package/dist/browser-state-authority.d.ts +27 -0
- package/dist/{chunk-T4T2PGU4.js → chunk-2PQMSRCB.js} +37891 -17463
- package/dist/chunk-2PQMSRCB.js.map +1 -0
- package/dist/codemode.d.ts +23 -0
- package/dist/controller-data-plane.d.ts +12 -0
- package/dist/editable-artifact-live-hints.d.ts +11 -0
- package/dist/editable-artifact-native-kernel.d.ts +37 -0
- package/dist/editable-artifact-office-import.d.ts +22 -0
- package/dist/editable-artifact-production.d.ts +29 -0
- package/dist/editable-artifact-websocket.d.ts +49 -0
- package/dist/editable-artifact-workspace-files.d.ts +23 -0
- package/dist/github-browser-flow.d.ts +6 -0
- package/dist/http/auth.d.ts +1 -1
- package/dist/http/cors.d.ts +1 -0
- package/dist/http/sse.d.ts +18 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.js +1796 -22
- package/dist/index.js.map +1 -1
- package/dist/integrations/api-integrations.d.ts +24 -0
- package/dist/integrations/atlassian.d.ts +176 -0
- package/dist/integrations/fiken.d.ts +233 -0
- package/dist/integrations/github-skill-source.d.ts +5 -0
- package/dist/integrations/google-drive.d.ts +85 -0
- package/dist/integrations/oauth-client.d.ts +22 -1
- package/dist/integrations/provider-oauth.d.ts +17 -0
- package/dist/integrations/slack-bot.d.ts +175 -1
- package/dist/integrations/slack-interactions.d.ts +24 -6
- package/dist/integrations/social-api.d.ts +2 -1
- package/dist/interaction-holder-heartbeat.d.ts +17 -0
- package/dist/interaction-metrics.d.ts +11 -0
- package/dist/mcp/editable-artifact-query-schema.d.ts +4 -0
- package/dist/mcp/editable-artifacts.d.ts +13 -0
- package/dist/mcp/scheduled-task-view.d.ts +168 -0
- package/dist/mcp/server.d.ts +16 -4
- package/dist/memory-slack-delivery.d.ts +9 -0
- package/dist/model-catalog.d.ts +1 -0
- package/dist/routes/api-integrations.d.ts +8 -0
- package/dist/routes/browser-identities.d.ts +5 -0
- package/dist/routes/browser-sessions.d.ts +6 -0
- package/dist/routes/canonical-human-identities.d.ts +3 -0
- package/dist/routes/channels.d.ts +3 -0
- package/dist/routes/company-profile.d.ts +3 -0
- package/dist/routes/computer-sessions.d.ts +6 -0
- package/dist/routes/editable-artifacts.d.ts +44 -0
- package/dist/routes/integration-facets.d.ts +3 -0
- package/dist/routes/interaction-resources.d.ts +5 -0
- package/dist/routes/memory-slack-publications.d.ts +6 -0
- package/dist/routes/organization-memberships.d.ts +3 -0
- package/dist/routes/plugins.d.ts +8 -0
- package/dist/routes/sessions.d.ts +18 -2
- package/dist/routes/skills.d.ts +6 -0
- package/dist/routes/slack-task-policy.d.ts +3 -0
- package/dist/routes/supergrok.d.ts +3 -0
- package/dist/routes/video-generation.d.ts +3 -0
- package/dist/sandbox/channel-a.d.ts +62 -2
- package/dist/sandbox/machines.d.ts +2 -2
- package/dist/sandbox/metrics-ingestion.d.ts +6 -1
- package/dist/sandbox/viewer.d.ts +7 -3
- package/dist/slack-reaction-files.d.ts +27 -0
- package/dist/temporal-schedule-cleanup.d.ts +26 -0
- package/dist/transcription/providers/xai-subscription.d.ts +8 -0
- package/dist/xai-realtime.d.ts +26 -0
- package/dist/xai-subscription-auth.d.ts +23 -0
- package/package.json +20 -14
- package/src/app.ts +604 -64
- package/src/auth/canonical-human-session-admission.ts +116 -0
- package/src/auth/managed-auth.ts +101 -0
- package/src/browser-auth-broker.ts +155 -0
- package/src/browser-controller-authority.ts +186 -0
- package/src/browser-network-route.ts +34 -0
- package/src/browser-state-authority.ts +236 -0
- package/src/codemode.ts +186 -0
- package/src/controller-data-plane.ts +35 -0
- package/src/editable-artifact-live-hints.ts +64 -0
- package/src/editable-artifact-native-kernel.ts +659 -0
- package/src/editable-artifact-office-import.ts +230 -0
- package/src/editable-artifact-production.ts +419 -0
- package/src/editable-artifact-websocket.ts +311 -0
- package/src/editable-artifact-workspace-files.ts +186 -0
- package/src/github-browser-flow.ts +35 -6
- package/src/http/auth.ts +29 -9
- package/src/http/cors.ts +3 -0
- package/src/http/sse.ts +229 -5
- package/src/index.ts +119 -20
- package/src/integrations/api-integrations.ts +365 -0
- package/src/integrations/atlassian.ts +1621 -0
- package/src/integrations/fiken.ts +1230 -0
- package/src/integrations/github-skill-source.ts +142 -0
- package/src/integrations/google-drive.ts +1005 -64
- package/src/integrations/oauth-client.ts +123 -33
- package/src/integrations/provider-oauth.ts +756 -0
- package/src/integrations/slack-bot.ts +669 -11
- package/src/integrations/slack-interactions.ts +2063 -93
- package/src/integrations/social-api.ts +11 -0
- package/src/interaction-holder-heartbeat.ts +95 -0
- package/src/interaction-metrics.ts +159 -0
- package/src/mcp/documents.ts +146 -6
- package/src/mcp/editable-artifact-query-schema.ts +236 -0
- package/src/mcp/editable-artifacts.ts +448 -0
- package/src/mcp/scheduled-task-view.ts +34 -0
- package/src/mcp/server.ts +1756 -355
- package/src/memory-slack-delivery.ts +209 -0
- package/src/model-catalog.ts +19 -6
- package/src/routes/api-integrations.ts +410 -0
- package/src/routes/browser-identities.ts +160 -0
- package/src/routes/browser-sessions.ts +4482 -0
- package/src/routes/canonical-human-identities.ts +156 -0
- package/src/routes/channels.ts +90 -0
- package/src/routes/company-profile.ts +255 -0
- package/src/routes/computer-sessions.ts +1602 -0
- package/src/routes/connections.ts +421 -99
- package/src/routes/documents.ts +22 -3
- package/src/routes/editable-artifacts.ts +1159 -0
- package/src/routes/files.ts +106 -4
- package/src/routes/github.ts +18 -2
- package/src/routes/install.ts +7 -1
- package/src/routes/integration-facets.ts +258 -0
- package/src/routes/interaction-resources.ts +595 -0
- package/src/routes/memory-slack-publications.ts +216 -0
- package/src/routes/organization-memberships.ts +53 -0
- package/src/routes/packs.ts +437 -7
- package/src/routes/plugins.ts +752 -0
- package/src/routes/rigs.ts +77 -20
- package/src/routes/scheduled-tasks.ts +67 -40
- package/src/routes/sessions.ts +830 -278
- package/src/routes/skills.ts +256 -0
- package/src/routes/slack-task-policy.ts +115 -0
- package/src/routes/supergrok.ts +717 -0
- package/src/routes/transcription-recordings.ts +9 -2
- package/src/routes/transcriptions.ts +2 -1
- package/src/routes/video-generation.ts +162 -0
- package/src/routes/workspaces.ts +68 -28
- package/src/sandbox/channel-a.ts +750 -116
- package/src/sandbox/machines.ts +5 -5
- package/src/sandbox/metrics-ingestion.ts +121 -3
- package/src/sandbox/rematerialize.ts +35 -47
- package/src/sandbox/viewer.ts +39 -12
- package/src/slack-reaction-files.ts +181 -0
- package/src/temporal-schedule-cleanup.ts +135 -0
- package/src/transcription/providers/xai-subscription.ts +110 -0
- package/src/transcription/service.ts +17 -2
- package/src/xai-realtime.ts +216 -0
- package/src/xai-subscription-auth.ts +132 -0
- package/dist/chunk-T4T2PGU4.js.map +0 -1
- package/dist/mcp/toolspace.d.ts +0 -71
- package/src/mcp/toolspace.ts +0 -1190
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/observability.ts","../src/sandbox/auth-callout.ts","../src/sandbox/metrics-ingestion.ts"],"sourcesContent":["import {\n dbSearchPath,\n getSettings,\n resolveNatsCalloutConfig,\n resolveNatsControlPlaneAuth,\n retryStartupDependency,\n startupRetryOptions,\n temporalConnectionOptions,\n} from \"@opengeni/config\";\nimport type {\n ScheduledTask,\n ScheduledTaskOverlapPolicy,\n ScheduledTaskScheduleSpec,\n} from \"@opengeni/contracts\";\nimport {\n assertRuntimeDatabasePosture,\n createDb,\n markSessionWorkflowWakeDelivered,\n runtimeDatabaseReadyCheck,\n type Database,\n} from \"@opengeni/db\";\nimport { createNatsEventBus, type ResponderConnection } from \"@opengeni/events\";\nimport { createObservability, logStartupDependencyRetry } from \"@opengeni/observability\";\nimport { SESSION_WORKFLOW_WAKE_DISPATCHER_SCHEDULE_ID } from \"@opengeni/core\";\nimport {\n Connection,\n Client as TemporalClient,\n ScheduleNotFoundError,\n ScheduleOverlapPolicy,\n WorkflowExecutionAlreadyStartedError,\n} from \"@temporalio/client\";\nimport type { ScheduleOptions, ScheduleSpec, ScheduleUpdateOptions } from \"@temporalio/client\";\nimport { createAppComposition, type DocumentIndexClient, type SessionWorkflowClient } from \"./app\";\nimport { observabilityEventLogger } from \"./observability\";\nimport { startAuthCalloutResponder } from \"./sandbox/auth-callout\";\nimport { startHelloIngestion, startMetricsIngestion } from \"./sandbox/metrics-ingestion\";\nimport { startSlackInteractionPump } from \"./integrations/slack-interactions\";\n\n/**\n * A REJECT_DUPLICATE start collides on the deterministic workflowId when the\n * same manual trigger token fires twice. Temporal surfaces that as\n * WorkflowExecutionAlreadyStartedError; the caller treats it as an idempotent\n * no-op rather than a failure.\n */\nfunction isWorkflowAlreadyStarted(error: unknown): boolean {\n return error instanceof WorkflowExecutionAlreadyStartedError;\n}\n\nconst TEMPORAL_MONTHS = [\n \"JANUARY\",\n \"FEBRUARY\",\n \"MARCH\",\n \"APRIL\",\n \"MAY\",\n \"JUNE\",\n \"JULY\",\n \"AUGUST\",\n \"SEPTEMBER\",\n \"OCTOBER\",\n \"NOVEMBER\",\n \"DECEMBER\",\n] as const;\n\nexport async function createTemporalWorkflowClient(\n settings: ReturnType<typeof getSettings>,\n db: Database,\n): Promise<{\n client: SessionWorkflowClient;\n documentIndexer: DocumentIndexClient;\n close: () => Promise<void>;\n}> {\n const connection = await Connection.connect(temporalConnectionOptions(settings));\n const temporal = new TemporalClient({\n connection,\n namespace: settings.temporalNamespace,\n });\n const client: SessionWorkflowClient = {\n signalUserMessage: async ({ eventId, workflowId }) => {\n await temporal.workflow.getHandle(workflowId).signal(\"userMessage\", eventId);\n },\n wakeSessionWorkflow: async ({\n accountId,\n workspaceId,\n sessionId,\n workflowId,\n wakeRevision,\n interruptionRequested,\n }) => {\n await temporal.workflow.signalWithStart(\"sessionWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [{ accountId, workspaceId, sessionId }],\n signal: interruptionRequested ? \"sessionControl\" : \"queueChanged\",\n });\n await markSessionWorkflowWakeDelivered(db, {\n accountId,\n workspaceId,\n sessionId,\n temporalWorkflowId: workflowId,\n wakeRevision,\n });\n },\n requestSessionWorkflowWakeDispatch: async () => {\n await temporal.schedule\n .getHandle(SESSION_WORKFLOW_WAKE_DISPATCHER_SCHEDULE_ID)\n .trigger(ScheduleOverlapPolicy.BUFFER_ONE);\n },\n signalCodexCapacity: async ({\n accountId,\n workspaceId,\n sessionId,\n workflowId,\n wakeRevision,\n workflowWakeRevision,\n }) => {\n await temporal.workflow.signalWithStart(\"sessionWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [{ accountId, workspaceId, sessionId }],\n signal: \"codexCapacityChanged\",\n signalArgs: [wakeRevision],\n });\n await markSessionWorkflowWakeDelivered(db, {\n accountId,\n workspaceId,\n sessionId,\n temporalWorkflowId: workflowId,\n wakeRevision: workflowWakeRevision,\n });\n },\n signalApprovalDecision: async ({\n accountId,\n workspaceId,\n sessionId,\n eventId,\n workflowId,\n workflowWakeRevision,\n }) => {\n await temporal.workflow.signalWithStart(\"sessionWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [{ accountId, workspaceId, sessionId }],\n signal: \"approvalDecision\",\n signalArgs: [eventId],\n });\n await markSessionWorkflowWakeDelivered(db, {\n accountId,\n workspaceId,\n sessionId,\n temporalWorkflowId: workflowId,\n wakeRevision: workflowWakeRevision,\n });\n },\n syncScheduledTask: async ({ task }) => {\n const schedule = temporal.schedule.getHandle(task.temporalScheduleId);\n const options = temporalScheduleOptions(task, settings.temporalTaskQueue);\n try {\n await schedule.update(() => temporalScheduleUpdateOptions(options));\n } catch (error) {\n if (!shouldCreateScheduleAfterUpdateError(error)) {\n throw error;\n }\n await temporal.schedule.create(options);\n }\n },\n deleteScheduledTaskSchedule: async ({ temporalScheduleId }) => {\n await temporal.schedule\n .getHandle(temporalScheduleId)\n .delete()\n .catch(() => undefined);\n },\n triggerScheduledTask: async ({\n task,\n agentRunUsageIdempotencyKey,\n triggerWorkflowId,\n initiator,\n }) => {\n // Deterministic workflowId (derived from the trigger token by the\n // caller) + REJECT_DUPLICATE makes a retried manual trigger idempotent:\n // the second start collides on the id and is rejected instead of\n // spawning a second run. The shared idempotency key dedupes the charge.\n const workflowId = triggerWorkflowId;\n try {\n await temporal.workflow.start(\"scheduledTaskFireWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n workflowIdReusePolicy: \"REJECT_DUPLICATE\",\n args: [\n {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n taskId: task.id,\n triggerType: \"manual\",\n agentRunUsageIdempotencyKey,\n initiator,\n },\n ],\n });\n } catch (error) {\n // A duplicate trigger token started this run already; treat the retry\n // as a no-op so the (idempotent) usage charge stays the only effect.\n if (isWorkflowAlreadyStarted(error)) {\n return;\n }\n throw error;\n }\n },\n startRigVerification: async ({ workspaceId, changeId, versionId, workflowId }) => {\n const targetId = changeId ?? versionId;\n if (!targetId) {\n throw new Error(\"rig verification requires changeId or versionId\");\n }\n await temporal.workflow.start(\"rigVerificationWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId: workflowId ?? `rig-verification-${targetId}-${crypto.randomUUID()}`,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [\n {\n workspaceId,\n ...(changeId ? { changeId } : {}),\n ...(versionId ? { versionId } : {}),\n },\n ],\n });\n },\n check: async () => {\n await connection.workflowService.getSystemInfo({});\n },\n };\n const documentIndexer: DocumentIndexClient = {\n indexDocument: async (input) => {\n const { documentId } = input;\n const workflowId = `document-index-${documentId}-${crypto.randomUUID()}`;\n await temporal.workflow.start(\"documentIndexWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n args: [input],\n });\n },\n };\n return {\n client,\n documentIndexer,\n close: async () => {\n await connection.close();\n },\n };\n}\n\nexport async function startApi() {\n const settings = getSettings();\n const observability = createObservability(settings, { component: \"api\" });\n // Step I: standalone → dbSchema unset → searchPath undefined → today's plain\n // handle (public). Embedded → scoped to the dedicated schema + the host's RLS\n // strategy.\n const searchPath = dbSearchPath(settings);\n const dbClient = createDb(settings.databaseUrl, {\n ...(searchPath ? { searchPath } : {}),\n rlsStrategy: settings.rlsStrategy,\n });\n let bus: Awaited<ReturnType<typeof createNatsEventBus>> | undefined;\n let workflowClient: Awaited<ReturnType<typeof createTemporalWorkflowClient>> | undefined;\n const retryOptions = startupRetryOptions(settings);\n const onRetry = (event: Parameters<typeof logStartupDependencyRetry>[1]) =>\n logStartupDependencyRetry(observability, event);\n const databasePosture = {\n rlsStrategy: settings.rlsStrategy,\n expectedRole: settings.runtimeDatabaseRole,\n targetSchema: settings.dbSchema.trim() || \"public\",\n } as const;\n // The PRIVILEGED control-plane NATS login (M-AUTH): when the server runs with\n // auth_callout, api/worker authenticate as a static account user permitted to\n // request `agent.*.rpc`. Null in local dev (anonymous connect — the bus default).\n const controlPlaneAuth = resolveNatsControlPlaneAuth(settings);\n try {\n await retryStartupDependency(\n \"PostgreSQL runtime posture\",\n () => assertRuntimeDatabasePosture(dbClient.db, databasePosture),\n { ...retryOptions, onRetry },\n );\n bus = await retryStartupDependency(\n \"NATS\",\n () =>\n createNatsEventBus(\n settings.natsUrl,\n controlPlaneAuth\n ? { user: controlPlaneAuth.user, pass: controlPlaneAuth.password }\n : undefined,\n { logger: observabilityEventLogger(observability) },\n ),\n {\n ...retryOptions,\n onRetry,\n },\n );\n workflowClient = await retryStartupDependency(\n \"Temporal\",\n () => createTemporalWorkflowClient(settings, dbClient.db),\n {\n ...retryOptions,\n onRetry,\n },\n );\n } catch (error) {\n await Promise.allSettled([bus?.close(), workflowClient?.close(), dbClient.close()]);\n throw error;\n }\n if (!bus || !workflowClient) {\n await dbClient.close();\n throw new Error(\"OpenGeni API startup dependencies were not initialized\");\n }\n const { app, routeDeps } = createAppComposition({\n settings,\n db: dbClient.db,\n bus,\n workflowClient: workflowClient.client,\n documentIndexer: workflowClient.documentIndexer,\n observability,\n readinessChecks: {\n db: runtimeDatabaseReadyCheck(dbClient.db, databasePosture),\n },\n });\n const server = Bun.serve({\n hostname: settings.apiHost,\n port: settings.apiPort,\n idleTimeout: 255,\n fetch: app.fetch,\n });\n const stopSlackInteractionPump = settings.slackSigningSecret\n ? startSlackInteractionPump(routeDeps)\n : undefined;\n // M10 — start the metrics-ingestion consumer (agent heartbeats → DB last-sample\n // + downsampled series), gated on the selfhosted flag. A no-op when disabled.\n let stopMetricsIngestion: (() => void) | undefined;\n // Reconcile enrollments.has_display to the LIVE capability the agent reports in\n // its connect Hello (has_display was frozen at the enroll-time snapshot). Gated\n // on the same selfhosted flag.\n let stopHelloIngestion: (() => void) | undefined;\n // M-AUTH — start the NATS auth-callout responder (the tenancy boundary): it\n // validates an agent's enrollment bearer presented at NATS connect and mints a\n // workspace-scoped user JWT. Gated on the selfhosted flag + a resolvable callout\n // config; without the callout plane it never starts (selfhosted agents simply\n // cannot connect — graceful). It runs on its OWN connection (the callout auth\n // user), separate from the privileged control-plane bus.\n let authCalloutResponder: ResponderConnection | undefined;\n if (settings.sandboxSelfhostedEnabled) {\n stopMetricsIngestion = startMetricsIngestion({\n db: dbClient.db,\n bus,\n observability,\n });\n stopHelloIngestion = startHelloIngestion({\n db: dbClient.db,\n bus,\n observability,\n });\n observability.info(\"OpenGeni machine-metrics + hello ingestion consumers started\", {});\n\n const callout = resolveNatsCalloutConfig(settings);\n if (callout) {\n try {\n authCalloutResponder = await startAuthCalloutResponder(\n { db: dbClient.db, settings, callout, observability },\n settings.natsUrl,\n );\n } catch {\n // A responder start failure must not crash the API (other planes work); log\n // loudly — selfhosted agents will fail to connect until it is up.\n observability.error(\"OpenGeni NATS auth-callout responder failed to start\", {\n errorClass: \"NatsAuthCalloutOperationError\",\n errorCode: \"nats_auth_callout_start_failed\",\n origin: \"api\",\n });\n }\n } else {\n observability.warn(\n \"OpenGeni selfhosted enabled but the NATS auth-callout plane is not configured; selfhosted agents cannot connect\",\n {},\n );\n }\n }\n observability.info(\"OpenGeni API listening\", {\n host: settings.apiHost,\n port: settings.apiPort,\n });\n return {\n server,\n close: async () => {\n server.stop(true);\n stopSlackInteractionPump?.();\n stopMetricsIngestion?.();\n stopHelloIngestion?.();\n await Promise.allSettled([\n authCalloutResponder?.close(),\n bus.close(),\n workflowClient.close(),\n dbClient.close(),\n ]);\n },\n };\n}\n\nif (import.meta.main) {\n await startApi();\n}\n\nexport function temporalOverlapPolicy(policy: ScheduledTaskOverlapPolicy): ScheduleOverlapPolicy {\n if (policy === \"skip\") {\n return ScheduleOverlapPolicy.SKIP;\n }\n if (policy === \"buffer_one\") {\n return ScheduleOverlapPolicy.BUFFER_ONE;\n }\n return ScheduleOverlapPolicy.ALLOW_ALL;\n}\n\nexport function shouldCreateScheduleAfterUpdateError(error: unknown): boolean {\n return error instanceof ScheduleNotFoundError;\n}\n\nexport function temporalScheduleSpec(schedule: ScheduledTaskScheduleSpec): ScheduleSpec {\n if (schedule.type === \"interval\") {\n return {\n intervals: [temporalIntervalSpec(schedule)],\n ...(schedule.startAt ? { startAt: new Date(schedule.startAt) } : {}),\n ...(schedule.endAt ? { endAt: new Date(schedule.endAt) } : {}),\n };\n }\n if (schedule.type === \"calendar\") {\n return {\n calendars: [\n {\n hour: schedule.hour,\n minute: schedule.minute,\n second: 0,\n ...(schedule.daysOfWeek ? { dayOfWeek: schedule.daysOfWeek } : {}),\n },\n ],\n timezone: schedule.timeZone,\n };\n }\n const runAt = new Date(schedule.runAt);\n return {\n calendars: [\n {\n year: runAt.getUTCFullYear(),\n month: temporalMonth(runAt.getUTCMonth()),\n dayOfMonth: runAt.getUTCDate(),\n hour: runAt.getUTCHours(),\n minute: runAt.getUTCMinutes(),\n second: runAt.getUTCSeconds(),\n },\n ],\n timezone: \"UTC\",\n };\n}\n\nfunction temporalIntervalSpec(\n schedule: Extract<ScheduledTaskScheduleSpec, { type: \"interval\" }>,\n): NonNullable<ScheduleSpec[\"intervals\"]>[number] {\n const every = `${schedule.everySeconds}s` as `${number}s`;\n if (!schedule.startAt) {\n return { every };\n }\n\n // Temporal interval schedules match Epoch + (n * every) + offset. Its\n // top-level startAt only filters matching times before that boundary, so it\n // does not itself anchor the cadence. Derive the phase from startAt to make\n // the stored OpenGeni timestamp the first interval boundary rather than the\n // next epoch-aligned match.\n const everyMilliseconds = BigInt(schedule.everySeconds) * 1_000n;\n const startMilliseconds = BigInt(new Date(schedule.startAt).getTime());\n const offsetMilliseconds =\n ((startMilliseconds % everyMilliseconds) + everyMilliseconds) % everyMilliseconds;\n return {\n every,\n ...(offsetMilliseconds === 0n ? {} : { offset: `${offsetMilliseconds}ms` as `${number}ms` }),\n };\n}\n\nfunction temporalMonth(monthIndex: number) {\n return TEMPORAL_MONTHS[monthIndex]!;\n}\n\nfunction temporalScheduleOptions(task: ScheduledTask, taskQueue: string): ScheduleOptions {\n return {\n scheduleId: task.temporalScheduleId,\n spec: temporalScheduleSpec(task.schedule),\n action: {\n type: \"startWorkflow\",\n workflowType: \"scheduledTaskFireWorkflow\",\n taskQueue,\n args: [\n {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n taskId: task.id,\n triggerType: \"scheduled\",\n },\n ],\n },\n policies: {\n overlap: temporalOverlapPolicy(task.overlapPolicy),\n catchupWindow: \"24h\",\n pauseOnFailure: false,\n },\n state: {\n paused: task.status === \"paused\",\n ...(task.schedule.type === \"once\" ? { remainingActions: 1 } : {}),\n },\n memo: {\n accountId: task.accountId,\n workspaceId: task.workspaceId,\n scheduledTaskId: task.id,\n name: task.name,\n },\n };\n}\n\nfunction temporalScheduleUpdateOptions(options: ScheduleOptions): ScheduleUpdateOptions {\n return {\n spec: options.spec,\n action: options.action,\n ...(options.policies ? { policies: options.policies } : {}),\n state: options.state ?? {},\n ...(options.searchAttributes ? { searchAttributes: options.searchAttributes } : {}),\n ...(options.typedSearchAttributes\n ? { typedSearchAttributes: options.typedSearchAttributes }\n : {}),\n };\n}\n","import type { EventLogger } from \"@opengeni/events\";\nimport type { Attributes, AttributeValue, Observability } from \"@opengeni/observability\";\n\nexport function observabilityEventLogger(observability: Observability): EventLogger {\n return {\n debug: (message, attributes) => observability.debug(message, eventAttributes(attributes)),\n warn: (message, attributes) => observability.warn(message, eventAttributes(attributes)),\n };\n}\n\nfunction eventAttributes(attributes: Record<string, unknown> | undefined): Attributes | undefined {\n if (!attributes) {\n return undefined;\n }\n const projected: Attributes = {};\n for (const [key, value] of Object.entries(attributes)) {\n projected[key] = eventAttributeValue(value);\n }\n return projected;\n}\n\nfunction eventAttributeValue(value: unknown): AttributeValue {\n if (\n value === null ||\n value === undefined ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n return value;\n }\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n","// apps/api/src/sandbox/auth-callout.ts — the NATS AUTH-CALLOUT responder (the\n// bring-your-own-compute M-AUTH tenancy boundary; NATS Accounts per\n// workspace + §17 the isolation smoke + §19 the NATS-Accounts-misconfig leak risk).\n//\n// THE BOUNDARY THIS CLOSES: an external agent connects to NATS presenting its\n// `oge_` enrollment bearer as the connect auth-token. nats-server (configured with\n// `auth_callout`) issues an authorization request on $SYS.REQ.USER.AUTH. THIS\n// responder:\n// 1. decodes the authorization request (the `user_nkey` the response must scope\n// to, the `server_id` for the response `aud`, and the presented `auth_token`);\n// 2. VALIDATES the bearer with verifyEnrollmentBearer (HMAC, via\n// resolveEnrollmentSigningSecret) — an invalid/expired/forged bearer is denied;\n// 3. confirms the enrollment is still ACTIVE in the DB at the exact credential\n// generation (a revoked or re-enrolled machine denies an old bearer);\n// 4. signs a NATS user JWT granting pub/sub ONLY `agent.<ws>.>` + `_INBOX.>`\n// (deny-all-else by an allow-list) and returns it inside a signed\n// authorization-response JWT.\n//\n// That per-subject scope is the per-workspace ISOLATION: workspace A's agent is\n// cryptographically incapable of pub/sub on `agent.B.>`. nats-server enforces the\n// signed permission set; the boundary does not rely on subject naming alone (the M4\n// transport test proved the CODE constructs scoped subjects; THIS proves the SERVER\n// refuses cross-workspace access).\n//\n// SECURITY (§18): the bearer value + the account signing seed are NEVER logged. A\n// validation failure → a DENIAL response (the server refuses the connection); a\n// responder error → the request is left UNANSWERED (fail-closed; the server denies\n// on its callout timeout). The bearer's `exp` caps the minted credential's life so a\n// revoked/expired enrollment cannot outlive its bearer.\n\nimport {\n resolveEnrollmentSigningSecret,\n type NatsCalloutConfig,\n type Settings,\n} from \"@opengeni/config\";\nimport { verifyEnrollmentBearer } from \"@opengeni/contracts\";\nimport { getEnrollment, type Database } from \"@opengeni/db\";\nimport {\n createResponderConnection,\n decodeAuthRequest,\n mintAuthResponse,\n mintUserJwt,\n workspaceAgentPermissions,\n type ResponderConnection,\n} from \"@opengeni/events\";\nimport type { Observability } from \"@opengeni/observability\";\nimport { observabilityEventLogger } from \"../observability\";\n\n/** The NATS subject nats-server publishes authorization requests on (ADR-26). */\nexport const AUTH_CALLOUT_SUBJECT = \"$SYS.REQ.USER.AUTH\";\n/** Keep live NATS credentials short-lived while never outliving the bearer. */\nexport const NATS_USER_JWT_TTL_SECONDS = 5 * 60;\n\nexport interface AuthCalloutDeps {\n db: Database;\n settings: Settings;\n callout: NatsCalloutConfig;\n observability?: Observability;\n}\n\n/**\n * The pure validate→scoped-JWT decision, isolated from the NATS transport so it is\n * unit-testable. Given the raw authorization-request JWT bytes, returns the signed\n * authorization-response JWT bytes to reply with — a GRANT (embedding a scoped user\n * JWT) on success, a DENIAL (carrying `nats.error`, no user JWT) otherwise. NEVER\n * throws on a bad/invalid request: every failure becomes a signed denial (the\n * server then refuses the connection cleanly).\n */\nexport async function handleAuthorizationRequest(\n deps: AuthCalloutDeps,\n requestBytes: Uint8Array,\n): Promise<Uint8Array> {\n const requestJwt = Buffer.from(requestBytes).toString(\"utf8\");\n const decoded = decodeAuthRequest(requestJwt);\n if (!decoded) {\n // A malformed request we cannot even read the user_nkey/server_id from — there\n // is nothing to scope a response to. Leave it for the server's timeout by\n // throwing (the transport leaves it unanswered, fail-closed).\n deps.observability?.warn?.(\"auth-callout: undecodable authorization request\", {});\n throw new Error(\"undecodable authorization request\");\n }\n\n const deny = (reason: string): Uint8Array => {\n // A SIGNED denial: the server reads `nats.error` and refuses the connection.\n const response = mintAuthResponse({\n userPublicKey: decoded.userNkey,\n serverId: decoded.serverId,\n accountSeed: deps.callout.accountSeed,\n error: reason,\n });\n return Buffer.from(response, \"utf8\");\n };\n\n const bearer = decoded.authToken;\n if (!bearer) {\n return deny(\"missing enrollment bearer\");\n }\n\n const secret = resolveEnrollmentSigningSecret(deps.settings);\n if (!secret) {\n // The credential plane is off for this deployment — deny rather than mint an\n // unscoped credential. (The responder should not even be running in this case,\n // but fail-closed regardless.)\n return deny(\"enrollment credential plane disabled\");\n }\n\n const claims = await verifyEnrollmentBearer(secret, bearer);\n if (!claims) {\n // Invalid signature / malformed / expired bearer. NEVER log the bearer value.\n deps.observability?.warn?.(\"auth-callout: rejected an invalid enrollment bearer\", {});\n return deny(\"invalid or expired enrollment bearer\");\n }\n\n // Confirm the enrollment is still ACTIVE — a revoked machine is denied even with a\n // still-unexpired bearer (the revoke path flips status; this re-checks at connect).\n const enrollment = await getEnrollment(deps.db, claims.workspaceId, claims.enrollmentId);\n if (!enrollment || enrollment.status !== \"active\") {\n deps.observability?.warn?.(\"auth-callout: denied a revoked or unknown enrollment\", {\n workspaceId: claims.workspaceId,\n agentId: claims.agentId,\n });\n return deny(\"enrollment is not active\");\n }\n\n // Belt-and-braces: the bearer's agentId/enrollmentId must match the row we found.\n // (verifyEnrollmentBearer already binds them; this guards a future schema where\n // agentId != enrollmentId.)\n if (\n enrollment.workspaceId !== claims.workspaceId ||\n enrollment.id !== claims.enrollmentId ||\n enrollment.id !== claims.agentId ||\n claims.agentId !== claims.enrollmentId ||\n claims.subjectPrefix !== `agent.${claims.workspaceId}.${claims.agentId}`\n ) {\n return deny(\"enrollment identity mismatch\");\n }\n if (enrollment.credentialGeneration !== claims.credentialGeneration) {\n return deny(\"enrollment credential generation mismatch\");\n }\n\n // GRANT: a user JWT scoped to ONLY this workspace's agent subtree + the reply\n // inbox. This allow-list IS the per-workspace isolation boundary.\n const permissions = workspaceAgentPermissions(claims.workspaceId);\n const nowSeconds = Math.floor(Date.now() / 1000);\n const userJwt = mintUserJwt({\n userPublicKey: decoded.userNkey,\n accountSeed: deps.callout.accountSeed,\n name: claims.agentId,\n permissions,\n // Server-config-mode placement: the embedded user JWT's `aud` is the account\n // the user binds to (the configured `auth_callout.account`). All agents +\n // the privileged control plane share this account so subjects route; the\n // per-workspace isolation is carried by the subject permissions above.\n audienceAccount: deps.callout.accountName,\n // Tie the credential's life to the bearer's remaining life: a revoked/expired\n // enrollment cannot outlive its bearer at the NATS layer either.\n expiresAtSeconds: Math.min(claims.exp, nowSeconds + NATS_USER_JWT_TTL_SECONDS),\n });\n const response = mintAuthResponse({\n userPublicKey: decoded.userNkey,\n serverId: decoded.serverId,\n accountSeed: deps.callout.accountSeed,\n userJwt,\n });\n deps.observability?.info?.(\"auth-callout: granted a workspace-scoped NATS credential\", {\n workspaceId: claims.workspaceId,\n agentId: claims.agentId,\n });\n return Buffer.from(response, \"utf8\");\n}\n\n/**\n * Start the auth-callout responder: open a SEPARATE NATS connection authenticated\n * as the callout `auth_users` user, subscribe $SYS.REQ.USER.AUTH, and answer every\n * authorization request via {@link handleAuthorizationRequest}. Returns a handle\n * whose `close()` drains the connection. Gated by the caller (sandboxSelfhostedEnabled\n * + a resolvable callout config); a deployment without the callout plane never starts\n * it.\n */\nexport async function startAuthCalloutResponder(\n deps: AuthCalloutDeps,\n natsUrl: string,\n): Promise<ResponderConnection> {\n const connection = await createResponderConnection(\n natsUrl,\n { kind: \"user-password\", user: deps.callout.user, pass: deps.callout.password },\n AUTH_CALLOUT_SUBJECT,\n (bytes) => handleAuthorizationRequest(deps, bytes),\n {\n name: \"opengeni-auth-callout\",\n ...(deps.observability ? { logger: observabilityEventLogger(deps.observability) } : {}),\n },\n );\n deps.observability?.info?.(\"OpenGeni NATS auth-callout responder started\", {\n subject: AUTH_CALLOUT_SUBJECT,\n });\n return connection;\n}\n","// apps/api/src/sandbox/metrics-ingestion.ts — the M10 metrics INGESTION consumer\n// + the connect-Hello DISPLAY-REFRESH consumer. The\n// enrolled agent piggybacks a `MetricsSample` on its ~5s heartbeat (an\n// `AgentEvent` published one-way on `agent.<ws>.<id>.events`) and publishes a\n// `Hello` (its live self-description) on `agent.<ws>.<id>.hello` on every connect\n// /reconnect. This module owns the two agent→control-plane inbound consumers:\n//\n// `agent.*.*.events` (heartbeat) →\n// 1. touchEnrollmentLastSeen — the liveness cursor (online/reconnecting/offline\n// derivation + the M3 probe disambiguation).\n// 2. ingestMachineMetricsSample — UPSERT machine_metrics_latest (the \"now\" row)\n// + APPEND a machine_metrics_series row downsampled to ~1/min.\n// A GOING-OFFLINE event is not a metrics point — liveness flips via the lease/\n// probe path; we skip it here (no-op).\n//\n// `agent.*.*.hello` (connect) →\n// refreshEnrollmentDisplay — reconcile `enrollments.has_display` to the LIVE\n// capability the Hello reports. `has_display` was previously FROZEN at the\n// enroll-time offer snapshot; a machine that GAINS a display later (a Mac that\n// grants Screen Recording, a box whose Xvfb starts) or LOSES one never\n// re-surfaced. Consuming the Hello's `capabilities.desktop` / `display` makes\n// `has_display` track reality (both directions), which the desktop-capability\n// gate (packages/runtime capabilities.ts) keys off.\n// refreshEnrollmentOpStream — reconcile `enrollments.op_stream` to the LIVE\n// runner capability the Hello reports, leaving legacy request/reply exec as the\n// fallback unless the runner advertises the streaming engine.\n//\n// Both consumers are BEST-EFFORT and fail-soft: a decode/DB error for one message\n// is logged + swallowed (the bus subscription already swallows handler throws) so\n// a metrics blip / a display-refresh write failure never tears down the consumer,\n// back-pressures the agent, or breaks its connect.\n\nimport {\n clearEnrollmentWentOffline,\n getEnrollment,\n ingestMachineMetricsSample,\n sessionsWithActiveOpOnEnrollment,\n setEnrollmentDisplayState,\n setEnrollmentOpStreamState,\n setEnrollmentWentOffline,\n touchEnrollmentLastSeen,\n type AppendEventInput,\n type Database,\n type MachineMetricsSample,\n} from \"@opengeni/db\";\nimport { appendAndPublishEvents, type EventBus } from \"@opengeni/events\";\nimport type { Observability } from \"@opengeni/observability\";\nimport {\n AgentEvent,\n GoingOfflineReason,\n Hello,\n goingOfflineReasonToJSON,\n type MetricsSample,\n} from \"@opengeni/agent-proto\";\n\n/** The wildcard subject the agent event plane publishes heartbeats on. */\nexport const AGENT_EVENTS_SUBJECT = \"agent.*.*.events\";\n\n/** The wildcard subject the agent publishes its connect Hello on. */\nexport const AGENT_HELLO_SUBJECT = \"agent.*.*.hello\";\n\n/**\n * Parse `agent.<ws>.<id>.<tail>` → `{ workspaceId, agentId }`, requiring the\n * expected tail token. Returns null for a subject that does not match the shape\n * (defensive — the subscription pattern already constrains it).\n */\nfunction parseAgentSubject(\n subject: string,\n tail: \"events\" | \"hello\",\n): { workspaceId: string; agentId: string } | null {\n const parts = subject.split(\".\");\n if (parts.length !== 4 || parts[0] !== \"agent\" || parts[3] !== tail) {\n return null;\n }\n return { workspaceId: parts[1]!, agentId: parts[2]! };\n}\n\n/** Parse `agent.<ws>.<id>.events` → `{ workspaceId, agentId }` (heartbeat plane). */\nexport function parseAgentEventSubject(\n subject: string,\n): { workspaceId: string; agentId: string } | null {\n return parseAgentSubject(subject, \"events\");\n}\n\n/** Parse `agent.<ws>.<id>.hello` → `{ workspaceId, agentId }` (connect plane). */\nexport function parseAgentHelloSubject(\n subject: string,\n): { workspaceId: string; agentId: string } | null {\n return parseAgentSubject(subject, \"hello\");\n}\n\n/**\n * Project a wire `MetricsSample` (proto, ms-stamped, GPU as a repeated list) to\n * the DB `MachineMetricsSample`. The proto byte/count fields are protobuf-encoded\n * as decimal strings (uint64) on the TS side (ts-proto `string`); coerce to\n * numbers. The DB carries a single `gpuUtilPercent` + `gpuMemUsedBytes`/Total —\n * we take the FIRST GPU (the dashboard surfaces the primary accelerator); absent\n * GPUs stay null (the not-reported contract). A zero on a non-GPU field is the\n * agent's \"not reported\" (we keep it null-friendly via `nullIfZero` only for the\n * GPU plane; cpu/mem/disk 0 is a legitimate reading the dashboard shows as 0).\n */\nexport function wireSampleToDbSample(wire: MetricsSample): MachineMetricsSample {\n const num = (v: string | number): number => (typeof v === \"number\" ? v : Number(v));\n const firstGpu = wire.gpus[0];\n return {\n cpuPercent: wire.cpuPercent,\n load1: wire.load1,\n load5: wire.load5,\n load15: wire.load15,\n memUsedBytes: num(wire.memUsedBytes),\n memTotalBytes: num(wire.memTotalBytes),\n diskUsedBytes: num(wire.diskUsedBytes),\n diskTotalBytes: num(wire.diskTotalBytes),\n gpuUtilPercent: firstGpu ? firstGpu.utilPercent : null,\n gpuMemUsedBytes: firstGpu ? num(firstGpu.memUsedBytes) : null,\n gpuMemTotalBytes: firstGpu ? num(firstGpu.memTotalBytes) : null,\n contention: wire.runQueue,\n // The sample carries its own wall-clock stamp (epoch ms); fall back to now on\n // a missing/zero stamp so a series row is never NULL-dated.\n sampledAt:\n wire.sampledAtMs && Number(wire.sampledAtMs) > 0\n ? new Date(Number(wire.sampledAtMs))\n : new Date(),\n };\n}\n\n/**\n * Ingest ONE decoded heartbeat for an enrolled machine. Resolves the enrollment's\n * accountId (needed for the RLS-scoped writes) from the enrollment row; an\n * unknown/cross-workspace agentId is ignored (no row → no write). Touches\n * last-seen + upserts latest + downsamples the series.\n */\nexport async function ingestHeartbeat(\n db: Database,\n input: { workspaceId: string; agentId: string; sample: MetricsSample },\n): Promise<{ ingested: boolean; seriesAppended: boolean }> {\n // The enrollment row is the source of the accountId (the RLS principal) and the\n // existence check. A revoked machine still reports its accountId, so we ingest\n // (the dashboard shows its last sample); a truly unknown id is a no-op.\n const enrollment = await getEnrollment(db, input.workspaceId, input.agentId);\n if (!enrollment) {\n return { ingested: false, seriesAppended: false };\n }\n const sample = wireSampleToDbSample(input.sample);\n await touchEnrollmentLastSeen(db, {\n accountId: enrollment.accountId,\n workspaceId: input.workspaceId,\n enrollmentId: input.agentId,\n });\n const result = await ingestMachineMetricsSample(db, {\n accountId: enrollment.accountId,\n workspaceId: input.workspaceId,\n enrollmentId: input.agentId,\n sample,\n });\n return { ingested: true, seriesAppended: result.seriesAppended };\n}\n\n/**\n * Fan out one or more machine-LINK session events to the sessions that had an\n * active op running on the machine when its control link changed (per\n * `sessionsWithActiveOpOnEnrollment`) — the announce-only failure-visibility\n * plane. Each session's events are stamped on its OWN active turn. No matching\n * session ⇒ nothing is emitted (an idle-machine blip must never spam idle /\n * historical sessions). Called best-effort inside the handlers' fail-soft blocks.\n *\n * Each session's emission is ISOLATED: one session's append failing (a\n * session-specific constraint like a sequence collision from a racing writer, a\n * transient write error) is logged with that sessionId and skipped, never\n * aborting the fan-out — one session's failure must never cost the OTHER matching\n * sessions their events. A partial fan-out stays visible per-session in the logs.\n */\nasync function fanOutMachineLinkEvents(\n db: Database,\n bus: EventBus,\n observability: Observability | undefined,\n workspaceId: string,\n enrollmentId: string,\n build: (activeTurnId: string) => AppendEventInput[],\n): Promise<void> {\n const sessions = await sessionsWithActiveOpOnEnrollment(db, { workspaceId, enrollmentId });\n for (const session of sessions) {\n try {\n await appendAndPublishEvents(\n db,\n bus,\n workspaceId,\n session.sessionId,\n build(session.activeTurnId),\n );\n } catch (error) {\n observability?.warn?.(\"Failed to fan out a machine-link event to a session\", {\n workspaceId,\n sessionId: session.sessionId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n}\n\n/**\n * Decode a raw `AgentEvent` payload + ingest it (the per-message handler). A\n * heartbeat carrying a metrics sample is ingested; a going-offline records the\n * machine-plane marker + fans out the link-plane session events. Decode failures\n * are reported + swallowed. `bus` (when present) enables the session-event\n * fan-out; the live consumer always supplies it, pure unit tests may omit it.\n */\nexport async function handleAgentEventPayload(\n db: Database,\n observability: Observability | undefined,\n payload: Uint8Array,\n subject: string,\n bus?: EventBus,\n): Promise<void> {\n const ids = parseAgentEventSubject(subject);\n if (!ids) {\n return;\n }\n let event: AgentEvent;\n try {\n event = AgentEvent.decode(payload);\n } catch (error) {\n observability?.warn?.(\"Failed to decode an agent event for metrics ingestion\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n // A clean GoingOffline is the machine-plane's typed shutdown signal. Two things\n // happen, in this order:\n // 1. Record it ALWAYS on the machine plane (a Prometheus counter keyed by the\n // typed reason) so a fleet operator can see clean stops / self-updates /\n // host shutdowns. This fires unconditionally, independent of the DB.\n // 2. Stamp the enrollment's clean going-offline marker so the liveness\n // derivation reads the machine OFFLINE immediately instead of waiting out\n // the last_seen dead-detect window. Best-effort + fail-soft (like the rest\n // of this module): an unknown enrollment is a no-op and a DB error is\n // swallowed so a bad write never tears down the consumer. Deliberately does\n // NOT touch last-seen (a shutdown must not look \"more recently alive\").\n if (event.event?.$case === \"goingOffline\") {\n const reason = goingOfflineReasonToJSON(event.event.goingOffline.reason);\n observability?.incrementCounter({\n name: \"opengeni_machine_going_offline_total\",\n help: \"Total Connected Machine clean GoingOffline signals by typed reason.\",\n labels: { reason },\n });\n try {\n const enrollment = await getEnrollment(db, ids.workspaceId, ids.agentId);\n if (enrollment) {\n await setEnrollmentWentOffline(db, {\n accountId: enrollment.accountId,\n workspaceId: ids.workspaceId,\n enrollmentId: ids.agentId,\n reason,\n });\n // Fan out the link-plane events to the sessions with an active op on this\n // machine: machine.link.lost (its control link is going away) for every\n // clean going-offline, PLUS machine.runner.restarted when the reason is a\n // self-update restart specifically (link.lost fires for it too; this\n // distinguishes a restart from a plain stop / host shutdown).\n if (bus) {\n const isSelfUpdate =\n event.event.goingOffline.reason === GoingOfflineReason.GOING_OFFLINE_REASON_UPDATE;\n await fanOutMachineLinkEvents(\n db,\n bus,\n observability,\n ids.workspaceId,\n ids.agentId,\n (activeTurnId) => {\n const events: AppendEventInput[] = [\n { type: \"machine.link.lost\", turnId: activeTurnId, payload: { reason } },\n ];\n if (isSelfUpdate) {\n events.push({\n type: \"machine.runner.restarted\",\n turnId: activeTurnId,\n payload: {},\n });\n }\n return events;\n },\n );\n }\n }\n } catch (error) {\n observability?.warn?.(\"Failed to record a machine clean going-offline\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n return;\n }\n if (event.event?.$case !== \"heartbeat\") {\n return; // an unknown event kind → not a metrics point.\n }\n const metrics = event.event.heartbeat.metrics;\n if (!metrics) {\n return; // a heartbeat without a sample → liveness already touched elsewhere.\n }\n try {\n await ingestHeartbeat(db, {\n workspaceId: ids.workspaceId,\n agentId: ids.agentId,\n sample: metrics,\n });\n } catch (error) {\n observability?.warn?.(\"Failed to ingest a machine metrics heartbeat\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\n/**\n * Start the metrics-ingestion consumer: subscribe `agent.*.*.events` and ingest\n * every heartbeat. Gated by sandboxSelfhostedEnabled (the caller checks the flag;\n * a disabled deployment never starts the consumer). Returns the unsubscribe fn.\n */\nexport function startMetricsIngestion(deps: {\n db: Database;\n bus: EventBus;\n observability?: Observability;\n}): () => void {\n return deps.bus.subscribeAgentEvents(AGENT_EVENTS_SUBJECT, (payload, subject) =>\n handleAgentEventPayload(deps.db, deps.observability, payload, subject, deps.bus),\n );\n}\n\n// ── Connect-Hello display refresh ─────────────────────────────────────────────\n\n/**\n * The LIVE display presence the agent's Hello reports: a desktop framebuffer is\n * available (`capabilities.desktop`, which the agent sets true only when a display\n * probes AND it can stream it) OR a `Display` detail is present. An unset\n * Capabilities (or a headless machine) → false. This is what `has_display` should\n * track, replacing the enroll-time snapshot.\n */\nexport function helloReportsDisplay(hello: Hello): boolean {\n const caps = hello.capabilities;\n if (!caps) {\n return false;\n }\n // A CAPTURE-BLOCKED display is NOT a usable display: a Mac reports a display but\n // withholds `desktop` and sets `desktopUnavailableReason` when Screen Recording\n // (TCC) is not granted. Treating it as \"has display\" is exactly how the 0.1.3\n // incident hid — the machine claimed a desktop it could not capture, so it was\n // offered for computer-use and the model saw a blank. Gate it out here (the single\n // source of truth for `has_display`, consumed by both the machine state and the\n // capability negotiation). The `display`-present fallback is preserved for every\n // other case (e.g. a relay-less agent that reports a display but not `desktop`).\n if (caps.desktopUnavailableReason) {\n return false;\n }\n return caps.desktop === true || caps.display != null;\n}\n\n/**\n * The human, actionable reason a display is present but UNUSABLE (macOS Screen\n * Recording / TCC not granted), or null when capture is permitted / the machine is\n * headless. Normalizes the proto's non-optional \"\" empty string to null so the DB\n * carries a clean tri-state (a real reason vs. no reason) — the Machines dashboard\n * shows \"display: capture not granted\" only when this is non-null.\n */\nexport function helloDesktopUnavailableReason(hello: Hello): string | null {\n const reason = hello.capabilities?.desktopUnavailableReason;\n return reason ? reason : null;\n}\n\n/** Whether the runner's current Hello advertises the op-stream engine. */\nexport function helloReportsOpStream(hello: Hello): boolean {\n return hello.capabilities?.opStream === true;\n}\n\n/**\n * Reconcile `enrollments.has_display` (+ the capture-blocked reason) to what a Hello\n * reports. Resolves the enrollment (the accountId is the RLS principal + the\n * existence check + the current values). A no-change Hello short-circuits BEFORE\n * issuing any write (and the DB writer is itself change-guarded on BOTH fields as a\n * backstop), so a steady state never churns. An unknown/cross-workspace agentId is a\n * no-op.\n */\nexport async function refreshEnrollmentDisplay(\n db: Database,\n input: {\n workspaceId: string;\n agentId: string;\n hasDisplay: boolean;\n desktopUnavailableReason?: string | null;\n },\n): Promise<{ updated: boolean }> {\n const desktopUnavailableReason = input.desktopUnavailableReason ?? null;\n const enrollment = await getEnrollment(db, input.workspaceId, input.agentId);\n if (!enrollment) {\n return { updated: false };\n }\n if (\n enrollment.hasDisplay === input.hasDisplay &&\n (enrollment.desktopUnavailableReason ?? null) === desktopUnavailableReason\n ) {\n // Both fields unchanged — do not even issue the UPDATE (no churn on a\n // steady-state Hello).\n return { updated: false };\n }\n return await setEnrollmentDisplayState(db, {\n accountId: enrollment.accountId,\n workspaceId: input.workspaceId,\n enrollmentId: input.agentId,\n hasDisplay: input.hasDisplay,\n desktopUnavailableReason,\n });\n}\n\n/**\n * Reconcile `enrollments.op_stream` to what a Hello reports. Resolves the\n * enrollment first so the accountId remains the RLS principal and so a no-change\n * Hello short-circuits BEFORE issuing any write (the DB writer is itself\n * change-guarded as a backstop). An unknown/cross-workspace agentId is a no-op.\n */\nexport async function refreshEnrollmentOpStream(\n db: Database,\n input: {\n workspaceId: string;\n agentId: string;\n opStream: boolean;\n },\n): Promise<{ updated: boolean }> {\n const enrollment = await getEnrollment(db, input.workspaceId, input.agentId);\n if (!enrollment) {\n return { updated: false };\n }\n if (enrollment.opStream === input.opStream) {\n // The capability is unchanged — do not even issue the UPDATE (no churn on a\n // steady-state Hello).\n return { updated: false };\n }\n return await setEnrollmentOpStreamState(db, {\n accountId: enrollment.accountId,\n workspaceId: input.workspaceId,\n enrollmentId: input.agentId,\n opStream: input.opStream,\n });\n}\n\n/**\n * Decode a raw `Hello` payload + refresh the enrollment's display cursor + clear\n * any pending clean going-offline marker and, when the reconnect actually cleared\n * one, fan out machine.link.restored to the sessions with an active op on the\n * machine (the per-message handler for the hello plane). Decode failures + write\n * failures are reported + swallowed — a Hello must NEVER break the agent's connect.\n * `bus` (when present) enables the link.restored fan-out.\n */\nexport async function handleHelloPayload(\n db: Database,\n observability: Observability | undefined,\n payload: Uint8Array,\n subject: string,\n bus?: EventBus,\n): Promise<void> {\n const ids = parseAgentHelloSubject(subject);\n if (!ids) {\n return;\n }\n let hello: Hello;\n try {\n hello = Hello.decode(payload);\n } catch (error) {\n observability?.warn?.(\"Failed to decode an agent Hello for display refresh\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n try {\n await refreshEnrollmentDisplay(db, {\n workspaceId: ids.workspaceId,\n agentId: ids.agentId,\n hasDisplay: helloReportsDisplay(hello),\n desktopUnavailableReason: helloDesktopUnavailableReason(hello),\n });\n await refreshEnrollmentOpStream(db, {\n workspaceId: ids.workspaceId,\n agentId: ids.agentId,\n opStream: helloReportsOpStream(hello),\n });\n } catch (error) {\n observability?.warn?.(\"Failed to refresh an enrollment's capabilities from a Hello\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n // A reconnect Hello re-announces the machine, so any pending clean going-offline\n // marker no longer holds — clear it so the liveness derivation stops reading the\n // machine offline. Best-effort + fail-soft, and change-guarded in the DB (a\n // steady-state Hello with no marker writes nothing), so this never breaks the\n // agent's connect and never churns. When a marker was ACTUALLY cleared (the\n // machine had been reported link.lost), fan out machine.link.restored to the\n // sessions with an active op on it — a restored only ever pairs a prior lost, so\n // a routine connect Hello (no marker) emits nothing.\n try {\n const enrollment = await getEnrollment(db, ids.workspaceId, ids.agentId);\n if (enrollment) {\n const { cleared } = await clearEnrollmentWentOffline(db, {\n accountId: enrollment.accountId,\n workspaceId: ids.workspaceId,\n enrollmentId: ids.agentId,\n });\n if (cleared && bus) {\n await fanOutMachineLinkEvents(\n db,\n bus,\n observability,\n ids.workspaceId,\n ids.agentId,\n (activeTurnId) => [{ type: \"machine.link.restored\", turnId: activeTurnId, payload: {} }],\n );\n }\n }\n } catch (error) {\n observability?.warn?.(\"Failed to clear a machine going-offline marker on a Hello\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\n/**\n * Start the Hello display-refresh consumer: subscribe `agent.*.*.hello` and\n * reconcile `has_display` to the live capability the agent reports on every\n * connect. Gated by sandboxSelfhostedEnabled (the caller checks the flag). Returns\n * the unsubscribe fn.\n */\nexport function startHelloIngestion(deps: {\n db: Database;\n bus: EventBus;\n observability?: Observability;\n}): () => void {\n return deps.bus.subscribeAgentEvents(AGENT_HELLO_SUBJECT, (payload, subject) =>\n handleHelloPayload(deps.db, deps.observability, payload, subject, deps.bus),\n );\n}\n"],"mappings":";;;;;;AAAA;AAAA,EACE;AAAA,EACA;A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AQ,SAAS,CAAC;AAAA,IACzB,GAAI,QAAQ,mBAAmB,EAAE,kBAAkB,QAAQ,iBAAiB,IAAI,CAAC;AAAA,IACjF,GAAI,QAAQ,wBACR,EAAE,uBAAuB,QAAQ,sBAAsB,IACvD,CAAC;AAAA,EACP;AACF;","names":["response","getEnrollment"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/observability.ts","../src/sandbox/auth-callout.ts","../src/sandbox/metrics-ingestion.ts","../src/memory-slack-delivery.ts","../src/editable-artifact-websocket.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"],"sourcesContent":["import {\n dbSearchPath,\n getSettings,\n resolveNatsCalloutConfig,\n resolveNatsControlPlaneAuth,\n retryStartupDependency,\n startupRetryOptions,\n temporalConnectionOptions,\n} from \"@opengeni/config\";\nimport type {\n ScheduledTask,\n ScheduledTaskOverlapPolicy,\n ScheduledTaskScheduleSpec,\n} from \"@opengeni/contracts\";\nimport {\n assertRuntimeDatabasePosture,\n createDb,\n markSessionWorkflowWakeDelivered,\n runtimeDatabaseReadyCheck,\n type Database,\n} from \"@opengeni/db\";\nimport { createNatsEventBus, type ResponderConnection } from \"@opengeni/events\";\nimport { createObservability, logStartupDependencyRetry } from \"@opengeni/observability\";\nimport { createObjectStorage } from \"@opengeni/storage\";\nimport { isArtifactRuntimeConfigured } from \"@opengeni/artifact-tool/runtime/development\";\nimport { SESSION_WORKFLOW_WAKE_DISPATCHER_SCHEDULE_ID } from \"@opengeni/core\";\nimport {\n Connection,\n Client as TemporalClient,\n ScheduleNotFoundError,\n ScheduleOverlapPolicy,\n WorkflowExecutionAlreadyStartedError,\n} from \"@temporalio/client\";\nimport type { ScheduleOptions, ScheduleSpec, ScheduleUpdateOptions } from \"@temporalio/client\";\nimport { createAppComposition, type DocumentIndexClient, type SessionWorkflowClient } from \"./app\";\nimport { observabilityEventLogger } from \"./observability\";\nimport { startAuthCalloutResponder } from \"./sandbox/auth-callout\";\nimport { startHelloIngestion, startMetricsIngestion } from \"./sandbox/metrics-ingestion\";\nimport { startSlackInteractionPump } from \"./integrations/slack-interactions\";\nimport { startMemorySlackPublicationPump } from \"./memory-slack-delivery\";\nimport { startTemporalScheduleCleanupPump } from \"./temporal-schedule-cleanup\";\nimport {\n EDITABLE_ARTIFACT_LIVE_WEBSOCKET_MAX_MESSAGE_BYTES,\n EditableArtifactWebSocketTransport,\n type EditableArtifactWebSocketConnection,\n} from \"./editable-artifact-websocket\";\nimport {\n createStandaloneEditableArtifactApplication,\n type StandaloneEditableArtifactApplication,\n} from \"./editable-artifact-production\";\n\n/**\n * A REJECT_DUPLICATE start collides on the deterministic workflowId when the\n * same manual trigger token fires twice. Temporal surfaces that as\n * WorkflowExecutionAlreadyStartedError; the caller treats it as an idempotent\n * no-op rather than a failure.\n */\nfunction isWorkflowAlreadyStarted(error: unknown): boolean {\n return error instanceof WorkflowExecutionAlreadyStartedError;\n}\n\nconst TEMPORAL_MONTHS = [\n \"JANUARY\",\n \"FEBRUARY\",\n \"MARCH\",\n \"APRIL\",\n \"MAY\",\n \"JUNE\",\n \"JULY\",\n \"AUGUST\",\n \"SEPTEMBER\",\n \"OCTOBER\",\n \"NOVEMBER\",\n \"DECEMBER\",\n] as const;\n\nexport async function createTemporalWorkflowClient(\n settings: ReturnType<typeof getSettings>,\n db: Database,\n): Promise<{\n client: SessionWorkflowClient;\n documentIndexer: DocumentIndexClient;\n close: () => Promise<void>;\n}> {\n const connection = await Connection.connect(temporalConnectionOptions(settings));\n const temporal = new TemporalClient({\n connection,\n namespace: settings.temporalNamespace,\n });\n const client: SessionWorkflowClient = {\n signalUserMessage: async ({ eventId, workflowId }) => {\n await temporal.workflow.getHandle(workflowId).signal(\"userMessage\", eventId);\n },\n wakeSessionWorkflow: async ({\n accountId,\n workspaceId,\n sessionId,\n workflowId,\n wakeRevision,\n interruptionRequested,\n }) => {\n await temporal.workflow.signalWithStart(\"sessionWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [{ accountId, workspaceId, sessionId }],\n signal: interruptionRequested ? \"sessionControl\" : \"queueChanged\",\n });\n await markSessionWorkflowWakeDelivered(db, {\n accountId,\n workspaceId,\n sessionId,\n temporalWorkflowId: workflowId,\n wakeRevision,\n });\n },\n requestSessionWorkflowWakeDispatch: async () => {\n await temporal.schedule\n .getHandle(SESSION_WORKFLOW_WAKE_DISPATCHER_SCHEDULE_ID)\n .trigger(ScheduleOverlapPolicy.BUFFER_ONE);\n },\n signalCodexCapacity: async ({\n accountId,\n workspaceId,\n sessionId,\n workflowId,\n wakeRevision,\n workflowWakeRevision,\n }) => {\n await temporal.workflow.signalWithStart(\"sessionWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [{ accountId, workspaceId, sessionId }],\n signal: \"codexCapacityChanged\",\n signalArgs: [wakeRevision],\n });\n await markSessionWorkflowWakeDelivered(db, {\n accountId,\n workspaceId,\n sessionId,\n temporalWorkflowId: workflowId,\n wakeRevision: workflowWakeRevision,\n });\n },\n signalApprovalDecision: async ({\n accountId,\n workspaceId,\n sessionId,\n eventId,\n workflowId,\n workflowWakeRevision,\n }) => {\n await temporal.workflow.signalWithStart(\"sessionWorkflow\", {\n taskQueue: settings.temporalTaskQueue,\n workflowId,\n workflowIdReusePolicy: \"ALLOW_DUPLICATE\",\n args: [{ accountId, workspaceId, sessionId }],\n signal: \"approvalDecision\",\n signalArgs: [eventId],\n });\n await markSessionWorkflowWakeDelivered(db, {\n accountId,\n workspaceId,\n sessionId,\n temporalWorkflowId: workflowId,\n wakeRevision: workflowWakeRevision,\n });\n },\n syncScheduledTask: async ({ task }) => {\n const schedule = temporal.schedule.getHandle(task.temporalScheduleId);\n if (task.schedule.type === \"manual\") {\n try {\n await schedule.delete();\n } catch (error) {\n if (!(error instanceof ScheduleNotFoundError)) throw error;\n }\n return;\n }\n const options = temporalScheduleOptions(task, settings.temporalTaskQueue);\n try {\n await schedule.update(() => temporalScheduleUpdateOptions(options));\n } catch (error) {\n if (!shouldCreateScheduleAfterUpdateError(error)) {\n throw error;\n }\n await temporal.schedule.create(options);\n }\n },\n deleteScheduledTaskSchedule: async ({ temporalScheduleId }) => {\n try {\n await temporal.withDeadline(Date.now() + 5_000, async () => {\n await temporal.schedule.getHandle(temporalScheduleId).delete();\n });\n } catch (error) {\n if (error instanceof ScheduleNotFoundError) return;\n throw error;\n }\n },\n triggerScheduledTask: async ({\n task,\n agentRunUsageIdempotencyKey,\n triggerWorkflowId,\n initiator,\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 },\n ],\n });\n } catch (error) {\n // A duplicate trigger token started this run already; treat the retry\n // as a no-op so the (idempotent) usage charge stays the only effect.\n if (isWorkflowAlreadyStarted(error)) {\n return;\n }\n throw error;\n }\n },\n startRigVerification: async ({ workspaceId, changeId, versionId, workflowId }) => {\n const targetId = changeId ?? versionId;\n if (!targetId) {\n throw new Error(\"rig verification requires changeId or versionId\");\n }\n 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 const settings = getSettings();\n const observability = createObservability(settings, { component: \"api\" });\n // Step I: standalone → dbSchema unset → searchPath undefined → today's plain\n // handle (public). Embedded → scoped to the dedicated schema + the host's RLS\n // strategy.\n const searchPath = dbSearchPath(settings);\n const dbClient = createDb(settings.databaseUrl, {\n ...(searchPath ? { searchPath } : {}),\n rlsStrategy: settings.rlsStrategy,\n });\n let bus: Awaited<ReturnType<typeof createNatsEventBus>> | undefined;\n let workflowClient: Awaited<ReturnType<typeof createTemporalWorkflowClient>> | undefined;\n const retryOptions = startupRetryOptions(settings);\n const onRetry = (event: Parameters<typeof logStartupDependencyRetry>[1]) =>\n logStartupDependencyRetry(observability, event);\n const databasePosture = {\n rlsStrategy: settings.rlsStrategy,\n expectedRole: settings.runtimeDatabaseRole,\n targetSchema: settings.dbSchema.trim() || \"public\",\n } as const;\n // The PRIVILEGED control-plane NATS login (M-AUTH): when the server runs with\n // auth_callout, api/worker authenticate as a static account user permitted to\n // request `agent.*.rpc`. Null in local dev (anonymous connect — the bus default).\n const controlPlaneAuth = resolveNatsControlPlaneAuth(settings);\n try {\n await retryStartupDependency(\n \"PostgreSQL runtime posture\",\n () => assertRuntimeDatabasePosture(dbClient.db, databasePosture),\n { ...retryOptions, onRetry },\n );\n bus = await retryStartupDependency(\n \"NATS\",\n () =>\n createNatsEventBus(\n settings.natsUrl,\n controlPlaneAuth\n ? { user: controlPlaneAuth.user, pass: controlPlaneAuth.password }\n : undefined,\n { logger: observabilityEventLogger(observability) },\n ),\n {\n ...retryOptions,\n onRetry,\n },\n );\n workflowClient = await retryStartupDependency(\n \"Temporal\",\n () => createTemporalWorkflowClient(settings, dbClient.db),\n {\n ...retryOptions,\n onRetry,\n },\n );\n } catch (error) {\n await Promise.allSettled([bus?.close(), workflowClient?.close(), dbClient.close()]);\n throw error;\n }\n if (!bus || !workflowClient) {\n await dbClient.close();\n throw new Error(\"OpenGeni API startup dependencies were not initialized\");\n }\n const 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(routeDeps.editableArtifacts);\n const server = Bun.serve<EditableArtifactWebSocketConnection>({\n hostname: settings.apiHost,\n port: settings.apiPort,\n idleTimeout: 255,\n fetch: (request, bunServer) => {\n if (artifactWebSockets.handles(request)) {\n return artifactWebSockets.upgrade(request, bunServer);\n }\n return app.fetch(request);\n },\n websocket: {\n maxPayloadLength: EDITABLE_ARTIFACT_LIVE_WEBSOCKET_MAX_MESSAGE_BYTES,\n backpressureLimit: 16 * 1024 * 1024,\n closeOnBackpressureLimit: true,\n open: (socket) => artifactWebSockets.websocket.open(socket),\n message: (socket, message) => artifactWebSockets.websocket.message(socket, message),\n close: (socket) => artifactWebSockets.websocket.close(socket),\n },\n });\n const stopSlackInteractionPump = settings.slackSigningSecret\n ? startSlackInteractionPump(routeDeps)\n : undefined;\n const stopMemorySlackPublicationPump = startMemorySlackPublicationPump(routeDeps);\n const stopTemporalScheduleCleanupPump = startTemporalScheduleCleanupPump({\n db: dbClient.db,\n deleteSchedule: async (temporalScheduleId) => {\n await workflowClient.client.deleteScheduledTaskSchedule({ temporalScheduleId });\n },\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 });\n stopHelloIngestion = startHelloIngestion({\n db: dbClient.db,\n bus,\n observability,\n });\n observability.info(\"OpenGeni machine-metrics + hello ingestion consumers started\", {});\n\n const callout = resolveNatsCalloutConfig(settings);\n if (callout) {\n try {\n authCalloutResponder = await startAuthCalloutResponder(\n { db: dbClient.db, settings, callout, observability },\n settings.natsUrl,\n );\n } catch {\n // A responder start failure must not crash the API (other planes work); log\n // loudly — selfhosted agents will fail to connect until it is up.\n observability.error(\"OpenGeni NATS auth-callout responder failed to start\", {\n errorClass: \"NatsAuthCalloutOperationError\",\n errorCode: \"nats_auth_callout_start_failed\",\n origin: \"api\",\n });\n }\n } else {\n observability.warn(\n \"OpenGeni selfhosted enabled but the NATS auth-callout plane is not configured; selfhosted agents cannot connect\",\n {},\n );\n }\n }\n observability.info(\"OpenGeni API listening\", {\n host: settings.apiHost,\n port: settings.apiPort,\n });\n return {\n server,\n close: async () => {\n server.stop(true);\n stopSlackInteractionPump?.();\n await stopMemorySlackPublicationPump();\n stopMetricsIngestion?.();\n stopHelloIngestion?.();\n await stopTemporalScheduleCleanupPump();\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 await startApi();\n}\n\nexport function temporalOverlapPolicy(policy: ScheduledTaskOverlapPolicy): ScheduleOverlapPolicy {\n if (policy === \"skip\") {\n return ScheduleOverlapPolicy.SKIP;\n }\n if (policy === \"buffer_one\") {\n return ScheduleOverlapPolicy.BUFFER_ONE;\n }\n return ScheduleOverlapPolicy.ALLOW_ALL;\n}\n\nexport function shouldCreateScheduleAfterUpdateError(error: unknown): boolean {\n return error instanceof ScheduleNotFoundError;\n}\n\nexport function temporalScheduleSpec(schedule: ScheduledTaskScheduleSpec): ScheduleSpec {\n if (schedule.type === \"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 (task.action.kind !== \"knowledge_source_sync\") 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 type { EventLogger } from \"@opengeni/events\";\nimport type { Attributes, AttributeValue, Observability } from \"@opengeni/observability\";\n\nexport function observabilityEventLogger(observability: Observability): EventLogger {\n return {\n debug: (message, attributes) => observability.debug(message, eventAttributes(attributes)),\n warn: (message, attributes) => observability.warn(message, eventAttributes(attributes)),\n };\n}\n\nfunction eventAttributes(attributes: Record<string, unknown> | undefined): Attributes | undefined {\n if (!attributes) {\n return undefined;\n }\n const projected: Attributes = {};\n for (const [key, value] of Object.entries(attributes)) {\n projected[key] = eventAttributeValue(value);\n }\n return projected;\n}\n\nfunction eventAttributeValue(value: unknown): AttributeValue {\n if (\n value === null ||\n value === undefined ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n return value;\n }\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n","// apps/api/src/sandbox/auth-callout.ts — the NATS AUTH-CALLOUT responder (the\n// bring-your-own-compute M-AUTH tenancy boundary; NATS Accounts per\n// workspace + §17 the isolation smoke + §19 the NATS-Accounts-misconfig leak risk).\n//\n// THE BOUNDARY THIS CLOSES: an external agent connects to NATS presenting its\n// `oge_` enrollment bearer as the connect auth-token. nats-server (configured with\n// `auth_callout`) issues an authorization request on $SYS.REQ.USER.AUTH. THIS\n// responder:\n// 1. decodes the authorization request (the `user_nkey` the response must scope\n// to, the `server_id` for the response `aud`, and the presented `auth_token`);\n// 2. VALIDATES the bearer with verifyEnrollmentBearer (HMAC, via\n// resolveEnrollmentSigningSecret) — an invalid/expired/forged bearer is denied;\n// 3. confirms the enrollment is still ACTIVE in the DB at the exact credential\n// generation (a revoked or re-enrolled machine denies an old bearer);\n// 4. signs a NATS user JWT granting pub/sub ONLY `agent.<ws>.>` + `_INBOX.>`\n// (deny-all-else by an allow-list) and returns it inside a signed\n// authorization-response JWT.\n//\n// That per-subject scope is the per-workspace ISOLATION: workspace A's agent is\n// cryptographically incapable of pub/sub on `agent.B.>`. nats-server enforces the\n// signed permission set; the boundary does not rely on subject naming alone (the M4\n// transport test proved the CODE constructs scoped subjects; THIS proves the SERVER\n// refuses cross-workspace access).\n//\n// SECURITY (§18): the bearer value + the account signing seed are NEVER logged. A\n// validation failure → a DENIAL response (the server refuses the connection); a\n// responder error → the request is left UNANSWERED (fail-closed; the server denies\n// on its callout timeout). The bearer's `exp` caps the minted credential's life so a\n// revoked/expired enrollment cannot outlive its bearer.\n\nimport {\n resolveEnrollmentSigningSecret,\n type NatsCalloutConfig,\n type Settings,\n} from \"@opengeni/config\";\nimport { verifyEnrollmentBearer } from \"@opengeni/contracts\";\nimport { getEnrollment, type Database } from \"@opengeni/db\";\nimport {\n createResponderConnection,\n decodeAuthRequest,\n mintAuthResponse,\n mintUserJwt,\n workspaceAgentPermissions,\n type ResponderConnection,\n} from \"@opengeni/events\";\nimport type { Observability } from \"@opengeni/observability\";\nimport { observabilityEventLogger } from \"../observability\";\n\n/** The NATS subject nats-server publishes authorization requests on (ADR-26). */\nexport const AUTH_CALLOUT_SUBJECT = \"$SYS.REQ.USER.AUTH\";\n/** Keep live NATS credentials short-lived while never outliving the bearer. */\nexport const NATS_USER_JWT_TTL_SECONDS = 5 * 60;\n\nexport interface AuthCalloutDeps {\n db: Database;\n settings: Settings;\n callout: NatsCalloutConfig;\n observability?: Observability;\n}\n\n/**\n * The pure validate→scoped-JWT decision, isolated from the NATS transport so it is\n * unit-testable. Given the raw authorization-request JWT bytes, returns the signed\n * authorization-response JWT bytes to reply with — a GRANT (embedding a scoped user\n * JWT) on success, a DENIAL (carrying `nats.error`, no user JWT) otherwise. NEVER\n * throws on a bad/invalid request: every failure becomes a signed denial (the\n * server then refuses the connection cleanly).\n */\nexport async function handleAuthorizationRequest(\n deps: AuthCalloutDeps,\n requestBytes: Uint8Array,\n): Promise<Uint8Array> {\n const requestJwt = Buffer.from(requestBytes).toString(\"utf8\");\n const decoded = decodeAuthRequest(requestJwt);\n if (!decoded) {\n // A malformed request we cannot even read the user_nkey/server_id from — there\n // is nothing to scope a response to. Leave it for the server's timeout by\n // throwing (the transport leaves it unanswered, fail-closed).\n deps.observability?.warn?.(\"auth-callout: undecodable authorization request\", {});\n throw new Error(\"undecodable authorization request\");\n }\n\n const deny = (reason: string): Uint8Array => {\n // A SIGNED denial: the server reads `nats.error` and refuses the connection.\n const response = mintAuthResponse({\n userPublicKey: decoded.userNkey,\n serverId: decoded.serverId,\n accountSeed: deps.callout.accountSeed,\n error: reason,\n });\n return Buffer.from(response, \"utf8\");\n };\n\n const bearer = decoded.authToken;\n if (!bearer) {\n return deny(\"missing enrollment bearer\");\n }\n\n const secret = resolveEnrollmentSigningSecret(deps.settings);\n if (!secret) {\n // The credential plane is off for this deployment — deny rather than mint an\n // unscoped credential. (The responder should not even be running in this case,\n // but fail-closed regardless.)\n return deny(\"enrollment credential plane disabled\");\n }\n\n const claims = await verifyEnrollmentBearer(secret, bearer);\n if (!claims) {\n // Invalid signature / malformed / expired bearer. NEVER log the bearer value.\n deps.observability?.warn?.(\"auth-callout: rejected an invalid enrollment bearer\", {});\n return deny(\"invalid or expired enrollment bearer\");\n }\n\n // Confirm the enrollment is still ACTIVE — a revoked machine is denied even with a\n // still-unexpired bearer (the revoke path flips status; this re-checks at connect).\n const enrollment = await getEnrollment(deps.db, claims.workspaceId, claims.enrollmentId);\n if (!enrollment || enrollment.status !== \"active\") {\n deps.observability?.warn?.(\"auth-callout: denied a revoked or unknown enrollment\", {\n workspaceId: claims.workspaceId,\n agentId: claims.agentId,\n });\n return deny(\"enrollment is not active\");\n }\n\n // Belt-and-braces: the bearer's agentId/enrollmentId must match the row we found.\n // (verifyEnrollmentBearer already binds them; this guards a future schema where\n // agentId != enrollmentId.)\n if (\n enrollment.workspaceId !== claims.workspaceId ||\n enrollment.id !== claims.enrollmentId ||\n enrollment.id !== claims.agentId ||\n claims.agentId !== claims.enrollmentId ||\n claims.subjectPrefix !== `agent.${claims.workspaceId}.${claims.agentId}`\n ) {\n return deny(\"enrollment identity mismatch\");\n }\n if (enrollment.credentialGeneration !== claims.credentialGeneration) {\n return deny(\"enrollment credential generation mismatch\");\n }\n\n // GRANT: a user JWT scoped to ONLY this workspace's agent subtree + the reply\n // inbox. This allow-list IS the per-workspace isolation boundary.\n const permissions = workspaceAgentPermissions(claims.workspaceId);\n const nowSeconds = Math.floor(Date.now() / 1000);\n const userJwt = mintUserJwt({\n userPublicKey: decoded.userNkey,\n accountSeed: deps.callout.accountSeed,\n name: claims.agentId,\n permissions,\n // Server-config-mode placement: the embedded user JWT's `aud` is the account\n // the user binds to (the configured `auth_callout.account`). All agents +\n // the privileged control plane share this account so subjects route; the\n // per-workspace isolation is carried by the subject permissions above.\n audienceAccount: deps.callout.accountName,\n // Tie the credential's life to the bearer's remaining life: a revoked/expired\n // enrollment cannot outlive its bearer at the NATS layer either.\n expiresAtSeconds: Math.min(claims.exp, nowSeconds + NATS_USER_JWT_TTL_SECONDS),\n });\n const response = mintAuthResponse({\n userPublicKey: decoded.userNkey,\n serverId: decoded.serverId,\n accountSeed: deps.callout.accountSeed,\n userJwt,\n });\n deps.observability?.info?.(\"auth-callout: granted a workspace-scoped NATS credential\", {\n workspaceId: claims.workspaceId,\n agentId: claims.agentId,\n });\n return Buffer.from(response, \"utf8\");\n}\n\n/**\n * Start the auth-callout responder: open a SEPARATE NATS connection authenticated\n * as the callout `auth_users` user, subscribe $SYS.REQ.USER.AUTH, and answer every\n * authorization request via {@link handleAuthorizationRequest}. Returns a handle\n * whose `close()` drains the connection. Gated by the caller (sandboxSelfhostedEnabled\n * + a resolvable callout config); a deployment without the callout plane never starts\n * it.\n */\nexport async function startAuthCalloutResponder(\n deps: AuthCalloutDeps,\n natsUrl: string,\n): Promise<ResponderConnection> {\n const connection = await createResponderConnection(\n natsUrl,\n { kind: \"user-password\", user: deps.callout.user, pass: deps.callout.password },\n AUTH_CALLOUT_SUBJECT,\n (bytes) => handleAuthorizationRequest(deps, bytes),\n {\n name: \"opengeni-auth-callout\",\n ...(deps.observability ? { logger: observabilityEventLogger(deps.observability) } : {}),\n },\n );\n deps.observability?.info?.(\"OpenGeni NATS auth-callout responder started\", {\n subject: AUTH_CALLOUT_SUBJECT,\n });\n return connection;\n}\n","// apps/api/src/sandbox/metrics-ingestion.ts — the M10 metrics INGESTION consumer\n// + the connect-Hello DISPLAY-REFRESH consumer. The\n// enrolled agent piggybacks a `MetricsSample` on its ~5s heartbeat (an\n// `AgentEvent` published one-way on `agent.<ws>.<id>.events`) and publishes a\n// `Hello` (its live self-description) on `agent.<ws>.<id>.hello` on every connect\n// /reconnect. This module owns the two agent→control-plane inbound consumers:\n//\n// `agent.*.*.events` (heartbeat) →\n// 1. touchEnrollmentLastSeen — the liveness cursor (online/reconnecting/offline\n// derivation + the M3 probe disambiguation).\n// 2. ingestMachineMetricsSample — UPSERT machine_metrics_latest (the \"now\" row)\n// + APPEND a machine_metrics_series row downsampled to ~1/min.\n// A GOING-OFFLINE event is not a metrics point — liveness flips via the lease/\n// probe path; we skip it here (no-op).\n//\n// `agent.*.*.hello` (connect) →\n// refreshEnrollmentDisplay — reconcile `enrollments.has_display` to the LIVE\n// capability the Hello reports. `has_display` was previously FROZEN at the\n// enroll-time offer snapshot; a machine that GAINS a display later (a Mac that\n// grants Screen Recording, a box whose Xvfb starts) or LOSES one never\n// re-surfaced. Consuming the Hello's `capabilities.desktop` / `display` makes\n// `has_display` track reality (both directions), which the desktop-capability\n// gate (packages/runtime capabilities.ts) keys off.\n// refreshEnrollmentOpStream — reconcile `enrollments.op_stream` to the LIVE\n// runner capability the Hello reports, leaving legacy request/reply exec as the\n// fallback unless the runner advertises the streaming engine.\n//\n// Both consumers are BEST-EFFORT and fail-soft: a decode/DB error for one message\n// is logged + swallowed (the bus subscription already swallows handler throws) so\n// a metrics blip / a display-refresh write failure never tears down the consumer,\n// back-pressures the agent, or breaks its connect.\n\nimport {\n clearEnrollmentWentOffline,\n disconnectAttachedBrowserDevices,\n getEnrollment,\n ingestMachineMetricsSample,\n reconcileAttachedBrowserInventory,\n sessionsWithActiveOpOnEnrollment,\n setEnrollmentDisplayState,\n setEnrollmentOpStreamState,\n setEnrollmentWentOffline,\n touchEnrollmentLastSeen,\n type AppendEventInput,\n type Database,\n type MachineMetricsSample,\n} from \"@opengeni/db\";\nimport {\n AttachedBrowserInventorySnapshot as AttachedBrowserInventoryContract,\n type AttachedBrowserInventorySnapshot as AttachedBrowserInventoryContractValue,\n} from \"@opengeni/contracts\";\nimport { appendAndPublishEvents, type EventBus } from \"@opengeni/events\";\nimport type { Observability } from \"@opengeni/observability\";\nimport {\n AgentEvent,\n Arch,\n GoingOfflineReason,\n Hello,\n Os,\n goingOfflineReasonToJSON,\n type AttachedBrowserInventorySnapshot as WireAttachedBrowserInventorySnapshot,\n type MetricsSample,\n} from \"@opengeni/agent-proto\";\n\n/** The wildcard subject the agent event plane publishes heartbeats on. */\nexport const AGENT_EVENTS_SUBJECT = \"agent.*.*.events\";\n\n/** The wildcard subject the agent publishes its connect Hello on. */\nexport const AGENT_HELLO_SUBJECT = \"agent.*.*.hello\";\n\n/**\n * Parse `agent.<ws>.<id>.<tail>` → `{ workspaceId, agentId }`, requiring the\n * expected tail token. Returns null for a subject that does not match the shape\n * (defensive — the subscription pattern already constrains it).\n */\nfunction parseAgentSubject(\n subject: string,\n tail: \"events\" | \"hello\",\n): { workspaceId: string; agentId: string } | null {\n const parts = subject.split(\".\");\n if (parts.length !== 4 || parts[0] !== \"agent\" || parts[3] !== tail) {\n return null;\n }\n return { workspaceId: parts[1]!, agentId: parts[2]! };\n}\n\n/** Parse `agent.<ws>.<id>.events` → `{ workspaceId, agentId }` (heartbeat plane). */\nexport function parseAgentEventSubject(\n subject: string,\n): { workspaceId: string; agentId: string } | null {\n return parseAgentSubject(subject, \"events\");\n}\n\n/** Parse `agent.<ws>.<id>.hello` → `{ workspaceId, agentId }` (connect plane). */\nexport function parseAgentHelloSubject(\n subject: string,\n): { workspaceId: string; agentId: string } | null {\n return parseAgentSubject(subject, \"hello\");\n}\n\n/**\n * Project a wire `MetricsSample` (proto, ms-stamped, GPU as a repeated list) to\n * the DB `MachineMetricsSample`. The proto byte/count fields are protobuf-encoded\n * as decimal strings (uint64) on the TS side (ts-proto `string`); coerce to\n * numbers. The DB carries a single `gpuUtilPercent` + `gpuMemUsedBytes`/Total —\n * we take the FIRST GPU (the dashboard surfaces the primary accelerator); absent\n * GPUs stay null (the not-reported contract). A zero on a non-GPU field is the\n * agent's \"not reported\" (we keep it null-friendly via `nullIfZero` only for the\n * GPU plane; cpu/mem/disk 0 is a legitimate reading the dashboard shows as 0).\n */\nexport function wireSampleToDbSample(wire: MetricsSample): MachineMetricsSample {\n const num = (v: string | number): number => (typeof v === \"number\" ? v : Number(v));\n const firstGpu = wire.gpus[0];\n return {\n cpuPercent: wire.cpuPercent,\n load1: wire.load1,\n load5: wire.load5,\n load15: wire.load15,\n memUsedBytes: num(wire.memUsedBytes),\n memTotalBytes: num(wire.memTotalBytes),\n diskUsedBytes: num(wire.diskUsedBytes),\n diskTotalBytes: num(wire.diskTotalBytes),\n gpuUtilPercent: firstGpu ? firstGpu.utilPercent : null,\n gpuMemUsedBytes: firstGpu ? num(firstGpu.memUsedBytes) : null,\n gpuMemTotalBytes: firstGpu ? num(firstGpu.memTotalBytes) : null,\n contention: wire.runQueue,\n // The sample carries its own wall-clock stamp (epoch ms); fall back to now on\n // a missing/zero stamp so a series row is never NULL-dated.\n sampledAt:\n wire.sampledAtMs && Number(wire.sampledAtMs) > 0\n ? new Date(Number(wire.sampledAtMs))\n : new Date(),\n };\n}\n\n/** 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 });\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 ONE decoded heartbeat for an enrolled machine. Resolves the enrollment's\n * accountId (needed for the RLS-scoped writes) from the enrollment row; an\n * unknown/cross-workspace agentId is ignored (no row → no write). Touches\n * last-seen + upserts latest + downsamples the series.\n */\nexport async function ingestHeartbeat(\n db: Database,\n input: { workspaceId: string; agentId: string; sample: MetricsSample },\n): Promise<{ ingested: boolean; seriesAppended: boolean }> {\n // The enrollment row is the source of the accountId (the RLS principal) and the\n // existence check. A revoked machine still reports its accountId, so we ingest\n // (the dashboard shows its last sample); a truly unknown id is a no-op.\n const enrollment = await getEnrollment(db, input.workspaceId, input.agentId);\n if (!enrollment) {\n return { ingested: false, seriesAppended: false };\n }\n const sample = wireSampleToDbSample(input.sample);\n await touchEnrollmentLastSeen(db, {\n accountId: enrollment.accountId,\n workspaceId: input.workspaceId,\n enrollmentId: input.agentId,\n });\n const result = await ingestMachineMetricsSample(db, {\n accountId: enrollment.accountId,\n workspaceId: input.workspaceId,\n enrollmentId: input.agentId,\n sample,\n });\n return { ingested: true, seriesAppended: result.seriesAppended };\n}\n\n/**\n * Fan out one or more machine-LINK session events to the sessions that had an\n * active op running on the machine when its control link changed (per\n * `sessionsWithActiveOpOnEnrollment`) — the announce-only failure-visibility\n * plane. Each session's events are stamped on its OWN active turn. No matching\n * session ⇒ nothing is emitted (an idle-machine blip must never spam idle /\n * historical sessions). Called best-effort inside the handlers' fail-soft blocks.\n *\n * Each session's emission is ISOLATED: one session's append failing (a\n * session-specific constraint like a sequence collision from a racing writer, a\n * transient write error) is logged with that sessionId and skipped, never\n * aborting the fan-out — one session's failure must never cost the OTHER matching\n * sessions their events. A partial fan-out stays visible per-session in the logs.\n */\nasync function fanOutMachineLinkEvents(\n db: Database,\n bus: EventBus,\n observability: Observability | undefined,\n workspaceId: string,\n enrollmentId: string,\n build: (activeTurnId: string) => AppendEventInput[],\n): Promise<void> {\n const sessions = await sessionsWithActiveOpOnEnrollment(db, { workspaceId, enrollmentId });\n for (const session of sessions) {\n try {\n await appendAndPublishEvents(\n db,\n bus,\n workspaceId,\n session.sessionId,\n build(session.activeTurnId),\n );\n } catch (error) {\n observability?.warn?.(\"Failed to fan out a machine-link event to a session\", {\n workspaceId,\n sessionId: session.sessionId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n}\n\n/**\n * Decode a raw `AgentEvent` payload + ingest it (the per-message handler). A\n * heartbeat carrying a metrics sample is ingested; a going-offline records the\n * machine-plane marker + fans out the link-plane session events. Decode failures\n * are reported + swallowed. `bus` (when present) enables the session-event\n * fan-out; the live consumer always supplies it, pure unit tests may omit it.\n */\nexport async function handleAgentEventPayload(\n db: Database,\n observability: Observability | undefined,\n payload: Uint8Array,\n subject: string,\n bus?: EventBus,\n): Promise<void> {\n const ids = parseAgentEventSubject(subject);\n if (!ids) {\n return;\n }\n let event: AgentEvent;\n try {\n event = AgentEvent.decode(payload);\n } catch (error) {\n observability?.warn?.(\"Failed to decode an agent event for metrics ingestion\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n // A clean GoingOffline is the machine-plane's typed shutdown signal. Two things\n // happen, in this order:\n // 1. Record it ALWAYS on the machine plane (a Prometheus counter keyed by the\n // typed reason) so a fleet operator can see clean stops / self-updates /\n // host shutdowns. This fires unconditionally, independent of the DB.\n // 2. Stamp the enrollment's clean going-offline marker so the liveness\n // derivation reads the machine OFFLINE immediately instead of waiting out\n // the last_seen dead-detect window. Best-effort + fail-soft (like the rest\n // of this module): an unknown enrollment is a no-op and a DB error is\n // swallowed so a bad write never tears down the consumer. Deliberately does\n // NOT touch last-seen (a shutdown must not look \"more recently alive\").\n if (event.event?.$case === \"goingOffline\") {\n const reason = goingOfflineReasonToJSON(event.event.goingOffline.reason);\n observability?.incrementCounter({\n name: \"opengeni_machine_going_offline_total\",\n help: \"Total Connected Machine clean GoingOffline signals by typed reason.\",\n labels: { reason },\n });\n try {\n const enrollment = await getEnrollment(db, ids.workspaceId, ids.agentId);\n if (enrollment) {\n await setEnrollmentWentOffline(db, {\n accountId: enrollment.accountId,\n workspaceId: ids.workspaceId,\n enrollmentId: ids.agentId,\n reason,\n });\n 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 !== \"heartbeat\") {\n return; // an unknown event kind → not a metrics point.\n }\n const heartbeat = event.event.heartbeat;\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 const metrics = heartbeat.metrics;\n if (!metrics) return;\n try {\n await ingestHeartbeat(db, {\n workspaceId: ids.workspaceId,\n agentId: ids.agentId,\n sample: metrics,\n });\n } catch (error) {\n observability?.warn?.(\"Failed to ingest a machine metrics heartbeat\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\n/**\n * Start the metrics-ingestion consumer: subscribe `agent.*.*.events` and ingest\n * every heartbeat. Gated by sandboxSelfhostedEnabled (the caller checks the flag;\n * a disabled deployment never starts the consumer). Returns the unsubscribe fn.\n */\nexport function startMetricsIngestion(deps: {\n db: Database;\n bus: EventBus;\n observability?: Observability;\n}): () => void {\n return deps.bus.subscribeAgentEvents(AGENT_EVENTS_SUBJECT, (payload, subject) =>\n handleAgentEventPayload(deps.db, deps.observability, payload, subject, deps.bus),\n );\n}\n\n// ── Connect-Hello display refresh ─────────────────────────────────────────────\n\n/**\n * The LIVE display presence the agent's Hello reports: a desktop framebuffer is\n * available (`capabilities.desktop`, which the agent sets true only when a display\n * probes AND it can stream it) OR a `Display` detail is present. An unset\n * Capabilities (or a headless machine) → false. This is what `has_display` should\n * track, replacing the enroll-time snapshot.\n */\nexport function helloReportsDisplay(hello: Hello): boolean {\n const caps = hello.capabilities;\n if (!caps) {\n return false;\n }\n // A CAPTURE-BLOCKED display is NOT a usable display: a Mac reports a display but\n // withholds `desktop` and sets `desktopUnavailableReason` when Screen Recording\n // (TCC) is not granted. Treating it as \"has display\" is exactly how the 0.1.3\n // incident hid — the machine claimed a desktop it could not capture, so it was\n // offered for computer-use and the model saw a blank. Gate it out here (the single\n // source of truth for `has_display`, consumed by both the machine state and the\n // capability negotiation). The `display`-present fallback is preserved for every\n // other case (e.g. a relay-less agent that reports a display but not `desktop`).\n if (caps.desktopUnavailableReason) {\n return false;\n }\n return caps.desktop === true || caps.display != null;\n}\n\n/**\n * The human, actionable reason a display is present but UNUSABLE (macOS Screen\n * Recording / TCC not granted), or null when capture is permitted / the machine is\n * headless. Normalizes the proto's non-optional \"\" empty string to null so the DB\n * carries a clean tri-state (a real reason vs. no reason) — the Machines dashboard\n * shows \"display: capture not granted\" only when this is non-null.\n */\nexport function helloDesktopUnavailableReason(hello: Hello): string | null {\n const reason = hello.capabilities?.desktopUnavailableReason;\n return reason ? reason : null;\n}\n\n/** Whether the runner's current Hello advertises the op-stream engine. */\nexport function helloReportsOpStream(hello: Hello): boolean {\n return hello.capabilities?.opStream === true;\n}\n\n/**\n * Reconcile `enrollments.has_display` (+ the capture-blocked reason) to what a Hello\n * reports. Resolves the enrollment (the accountId is the RLS principal + the\n * existence check + the current values). A no-change Hello short-circuits BEFORE\n * issuing any write (and the DB writer is itself change-guarded on BOTH fields as a\n * backstop), so a steady state never churns. An unknown/cross-workspace agentId is a\n * no-op.\n */\nexport async function refreshEnrollmentDisplay(\n db: Database,\n input: {\n workspaceId: string;\n agentId: string;\n hasDisplay: boolean;\n desktopUnavailableReason?: string | null;\n },\n): Promise<{ updated: boolean }> {\n const desktopUnavailableReason = input.desktopUnavailableReason ?? null;\n const enrollment = await getEnrollment(db, input.workspaceId, input.agentId);\n if (!enrollment) {\n return { updated: false };\n }\n if (\n enrollment.hasDisplay === input.hasDisplay &&\n (enrollment.desktopUnavailableReason ?? null) === desktopUnavailableReason\n ) {\n // Both fields unchanged — do not even issue the UPDATE (no churn on a\n // steady-state Hello).\n return { updated: false };\n }\n return await setEnrollmentDisplayState(db, {\n accountId: enrollment.accountId,\n workspaceId: input.workspaceId,\n enrollmentId: input.agentId,\n hasDisplay: input.hasDisplay,\n desktopUnavailableReason,\n });\n}\n\n/**\n * Reconcile `enrollments.op_stream` to what a Hello reports. Resolves the\n * enrollment first so the accountId remains the RLS principal and so a no-change\n * Hello short-circuits BEFORE issuing any write (the DB writer is itself\n * change-guarded as a backstop). An unknown/cross-workspace agentId is a no-op.\n */\nexport async function refreshEnrollmentOpStream(\n db: Database,\n input: {\n workspaceId: string;\n agentId: string;\n opStream: boolean;\n },\n): Promise<{ updated: boolean }> {\n const enrollment = await getEnrollment(db, input.workspaceId, input.agentId);\n if (!enrollment) {\n return { updated: false };\n }\n if (enrollment.opStream === input.opStream) {\n // The capability is unchanged — do not even issue the UPDATE (no churn on a\n // steady-state Hello).\n return { updated: false };\n }\n return await setEnrollmentOpStreamState(db, {\n accountId: enrollment.accountId,\n workspaceId: input.workspaceId,\n enrollmentId: input.agentId,\n opStream: input.opStream,\n });\n}\n\n/**\n * Decode a raw `Hello` payload + refresh the enrollment's display cursor + clear\n * any pending clean going-offline marker and, when the reconnect actually cleared\n * one, fan out machine.link.restored to the sessions with an active op on the\n * machine (the per-message handler for the hello plane). Decode failures + write\n * failures are reported + swallowed — a Hello must NEVER break the agent's connect.\n * `bus` (when present) enables the link.restored fan-out.\n */\nexport async function handleHelloPayload(\n db: Database,\n observability: Observability | undefined,\n payload: Uint8Array,\n subject: string,\n bus?: EventBus,\n): Promise<void> {\n const ids = parseAgentHelloSubject(subject);\n if (!ids) {\n return;\n }\n let hello: Hello;\n try {\n hello = Hello.decode(payload);\n } catch (error) {\n observability?.warn?.(\"Failed to decode an agent Hello for display refresh\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n try {\n await refreshEnrollmentDisplay(db, {\n workspaceId: ids.workspaceId,\n agentId: ids.agentId,\n hasDisplay: helloReportsDisplay(hello),\n desktopUnavailableReason: helloDesktopUnavailableReason(hello),\n });\n await refreshEnrollmentOpStream(db, {\n workspaceId: ids.workspaceId,\n agentId: ids.agentId,\n opStream: helloReportsOpStream(hello),\n });\n } catch (error) {\n observability?.warn?.(\"Failed to refresh an enrollment's capabilities from a Hello\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n // A reconnect Hello re-announces the machine, so any pending clean going-offline\n // marker no longer holds — clear it so the liveness derivation stops reading the\n // machine offline. Best-effort + fail-soft, and change-guarded in the DB (a\n // steady-state Hello with no marker writes nothing), so this never breaks the\n // agent's connect and never churns. When a marker was ACTUALLY cleared (the\n // machine had been reported link.lost), fan out machine.link.restored to the\n // sessions with an active op on it — a restored only ever pairs a prior lost, so\n // a routine connect Hello (no marker) emits nothing.\n try {\n const enrollment = await getEnrollment(db, ids.workspaceId, ids.agentId);\n if (enrollment) {\n const { cleared } = await clearEnrollmentWentOffline(db, {\n accountId: enrollment.accountId,\n workspaceId: ids.workspaceId,\n enrollmentId: ids.agentId,\n });\n if (cleared && bus) {\n await fanOutMachineLinkEvents(\n db,\n bus,\n observability,\n ids.workspaceId,\n ids.agentId,\n (activeTurnId) => [{ type: \"machine.link.restored\", turnId: activeTurnId, payload: {} }],\n );\n }\n }\n } catch (error) {\n observability?.warn?.(\"Failed to clear a machine going-offline marker on a Hello\", {\n subject,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\n/**\n * Start the Hello display-refresh consumer: subscribe `agent.*.*.hello` and\n * reconcile `has_display` to the live capability the agent reports on every\n * connect. Gated by sandboxSelfhostedEnabled (the caller checks the flag). Returns\n * the unsubscribe fn.\n */\nexport function startHelloIngestion(deps: {\n db: Database;\n bus: EventBus;\n observability?: Observability;\n}): () => void {\n return deps.bus.subscribeAgentEvents(AGENT_HELLO_SUBJECT, (payload, subject) =>\n handleHelloPayload(deps.db, deps.observability, payload, subject, deps.bus),\n );\n}\n","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(\"&\", \"&\").replaceAll(\"<\", \"<\").replaceAll(\">\", \">\");\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} from \"@opengeni/core\";\n\nexport const EDITABLE_ARTIFACT_LIVE_WEBSOCKET_PATH = \"/v1/editable-artifacts/live\";\nexport const EDITABLE_ARTIFACT_LIVE_WEBSOCKET_PROTOCOL = \"opengeni-artifact-v1\";\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 = Readonly<{\n data: EditableArtifactWebSocketConnection;\n send(data: Uint8Array, compress?: boolean): number;\n close(code?: number, reason?: string): void;\n readonly bufferedAmount?: number;\n getBufferedAmount?(): number;\n}>;\n\nexport type EditableArtifactWebSocketUpgradeServer = Readonly<{\n upgrade(\n request: Request,\n options: Readonly<{\n data: EditableArtifactWebSocketConnection;\n headers: HeadersInit;\n }>,\n ): boolean;\n}>;\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(private readonly application: EditableArtifactApplicationPort | undefined) {\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(this.application);\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 implements EditableArtifactLiveSinkPort {\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(private readonly application: EditableArtifactApplicationPort) {}\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 });\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 { 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_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 EDITABLE_ARTIFACT_LIVE_PROTOCOL_VERSION,\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 {\n PostgresEditableArtifactLiveReadStore,\n PostgresEditableArtifactLiveTicketStore,\n PostgresEditableArtifactStore,\n listEditableArtifactIdsForSession,\n touchEditableArtifactSessionLink,\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 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 if (\n request.protocolVersion !== EDITABLE_ARTIFACT_LIVE_PROTOCOL_VERSION ||\n request.modelSchemaVersion !== 1 ||\n request.kernelVersion !== runtime.buildIdentity\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 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.includes(1) ||\n !capabilities.supportedOperationProtocolVersions.includes(1) ||\n !capabilities.supportedSnapshotProtocolVersions.includes(1)\n ) {\n throw new Error(\"Verified artifact materializer profile is incompatible\");\n }\n const codecVersion = capabilities.codecVersions[\"opengeni.xlsx\"];\n return Object.freeze({\n async resolve(input: Parameters<EditableArtifactMaterializationProfilePort[\"resolve\"]>[0]) {\n if (\n input.modality !== \"spreadsheet\" ||\n input.format !== \"xlsx\" ||\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 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 MODEL_SCHEMA_VERSION = 1;\nconst OPERATION_PROTOCOL_VERSION = 1;\nconst CRDT_STATE_VERSION = 1;\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: 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: MODEL_SCHEMA_VERSION,\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: MODEL_SCHEMA_VERSION,\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: OPERATION_PROTOCOL_VERSION,\n crdtStateVersion: CRDT_STATE_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: MODEL_SCHEMA_VERSION,\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: OPERATION_PROTOCOL_VERSION,\n crdtStateVersion: CRDT_STATE_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: MODEL_SCHEMA_VERSION,\n kernelVersion: this.runtime.buildIdentity,\n fullCrdtStateVerified: true as const,\n coveredCausalFrontier,\n operationProtocolVersion: OPERATION_PROTOCOL_VERSION,\n crdtStateVersion: CRDT_STATE_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: MODEL_SCHEMA_VERSION,\n kernelVersion: this.runtime.buildIdentity,\n nativeRevision,\n ...(replayedTarget ? { replayedTarget } : {}),\n });\n } finally {\n session.dispose();\n }\n }\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 EditableArtifactOfficeImportPort,\n type EditableArtifactModality,\n} from \"@opengeni/core/editable-artifacts\";\nimport { getFile } from \"@opengeni/db\";\nimport {\n MAX_BOUNDED_OBJECT_CHUNK_BYTES,\n type BoundedImmutableObjectWritePort,\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 readFile?: typeof getFile;\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 readFile: typeof getFile;\n\n constructor(private readonly dependencies: EditableArtifactOfficeImportAdapterDependencies) {\n this.readFile = dependencies.readFile ?? getFile;\n }\n\n async prepare(\n input: Parameters<EditableArtifactOfficeImportPort[\"prepare\"]>[0],\n ): ReturnType<EditableArtifactOfficeImportPort[\"prepare\"]> {\n throwIfAborted(input.signal);\n const file = await this.readFile(this.dependencies.db, input.scope.workspaceId, input.fileId);\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 getFile>>>,\n signal?: AbortSignal,\n): Promise<Uint8Array> {\n throwIfAborted(signal);\n const before = await storage.headFile(file);\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 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 storage.headFile(file);\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\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 type { ObjectHead, 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 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 const stored = await storage.headObject(objectKey);\n assertStoredExport(stored, download.byteSize, download.mimeType, sha256);\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 assertStoredExport(\n await storage.headObject(objectKey),\n download.byteSize,\n download.mimeType,\n sha256,\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\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"],"mappings":";;;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,0BAAoD;AAC7D,SAAS,qBAAqB,iCAAiC;AAC/D,SAAS,2BAA2B;AACpC,SAAS,mCAAmC;AAC5C,SAAS,oDAAoD;AAC7D;AAAA,EACE;AAAA,EACA,UAAU;AAAA,EACV;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;AC7BA,SAAS,yBAAyB,eAA2C;AAClF,SAAO;AAAA,IACL,OAAO,CAAC,SAAS,eAAe,cAAc,MAAM,SAAS,gBAAgB,UAAU,CAAC;AAAA,IACxF,MAAM,CAAC,SAAS,eAAe,cAAc,KAAK,SAAS,gBAAgB,UAAU,CAAC;AAAA,EACxF;AACF;AAEA,SAAS,gBAAgB,YAAyE;AAChG,MAAI,CAAC,YAAY;AACf,WAAO;AAAA,EACT;AACA,QAAM,YAAwB,CAAC;AAC/B,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,UAAU,GAAG;AACrD,cAAU,GAAG,I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AS,wBAAyB,QAAO;AACzD,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","createHash","MAX_EDITABLE_ARTIFACT_SNAPSHOT_BYTES","MAX_BOUNDED_OBJECT_CHUNK_BYTES","replayedTarget","createHash","MAX_EDITABLE_ARTIFACT_SNAPSHOT_BYTES","editableArtifactCausalFrontier","editableArtifactContentHash","editableArtifactReplicaId","editableArtifactStateHash","throwIfAborted","createHash","throwIfAborted","MAX_EDITABLE_ARTIFACT_SNAPSHOT_BYTES","createHash","MAX_BOUNDED_OBJECT_CHUNK_BYTES"]}
|