@opengeni/worker-bundle 0.20.3 → 0.22.1-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 (184) hide show
  1. package/dist/activities/agent-turn/admission.d.ts +52 -0
  2. package/dist/activities/agent-turn/agent-build.d.ts +89 -0
  3. package/dist/activities/agent-turn/claim.d.ts +67 -0
  4. package/dist/activities/agent-turn/codex-capacity.d.ts +40 -0
  5. package/dist/activities/agent-turn/codex.d.ts +32 -0
  6. package/dist/activities/agent-turn/compaction-prep.d.ts +88 -0
  7. package/dist/activities/agent-turn/credential-leases.d.ts +56 -0
  8. package/dist/activities/agent-turn/errors.d.ts +253 -0
  9. package/dist/activities/agent-turn/failure-settlement.d.ts +33 -0
  10. package/dist/activities/agent-turn/file-resources.d.ts +37 -0
  11. package/dist/activities/agent-turn/finalization.d.ts +42 -0
  12. package/dist/activities/agent-turn/github-repository-bindings.d.ts +105 -0
  13. package/dist/activities/agent-turn/governance-model.d.ts +66 -0
  14. package/dist/activities/agent-turn/history-sink.d.ts +52 -0
  15. package/dist/activities/agent-turn/history.d.ts +63 -0
  16. package/dist/activities/agent-turn/media-artifacts.d.ts +145 -0
  17. package/dist/activities/agent-turn/model-usage.d.ts +218 -0
  18. package/dist/activities/agent-turn/quiescence.d.ts +135 -0
  19. package/dist/activities/agent-turn/run-credentials.d.ts +84 -0
  20. package/dist/activities/agent-turn/run.d.ts +3 -0
  21. package/dist/activities/agent-turn/sandbox-establish.d.ts +93 -0
  22. package/dist/activities/agent-turn/sandbox-provision.d.ts +89 -0
  23. package/dist/activities/agent-turn/sandbox-route.d.ts +151 -0
  24. package/dist/activities/agent-turn/sandbox-runtime.d.ts +44 -0
  25. package/dist/activities/agent-turn/stream-attempt.d.ts +107 -0
  26. package/dist/activities/agent-turn/tool-environment.d.ts +142 -0
  27. package/dist/activities/agent-turn/tool-policy.d.ts +127 -0
  28. package/dist/activities/agent-turn/tool-result-spill.d.ts +59 -0
  29. package/dist/activities/agent-turn/turn-context.d.ts +144 -0
  30. package/dist/activities/agent-turn/xai-capacity.d.ts +2 -0
  31. package/dist/activities/agent-turn.d.ts +12 -954
  32. package/dist/activities/automations.d.ts +16 -0
  33. package/dist/activities/common.d.ts +1 -1
  34. package/dist/activities/connector-attachments.d.ts +13 -0
  35. package/dist/activities/documents.d.ts +1 -0
  36. package/dist/activities/environment.d.ts +26 -15
  37. package/dist/activities/generated-images.d.ts +1 -1
  38. package/dist/activities/git-credential-renewal.d.ts +3 -1
  39. package/dist/activities/goals.d.ts +4 -1
  40. package/dist/activities/google-drive-provider.d.ts +29 -0
  41. package/dist/activities/google-drive-publication.d.ts +17 -4
  42. package/dist/activities/incident-telemetry-authority.d.ts +52 -0
  43. package/dist/activities/incident-telemetry-preflight.d.ts +71 -0
  44. package/dist/activities/knowledge-source-sync.d.ts +4 -0
  45. package/dist/activities/mcp-credentials.d.ts +9 -3
  46. package/dist/activities/open-suffix-resume.d.ts +77 -0
  47. package/dist/activities/packs.d.ts +3 -11
  48. package/dist/activities/parent-wake.d.ts +19 -0
  49. package/dist/activities/retained-screenshot-reaper.d.ts +1 -1
  50. package/dist/activities/retained-screenshots.d.ts +1 -1
  51. package/dist/activities/rig-verification.d.ts +1 -1
  52. package/dist/activities/run-input.d.ts +9 -10
  53. package/dist/activities/sandbox-images.d.ts +1 -14
  54. package/dist/activities/sandbox-lease.d.ts +21 -3
  55. package/dist/activities/scheduled-tasks.d.ts +47 -0
  56. package/dist/activities/types.d.ts +23 -2
  57. package/dist/activities/video-media-validation.d.ts +1 -1
  58. package/dist/activities/video-output-retention.d.ts +1 -2
  59. package/dist/activities/xai-auth.d.ts +3 -0
  60. package/dist/{activities-control-BJSDRSIP.js → activities-control-DKG22ONJ.js} +2646 -551
  61. package/dist/activities-control-DKG22ONJ.js.map +1 -0
  62. package/dist/activities-control.d.ts +6 -2
  63. package/dist/activities-turn-4IMC3MAA.js +21326 -0
  64. package/dist/activities-turn-4IMC3MAA.js.map +1 -0
  65. package/dist/activities.d.ts +7 -3
  66. package/dist/artifact-materializer-entry.js +41 -22
  67. package/dist/artifact-materializer-entry.js.map +1 -1
  68. package/dist/{chunk-N5TJIFCE.js → chunk-CE7TPKBS.js} +468 -1
  69. package/dist/chunk-CE7TPKBS.js.map +1 -0
  70. package/dist/chunk-CNYGVRKF.js +4698 -0
  71. package/dist/chunk-CNYGVRKF.js.map +1 -0
  72. package/dist/connection-provider-use.d.ts +18 -0
  73. package/dist/editable-artifact-materializer.d.ts +4 -3
  74. package/dist/github-rest-mcp.d.ts +26 -0
  75. package/dist/index.d.ts +10 -2
  76. package/dist/index.js +58 -14
  77. package/dist/index.js.map +1 -1
  78. package/dist/knowledge-source-sync-activity-policy.d.ts +2 -0
  79. package/dist/model-context-contributions.d.ts +8 -4
  80. package/dist/observability-metrics.d.ts +63 -4
  81. package/dist/opensandbox-kubernetes-inventory.d.ts +21 -0
  82. package/dist/personal-github-git-credentials.d.ts +9 -0
  83. package/dist/pr-review-credentials.d.ts +6 -0
  84. package/dist/sandbox-archive-storage.d.ts +45 -0
  85. package/dist/sandbox-resume.d.ts +65 -6
  86. package/dist/sandbox-routing.d.ts +38 -2
  87. package/dist/scheduled-alert-occurrence.d.ts +33 -0
  88. package/dist/workflow-bundle.js +87 -28
  89. package/dist/workflows/activities.d.ts +1 -0
  90. package/dist/workflows/automations.d.ts +6 -0
  91. package/dist/workflows/document-index.d.ts +1 -0
  92. package/dist/workflows.d.ts +1 -0
  93. package/package.json +17 -17
  94. package/src/activities/agent-turn/admission.ts +292 -0
  95. package/src/activities/agent-turn/agent-build.ts +802 -0
  96. package/src/activities/agent-turn/claim.ts +590 -0
  97. package/src/activities/agent-turn/codex-capacity.ts +720 -0
  98. package/src/activities/agent-turn/codex.ts +94 -0
  99. package/src/activities/agent-turn/compaction-prep.ts +722 -0
  100. package/src/activities/agent-turn/credential-leases.ts +240 -0
  101. package/src/activities/agent-turn/errors.ts +1068 -0
  102. package/src/activities/agent-turn/failure-settlement.ts +1436 -0
  103. package/src/activities/agent-turn/file-resources.ts +227 -0
  104. package/src/activities/agent-turn/finalization.ts +754 -0
  105. package/src/activities/agent-turn/github-repository-bindings.ts +300 -0
  106. package/src/activities/agent-turn/governance-model.ts +465 -0
  107. package/src/activities/agent-turn/history-sink.ts +139 -0
  108. package/src/activities/agent-turn/history.ts +200 -0
  109. package/src/activities/agent-turn/media-artifacts.ts +359 -0
  110. package/src/activities/agent-turn/model-usage.ts +823 -0
  111. package/src/activities/agent-turn/quiescence.ts +353 -0
  112. package/src/activities/agent-turn/run-credentials.ts +761 -0
  113. package/src/activities/agent-turn/run.ts +1530 -0
  114. package/src/activities/agent-turn/sandbox-establish.ts +1207 -0
  115. package/src/activities/agent-turn/sandbox-provision.ts +569 -0
  116. package/src/activities/agent-turn/sandbox-route.ts +358 -0
  117. package/src/activities/agent-turn/sandbox-runtime.ts +731 -0
  118. package/src/activities/agent-turn/stream-attempt.ts +1670 -0
  119. package/src/activities/agent-turn/tool-environment.ts +729 -0
  120. package/src/activities/agent-turn/tool-policy.ts +216 -0
  121. package/src/activities/agent-turn/tool-result-spill.ts +265 -0
  122. package/src/activities/agent-turn/turn-context.ts +281 -0
  123. package/src/activities/agent-turn/xai-capacity.ts +229 -0
  124. package/src/activities/agent-turn.ts +12 -12701
  125. package/src/activities/api-integrations.ts +3 -0
  126. package/src/activities/automations.ts +214 -0
  127. package/src/activities/codemode-dispatcher.ts +12 -1
  128. package/src/activities/common.ts +1 -5
  129. package/src/activities/connector-attachments.ts +168 -0
  130. package/src/activities/context-compaction.ts +18 -0
  131. package/src/activities/environment.ts +151 -55
  132. package/src/activities/generated-images.ts +26 -11
  133. package/src/activities/git-credential-renewal.ts +13 -3
  134. package/src/activities/goals.ts +85 -19
  135. package/src/activities/google-drive-provider.ts +178 -0
  136. package/src/activities/google-drive-publication.ts +147 -49
  137. package/src/activities/incident-telemetry-authority.ts +327 -0
  138. package/src/activities/incident-telemetry-preflight.ts +317 -0
  139. package/src/activities/knowledge-source-sync.ts +178 -37
  140. package/src/activities/mcp-credentials.ts +191 -17
  141. package/src/activities/open-suffix-resume.ts +422 -0
  142. package/src/activities/packs.ts +12 -60
  143. package/src/activities/parent-wake.ts +64 -14
  144. package/src/activities/retained-screenshot-reaper.ts +6 -3
  145. package/src/activities/retained-screenshots.ts +15 -47
  146. package/src/activities/rig-verification.ts +1 -1
  147. package/src/activities/run-input.ts +102 -142
  148. package/src/activities/sandbox-images.ts +7 -166
  149. package/src/activities/sandbox-lease.ts +406 -15
  150. package/src/activities/scheduled-tasks.ts +2103 -411
  151. package/src/activities/session-state.ts +10 -2
  152. package/src/activities/types.ts +32 -2
  153. package/src/activities/video-media-validation.ts +3 -3
  154. package/src/activities/video-output-retention.ts +2 -57
  155. package/src/activities/xai-auth.ts +8 -0
  156. package/src/activities-control.ts +2 -0
  157. package/src/activities.ts +3 -0
  158. package/src/activity-services.ts +13 -4
  159. package/src/connection-provider-use.ts +36 -0
  160. package/src/editable-artifact-materializer-subprocess.ts +25 -14
  161. package/src/editable-artifact-materializer.ts +29 -18
  162. package/src/github-rest-mcp.ts +713 -0
  163. package/src/http.ts +16 -6
  164. package/src/index.ts +40 -5
  165. package/src/knowledge-source-sync-activity-policy.ts +2 -0
  166. package/src/model-context-contributions.ts +33 -10
  167. package/src/observability-metrics.ts +357 -0
  168. package/src/opensandbox-kubernetes-inventory.ts +292 -0
  169. package/src/personal-github-git-credentials.ts +331 -0
  170. package/src/pr-review-credentials.ts +163 -0
  171. package/src/sandbox-archive-storage.ts +159 -0
  172. package/src/sandbox-resume.ts +449 -63
  173. package/src/sandbox-routing.ts +314 -16
  174. package/src/scheduled-alert-occurrence.ts +176 -0
  175. package/src/workflows/activities.ts +18 -2
  176. package/src/workflows/automations.ts +11 -0
  177. package/src/workflows/session.ts +13 -3
  178. package/src/workflows.ts +1 -0
  179. package/dist/activities-control-BJSDRSIP.js.map +0 -1
  180. package/dist/activities-turn-J5YO7XXX.js +0 -17243
  181. package/dist/activities-turn-J5YO7XXX.js.map +0 -1
  182. package/dist/chunk-N5TJIFCE.js.map +0 -1
  183. package/dist/chunk-P6Z2SLAA.js +0 -3092
  184. package/dist/chunk-P6Z2SLAA.js.map +0 -1
@@ -16,6 +16,7 @@
16
16
 
17
17
  import { sandboxLifecycleTransitionWaitMs, type Settings } from "@opengeni/config";
18
18
  import {
19
+ adoptConnectedMachineSessionBackgroundCommand,
19
20
  advanceWorkspaceGenerationForRetainedProcess,
20
21
  advanceWorkspaceGeneration,
21
22
  getRetainedProcess,
@@ -25,17 +26,24 @@ import {
25
26
  verifyRetainedProcessMutationSettlement,
26
27
  verifyWorkspaceMutationSettlement,
27
28
  getSandbox,
28
- getEnrollment,
29
+ getLiveEnrollmentConnection,
29
30
  markWarmLeaseInstanceLost,
30
31
  readLease,
31
32
  readActiveSandbox,
33
+ resolvePersonalMachineConnectionForAttempt,
32
34
  SandboxRetainedProcessPromotionFencedError,
33
35
  type Database,
36
+ type EnrollmentRecord,
34
37
  type SandboxWorkspaceMutationAdmission,
35
38
  } from "@opengeni/db";
39
+ import {
40
+ settleConnectedMachineSessionBackgroundCommand,
41
+ settleSessionBackgroundCommandForRetainedProcess,
42
+ } from "@opengeni/db/session-background-commands";
36
43
  import type { EventBus } from "@opengeni/events";
37
44
  import {
38
45
  buildSelfhostedBackendSession,
46
+ ActiveBackendUnresolvableError,
39
47
  establishSandboxSessionFromEnvelope,
40
48
  isProviderSandboxGoneDuringRoutedOperation,
41
49
  isProviderSandboxNotFoundError,
@@ -45,6 +53,7 @@ import {
45
53
  RoutingBackendRecoveryRequiredError,
46
54
  RoutingSandboxSession,
47
55
  resolveModalCheckpointProviderBindingForSession,
56
+ resolveConnectedMachineWorkspaceRoot,
48
57
  sandboxProviderInstanceIdFromEnvelope,
49
58
  sandboxBackendForSdkBackendId,
50
59
  selectBackend,
@@ -56,10 +65,13 @@ import {
56
65
  type RoutableSandbox,
57
66
  type ResolvedActiveBackend,
58
67
  type RoutingMutationSettlementResult,
68
+ type RoutingSandboxFirstOperationObserver,
59
69
  type RoutingSandboxOperationObserver,
70
+ type RoutingSandboxWaitObservation,
60
71
  type RoutingRetainedProcess,
61
72
  type RoutingRetainedProcessTerminalProof,
62
73
  type SelfhostedOpObserver,
74
+ type SelfhostedConnectionBinding,
63
75
  type SelfhostedRelayConfig,
64
76
  type OpStreamJournal,
65
77
  type SelfhostedOpStreamDeps,
@@ -116,6 +128,18 @@ type TurnRoutingWiringServices = RoutingWiringServices & {
116
128
  export type RoutingWiringIds = {
117
129
  workspaceId: string;
118
130
  sessionId: string;
131
+ resourceAccountId?: string;
132
+ resourceSubjectId?: string;
133
+ /** Frozen initiating-human authority for personal Connected Machine use.
134
+ * Every routed operation reasserts this exact accepted attempt before the
135
+ * control-plane connection is resolved. */
136
+ personalMachineAttempt?: {
137
+ accountId: string;
138
+ subjectId: string;
139
+ turnId: string;
140
+ attemptId: string;
141
+ executionGeneration: number;
142
+ };
119
143
  /** Canonical turn-attempt fence used to admit persistable-home mutations.
120
144
  * Omit outside a running worker attempt; mutation hooks then remain disabled. */
121
145
  workspaceMutationFence?: {
@@ -403,11 +427,12 @@ function beforePersistableHomeMutation(
403
427
  | ((input: {
404
428
  op: string;
405
429
  backend: ResolvedActiveBackend;
430
+ onCaptureWait?: (observation: RoutingSandboxWaitObservation) => void;
406
431
  }) => Promise<PersistableMutationAdmission | null>)
407
432
  | undefined {
408
433
  const fence = ids.workspaceMutationFence;
409
434
  if (!home || !fence) return undefined;
410
- return async ({ op, backend }) => {
435
+ return async ({ op, backend, onCaptureWait }) => {
411
436
  // A connected-machine target is intentionally non-persistable: its writes
412
437
  // do not dirty the session home's archive. Exact home identity metadata is
413
438
  // present only on a verified durable home route.
@@ -436,6 +461,7 @@ function beforePersistableHomeMutation(
436
461
  operation: op,
437
462
  captureWaitMs: sandboxLifecycleTransitionWaitMs(services.settings),
438
463
  ...(services.waitSignal ? { waitSignal: services.waitSignal } : {}),
464
+ ...(onCaptureWait ? { onCaptureWait } : {}),
439
465
  });
440
466
  return { admission, providerBinding };
441
467
  };
@@ -489,6 +515,10 @@ function afterPersistableHomeMutation(
489
515
  admittedWorkspaceGeneration: exactAdmission.workspaceGeneration,
490
516
  operation: op,
491
517
  providerBinding: boundAdmission.providerBinding ?? null,
518
+ backgroundCommand: {
519
+ commandId: retainedProcess.id,
520
+ command: op,
521
+ },
492
522
  owner: {
493
523
  kind: "turn",
494
524
  turnId: fence.turnId,
@@ -653,6 +683,15 @@ function settleRetainedProcessForTurn(
653
683
  reason: proof.reason,
654
684
  idleGraceMs: services.settings.sandboxIdleGraceMs,
655
685
  });
686
+ await settleSessionBackgroundCommandForRetainedProcess(services.db, {
687
+ accountId: fence.accountId,
688
+ workspaceId: ids.workspaceId,
689
+ sessionId: ids.sessionId,
690
+ retainedProcessId: process.id,
691
+ outcome: proof.outcome,
692
+ exitCode: proof.exitCode,
693
+ reason: proof.reason,
694
+ });
656
695
  };
657
696
  }
658
697
 
@@ -687,6 +726,8 @@ export function wrapTurnBoxWithRouting(
687
726
  established: EstablishedSandboxSession,
688
727
  ): EstablishedSandboxSession {
689
728
  const { db, settings, bus, onOp } = services;
729
+ const backgroundCommandAccountId = ids.workspaceMutationFence?.accountId;
730
+ const backgroundCommandAttempt = ids.workspaceMutationFence;
690
731
  const beforeMutation = beforePersistableHomeMutation(services, ids, ids.homeLease);
691
732
  const afterMutation = afterPersistableHomeMutation(services, ids, ids.homeLease);
692
733
  const beforeProcessMutation = beforeRetainedProcessMutation(services, ids);
@@ -697,27 +738,75 @@ export function wrapTurnBoxWithRouting(
697
738
  defaultBackend: established.session as RoutableBackendSession,
698
739
  defaultKind: established.backendId,
699
740
  getSandbox: async (sandboxId): Promise<RoutableSandbox | null> => {
700
- const sandbox = await getSandbox(db, ids.workspaceId, sandboxId);
741
+ const sandbox = await getSandbox(
742
+ db,
743
+ ids.resourceAccountId && ids.resourceSubjectId
744
+ ? {
745
+ accountId: ids.resourceAccountId,
746
+ workspaceId: ids.workspaceId,
747
+ subjectId: ids.resourceSubjectId,
748
+ }
749
+ : ids.workspaceId,
750
+ sandboxId,
751
+ );
701
752
  return sandbox
702
753
  ? {
703
754
  id: sandbox.id,
755
+ workspaceId: sandbox.workspaceId,
704
756
  kind: sandbox.kind,
705
757
  name: sandbox.name,
758
+ ...(sandbox.scope ? { scope: sandbox.scope } : {}),
706
759
  enrollmentId: sandbox.enrollmentId,
707
760
  }
708
761
  : null;
709
762
  },
710
763
  controlRpcFactory: controlRpcFactory(bus),
711
- resolveSelfhostedOpStream: async (sandbox) => {
712
- if (!sandbox.enrollmentId) return undefined;
713
- const enrollment = await getEnrollment(db, ids.workspaceId, sandbox.enrollmentId);
714
- return opStreamDepsFor(services, enrollment?.opStream === true);
764
+ resolveSelfhostedConnection: async (sandbox) => {
765
+ if (!sandbox.enrollmentId) return null;
766
+ const enrollment = await resolveRoutedMachineConnection(db, ids, sandbox);
767
+ return connectionBindingFor(services, enrollment);
715
768
  },
716
769
  relay: relayConfigFromSettings(settings),
717
770
  // A selfhosted swap target runs real commands too, so give it the same split
718
771
  // deadlines the machine-primary establish path uses (short control, long exec).
719
772
  ...selfhostedResolverTimeouts(settings),
720
773
  ...(onOp !== undefined ? { selfhostedOnOp: onOp } : {}),
774
+ ...(backgroundCommandAccountId && backgroundCommandAttempt
775
+ ? {
776
+ selfhostedAdoptBackgroundCommand: async (command) => {
777
+ const adopted = await adoptConnectedMachineSessionBackgroundCommand(db, {
778
+ accountId: backgroundCommandAccountId,
779
+ workspaceId: ids.workspaceId,
780
+ sessionId: ids.sessionId,
781
+ turnId: backgroundCommandAttempt.turnId,
782
+ executionGeneration: backgroundCommandAttempt.executionGeneration,
783
+ attemptId: backgroundCommandAttempt.attemptId,
784
+ commandId: crypto.randomUUID(),
785
+ controlWorkspaceId: command.controlWorkspaceId,
786
+ enrollmentId: command.enrollmentId,
787
+ connectionInstanceId: command.connectionInstanceId,
788
+ opId: command.opId,
789
+ command: command.command,
790
+ });
791
+ return { commandId: adopted.id };
792
+ },
793
+ selfhostedSettleBackgroundCommand: async (command) => {
794
+ await settleConnectedMachineSessionBackgroundCommand(db, {
795
+ accountId: backgroundCommandAccountId,
796
+ workspaceId: ids.workspaceId,
797
+ sessionId: ids.sessionId,
798
+ commandId: command.commandId,
799
+ controlWorkspaceId: command.controlWorkspaceId,
800
+ enrollmentId: command.enrollmentId,
801
+ connectionInstanceId: command.connectionInstanceId,
802
+ opId: command.opId,
803
+ outcome: command.outcome,
804
+ exitCode: command.exitCode,
805
+ reason: command.reason,
806
+ });
807
+ },
808
+ }
809
+ : {}),
721
810
  // The turn's declared environment → a selfhosted swap target's manifest, so the
722
811
  // SDK's per-turn manifest-env delta is empty (no "cannot change manifest
723
812
  // environment variables" throw when the turn pins to a vm). Mirrors the group
@@ -867,9 +956,12 @@ export function wrapLazyTurnBoxWithRouting(
867
956
  sandboxGroupId: string;
868
957
  backend: string;
869
958
  };
959
+ onFirstOperation?: RoutingSandboxFirstOperationObserver;
870
960
  },
871
961
  ): EstablishedSandboxSession {
872
962
  const { db, settings, bus, onOp } = services;
963
+ const backgroundCommandAccountId = ids.workspaceMutationFence?.accountId;
964
+ const backgroundCommandAttempt = ids.workspaceMutationFence;
873
965
  const beforeMutation = beforePersistableHomeMutation(services, ids, args.homeLeaseIdentity);
874
966
  const afterMutation = afterPersistableHomeMutation(services, ids, args.homeLeaseIdentity);
875
967
  const beforeProcessMutation = beforeRetainedProcessMutation(services, ids);
@@ -892,25 +984,73 @@ export function wrapLazyTurnBoxWithRouting(
892
984
  defaultBackend: syntheticSession,
893
985
  defaultKind: "unprovisioned",
894
986
  getSandbox: async (sandboxId): Promise<RoutableSandbox | null> => {
895
- const sandbox = await getSandbox(db, ids.workspaceId, sandboxId);
987
+ const sandbox = await getSandbox(
988
+ db,
989
+ ids.resourceAccountId && ids.resourceSubjectId
990
+ ? {
991
+ accountId: ids.resourceAccountId,
992
+ workspaceId: ids.workspaceId,
993
+ subjectId: ids.resourceSubjectId,
994
+ }
995
+ : ids.workspaceId,
996
+ sandboxId,
997
+ );
896
998
  return sandbox
897
999
  ? {
898
1000
  id: sandbox.id,
1001
+ workspaceId: sandbox.workspaceId,
899
1002
  kind: sandbox.kind,
900
1003
  name: sandbox.name,
1004
+ ...(sandbox.scope ? { scope: sandbox.scope } : {}),
901
1005
  enrollmentId: sandbox.enrollmentId,
902
1006
  }
903
1007
  : null;
904
1008
  },
905
1009
  controlRpcFactory: controlRpcFactory(bus),
906
- resolveSelfhostedOpStream: async (sandbox) => {
907
- if (!sandbox.enrollmentId) return undefined;
908
- const enrollment = await getEnrollment(db, ids.workspaceId, sandbox.enrollmentId);
909
- return opStreamDepsFor(services, enrollment?.opStream === true);
1010
+ resolveSelfhostedConnection: async (sandbox) => {
1011
+ if (!sandbox.enrollmentId) return null;
1012
+ const enrollment = await resolveRoutedMachineConnection(db, ids, sandbox);
1013
+ return connectionBindingFor(services, enrollment);
910
1014
  },
911
1015
  relay: relayConfigFromSettings(settings),
912
1016
  ...selfhostedResolverTimeouts(settings),
913
1017
  ...(onOp !== undefined ? { selfhostedOnOp: onOp } : {}),
1018
+ ...(backgroundCommandAccountId && backgroundCommandAttempt
1019
+ ? {
1020
+ selfhostedAdoptBackgroundCommand: async (command) => {
1021
+ const adopted = await adoptConnectedMachineSessionBackgroundCommand(db, {
1022
+ accountId: backgroundCommandAccountId,
1023
+ workspaceId: ids.workspaceId,
1024
+ sessionId: ids.sessionId,
1025
+ turnId: backgroundCommandAttempt.turnId,
1026
+ executionGeneration: backgroundCommandAttempt.executionGeneration,
1027
+ attemptId: backgroundCommandAttempt.attemptId,
1028
+ commandId: crypto.randomUUID(),
1029
+ controlWorkspaceId: command.controlWorkspaceId,
1030
+ enrollmentId: command.enrollmentId,
1031
+ connectionInstanceId: command.connectionInstanceId,
1032
+ opId: command.opId,
1033
+ command: command.command,
1034
+ });
1035
+ return { commandId: adopted.id };
1036
+ },
1037
+ selfhostedSettleBackgroundCommand: async (command) => {
1038
+ await settleConnectedMachineSessionBackgroundCommand(db, {
1039
+ accountId: backgroundCommandAccountId,
1040
+ workspaceId: ids.workspaceId,
1041
+ sessionId: ids.sessionId,
1042
+ commandId: command.commandId,
1043
+ controlWorkspaceId: command.controlWorkspaceId,
1044
+ enrollmentId: command.enrollmentId,
1045
+ connectionInstanceId: command.connectionInstanceId,
1046
+ opId: command.opId,
1047
+ outcome: command.outcome,
1048
+ exitCode: command.exitCode,
1049
+ reason: command.reason,
1050
+ });
1051
+ },
1052
+ }
1053
+ : {}),
914
1054
  ...(ids.environment !== undefined ? { environment: ids.environment } : {}),
915
1055
  ...(ids.transientExecEnvironment !== undefined
916
1056
  ? { transientExecEnvironment: ids.transientExecEnvironment }
@@ -956,6 +1096,7 @@ export function wrapLazyTurnBoxWithRouting(
956
1096
  return routedResolver(pointer);
957
1097
  },
958
1098
  ...(services.onSandboxOperation ? { onOperation: services.onSandboxOperation } : {}),
1099
+ ...(args.onFirstOperation ? { onFirstOperation: args.onFirstOperation } : {}),
959
1100
  ...(beforeMutation ? { beforeMutation } : {}),
960
1101
  ...(afterMutation ? { afterMutation } : {}),
961
1102
  ...(beforeProcessMutation ? { beforeProcessMutation } : {}),
@@ -1018,12 +1159,31 @@ export function wrapLazyTurnBoxWithRouting(
1018
1159
  }
1019
1160
 
1020
1161
  export type SelfhostedTurnSessionArgs = {
1162
+ accountId: string;
1163
+ /** Authorization/session workspace. */
1021
1164
  workspaceId: string;
1165
+ sessionId: string;
1166
+ /** Physical machine-origin workspace used in control-plane routing. */
1167
+ controlWorkspaceId?: string;
1168
+ /** Exact launching attempt required before a live Connected Machine command
1169
+ * can transfer into session ownership. Omitted by non-turn/test callers,
1170
+ * which therefore cannot yield a durable background command. */
1171
+ backgroundCommandAttempt?: Pick<
1172
+ NonNullable<RoutingWiringIds["workspaceMutationFence"]>,
1173
+ "turnId" | "executionGeneration" | "attemptId"
1174
+ >;
1022
1175
  /** The target machine's enrollment id == the agent subject id. */
1023
1176
  agentId: string;
1177
+ /** Exact daemon process currently leased for the enrollment. */
1178
+ connectionInstanceId: string;
1024
1179
  /** Whether the target machine advertised Capabilities.op_stream in its latest
1025
1180
  * Hello. The runtime-side transport gate must still require the server flag. */
1026
1181
  opStream: boolean;
1182
+ /** Desired per-enrollment command policy and capability from the same live
1183
+ * enrollment snapshot as the process identity. */
1184
+ operationResourcePolicy: EnrollmentRecord["operationPolicy"];
1185
+ operationResourcePolicySupported: boolean;
1186
+ operationCpuQuotaSupported: boolean;
1027
1187
  /** The active pointer's epoch — the control-op fence echoed to the agent. */
1028
1188
  epoch: number;
1029
1189
  /** The run's declared sandbox environment (the SAME object fed to buildAgent +
@@ -1034,6 +1194,13 @@ export type SelfhostedTurnSessionArgs = {
1034
1194
  transientExecEnvironment?: () => Readonly<Record<string, string>>;
1035
1195
  /** The session working directory (per-session pointer). Null ⇒ workspace_root. */
1036
1196
  workingDir: string | null;
1197
+ /** Effective absolute host-native root frozen for this attempt. */
1198
+ workspaceRoot: string;
1199
+ /** Present only for a user-owned machine. Every provider operation rechecks
1200
+ * this frozen accepted-attempt authority immediately before dispatch. */
1201
+ personalMachineAttempt?: NonNullable<RoutingWiringIds["personalMachineAttempt"]> & {
1202
+ sessionId: string;
1203
+ };
1037
1204
  };
1038
1205
 
1039
1206
  /**
@@ -1074,16 +1241,78 @@ function opStreamDepsFor(
1074
1241
  };
1075
1242
  }
1076
1243
 
1244
+ /** Project one enrollment read into one exact runtime route. Capability and
1245
+ * process identity must be taken from the same snapshot. */
1246
+ function connectionBindingFor(
1247
+ services: RoutingWiringServices,
1248
+ enrollment: EnrollmentRecord | null,
1249
+ ): SelfhostedConnectionBinding | null {
1250
+ if (!enrollment?.connectionInstanceId) return null;
1251
+ const opStream = opStreamDepsFor(services, enrollment.opStream === true);
1252
+ return {
1253
+ workspaceId: enrollment.workspaceId,
1254
+ connectionInstanceId: enrollment.connectionInstanceId,
1255
+ workspaceRoot: enrollment.workspaceRoot,
1256
+ ...(opStream !== undefined ? { opStream } : {}),
1257
+ operationResourcePolicy: enrollment.operationPolicy,
1258
+ operationResourcePolicySupported: enrollment.agentCapabilities.operationResourcePolicy === true,
1259
+ operationCpuQuotaSupported: enrollment.agentCapabilities.operationCpuQuota === true,
1260
+ };
1261
+ }
1262
+
1263
+ /** Personal-machine discovery is not execution authority. Recheck the frozen
1264
+ * initiating human, exact current attempt, immutable authorization snapshot,
1265
+ * and current visibility-keyed grant immediately before each routed operation
1266
+ * resolves a live control-plane connection. */
1267
+ async function resolveRoutedMachineConnection(
1268
+ db: Database,
1269
+ ids: RoutingWiringIds,
1270
+ sandbox: RoutableSandbox,
1271
+ ): Promise<EnrollmentRecord | null> {
1272
+ if (!sandbox.enrollmentId) return null;
1273
+ if (sandbox.scope !== "user") {
1274
+ return await getLiveEnrollmentConnection(
1275
+ db,
1276
+ ids.resourceAccountId && ids.resourceSubjectId
1277
+ ? {
1278
+ accountId: ids.resourceAccountId,
1279
+ workspaceId: ids.workspaceId,
1280
+ subjectId: ids.resourceSubjectId,
1281
+ }
1282
+ : sandbox.workspaceId,
1283
+ sandbox.enrollmentId,
1284
+ );
1285
+ }
1286
+ const authority = ids.personalMachineAttempt;
1287
+ if (!authority) return null;
1288
+ return await resolvePersonalMachineConnectionForAttempt(db, {
1289
+ accountId: authority.accountId,
1290
+ workspaceId: ids.workspaceId,
1291
+ subjectId: authority.subjectId,
1292
+ sessionId: ids.sessionId,
1293
+ turnId: authority.turnId,
1294
+ attemptId: authority.attemptId,
1295
+ executionGeneration: authority.executionGeneration,
1296
+ enrollmentId: sandbox.enrollmentId,
1297
+ requireActiveSandbox: true,
1298
+ });
1299
+ }
1300
+
1077
1301
  export async function establishSelfhostedTurnSession(
1078
1302
  services: RoutingWiringServices,
1079
1303
  args: SelfhostedTurnSessionArgs,
1080
1304
  ): Promise<EstablishedSandboxSession> {
1081
- const { settings, bus, onOp } = services;
1305
+ const { db, settings, bus, onOp } = services;
1082
1306
  const { timeoutMs, execTimeoutMs } = selfhostedTimeoutsFromSettings(settings);
1083
1307
  const opStream = opStreamDepsFor(services, args.opStream);
1084
1308
  const { client, session } = await buildSelfhostedBackendSession({
1085
1309
  workspaceId: args.workspaceId,
1310
+ ...(args.controlWorkspaceId !== undefined
1311
+ ? { controlWorkspaceId: args.controlWorkspaceId }
1312
+ : {}),
1086
1313
  agentId: args.agentId,
1314
+ connectionInstanceId: args.connectionInstanceId,
1315
+ workspaceRoot: args.workspaceRoot,
1087
1316
  relay: relayConfigFromSettings(settings),
1088
1317
  controlRpcFactory: controlRpcFactory(bus),
1089
1318
  epoch: args.epoch,
@@ -1091,16 +1320,85 @@ export async function establishSelfhostedTurnSession(
1091
1320
  ...(args.transientExecEnvironment !== undefined
1092
1321
  ? { transientExecEnvironment: args.transientExecEnvironment }
1093
1322
  : {}),
1094
- workingDir: args.workingDir,
1095
1323
  // Give this turn's exec ops the long deadline (control ops stay short) so a real
1096
1324
  // command is not killed at the control wall.
1097
1325
  timeoutMs,
1098
1326
  execTimeoutMs,
1327
+ operationResourcePolicy: args.operationResourcePolicy,
1328
+ operationResourcePolicySupported: args.operationResourcePolicySupported,
1329
+ operationCpuQuotaSupported: args.operationCpuQuotaSupported,
1330
+ resolveOperationAdmission: async () => {
1331
+ const enrollment = args.personalMachineAttempt
1332
+ ? await resolvePersonalMachineConnectionForAttempt(db, {
1333
+ accountId: args.personalMachineAttempt.accountId,
1334
+ workspaceId: args.workspaceId,
1335
+ subjectId: args.personalMachineAttempt.subjectId,
1336
+ sessionId: args.personalMachineAttempt.sessionId,
1337
+ turnId: args.personalMachineAttempt.turnId,
1338
+ attemptId: args.personalMachineAttempt.attemptId,
1339
+ executionGeneration: args.personalMachineAttempt.executionGeneration,
1340
+ enrollmentId: args.agentId,
1341
+ requireActiveSandbox: true,
1342
+ })
1343
+ : await getLiveEnrollmentConnection(
1344
+ db,
1345
+ args.controlWorkspaceId ?? args.workspaceId,
1346
+ args.agentId,
1347
+ );
1348
+ const binding = connectionBindingFor(services, enrollment);
1349
+ if (!binding) return null;
1350
+ if (!binding.workspaceRoot) {
1351
+ throw new ActiveBackendUnresolvableError(
1352
+ "workspace_root_unavailable",
1353
+ "Connected Machine no longer has a reported workspace root",
1354
+ );
1355
+ }
1356
+ return {
1357
+ ...binding,
1358
+ workspaceRoot: resolveConnectedMachineWorkspaceRoot(binding.workspaceRoot, args.workingDir),
1359
+ };
1360
+ },
1361
+ ...(args.backgroundCommandAttempt
1362
+ ? {
1363
+ adoptBackgroundCommand: async (command) => {
1364
+ const adopted = await adoptConnectedMachineSessionBackgroundCommand(db, {
1365
+ accountId: args.accountId,
1366
+ workspaceId: args.workspaceId,
1367
+ sessionId: args.sessionId,
1368
+ turnId: args.backgroundCommandAttempt!.turnId,
1369
+ executionGeneration: args.backgroundCommandAttempt!.executionGeneration,
1370
+ attemptId: args.backgroundCommandAttempt!.attemptId,
1371
+ commandId: crypto.randomUUID(),
1372
+ controlWorkspaceId: command.controlWorkspaceId,
1373
+ enrollmentId: command.enrollmentId,
1374
+ connectionInstanceId: command.connectionInstanceId,
1375
+ opId: command.opId,
1376
+ command: command.command,
1377
+ });
1378
+ return { commandId: adopted.id };
1379
+ },
1380
+ }
1381
+ : {}),
1382
+ settleBackgroundCommand: async (command) => {
1383
+ await settleConnectedMachineSessionBackgroundCommand(db, {
1384
+ accountId: args.accountId,
1385
+ workspaceId: args.workspaceId,
1386
+ sessionId: args.sessionId,
1387
+ commandId: command.commandId,
1388
+ controlWorkspaceId: command.controlWorkspaceId,
1389
+ enrollmentId: command.enrollmentId,
1390
+ connectionInstanceId: command.connectionInstanceId,
1391
+ opId: command.opId,
1392
+ outcome: command.outcome,
1393
+ exitCode: command.exitCode,
1394
+ reason: command.reason,
1395
+ });
1396
+ },
1099
1397
  // Meter every control op (out-of-band telemetry) — no-op when unwired.
1100
1398
  ...(onOp !== undefined ? { onOp } : {}),
1101
1399
  // The streaming exec transport — present iff the machine advertised the
1102
- // capability AND the server flag is on. It is required when execTimeoutMs=0;
1103
- // legacy request/reply remains available only for explicitly bounded exec.
1400
+ // capability AND the server flag is on. Connected Machine exec fails closed
1401
+ // when it is absent; there is no request/reply downgrade.
1104
1402
  ...(opStream !== undefined ? { opStream } : {}),
1105
1403
  });
1106
1404
  return {
@@ -0,0 +1,176 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ const MAX_SCHEDULED_TASK_ID_BYTES = 256;
4
+ const MAX_STARTS_AT_BYTES = 256;
5
+ const MAX_PROVIDER_BYTES = 256;
6
+ const MAX_FINGERPRINT_BYTES = 1_024;
7
+ const MAX_LABELS = 256;
8
+ const MAX_LABEL_KEY_BYTES = 256;
9
+ const MAX_LABEL_VALUE_BYTES = 4_096;
10
+ const OFFSET_TIMESTAMP =
11
+ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:Z|[+-](\d{2}):(\d{2}))$/;
12
+
13
+ export type ScheduledAlertOccurrenceDeclaration = {
14
+ status: "firing" | "resolved";
15
+ startsAt: string;
16
+ fingerprint: string;
17
+ labels: Record<string, string>;
18
+ provider?: string;
19
+ };
20
+
21
+ export type ScheduledAlertOccurrenceIdentity = {
22
+ status: "firing" | "resolved";
23
+ sessionCreateIdempotencyKey: string;
24
+ /** Exact bounded labels from the validated structured occurrence. */
25
+ labels: Readonly<Record<string, string>>;
26
+ };
27
+
28
+ /**
29
+ * Bind the series-stable occurrence identity to one accepted task execution
30
+ * definition. A later task revision must not adopt the prior responder root,
31
+ * because that session has already frozen the old prompt/tool/authority policy.
32
+ */
33
+ export function scheduledAlertResponderSessionCreateIdempotencyKey(input: {
34
+ occurrence: ScheduledAlertOccurrenceIdentity;
35
+ taskAuthorityRevision: number;
36
+ taskExecutionDigest: string;
37
+ }): string {
38
+ const digest = createHash("sha256")
39
+ .update(
40
+ JSON.stringify({
41
+ version: 1,
42
+ occurrenceKey: input.occurrence.sessionCreateIdempotencyKey,
43
+ taskAuthorityRevision: input.taskAuthorityRevision,
44
+ taskExecutionDigest: input.taskExecutionDigest,
45
+ }),
46
+ )
47
+ .digest("hex");
48
+ return `scheduled-alert-occurrence:v1:${digest}`;
49
+ }
50
+
51
+ /**
52
+ * Derive one content-free, workspace-bound identity for an Alertmanager-style
53
+ * alert occurrence. Missing or malformed metadata deliberately returns null so
54
+ * ordinary scheduled tasks retain their existing new-session-per-run behavior.
55
+ */
56
+ export function scheduledAlertOccurrenceIdentity(input: {
57
+ workspaceId: string;
58
+ scheduledTaskId: string;
59
+ metadata: Record<string, unknown>;
60
+ }): ScheduledAlertOccurrenceIdentity | null {
61
+ const scheduledTaskId = boundedString(input.scheduledTaskId, MAX_SCHEDULED_TASK_ID_BYTES);
62
+ if (!scheduledTaskId) return null;
63
+
64
+ const alert = record(input.metadata.alert);
65
+ if (!alert) return null;
66
+
67
+ const status = alert.status;
68
+ if (status !== "firing" && status !== "resolved") return null;
69
+
70
+ const startsAt = canonicalTimestamp(alert.startsAt);
71
+ const fingerprint = boundedString(alert.fingerprint, MAX_FINGERPRINT_BYTES);
72
+ const labels = canonicalLabels(alert.labels);
73
+ if (!startsAt || !fingerprint || !labels) return null;
74
+
75
+ const provider = boundedString(
76
+ alert.provider ?? input.metadata.alertProvider ?? input.metadata.provider ?? "alertmanager",
77
+ MAX_PROVIDER_BYTES,
78
+ );
79
+ if (!provider) return null;
80
+ const digest = createHash("sha256")
81
+ .update(
82
+ JSON.stringify({
83
+ version: 1,
84
+ workspaceId: input.workspaceId,
85
+ scheduledTaskId,
86
+ provider,
87
+ fingerprint,
88
+ startsAt,
89
+ labels,
90
+ }),
91
+ )
92
+ .digest("hex");
93
+ return {
94
+ status,
95
+ sessionCreateIdempotencyKey: `scheduled-alert-occurrence:v1:${digest}`,
96
+ labels: Object.fromEntries(labels),
97
+ };
98
+ }
99
+
100
+ function record(value: unknown): Record<string, unknown> | null {
101
+ return value !== null && typeof value === "object" && !Array.isArray(value)
102
+ ? (value as Record<string, unknown>)
103
+ : null;
104
+ }
105
+
106
+ function boundedString(value: unknown, maxBytes: number): string | null {
107
+ if (typeof value !== "string") return null;
108
+ const normalized = value.trim();
109
+ if (!normalized || Buffer.byteLength(normalized, "utf8") > maxBytes) return null;
110
+ return normalized;
111
+ }
112
+
113
+ function canonicalTimestamp(value: unknown): string | null {
114
+ if (typeof value !== "string") return null;
115
+ const trimmed = value.trim();
116
+ if (!trimmed || Buffer.byteLength(trimmed, "utf8") > MAX_STARTS_AT_BYTES) return null;
117
+ const match = OFFSET_TIMESTAMP.exec(trimmed);
118
+ if (!match) return null;
119
+ const [
120
+ ,
121
+ yearText,
122
+ monthText,
123
+ dayText,
124
+ hourText,
125
+ minuteText,
126
+ secondText,
127
+ ,
128
+ offsetHourText,
129
+ offsetMinuteText,
130
+ ] = match;
131
+ const year = Number(yearText);
132
+ const month = Number(monthText);
133
+ const day = Number(dayText);
134
+ const hour = Number(hourText);
135
+ const minute = Number(minuteText);
136
+ const second = secondText === undefined ? 0 : Number(secondText);
137
+ const offsetHour = offsetHourText === undefined ? 0 : Number(offsetHourText);
138
+ const offsetMinute = offsetMinuteText === undefined ? 0 : Number(offsetMinuteText);
139
+ const leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
140
+ const daysInMonth = [31, leapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
141
+ if (
142
+ month < 1 ||
143
+ month > 12 ||
144
+ day < 1 ||
145
+ day > daysInMonth[month - 1]! ||
146
+ hour > 23 ||
147
+ minute > 59 ||
148
+ second > 59 ||
149
+ offsetHour > 23 ||
150
+ offsetMinute > 59
151
+ ) {
152
+ return null;
153
+ }
154
+ const parsed = new Date(trimmed);
155
+ return Number.isFinite(parsed.getTime()) ? trimmed : null;
156
+ }
157
+
158
+ function canonicalLabels(value: unknown): Array<readonly [string, string]> | null {
159
+ const labels = record(value);
160
+ if (!labels) return null;
161
+ const entries = Object.entries(labels);
162
+ if (entries.length === 0 || entries.length > MAX_LABELS) return null;
163
+ const canonical: Array<readonly [string, string]> = [];
164
+ for (const [key, rawValue] of entries) {
165
+ if (
166
+ !key ||
167
+ Buffer.byteLength(key, "utf8") > MAX_LABEL_KEY_BYTES ||
168
+ typeof rawValue !== "string" ||
169
+ Buffer.byteLength(rawValue, "utf8") > MAX_LABEL_VALUE_BYTES
170
+ ) {
171
+ return null;
172
+ }
173
+ canonical.push([key, rawValue]);
174
+ }
175
+ return canonical.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));
176
+ }