@opengeni/db 3.7.4 → 4.0.0-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/dist/automations.d.ts +4 -0
  2. package/dist/canonical-human-identities.js +3 -3
  3. package/dist/capability-integrations.d.ts +2 -0
  4. package/dist/{chunk-6DPJA36C.js → chunk-2XEZK4LF.js} +7 -1
  5. package/dist/chunk-2XEZK4LF.js.map +1 -0
  6. package/dist/{chunk-4NAR7FBA.js → chunk-3RI33YQN.js} +67 -1
  7. package/dist/chunk-3RI33YQN.js.map +1 -0
  8. package/dist/{chunk-SZAWDXQC.js → chunk-CJROYHSC.js} +3 -3
  9. package/dist/{chunk-DZCYW2WT.js → chunk-MX6V5F65.js} +2 -2
  10. package/dist/{chunk-S3TDDCS2.js → chunk-N5VXJ4I2.js} +151 -78
  11. package/dist/chunk-N5VXJ4I2.js.map +1 -0
  12. package/dist/{chunk-U4WPPEBH.js → chunk-NLFHMPUB.js} +2 -2
  13. package/dist/{chunk-5NNCGFQY.js → chunk-P6NSEG2S.js} +2 -2
  14. package/dist/{chunk-O56DM5GZ.js → chunk-QM6YOWHZ.js} +624 -57
  15. package/dist/chunk-QM6YOWHZ.js.map +1 -0
  16. package/dist/{chunk-US4IS6IV.js → chunk-RZNOSEMC.js} +2 -2
  17. package/dist/{chunk-F6PBS6WE.js → chunk-UFAMOUWL.js} +2 -2
  18. package/dist/codemode-operations.d.ts +5 -0
  19. package/dist/codex-token-resolver.d.ts +6 -2
  20. package/dist/connection-token-resolver.d.ts +8 -0
  21. package/dist/editable-artifact-durable-export.js +2 -2
  22. package/dist/editable-artifacts.js +3 -3
  23. package/dist/generated-images.d.ts +15 -0
  24. package/dist/index.d.ts +393 -91
  25. package/dist/index.js +9992 -6069
  26. package/dist/index.js.map +1 -1
  27. package/dist/insights.d.ts +9 -0
  28. package/dist/managed-auth-session-sets.js +3 -3
  29. package/dist/managed-user-setup.d.ts +3 -0
  30. package/dist/mcp-oauth.d.ts +80 -0
  31. package/dist/migrate.d.ts +1 -0
  32. package/dist/migrate.js +3 -1
  33. package/dist/model-catalog.d.ts +153 -0
  34. package/dist/model-context-snapshots.d.ts +20 -0
  35. package/dist/new-session-drafts.d.ts +12 -0
  36. package/dist/organization-membership-lifecycle.d.ts +8 -1
  37. package/dist/organization-model-providers.d.ts +101 -0
  38. package/dist/pack-components.d.ts +1 -0
  39. package/dist/pr-review.d.ts +9 -0
  40. package/dist/provision-roles.js +1 -1
  41. package/dist/runtime-posture.d.ts +8 -8
  42. package/dist/schema.d.ts +7708 -5050
  43. package/dist/schema.js +25 -1
  44. package/dist/session-background-commands.d.ts +18 -6
  45. package/dist/session-background-commands.js +15 -9
  46. package/dist/session-control.d.ts +37 -2
  47. package/dist/session-goal-pacing.d.ts +3 -6
  48. package/dist/session-queue-commands.d.ts +17 -0
  49. package/dist/session-tenancy.js +3 -3
  50. package/dist/tool-gateway-approvals.d.ts +31 -0
  51. package/dist/video-generation.js +3 -3
  52. package/dist/workspace-artifacts.d.ts +17 -3
  53. package/dist/xai-subscription.d.ts +8 -0
  54. package/drizzle/0387_bound_host_export_session_payloads.sql +165 -0
  55. package/drizzle/0388_sandbox_provider_deadline_interactions.sql +491 -0
  56. package/drizzle/0389_model_catalog_and_gateway_custom_models.sql +241 -0
  57. package/drizzle/0390_organization_model_provider_connections.sql +197 -0
  58. package/drizzle/0391_sandbox_provider_deadline_interaction_followup.sql +295 -0
  59. package/drizzle/0392_context_compaction_pending_observability.sql +198 -0
  60. package/drizzle/0393_workspace_memory_and_learning_defaults.sql +102 -0
  61. package/drizzle/0394_session_selected_skill_activation.sql +20 -0
  62. package/drizzle/0395_scheduled_task_unclaimed_occurrence_invalidation.sql +154 -0
  63. package/drizzle/0396_model_call_equivalent_credit_cost.sql +28 -0
  64. package/drizzle/0397_sandbox_deadline_rotation_preemption.sql +113 -0
  65. package/drizzle/0398_organization_workspace_management_entry.sql +206 -0
  66. package/drizzle/0399_additional_managed_organization_creation.sql +691 -0
  67. package/drizzle/0400_session_attempt_model_context_snapshots.sql +65 -0
  68. package/drizzle/0401_organization_user_setup_token_transport.sql +178 -0
  69. package/drizzle/0402_session_input_wait_and_background_command_results.sql +1023 -0
  70. package/drizzle/0403_codex_unconditional_credential_leasing.sql +181 -0
  71. package/drizzle/0404_mcp_oauth_authorization_server.sql +471 -0
  72. package/drizzle/0405_tool_gateway_approval_capabilities.sql +184 -0
  73. package/drizzle/0406_workspace_html_site_sources.sql +71 -0
  74. package/package.json +6 -6
  75. package/src/automations.ts +9 -1
  76. package/src/capability-integrations.ts +8 -0
  77. package/src/codemode-operations.ts +31 -21
  78. package/src/codex-token-resolver.ts +16 -6
  79. package/src/connection-token-resolver.ts +52 -3
  80. package/src/generated-images.ts +70 -6
  81. package/src/index.ts +3894 -994
  82. package/src/insights-model-bundle.ts +54 -5
  83. package/src/insights.ts +53 -7
  84. package/src/managed-user-setup.ts +14 -3
  85. package/src/mcp-oauth.ts +488 -0
  86. package/src/migrate.ts +9 -1
  87. package/src/model-catalog.ts +682 -0
  88. package/src/model-context-snapshots.ts +151 -0
  89. package/src/new-session-drafts.ts +66 -21
  90. package/src/organization-membership-lifecycle.ts +47 -5
  91. package/src/organization-model-providers.ts +614 -0
  92. package/src/pack-components.ts +15 -2
  93. package/src/pr-review.ts +19 -0
  94. package/src/provision-roles.ts +4 -0
  95. package/src/runtime-posture.ts +64 -0
  96. package/src/schema.ts +666 -61
  97. package/src/session-background-commands.ts +180 -78
  98. package/src/session-control.ts +181 -12
  99. package/src/session-goal-pacing.ts +4 -8
  100. package/src/session-queue-commands.ts +157 -82
  101. package/src/tool-gateway-approvals.ts +168 -0
  102. package/src/workspace-artifacts.ts +633 -178
  103. package/src/xai-subscription.ts +66 -14
  104. package/dist/chunk-4NAR7FBA.js.map +0 -1
  105. package/dist/chunk-6DPJA36C.js.map +0 -1
  106. package/dist/chunk-O56DM5GZ.js.map +0 -1
  107. package/dist/chunk-S3TDDCS2.js.map +0 -1
  108. /package/dist/{chunk-SZAWDXQC.js.map → chunk-CJROYHSC.js.map} +0 -0
  109. /package/dist/{chunk-DZCYW2WT.js.map → chunk-MX6V5F65.js.map} +0 -0
  110. /package/dist/{chunk-U4WPPEBH.js.map → chunk-NLFHMPUB.js.map} +0 -0
  111. /package/dist/{chunk-5NNCGFQY.js.map → chunk-P6NSEG2S.js.map} +0 -0
  112. /package/dist/{chunk-US4IS6IV.js.map → chunk-RZNOSEMC.js.map} +0 -0
  113. /package/dist/{chunk-F6PBS6WE.js.map → chunk-UFAMOUWL.js.map} +0 -0
@@ -2,7 +2,7 @@ import {
2
2
  rawRows,
3
3
  withRlsContext,
4
4
  withWorkspaceRls
5
- } from "./chunk-F6PBS6WE.js";
5
+ } from "./chunk-UFAMOUWL.js";
6
6
  import {
7
7
  connections,
8
8
  creditLedgerEntries,
@@ -14,7 +14,7 @@ import {
14
14
  workspaceVideoGenerationPolicies,
15
15
  workspaceVideoGenerationQuotas,
16
16
  workspaces
17
- } from "./chunk-O56DM5GZ.js";
17
+ } from "./chunk-QM6YOWHZ.js";
18
18
 
19
19
  // src/video-generation.ts
20
20
  import {
@@ -992,4 +992,4 @@ export {
992
992
  mediaGenerationResultForStoredOperation,
993
993
  getVideoGenerationOperationSummary
994
994
  };
995
- //# sourceMappingURL=chunk-SZAWDXQC.js.map
995
+ //# sourceMappingURL=chunk-CJROYHSC.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  nestedPostgresSqlState,
3
3
  rawRows
4
- } from "./chunk-F6PBS6WE.js";
4
+ } from "./chunk-UFAMOUWL.js";
5
5
 
6
6
  // src/managed-auth-session-sets.ts
7
7
  import {
@@ -296,4 +296,4 @@ export {
296
296
  reapManagedAuthIsolatedSessions,
297
297
  reapExpiredManagedAuthSessionSets
298
298
  };
299
- //# sourceMappingURL=chunk-DZCYW2WT.js.map
299
+ //# sourceMappingURL=chunk-MX6V5F65.js.map
@@ -1,14 +1,30 @@
1
1
  import {
2
- withRlsContext
3
- } from "./chunk-F6PBS6WE.js";
2
+ withRlsContext,
3
+ withSessionActivityRlsContext
4
+ } from "./chunk-UFAMOUWL.js";
4
5
  import {
5
6
  sandboxRetainedProcesses,
6
7
  sessionBackgroundCommands,
8
+ sessionEvents,
7
9
  sessions
8
- } from "./chunk-O56DM5GZ.js";
10
+ } from "./chunk-QM6YOWHZ.js";
9
11
 
10
12
  // src/session-background-commands.ts
11
13
  import { and, desc, eq, inArray, sql } from "drizzle-orm";
14
+ var SESSION_BACKGROUND_COMMAND_REASON_MAX_BYTES = 512;
15
+ function boundedSessionBackgroundCommandReason(value, label) {
16
+ const normalized = value.trim();
17
+ let bounded = "";
18
+ let bytes = 0;
19
+ for (const character of normalized) {
20
+ const characterBytes = Buffer.byteLength(character, "utf8");
21
+ if (bytes + characterBytes > SESSION_BACKGROUND_COMMAND_REASON_MAX_BYTES) break;
22
+ bounded += character;
23
+ bytes += characterBytes;
24
+ }
25
+ if (!bounded) throw new Error(`${label} must not be empty`);
26
+ return bounded;
27
+ }
12
28
  function commandPreview(value) {
13
29
  const normalized = value.replace(/\s+/g, " ").trim();
14
30
  return Array.from(normalized).slice(0, 512).join("");
@@ -210,8 +226,10 @@ function connectedClaimIdentityWhere(claim) {
210
226
  );
211
227
  }
212
228
  async function recordConnectedMachineBackgroundCommandProof(db, input) {
213
- const reason = input.proof.reason.trim().slice(0, 512);
214
- if (!reason) throw new Error("Connected command proof reason must not be empty");
229
+ const reason = boundedSessionBackgroundCommandReason(
230
+ input.proof.reason,
231
+ "Connected command proof reason"
232
+ );
215
233
  if (input.proof.outcome === "exited" && input.proof.exitCode === null) {
216
234
  throw new Error("Connected command exit proof requires an exit code");
217
235
  }
@@ -266,41 +284,46 @@ async function deferConnectedMachineBackgroundCommandReconciliation(db, input) {
266
284
  }
267
285
  );
268
286
  }
269
- async function settleClaimedConnectedMachineBackgroundCommand(db, input) {
270
- return await withRlsContext(
287
+ async function settleClaimedConnectedMachineBackgroundCommandWithMutation(db, input, mutateTerminal) {
288
+ return await withSessionActivityRlsContext(
271
289
  db,
272
290
  { accountId: input.claim.accountId, workspaceId: input.claim.workspaceId },
273
- async (scopedDb) => {
274
- const rows = await scopedDb.execute(sql`
275
- update ${sessionBackgroundCommands} command set
276
- state = command.reconcile_proof_outcome,
277
- exit_code = case
278
- when command.reconcile_proof_outcome = 'exited'
279
- then command.reconcile_proof_exit_code
280
- else null
281
- end,
282
- settlement_reason = command.reconcile_proof_reason,
283
- settled_at = command.reconcile_proof_observed_at,
284
- reconcile_claim_id = null,
285
- reconcile_claimed_at = null,
286
- last_reconcile_outcome = 'settled_' || command.reconcile_proof_outcome,
287
- updated_at = clock_timestamp()
288
- where command.id = ${input.claim.commandId}
289
- and command.account_id = ${input.claim.accountId}
290
- and command.workspace_id = ${input.claim.workspaceId}
291
- and command.session_id = ${input.claim.sessionId}
292
- and command.provider = 'connected_machine'
293
- and command.control_workspace_id = ${input.claim.controlWorkspaceId}
294
- and command.enrollment_id = ${input.claim.enrollmentId}
295
- and command.connection_instance_id = ${input.claim.connectionInstanceId}
296
- and command.op_id = ${input.claim.opId}
297
- and command.reconcile_claim_id = ${input.claim.claimId}
298
- and command.state in ('running', 'stopping')
299
- and command.reconcile_proof_outcome in ('exited', 'lost')
300
- and command.reconcile_proof_observed_at is not null
301
- returning command.id
302
- `);
303
- return rows.length === 1;
291
+ async (tx) => {
292
+ await mutateTerminal.prepare(tx);
293
+ const rows = await tx.execute(sql`
294
+ update ${sessionBackgroundCommands} command set
295
+ state = command.reconcile_proof_outcome,
296
+ exit_code = case
297
+ when command.reconcile_proof_outcome = 'exited'
298
+ then command.reconcile_proof_exit_code
299
+ else null
300
+ end,
301
+ settlement_reason = command.reconcile_proof_reason,
302
+ settled_at = command.reconcile_proof_observed_at,
303
+ reconcile_claim_id = null,
304
+ reconcile_claimed_at = null,
305
+ last_reconcile_outcome = 'settled_' || command.reconcile_proof_outcome,
306
+ updated_at = clock_timestamp()
307
+ where command.id = ${input.claim.commandId}
308
+ and command.account_id = ${input.claim.accountId}
309
+ and command.workspace_id = ${input.claim.workspaceId}
310
+ and command.session_id = ${input.claim.sessionId}
311
+ and command.provider = 'connected_machine'
312
+ and command.control_workspace_id = ${input.claim.controlWorkspaceId}
313
+ and command.enrollment_id = ${input.claim.enrollmentId}
314
+ and command.connection_instance_id = ${input.claim.connectionInstanceId}
315
+ and command.op_id = ${input.claim.opId}
316
+ and command.reconcile_claim_id = ${input.claim.claimId}
317
+ and command.state in ('running', 'stopping')
318
+ and command.reconcile_proof_outcome in ('exited', 'lost')
319
+ and command.reconcile_proof_observed_at is not null
320
+ returning command.id
321
+ `);
322
+ if (rows.length !== 1) return false;
323
+ const [row] = await tx.select().from(sessionBackgroundCommands).where(eq(sessionBackgroundCommands.id, input.claim.commandId)).limit(1);
324
+ if (!row) throw new Error("Settled Connected Machine command disappeared");
325
+ await mutateTerminal.commit(tx, mapCommand(row));
326
+ return true;
304
327
  }
305
328
  );
306
329
  }
@@ -427,47 +450,75 @@ async function requestWorkspaceBackgroundCommandCancellationsInTransaction(db, i
427
450
  `);
428
451
  return Number(rows[0]?.commandCount ?? 0);
429
452
  }
430
- async function settleSessionBackgroundCommandForRetainedProcess(db, input) {
431
- return await withRlsContext(
432
- db,
433
- { accountId: input.accountId, workspaceId: input.workspaceId },
434
- async (scopedDb) => {
435
- const [row] = await scopedDb.update(sessionBackgroundCommands).set({
436
- state: input.outcome,
437
- exitCode: input.outcome === "exited" ? input.exitCode : null,
438
- settlementReason: input.reason.slice(0, 512),
439
- settledAt: /* @__PURE__ */ new Date(),
440
- reconcileClaimId: null,
441
- reconcileClaimedAt: null,
442
- lastReconcileOutcome: `settled_${input.outcome}`,
443
- updatedAt: /* @__PURE__ */ new Date()
444
- }).where(
445
- and(
446
- eq(sessionBackgroundCommands.workspaceId, input.workspaceId),
447
- eq(sessionBackgroundCommands.sessionId, input.sessionId),
448
- eq(sessionBackgroundCommands.retainedProcessId, input.retainedProcessId),
449
- inArray(sessionBackgroundCommands.state, ["running", "stopping"])
450
- )
451
- ).returning();
452
- return row ? mapCommand(row) : null;
453
- }
453
+ async function settleSessionBackgroundCommandForRetainedProcessInTransaction(tx, input, mutateTerminal) {
454
+ const reason = boundedSessionBackgroundCommandReason(
455
+ input.reason,
456
+ "Managed command settlement reason"
454
457
  );
458
+ await mutateTerminal.prepare(tx);
459
+ const [updatedRow] = await tx.update(sessionBackgroundCommands).set({
460
+ state: input.outcome,
461
+ exitCode: input.outcome === "exited" ? input.exitCode : null,
462
+ settlementReason: reason,
463
+ settledAt: /* @__PURE__ */ new Date(),
464
+ reconcileClaimId: null,
465
+ reconcileClaimedAt: null,
466
+ lastReconcileOutcome: `settled_${input.outcome}`,
467
+ updatedAt: /* @__PURE__ */ new Date()
468
+ }).where(
469
+ and(
470
+ eq(sessionBackgroundCommands.workspaceId, input.workspaceId),
471
+ eq(sessionBackgroundCommands.sessionId, input.sessionId),
472
+ eq(sessionBackgroundCommands.retainedProcessId, input.retainedProcessId),
473
+ inArray(sessionBackgroundCommands.state, ["running", "stopping"])
474
+ )
475
+ ).returning();
476
+ let row = updatedRow;
477
+ if (!row) {
478
+ const [current] = await tx.select().from(sessionBackgroundCommands).where(
479
+ and(
480
+ eq(sessionBackgroundCommands.workspaceId, input.workspaceId),
481
+ eq(sessionBackgroundCommands.sessionId, input.sessionId),
482
+ eq(sessionBackgroundCommands.retainedProcessId, input.retainedProcessId)
483
+ )
484
+ ).for("update").limit(1);
485
+ if (!current) return null;
486
+ if (current.state !== input.outcome || current.exitCode !== (input.outcome === "exited" ? input.exitCode : null)) {
487
+ throw new Error("Managed background command terminal state conflicts with process proof");
488
+ }
489
+ const [existingEvent] = await tx.select({ id: sessionEvents.id }).from(sessionEvents).where(
490
+ and(
491
+ eq(sessionEvents.workspaceId, input.workspaceId),
492
+ eq(sessionEvents.sessionId, input.sessionId),
493
+ eq(sessionEvents.type, "session.command.finished"),
494
+ sql`${sessionEvents.payload} ->> 'commandId' = ${current.id}`
495
+ )
496
+ ).limit(1);
497
+ if (existingEvent) return mapCommand(current);
498
+ row = current;
499
+ }
500
+ const command = mapCommand(row);
501
+ await mutateTerminal.commit(tx, command);
502
+ return command;
455
503
  }
456
- async function settleConnectedMachineSessionBackgroundCommand(db, input) {
457
- return await withRlsContext(
504
+ async function settleConnectedMachineSessionBackgroundCommandWithMutation(db, input, mutateTerminal) {
505
+ const reason = boundedSessionBackgroundCommandReason(
506
+ input.reason,
507
+ "Connected command settlement reason"
508
+ );
509
+ if (input.outcome === "exited" && input.exitCode === null) {
510
+ throw new Error("Connected command exit settlement requires an exit code");
511
+ }
512
+ if (input.outcome === "lost" && input.exitCode !== null) {
513
+ throw new Error("Connected command loss settlement cannot carry an exit code");
514
+ }
515
+ return await withSessionActivityRlsContext(
458
516
  db,
459
517
  { accountId: input.accountId, workspaceId: input.workspaceId },
460
- async (scopedDb) => {
518
+ async (tx) => {
519
+ await mutateTerminal.prepare(tx);
461
520
  const settledAt = /* @__PURE__ */ new Date();
462
- const reason = input.reason.trim().slice(0, 512);
463
- if (!reason) throw new Error("Connected command settlement reason must not be empty");
464
- if (input.outcome === "exited" && input.exitCode === null) {
465
- throw new Error("Connected command exit settlement requires an exit code");
466
- }
467
- if (input.outcome === "lost" && input.exitCode !== null) {
468
- throw new Error("Connected command loss settlement cannot carry an exit code");
469
- }
470
- const [row] = await scopedDb.update(sessionBackgroundCommands).set({
521
+ const [row] = await tx.update(sessionBackgroundCommands).set({
471
522
  state: input.outcome,
472
523
  exitCode: input.outcome === "exited" ? input.exitCode : null,
473
524
  settlementReason: reason,
@@ -493,12 +544,33 @@ async function settleConnectedMachineSessionBackgroundCommand(db, input) {
493
544
  inArray(sessionBackgroundCommands.state, ["running", "stopping"])
494
545
  )
495
546
  ).returning();
547
+ if (!row) return null;
548
+ const command = mapCommand(row);
549
+ await mutateTerminal.commit(tx, command);
550
+ return command;
551
+ }
552
+ );
553
+ }
554
+ async function getSessionBackgroundCommand(db, input) {
555
+ return await withRlsContext(
556
+ db,
557
+ { accountId: input.accountId, workspaceId: input.workspaceId },
558
+ async (scopedDb) => {
559
+ const [row] = await scopedDb.select().from(sessionBackgroundCommands).where(
560
+ and(
561
+ eq(sessionBackgroundCommands.workspaceId, input.workspaceId),
562
+ eq(sessionBackgroundCommands.sessionId, input.sessionId),
563
+ eq(sessionBackgroundCommands.id, input.commandId)
564
+ )
565
+ ).limit(1);
496
566
  return row ? mapCommand(row) : null;
497
567
  }
498
568
  );
499
569
  }
500
570
 
501
571
  export {
572
+ SESSION_BACKGROUND_COMMAND_REASON_MAX_BYTES,
573
+ boundedSessionBackgroundCommandReason,
502
574
  backgroundCommandActivityForSessions,
503
575
  listSessionBackgroundCommands,
504
576
  insertManagedSessionBackgroundCommandInTransaction,
@@ -506,11 +578,12 @@ export {
506
578
  claimConnectedMachineSessionBackgroundCommands,
507
579
  recordConnectedMachineBackgroundCommandProof,
508
580
  deferConnectedMachineBackgroundCommandReconciliation,
509
- settleClaimedConnectedMachineBackgroundCommand,
581
+ settleClaimedConnectedMachineBackgroundCommandWithMutation,
510
582
  requestSessionBackgroundCommandCancellation,
511
583
  requestSessionBackgroundCommandCancellationsInTransaction,
512
584
  requestWorkspaceBackgroundCommandCancellationsInTransaction,
513
- settleSessionBackgroundCommandForRetainedProcess,
514
- settleConnectedMachineSessionBackgroundCommand
585
+ settleSessionBackgroundCommandForRetainedProcessInTransaction,
586
+ settleConnectedMachineSessionBackgroundCommandWithMutation,
587
+ getSessionBackgroundCommand
515
588
  };
516
- //# sourceMappingURL=chunk-S3TDDCS2.js.map
589
+ //# sourceMappingURL=chunk-N5VXJ4I2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/session-background-commands.ts"],"sourcesContent":["import type {\n SessionBackgroundCommand,\n SessionBackgroundCommandActivity,\n} from \"@opengeni/contracts\";\nimport { and, desc, eq, inArray, sql } from \"drizzle-orm\";\n\nimport type { Database, SessionActivityDatabase } from \"./database\";\nimport { withRlsContext, withSessionActivityRlsContext } from \"./database\";\nimport * as schema from \"./schema\";\n\nexport type ConnectedMachineBackgroundCommandProof = {\n outcome: \"exited\" | \"lost\";\n exitCode: number | null;\n reason: string;\n observedAt: Date;\n};\n\nexport const SESSION_BACKGROUND_COMMAND_REASON_MAX_BYTES = 512;\n\nexport function boundedSessionBackgroundCommandReason(value: string, label: string): string {\n const normalized = value.trim();\n let bounded = \"\";\n let bytes = 0;\n for (const character of normalized) {\n const characterBytes = Buffer.byteLength(character, \"utf8\");\n if (bytes + characterBytes > SESSION_BACKGROUND_COMMAND_REASON_MAX_BYTES) break;\n bounded += character;\n bytes += characterBytes;\n }\n if (!bounded) throw new Error(`${label} must not be empty`);\n return bounded;\n}\n\nexport type SessionBackgroundCommandTerminalMutation = {\n prepare: (tx: SessionActivityDatabase) => Promise<void>;\n commit: (tx: SessionActivityDatabase, command: SessionBackgroundCommand) => Promise<void>;\n};\n\nexport type ConnectedMachineBackgroundCommandClaim = {\n commandId: string;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n claimId: string;\n state: \"running\" | \"stopping\";\n controlWorkspaceId: string;\n enrollmentId: string;\n connectionInstanceId: string;\n opId: string;\n reconcileAttempts: number;\n proof: ConnectedMachineBackgroundCommandProof | null;\n};\n\ntype ConnectedMachineBackgroundCommandClaimRow = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n commandId: string;\n claimId: string;\n commandState: string;\n controlWorkspaceId: string;\n enrollmentId: string;\n connectionInstanceId: string;\n opId: string;\n reconcileAttempts: number | string;\n reconcileProofOutcome: string | null;\n reconcileProofExitCode: number | string | null;\n reconcileProofReason: string | null;\n reconcileProofObservedAt: Date | string | null;\n};\n\nfunction commandPreview(value: string): string {\n const normalized = value.replace(/\\s+/g, \" \").trim();\n return Array.from(normalized).slice(0, 512).join(\"\");\n}\n\nfunction mapCommand(\n row: typeof schema.sessionBackgroundCommands.$inferSelect,\n): SessionBackgroundCommand {\n return {\n id: row.id,\n workspaceId: row.workspaceId,\n sessionId: row.sessionId,\n provider: row.provider,\n state: row.state,\n commandPreview: row.commandPreview,\n cancelRequestedAt: row.cancelRequestedAt?.toISOString() ?? null,\n exitCode: row.exitCode ?? null,\n settlementReason: row.settlementReason ?? null,\n startedAt: row.startedAt.toISOString(),\n settledAt: row.settledAt?.toISOString() ?? null,\n updatedAt: row.updatedAt.toISOString(),\n };\n}\n\nexport async function backgroundCommandActivityForSessions(\n db: Database,\n input: { accountId: string; workspaceId: string; sessionIds: string[] },\n): Promise<Map<string, SessionBackgroundCommandActivity>> {\n if (input.sessionIds.length === 0) return new Map();\n return await withRlsContext(\n db,\n { accountId: input.accountId, workspaceId: input.workspaceId },\n async (scopedDb) => {\n const rows = await scopedDb\n .select({\n sessionId: schema.sessionBackgroundCommands.sessionId,\n count: sql<number>`count(*)::int`,\n stoppingCount: sql<number>`count(*) filter (where ${schema.sessionBackgroundCommands.state} = 'stopping')::int`,\n })\n .from(schema.sessionBackgroundCommands)\n .where(\n and(\n eq(schema.sessionBackgroundCommands.workspaceId, input.workspaceId),\n inArray(schema.sessionBackgroundCommands.sessionId, input.sessionIds),\n inArray(schema.sessionBackgroundCommands.state, [\"running\", \"stopping\"]),\n ),\n )\n .groupBy(schema.sessionBackgroundCommands.sessionId);\n return new Map(\n rows.map((row) => [\n row.sessionId,\n {\n state: Number(row.stoppingCount) > 0 ? (\"stopping\" as const) : (\"running\" as const),\n count: Number(row.count),\n },\n ]),\n );\n },\n );\n}\n\nexport async function listSessionBackgroundCommands(\n db: Database,\n input: { accountId: string; workspaceId: string; sessionId: string },\n): Promise<SessionBackgroundCommand[]> {\n return await withRlsContext(\n db,\n { accountId: input.accountId, workspaceId: input.workspaceId },\n async (scopedDb) => {\n const rows = await scopedDb\n .select()\n .from(schema.sessionBackgroundCommands)\n .where(\n and(\n eq(schema.sessionBackgroundCommands.workspaceId, input.workspaceId),\n eq(schema.sessionBackgroundCommands.sessionId, input.sessionId),\n ),\n )\n .orderBy(\n desc(schema.sessionBackgroundCommands.startedAt),\n desc(schema.sessionBackgroundCommands.id),\n )\n .limit(1000);\n return rows.map(mapCommand);\n },\n );\n}\n\n/** @internal Caller must already hold the canonical session/control fence. */\nexport async function insertManagedSessionBackgroundCommandInTransaction(\n db: Database,\n input: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n commandId: string;\n retainedProcessId: string;\n command: string;\n },\n): Promise<SessionBackgroundCommand> {\n const [process] = await db\n .select({\n accountId: schema.sandboxRetainedProcesses.accountId,\n workspaceId: schema.sandboxRetainedProcesses.workspaceId,\n sessionId: schema.sandboxRetainedProcesses.sessionId,\n state: schema.sandboxRetainedProcesses.state,\n })\n .from(schema.sandboxRetainedProcesses)\n .where(eq(schema.sandboxRetainedProcesses.id, input.retainedProcessId))\n .for(\"update\")\n .limit(1);\n if (\n !process ||\n process.accountId !== input.accountId ||\n process.workspaceId !== input.workspaceId ||\n process.sessionId !== input.sessionId ||\n process.state !== \"active\"\n ) {\n throw new Error(\"Managed background command requires its exact active retained process\");\n }\n const [row] = await db\n .insert(schema.sessionBackgroundCommands)\n .values({\n id: input.commandId,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n provider: \"managed\",\n state: \"running\",\n retainedProcessId: input.retainedProcessId,\n commandPreview: commandPreview(input.command),\n })\n .onConflictDoUpdate({\n target: schema.sessionBackgroundCommands.retainedProcessId,\n targetWhere: sql`${schema.sessionBackgroundCommands.retainedProcessId} is not null`,\n set: { updatedAt: new Date() },\n })\n .returning();\n if (!row) throw new Error(\"Managed background command adoption returned no row\");\n if (\n row.accountId !== input.accountId ||\n row.workspaceId !== input.workspaceId ||\n row.sessionId !== input.sessionId ||\n row.provider !== \"managed\" ||\n row.retainedProcessId !== input.retainedProcessId\n ) {\n throw new Error(\"Managed background command adoption conflicted with another identity\");\n }\n return mapCommand(row);\n}\n\n/** @internal Caller must already hold the canonical exact-attempt fence. */\nexport async function insertConnectedMachineSessionBackgroundCommandInTransaction(\n db: Database,\n input: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n commandId: string;\n controlWorkspaceId: string;\n enrollmentId: string;\n connectionInstanceId: string;\n opId: string;\n command: string;\n },\n): Promise<SessionBackgroundCommand> {\n const [row] = await db\n .insert(schema.sessionBackgroundCommands)\n .values({\n id: input.commandId,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n provider: \"connected_machine\",\n state: \"running\",\n controlWorkspaceId: input.controlWorkspaceId,\n enrollmentId: input.enrollmentId,\n connectionInstanceId: input.connectionInstanceId,\n opId: input.opId,\n commandPreview: commandPreview(input.command),\n })\n .onConflictDoUpdate({\n target: [\n schema.sessionBackgroundCommands.controlWorkspaceId,\n schema.sessionBackgroundCommands.enrollmentId,\n schema.sessionBackgroundCommands.connectionInstanceId,\n schema.sessionBackgroundCommands.opId,\n ],\n targetWhere: sql`${schema.sessionBackgroundCommands.provider} = 'connected_machine'`,\n set: { updatedAt: new Date() },\n })\n .returning();\n if (!row) throw new Error(\"Connected Machine background command adoption returned no row\");\n if (\n row.accountId !== input.accountId ||\n row.workspaceId !== input.workspaceId ||\n row.sessionId !== input.sessionId ||\n row.provider !== \"connected_machine\" ||\n row.controlWorkspaceId !== input.controlWorkspaceId ||\n row.enrollmentId !== input.enrollmentId ||\n row.connectionInstanceId !== input.connectionInstanceId ||\n row.opId !== input.opId\n ) {\n throw new Error(\n \"Connected Machine background command adoption conflicted with another identity\",\n );\n }\n return mapCommand(row);\n}\n\n/** Claim exact Connected Machine locators globally for provider reconciliation.\n * The SECURITY DEFINER SQL function owns the bounded SKIP LOCKED inventory;\n * claim expiry is coordination recovery only and never implies command loss. */\nexport async function claimConnectedMachineSessionBackgroundCommands(\n db: Database,\n input: { claimId: string; limit: number; claimTtlMs: number },\n): Promise<ConnectedMachineBackgroundCommandClaim[]> {\n if (!Number.isSafeInteger(input.limit) || input.limit < 1 || input.limit > 100) {\n throw new Error(\"Connected command reconciliation limit must be between 1 and 100\");\n }\n if (\n !Number.isSafeInteger(input.claimTtlMs) ||\n input.claimTtlMs < 0 ||\n input.claimTtlMs > 3_600_000\n ) {\n throw new Error(\"Connected command reconciliation claim TTL is invalid\");\n }\n const rows = await db.execute<ConnectedMachineBackgroundCommandClaimRow>(sql`\n select account_id as \"accountId\",\n workspace_id as \"workspaceId\",\n session_id as \"sessionId\",\n command_id as \"commandId\",\n claim_id as \"claimId\",\n command_state as \"commandState\",\n control_workspace_id as \"controlWorkspaceId\",\n enrollment_id as \"enrollmentId\",\n connection_instance_id as \"connectionInstanceId\",\n op_id as \"opId\",\n reconcile_attempts as \"reconcileAttempts\",\n reconcile_proof_outcome as \"reconcileProofOutcome\",\n reconcile_proof_exit_code as \"reconcileProofExitCode\",\n reconcile_proof_reason as \"reconcileProofReason\",\n reconcile_proof_observed_at as \"reconcileProofObservedAt\"\n from opengeni_private.claim_connected_machine_background_commands(\n ${input.claimId}::uuid, ${input.limit}::integer, ${input.claimTtlMs}::bigint\n )\n `);\n return rows.map((row: ConnectedMachineBackgroundCommandClaimRow) => {\n if (row.commandState !== \"running\" && row.commandState !== \"stopping\") {\n throw new Error(`Connected command claim returned invalid state ${row.commandState}`);\n }\n const proof =\n row.reconcileProofOutcome === null\n ? null\n : row.reconcileProofOutcome === \"exited\" || row.reconcileProofOutcome === \"lost\"\n ? {\n outcome: row.reconcileProofOutcome,\n exitCode:\n row.reconcileProofExitCode === null ? null : Number(row.reconcileProofExitCode),\n reason: row.reconcileProofReason!,\n observedAt:\n row.reconcileProofObservedAt instanceof Date\n ? row.reconcileProofObservedAt\n : new Date(row.reconcileProofObservedAt!),\n }\n : (() => {\n throw new Error(\n `Connected command claim returned invalid proof ${row.reconcileProofOutcome}`,\n );\n })();\n return {\n commandId: row.commandId,\n accountId: row.accountId,\n workspaceId: row.workspaceId,\n sessionId: row.sessionId,\n claimId: row.claimId,\n state: row.commandState,\n controlWorkspaceId: row.controlWorkspaceId,\n enrollmentId: row.enrollmentId,\n connectionInstanceId: row.connectionInstanceId,\n opId: row.opId,\n reconcileAttempts: Number(row.reconcileAttempts),\n proof,\n };\n });\n}\n\nfunction connectedClaimIdentityWhere(claim: ConnectedMachineBackgroundCommandClaim) {\n return and(\n eq(schema.sessionBackgroundCommands.id, claim.commandId),\n eq(schema.sessionBackgroundCommands.accountId, claim.accountId),\n eq(schema.sessionBackgroundCommands.workspaceId, claim.workspaceId),\n eq(schema.sessionBackgroundCommands.sessionId, claim.sessionId),\n eq(schema.sessionBackgroundCommands.provider, \"connected_machine\"),\n eq(schema.sessionBackgroundCommands.controlWorkspaceId, claim.controlWorkspaceId),\n eq(schema.sessionBackgroundCommands.enrollmentId, claim.enrollmentId),\n eq(schema.sessionBackgroundCommands.connectionInstanceId, claim.connectionInstanceId),\n eq(schema.sessionBackgroundCommands.opId, claim.opId),\n eq(schema.sessionBackgroundCommands.reconcileClaimId, claim.claimId),\n inArray(schema.sessionBackgroundCommands.state, [\"running\", \"stopping\"]),\n );\n}\n\n/** Checkpoint one exact terminal provider observation before lifecycle settlement.\n * A retry may reuse an identical proof; a divergent proof is a hard identity fault. */\nexport async function recordConnectedMachineBackgroundCommandProof(\n db: Database,\n input: {\n claim: ConnectedMachineBackgroundCommandClaim;\n proof: ConnectedMachineBackgroundCommandProof;\n },\n): Promise<void> {\n const reason = boundedSessionBackgroundCommandReason(\n input.proof.reason,\n \"Connected command proof reason\",\n );\n if (input.proof.outcome === \"exited\" && input.proof.exitCode === null) {\n throw new Error(\"Connected command exit proof requires an exit code\");\n }\n if (input.proof.outcome === \"lost\" && input.proof.exitCode !== null) {\n throw new Error(\"Connected command loss proof cannot carry an exit code\");\n }\n await withRlsContext(\n db,\n { accountId: input.claim.accountId, workspaceId: input.claim.workspaceId },\n async (scopedDb) => {\n const [current] = await scopedDb\n .select()\n .from(schema.sessionBackgroundCommands)\n .where(connectedClaimIdentityWhere(input.claim))\n .for(\"update\")\n .limit(1);\n if (!current) throw new Error(\"Connected command proof was fenced by newer lifecycle state\");\n if (current.reconcileProofOutcome !== null) {\n const observedAt = current.reconcileProofObservedAt?.getTime() ?? null;\n if (\n current.reconcileProofOutcome !== input.proof.outcome ||\n current.reconcileProofExitCode !== input.proof.exitCode ||\n current.reconcileProofReason !== reason ||\n observedAt !== input.proof.observedAt.getTime()\n ) {\n throw new Error(\"Connected command reconciliation proof conflicts with durable proof\");\n }\n return;\n }\n const rows = await scopedDb\n .update(schema.sessionBackgroundCommands)\n .set({\n reconcileProofOutcome: input.proof.outcome,\n reconcileProofExitCode: input.proof.exitCode,\n reconcileProofReason: reason,\n reconcileProofObservedAt: input.proof.observedAt,\n lastReconcileOutcome: `proof_${input.proof.outcome}`,\n updatedAt: new Date(),\n })\n .where(connectedClaimIdentityWhere(input.claim))\n .returning({ id: schema.sessionBackgroundCommands.id });\n if (rows.length !== 1) {\n throw new Error(\"Connected command proof lost its exact claim during checkpoint\");\n }\n },\n );\n}\n\nexport async function deferConnectedMachineBackgroundCommandReconciliation(\n db: Database,\n input: {\n claim: ConnectedMachineBackgroundCommandClaim;\n outcome: string;\n retryAfterMs: number;\n },\n): Promise<boolean> {\n if (!Number.isSafeInteger(input.retryAfterMs) || input.retryAfterMs < 0) {\n throw new Error(\"Connected command reconciliation retry delay is invalid\");\n }\n const outcome = input.outcome.trim().slice(0, 64);\n if (!outcome) throw new Error(\"Connected command reconciliation outcome must not be empty\");\n return await withRlsContext(\n db,\n { accountId: input.claim.accountId, workspaceId: input.claim.workspaceId },\n async (scopedDb) => {\n const rows = await scopedDb\n .update(schema.sessionBackgroundCommands)\n .set({\n reconcileAfter: new Date(Date.now() + input.retryAfterMs),\n reconcileClaimId: null,\n reconcileClaimedAt: null,\n lastReconcileOutcome: outcome,\n updatedAt: new Date(),\n })\n .where(connectedClaimIdentityWhere(input.claim))\n .returning({ id: schema.sessionBackgroundCommands.id });\n return rows.length === 1;\n },\n );\n}\n\n/** Settle only from the proof already checkpointed under this exact claim. */\nexport async function settleClaimedConnectedMachineBackgroundCommandWithMutation(\n db: Database,\n input: { claim: ConnectedMachineBackgroundCommandClaim },\n mutateTerminal: SessionBackgroundCommandTerminalMutation,\n): Promise<boolean> {\n return await withSessionActivityRlsContext(\n db,\n { accountId: input.claim.accountId, workspaceId: input.claim.workspaceId },\n async (tx) => {\n await mutateTerminal.prepare(tx);\n const rows = await tx.execute<{ id: string }>(sql`\n update ${schema.sessionBackgroundCommands} command set\n state = command.reconcile_proof_outcome,\n exit_code = case\n when command.reconcile_proof_outcome = 'exited'\n then command.reconcile_proof_exit_code\n else null\n end,\n settlement_reason = command.reconcile_proof_reason,\n settled_at = command.reconcile_proof_observed_at,\n reconcile_claim_id = null,\n reconcile_claimed_at = null,\n last_reconcile_outcome = 'settled_' || command.reconcile_proof_outcome,\n updated_at = clock_timestamp()\n where command.id = ${input.claim.commandId}\n and command.account_id = ${input.claim.accountId}\n and command.workspace_id = ${input.claim.workspaceId}\n and command.session_id = ${input.claim.sessionId}\n and command.provider = 'connected_machine'\n and command.control_workspace_id = ${input.claim.controlWorkspaceId}\n and command.enrollment_id = ${input.claim.enrollmentId}\n and command.connection_instance_id = ${input.claim.connectionInstanceId}\n and command.op_id = ${input.claim.opId}\n and command.reconcile_claim_id = ${input.claim.claimId}\n and command.state in ('running', 'stopping')\n and command.reconcile_proof_outcome in ('exited', 'lost')\n and command.reconcile_proof_observed_at is not null\n returning command.id\n `);\n if (rows.length !== 1) return false;\n const [row] = await tx\n .select()\n .from(schema.sessionBackgroundCommands)\n .where(eq(schema.sessionBackgroundCommands.id, input.claim.commandId))\n .limit(1);\n if (!row) throw new Error(\"Settled Connected Machine command disappeared\");\n await mutateTerminal.commit(tx, mapCommand(row));\n return true;\n },\n );\n}\n\nexport async function requestSessionBackgroundCommandCancellation(\n db: Database,\n input: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n commandId: string;\n subjectId: string;\n },\n): Promise<{ command: SessionBackgroundCommand | null; accepted: boolean }> {\n return await withRlsContext(\n db,\n { accountId: input.accountId, workspaceId: input.workspaceId },\n async (scopedDb) =>\n await scopedDb.transaction(async (tx) => {\n const [current] = await tx\n .select()\n .from(schema.sessionBackgroundCommands)\n .where(\n and(\n eq(schema.sessionBackgroundCommands.workspaceId, input.workspaceId),\n eq(schema.sessionBackgroundCommands.sessionId, input.sessionId),\n eq(schema.sessionBackgroundCommands.id, input.commandId),\n ),\n )\n .for(\"update\")\n .limit(1);\n if (!current) return { command: null, accepted: false };\n if (current.state !== \"running\") {\n return { command: mapCommand(current), accepted: false };\n }\n const [updated] = await tx\n .update(schema.sessionBackgroundCommands)\n .set({\n state: \"stopping\",\n cancelRequestedAt: new Date(),\n cancelRequestedBy: input.subjectId.slice(0, 1024),\n reconcileAfter: new Date(),\n reconcileClaimId: null,\n reconcileClaimedAt: null,\n updatedAt: new Date(),\n })\n .where(eq(schema.sessionBackgroundCommands.id, current.id))\n .returning();\n if (current.retainedProcessId) {\n await tx\n .update(schema.sandboxRetainedProcesses)\n .set({ reconcileAfter: new Date(), lastReconcileOutcome: \"cancel_requested\" })\n .where(\n and(\n eq(schema.sandboxRetainedProcesses.id, current.retainedProcessId),\n eq(schema.sandboxRetainedProcesses.state, \"active\"),\n sql`${schema.sandboxRetainedProcesses.reconcileClaimId} is null`,\n ),\n );\n }\n return { command: mapCommand(updated!), accepted: true };\n }),\n );\n}\n\n/**\n * Transfer every active command in one or more session subtrees to the\n * provider-neutral stopping state inside the caller's existing control\n * transaction. The workspace-control mutation already excludes concurrent\n * session-tree changes, so the recursive walk and state transition are one\n * atomic Pause/Cancel effect. Steer deliberately never calls this seam.\n */\nexport async function requestSessionBackgroundCommandCancellationsInTransaction(\n db: Database,\n input: {\n workspaceId: string;\n rootSessionIds: string[];\n subjectId: string;\n },\n): Promise<number> {\n const rootSessionIds = [...new Set(input.rootSessionIds)];\n if (rootSessionIds.length === 0) return 0;\n const rows = await db.execute<{ commandCount: number | string }>(sql`\n with recursive roots(id) as (\n values ${sql.join(\n rootSessionIds.map((sessionId) => sql`(${sessionId}::uuid)`),\n sql`, `,\n )}\n ), subtree(id, path, cycle) as (\n select session.id, array[session.id]::uuid[], false\n from roots root\n join ${schema.sessions} session\n on session.workspace_id = ${input.workspaceId}\n and session.id = root.id\n union all\n select child.id, parent.path || child.id, child.id = any(parent.path)\n from subtree parent\n join ${schema.sessions} child\n on child.workspace_id = ${input.workspaceId}\n and child.parent_session_id = parent.id\n where not parent.cycle\n ), stopped as (\n update ${schema.sessionBackgroundCommands} command set\n state = 'stopping',\n cancel_requested_at = clock_timestamp(),\n cancel_requested_by = left(${input.subjectId}, 1024),\n reconcile_after = clock_timestamp(),\n reconcile_claim_id = null,\n reconcile_claimed_at = null,\n updated_at = clock_timestamp()\n where command.workspace_id = ${input.workspaceId}\n and command.session_id in (select id from subtree where not cycle)\n and command.state = 'running'\n returning command.retained_process_id\n ), nudged as (\n update ${schema.sandboxRetainedProcesses} process set\n reconcile_after = clock_timestamp(),\n reconcile_claim_id = null,\n reconcile_claimed_at = null,\n last_reconcile_outcome = 'cancel_requested'\n where process.id in (\n select stopped.retained_process_id\n from stopped\n where stopped.retained_process_id is not null\n )\n and process.state = 'active'\n returning process.id\n )\n select count(*)::integer as \"commandCount\" from stopped\n `);\n return Number(rows[0]?.commandCount ?? 0);\n}\n\n/** Workspace Pause owns every active command in that workspace. */\nexport async function requestWorkspaceBackgroundCommandCancellationsInTransaction(\n db: Database,\n input: { workspaceId: string; subjectId: string },\n): Promise<number> {\n const rows = await db.execute<{ commandCount: number | string }>(sql`\n with stopped as (\n update ${schema.sessionBackgroundCommands} command set\n state = 'stopping',\n cancel_requested_at = clock_timestamp(),\n cancel_requested_by = left(${input.subjectId}, 1024),\n reconcile_after = clock_timestamp(),\n reconcile_claim_id = null,\n reconcile_claimed_at = null,\n updated_at = clock_timestamp()\n where command.workspace_id = ${input.workspaceId}\n and command.state = 'running'\n returning command.retained_process_id\n ), nudged as (\n update ${schema.sandboxRetainedProcesses} process set\n reconcile_after = clock_timestamp(),\n reconcile_claim_id = null,\n reconcile_claimed_at = null,\n last_reconcile_outcome = 'cancel_requested'\n where process.id in (\n select stopped.retained_process_id\n from stopped\n where stopped.retained_process_id is not null\n )\n and process.state = 'active'\n returning process.id\n )\n select count(*)::integer as \"commandCount\" from stopped\n `);\n return Number(rows[0]?.commandCount ?? 0);\n}\n\nexport async function settleSessionBackgroundCommandForRetainedProcessInTransaction(\n tx: SessionActivityDatabase,\n input: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n retainedProcessId: string;\n outcome: \"exited\" | \"lost\";\n exitCode: number | null;\n reason: string;\n },\n mutateTerminal: SessionBackgroundCommandTerminalMutation,\n): Promise<SessionBackgroundCommand | null> {\n const reason = boundedSessionBackgroundCommandReason(\n input.reason,\n \"Managed command settlement reason\",\n );\n await mutateTerminal.prepare(tx);\n const [updatedRow] = await tx\n .update(schema.sessionBackgroundCommands)\n .set({\n state: input.outcome,\n exitCode: input.outcome === \"exited\" ? input.exitCode : null,\n settlementReason: reason,\n settledAt: new Date(),\n reconcileClaimId: null,\n reconcileClaimedAt: null,\n lastReconcileOutcome: `settled_${input.outcome}`,\n updatedAt: new Date(),\n })\n .where(\n and(\n eq(schema.sessionBackgroundCommands.workspaceId, input.workspaceId),\n eq(schema.sessionBackgroundCommands.sessionId, input.sessionId),\n eq(schema.sessionBackgroundCommands.retainedProcessId, input.retainedProcessId),\n inArray(schema.sessionBackgroundCommands.state, [\"running\", \"stopping\"]),\n ),\n )\n .returning();\n let row = updatedRow;\n if (!row) {\n const [current] = await tx\n .select()\n .from(schema.sessionBackgroundCommands)\n .where(\n and(\n eq(schema.sessionBackgroundCommands.workspaceId, input.workspaceId),\n eq(schema.sessionBackgroundCommands.sessionId, input.sessionId),\n eq(schema.sessionBackgroundCommands.retainedProcessId, input.retainedProcessId),\n ),\n )\n .for(\"update\")\n .limit(1);\n if (!current) return null;\n if (\n current.state !== input.outcome ||\n current.exitCode !== (input.outcome === \"exited\" ? input.exitCode : null)\n ) {\n throw new Error(\"Managed background command terminal state conflicts with process proof\");\n }\n const [existingEvent] = await tx\n .select({ id: schema.sessionEvents.id })\n .from(schema.sessionEvents)\n .where(\n and(\n eq(schema.sessionEvents.workspaceId, input.workspaceId),\n eq(schema.sessionEvents.sessionId, input.sessionId),\n eq(schema.sessionEvents.type, \"session.command.finished\"),\n sql`${schema.sessionEvents.payload} ->> 'commandId' = ${current.id}`,\n ),\n )\n .limit(1);\n if (existingEvent) return mapCommand(current);\n row = current;\n }\n const command = mapCommand(row);\n await mutateTerminal.commit(tx, command);\n return command;\n}\n\nexport async function settleConnectedMachineSessionBackgroundCommandWithMutation(\n db: Database,\n input: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n commandId: string;\n controlWorkspaceId: string;\n enrollmentId: string;\n connectionInstanceId: string;\n opId: string;\n outcome: \"exited\" | \"lost\";\n exitCode: number | null;\n reason: string;\n },\n mutateTerminal: SessionBackgroundCommandTerminalMutation,\n): Promise<SessionBackgroundCommand | null> {\n const reason = boundedSessionBackgroundCommandReason(\n input.reason,\n \"Connected command settlement reason\",\n );\n if (input.outcome === \"exited\" && input.exitCode === null) {\n throw new Error(\"Connected command exit settlement requires an exit code\");\n }\n if (input.outcome === \"lost\" && input.exitCode !== null) {\n throw new Error(\"Connected command loss settlement cannot carry an exit code\");\n }\n return await withSessionActivityRlsContext(\n db,\n { accountId: input.accountId, workspaceId: input.workspaceId },\n async (tx) => {\n await mutateTerminal.prepare(tx);\n const settledAt = new Date();\n const [row] = await tx\n .update(schema.sessionBackgroundCommands)\n .set({\n state: input.outcome,\n exitCode: input.outcome === \"exited\" ? input.exitCode : null,\n settlementReason: reason,\n settledAt,\n reconcileClaimId: null,\n reconcileClaimedAt: null,\n reconcileProofOutcome: input.outcome,\n reconcileProofExitCode: input.outcome === \"exited\" ? input.exitCode : null,\n reconcileProofReason: reason,\n reconcileProofObservedAt: settledAt,\n lastReconcileOutcome: `settled_${input.outcome}`,\n updatedAt: new Date(),\n })\n .where(\n and(\n eq(schema.sessionBackgroundCommands.workspaceId, input.workspaceId),\n eq(schema.sessionBackgroundCommands.sessionId, input.sessionId),\n eq(schema.sessionBackgroundCommands.id, input.commandId),\n eq(schema.sessionBackgroundCommands.provider, \"connected_machine\"),\n eq(schema.sessionBackgroundCommands.controlWorkspaceId, input.controlWorkspaceId),\n eq(schema.sessionBackgroundCommands.enrollmentId, input.enrollmentId),\n eq(schema.sessionBackgroundCommands.connectionInstanceId, input.connectionInstanceId),\n eq(schema.sessionBackgroundCommands.opId, input.opId),\n inArray(schema.sessionBackgroundCommands.state, [\"running\", \"stopping\"]),\n ),\n )\n .returning();\n if (!row) return null;\n const command = mapCommand(row);\n await mutateTerminal.commit(tx, command);\n return command;\n },\n );\n}\n\nexport async function getSessionBackgroundCommand(\n db: Database,\n input: { accountId: string; workspaceId: string; sessionId: string; commandId: string },\n): Promise<SessionBackgroundCommand | null> {\n return await withRlsContext(\n db,\n { accountId: input.accountId, workspaceId: input.workspaceId },\n async (scopedDb) => {\n const [row] = await scopedDb\n .select()\n .from(schema.sessionBackgroundCommands)\n .where(\n and(\n eq(schema.sessionBackgroundCommands.workspaceId, input.workspaceId),\n eq(schema.sessionBackgroundCommands.sessionId, input.sessionId),\n eq(schema.sessionBackgroundCommands.id, input.commandId),\n ),\n )\n .limit(1);\n return row ? mapCommand(row) : null;\n },\n );\n}\n"],"mappings":";;;;;;;;;;;;AAIA,SAAS,KAAK,MAAM,IAAI,SAAS,WAAW;AAarC,IAAM,8CAA8C;AAEpD,SAAS,sCAAsC,OAAe,OAAuB;AAC1F,QAAM,aAAa,MAAM,KAAK;AAC9B,MAAI,UAAU;AACd,MAAI,QAAQ;AACZ,aAAW,aAAa,YAAY;AAClC,UAAM,iBAAiB,OAAO,WAAW,WAAW,MAAM;AAC1D,QAAI,QAAQ,iBAAiB,4CAA6C;AAC1E,eAAW;AACX,aAAS;AAAA,EACX;AACA,MAAI,CAAC,QAAS,OAAM,IAAI,MAAM,GAAG,KAAK,oBAAoB;AAC1D,SAAO;AACT;AAwCA,SAAS,eAAe,OAAuB;AAC7C,QAAM,aAAa,MAAM,QAAQ,QAAQ,GAAG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AA0B,WAAW,MAAM,SAAS;AAAA,UAC9D,GAAU,0BAA0B,IAAI,MAAM,SAAS;AAAA,QACzD;AAAA,MACF,EACC,MAAM,CAAC;AACV,aAAO,MAAM,WAAW,GAAG,IAAI;AAAA,IACjC;AAAA,EACF;AACF;","names":[]}
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  nestedPostgresSqlState,
3
3
  rawRows
4
- } from "./chunk-F6PBS6WE.js";
4
+ } from "./chunk-UFAMOUWL.js";
5
5
 
6
6
  // src/canonical-human-identities.ts
7
7
  import { createHash } from "crypto";
@@ -309,4 +309,4 @@ export {
309
309
  getCanonicalHumanIdentityProjection,
310
310
  applyCanonicalHumanIdentityOperation
311
311
  };
312
- //# sourceMappingURL=chunk-U4WPPEBH.js.map
312
+ //# sourceMappingURL=chunk-NLFHMPUB.js.map
@@ -5,7 +5,7 @@ import {
5
5
  withWorkspaceRls,
6
6
  withWorkspaceSubjectRls,
7
7
  withWorkspaceSubjectSessionActivityRls
8
- } from "./chunk-F6PBS6WE.js";
8
+ } from "./chunk-UFAMOUWL.js";
9
9
 
10
10
  // src/session-tenancy.ts
11
11
  import { createHash } from "crypto";
@@ -481,4 +481,4 @@ export {
481
481
  forkSessionContent,
482
482
  replayAppliedSessionFork
483
483
  };
484
- //# sourceMappingURL=chunk-5NNCGFQY.js.map
484
+ //# sourceMappingURL=chunk-P6NSEG2S.js.map