@opengeni/worker-bundle 0.24.2-canary.0 → 0.26.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 (73) hide show
  1. package/dist/activities/agent-turn/agent-build.d.ts +3 -10
  2. package/dist/activities/agent-turn/claim.d.ts +7 -0
  3. package/dist/activities/agent-turn/credential-leases.d.ts +8 -0
  4. package/dist/activities/agent-turn/errors.d.ts +1 -1
  5. package/dist/activities/agent-turn/failure-settlement.d.ts +43 -1
  6. package/dist/activities/agent-turn/quiescence.d.ts +9 -6
  7. package/dist/activities/agent-turn/tool-environment.d.ts +2 -13
  8. package/dist/activities/agent-turn/tool-policy.d.ts +4 -0
  9. package/dist/activities/agent-turn/turn-context.d.ts +9 -1
  10. package/dist/activities/codemode-dispatcher.d.ts +10 -1
  11. package/dist/activities/codex-capacity.d.ts +32 -3
  12. package/dist/activities/codex-fleet-shadow.d.ts +1 -1
  13. package/dist/activities/codex-image-generation.d.ts +1 -1
  14. package/dist/activities/codex-rotation.d.ts +8 -67
  15. package/dist/activities/goals.d.ts +1 -1
  16. package/dist/activities/google-drive-publication.d.ts +2 -13
  17. package/dist/activities/image-generation-operation.d.ts +13 -4
  18. package/dist/activities/session-state.d.ts +4 -2
  19. package/dist/activities/types.d.ts +11 -1
  20. package/dist/{activities-control-ZWH7J4KZ.js → activities-control-CTEMLTHG.js} +45 -18
  21. package/dist/activities-control-CTEMLTHG.js.map +1 -0
  22. package/dist/activities-control.d.ts +2 -0
  23. package/dist/{activities-turn-I4OPLQLS.js → activities-turn-S5IU347A.js} +960 -815
  24. package/dist/activities-turn-S5IU347A.js.map +1 -0
  25. package/dist/activities.d.ts +2 -0
  26. package/dist/{chunk-65JEWP2Q.js → chunk-D4ZEFOYH.js} +1 -1
  27. package/dist/chunk-D4ZEFOYH.js.map +1 -0
  28. package/dist/{chunk-RQNH6CGR.js → chunk-TAUE3GYT.js} +117 -95
  29. package/dist/chunk-TAUE3GYT.js.map +1 -0
  30. package/dist/github-rest-mcp.d.ts +0 -2
  31. package/dist/index.d.ts +1 -0
  32. package/dist/index.js +2 -2
  33. package/dist/index.js.map +1 -1
  34. package/dist/observability-metrics.d.ts +1 -1
  35. package/dist/workflow-bundle.js +71 -8
  36. package/dist/workflows/activities.d.ts +1 -1
  37. package/dist/workflows/session.d.ts +3 -0
  38. package/package.json +17 -17
  39. package/src/activities/agent-turn/agent-build.ts +20 -26
  40. package/src/activities/agent-turn/claim.ts +26 -1
  41. package/src/activities/agent-turn/codex-capacity.ts +311 -234
  42. package/src/activities/agent-turn/credential-leases.ts +36 -0
  43. package/src/activities/agent-turn/errors.ts +29 -1
  44. package/src/activities/agent-turn/failure-settlement.ts +451 -323
  45. package/src/activities/agent-turn/quiescence.ts +21 -15
  46. package/src/activities/agent-turn/run.ts +18 -5
  47. package/src/activities/agent-turn/stream-attempt.ts +15 -1
  48. package/src/activities/agent-turn/tool-environment.ts +30 -32
  49. package/src/activities/agent-turn/tool-policy.ts +14 -8
  50. package/src/activities/agent-turn/turn-context.ts +13 -0
  51. package/src/activities/codemode-dispatcher.ts +235 -59
  52. package/src/activities/codex-capacity.ts +89 -10
  53. package/src/activities/codex-fleet-shadow.ts +8 -1
  54. package/src/activities/codex-image-generation.ts +19 -2
  55. package/src/activities/codex-rotation.ts +45 -142
  56. package/src/activities/goals.ts +9 -9
  57. package/src/activities/google-drive-publication.ts +4 -81
  58. package/src/activities/image-generation-operation.ts +28 -3
  59. package/src/activities/sandbox-lease.ts +29 -12
  60. package/src/activities/session-state.ts +17 -0
  61. package/src/activities/types.ts +16 -8
  62. package/src/activities.ts +1 -0
  63. package/src/github-rest-mcp.ts +0 -82
  64. package/src/observability-metrics.ts +4 -0
  65. package/src/sandbox-routing.ts +71 -16
  66. package/src/workflows/activities.ts +1 -0
  67. package/src/workflows/session.ts +85 -7
  68. package/dist/activities/api-integrations.d.ts +0 -21
  69. package/dist/activities-control-ZWH7J4KZ.js.map +0 -1
  70. package/dist/activities-turn-I4OPLQLS.js.map +0 -1
  71. package/dist/chunk-65JEWP2Q.js.map +0 -1
  72. package/dist/chunk-RQNH6CGR.js.map +0 -1
  73. package/src/activities/api-integrations.ts +0 -151
@@ -7,6 +7,7 @@ import {
7
7
  recoverSessionDispatch,
8
8
  reconcileSessionAttemptQuiescence,
9
9
  peekSessionWork as peekSessionWorkDb,
10
+ settleSessionInputWait as settleSessionInputWaitDb,
10
11
  countQueuedTurns,
11
12
  getSessionAttemptActivityRef,
12
13
  getSessionEvent,
@@ -42,6 +43,8 @@ import type {
42
43
  RecoverDispatchResult,
43
44
  RecoverEscapedMcpTimeoutInput,
44
45
  RecoverEscapedMcpTimeoutResult,
46
+ SettleSessionInputWaitInput,
47
+ SettleSessionInputWaitResult,
45
48
  } from "./types";
46
49
 
47
50
  export type SessionStateActivityOverrides = Partial<{
@@ -53,6 +56,7 @@ export type SessionStateActivityOverrides = Partial<{
53
56
  recoverSessionDispatch: typeof recoverSessionDispatch;
54
57
  reconcileSessionAttemptQuiescence: typeof reconcileSessionAttemptQuiescence;
55
58
  peekSessionWork: typeof peekSessionWorkDb;
59
+ settleSessionInputWait: typeof settleSessionInputWaitDb;
56
60
  countQueuedTurns: typeof countQueuedTurns;
57
61
  getSessionAttemptActivityRef: typeof getSessionAttemptActivityRef;
58
62
  getSessionEvent: typeof getSessionEvent;
@@ -93,6 +97,7 @@ export function createSessionStateActivities(
93
97
  const reconcileSessionAttemptQuiescenceFn =
94
98
  overrides.reconcileSessionAttemptQuiescence ?? reconcileSessionAttemptQuiescence;
95
99
  const peekSessionWorkFn = overrides.peekSessionWork ?? peekSessionWorkDb;
100
+ const settleSessionInputWaitFn = overrides.settleSessionInputWait ?? settleSessionInputWaitDb;
96
101
  const countQueuedTurnsFn = overrides.countQueuedTurns ?? countQueuedTurns;
97
102
  const getSessionAttemptActivityRefFn =
98
103
  overrides.getSessionAttemptActivityRef ?? getSessionAttemptActivityRef;
@@ -486,6 +491,17 @@ export function createSessionStateActivities(
486
491
  return peek;
487
492
  }
488
493
 
494
+ async function settleSessionInputWait(
495
+ input: SettleSessionInputWaitInput,
496
+ ): Promise<SettleSessionInputWaitResult> {
497
+ const { db, bus } = await services();
498
+ const result = await settleSessionInputWaitFn(db, input);
499
+ if (result.events.length > 0) {
500
+ await publishDurableSessionEventsFn(bus, input.workspaceId, input.sessionId, result.events);
501
+ }
502
+ return { action: result.action };
503
+ }
504
+
489
505
  async function expireSessionHumanInput(
490
506
  input: ExpireSessionHumanInputInput,
491
507
  ): Promise<ExpireSessionHumanInputResult> {
@@ -546,6 +562,7 @@ export function createSessionStateActivities(
546
562
  recoverDispatch,
547
563
  recoverEscapedMcpTimeout,
548
564
  peekSessionWork,
565
+ settleSessionInputWait,
549
566
  expireSessionHumanInput,
550
567
  expireSessionInteractionIntervention,
551
568
  markSessionIdle,
@@ -343,6 +343,18 @@ export type PeekSessionWorkInput = {
343
343
  sessionId: string;
344
344
  };
345
345
 
346
+ export type SettleSessionInputWaitInput = {
347
+ accountId: string;
348
+ workspaceId: string;
349
+ sessionId: string;
350
+ waitTurnId: string;
351
+ disposition: "held" | "timeout" | "superseded";
352
+ };
353
+
354
+ export type SettleSessionInputWaitResult = {
355
+ action: "held" | "timeout" | "superseded" | "stale";
356
+ };
357
+
346
358
  export type ExpireSessionHumanInputInput = {
347
359
  accountId: string;
348
360
  workspaceId: string;
@@ -378,14 +390,10 @@ export type MaybeContinueGoalInput = {
378
390
  };
379
391
 
380
392
  export type MaybeContinueGoalResult = {
381
- // `held`: an agent-declared `goal_wait` hold is current. No continuation was
382
- // materialized and the goal obligation stays armed; the workflow closes like
383
- // `none` and the wake outbox (deadline) or any producer's signalWithStart
384
- // restarts it.
385
- // `deferred`: idle backoff between consecutive no-input continuations. Same
386
- // shape as `held`: nothing materialized, obligation armed, a delayed outbox
387
- // wake at the pacing deadline (pulled to now by any new input) restarts it.
388
- action: "none" | "queue" | "continue" | "paused" | "held" | "deferred";
393
+ // `deferred`: idle backoff between consecutive no-input continuations.
394
+ // Nothing was materialized; the obligation remains armed and a delayed
395
+ // outbox wake at the pacing deadline restarts it.
396
+ action: "none" | "queue" | "continue" | "paused" | "deferred";
389
397
  };
390
398
 
391
399
  export type DispatchScheduledTaskRunInput = {
package/src/activities.ts CHANGED
@@ -101,6 +101,7 @@ export const reconcileSessionAttemptQuiescence =
101
101
  export const recoverDispatch = defaultControlActivities.recoverDispatch;
102
102
  export const recoverEscapedMcpTimeout = defaultControlActivities.recoverEscapedMcpTimeout;
103
103
  export const peekSessionWork = defaultControlActivities.peekSessionWork;
104
+ export const settleSessionInputWait = defaultControlActivities.settleSessionInputWait;
104
105
  export const expireSessionHumanInput = defaultControlActivities.expireSessionHumanInput;
105
106
  export const expireSessionInteractionIntervention =
106
107
  defaultControlActivities.expireSessionInteractionIntervention;
@@ -11,23 +11,16 @@ import {
11
11
  } from "@opengeni/contracts/personal-github";
12
12
  import { personalGitHubRepositoryResources } from "@opengeni/core";
13
13
  import {
14
- beginConnectorActionExecution,
15
- completeConnectorActionExecution,
16
14
  getConnectionMetadata,
17
15
  getPersonalGitHubRepositorySelectionState,
18
16
  hasAuditableGitHubInstallationAuthority,
19
17
  listGitHubInstallationAccessForWorkspace,
20
- prepareConnectorActionApproval,
21
18
  resolveAcceptedConnectionUse,
22
19
  type Database,
23
20
  type ResolveConnectionCredentialInput,
24
21
  type ResolveConnectionCredentialResult,
25
22
  type SessionTurnForExecution,
26
23
  } from "@opengeni/db";
27
- import {
28
- AttemptToolApprovalRequiredError,
29
- type AttemptToolAuthorization,
30
- } from "@opengeni/codemode";
31
24
  import { createGitHubAppInstallationTokenWithExpiry, githubAppBotIdentity } from "@opengeni/github";
32
25
  import {
33
26
  type AttemptConnectorActionBinding,
@@ -44,7 +37,6 @@ import {
44
37
  GitHubRestAuthorityError,
45
38
  githubRestConnectorActionOutcome,
46
39
  GitHubRestMcpServer,
47
- GitHubRestMutationNotExecutedError,
48
40
  type GitHubRestRepository,
49
41
  } from "@opengeni/runtime/github-rest-mcp";
50
42
 
@@ -60,7 +52,6 @@ export type GitHubRestMcpRuntime = {
60
52
  tools: ToolRef[];
61
53
  localMcpServers: LocalMcpServerRegistration[];
62
54
  connectorBindings: AttemptConnectorActionBinding[];
63
- authorizeCodemodeCall: AttemptToolAuthorization | null;
64
55
  };
65
56
 
66
57
  export async function buildGitHubRestMcpForTurn(input: {
@@ -81,7 +72,6 @@ export async function buildGitHubRestMcpForTurn(input: {
81
72
  tools: input.tools,
82
73
  localMcpServers: [],
83
74
  connectorBindings: [],
84
- authorizeCodemodeCall: null,
85
75
  };
86
76
  }
87
77
 
@@ -96,7 +86,6 @@ export async function buildGitHubRestMcpForTurn(input: {
96
86
  tools: input.tools,
97
87
  localMcpServers: [],
98
88
  connectorBindings: [],
99
- authorizeCodemodeCall: null,
100
89
  };
101
90
  }
102
91
  const configuredIds = new Set(input.settings.mcpServers.map((server) => server.id));
@@ -112,7 +101,6 @@ export async function buildGitHubRestMcpForTurn(input: {
112
101
  const localMcpServers: LocalMcpServerRegistration[] = [];
113
102
  const toolRefs: ToolRef[] = [];
114
103
  const connectorBindings: AttemptConnectorActionBinding[] = [];
115
- const codemodeActions = createCodemodeActionLifecycle(input, connectorBindings);
116
104
 
117
105
  if (appRepositories.length > 0) {
118
106
  const appResolver = workspaceAppAuthorityResolver(input, appRepositories);
@@ -123,7 +111,6 @@ export async function buildGitHubRestMcpForTurn(input: {
123
111
  authorityKind: "workspace_app",
124
112
  repositories: appRepositories,
125
113
  resolveAuthority: appResolver,
126
- completeCodemodeAction: codemodeActions.complete,
127
114
  }),
128
115
  });
129
116
  configs.push(internalMcpConfig(GITHUB_REST_MCP_APP_SERVER_ID, "GitHub — OpenGeni bot"));
@@ -141,7 +128,6 @@ export async function buildGitHubRestMcpForTurn(input: {
141
128
  authorityKind: "personal_oauth",
142
129
  repositories: personalRepositories,
143
130
  resolveAuthority: personalAuthorityResolver(input),
144
- completeCodemodeAction: codemodeActions.complete,
145
131
  }),
146
132
  });
147
133
  configs.push(internalMcpConfig(GITHUB_REST_MCP_PERSONAL_SERVER_ID, "GitHub — My account"));
@@ -159,74 +145,6 @@ export async function buildGitHubRestMcpForTurn(input: {
159
145
  tools: mergeToolRefs(input.tools, toolRefs),
160
146
  localMcpServers,
161
147
  connectorBindings,
162
- authorizeCodemodeCall: codemodeActions.authorize,
163
- };
164
- }
165
-
166
- function createCodemodeActionLifecycle(
167
- input: {
168
- db: Database;
169
- accountId: string;
170
- workspaceId: string;
171
- sessionId: string;
172
- attemptId: string;
173
- turn: SessionTurnForExecution;
174
- },
175
- bindings: AttemptConnectorActionBinding[],
176
- ): {
177
- authorize: AttemptToolAuthorization;
178
- complete: NonNullable<
179
- ConstructorParameters<typeof GitHubRestMcpServer>[0]["completeCodemodeAction"]
180
- >;
181
- } {
182
- const identity = {
183
- accountId: input.accountId,
184
- workspaceId: input.workspaceId,
185
- sessionId: input.sessionId,
186
- turnId: input.turn.id,
187
- attemptId: input.attemptId,
188
- executionGeneration: input.turn.executionGeneration,
189
- initiator: input.turn.initiator,
190
- };
191
- const executing = new Map<string, string>();
192
- return {
193
- authorize: async ({ call, entry }) => {
194
- if (call.caller.kind !== "codemode") return;
195
- const binding = bindings.find((candidate) => candidate.modelName === entry.modelName);
196
- if (!binding) return;
197
- const invocation = binding.call(call.operationId, call.arguments);
198
- const policy = await prepareConnectorActionApproval(input.db, identity, invocation);
199
- if (policy.managed && policy.decision === "ask") {
200
- throw new AttemptToolApprovalRequiredError();
201
- }
202
- if (policy.managed && policy.decision === "block") {
203
- throw new GitHubRestMutationNotExecutedError(
204
- "GitHub connector action is blocked by policy",
205
- );
206
- }
207
- const admission = await beginConnectorActionExecution(input.db, identity, invocation);
208
- if (!admission.allowed) {
209
- if (admission.reason === "approval_required") {
210
- throw new AttemptToolApprovalRequiredError();
211
- }
212
- throw new GitHubRestMutationNotExecutedError(
213
- `GitHub connector action was not executed: ${admission.reason}`,
214
- );
215
- }
216
- if (admission.managed) executing.set(call.operationId, admission.requestId);
217
- },
218
- complete: async ({ operationId, outcome }) => {
219
- const requestId = executing.get(operationId);
220
- if (!requestId) return;
221
- executing.delete(operationId);
222
- await completeConnectorActionExecution(input.db, {
223
- accountId: input.accountId,
224
- workspaceId: input.workspaceId,
225
- requestId,
226
- attemptId: input.attemptId,
227
- outcome,
228
- });
229
- },
230
148
  };
231
149
  }
232
150
 
@@ -1360,6 +1360,7 @@ export type TurnStartupPhase =
1360
1360
  | "tool_optional_connect"
1361
1361
  | "tool_attempt_catalog_build"
1362
1362
  | "tool_attempt_catalog_persist"
1363
+ | "tool_workspace_gateway_catalog_build"
1363
1364
  | "post_tool_preparation"
1364
1365
  | "agent_construction"
1365
1366
  | "post_agent_preparation"
@@ -1408,6 +1409,9 @@ export type TurnStartupPhase =
1408
1409
  | "model_prepare_runner_before_mcp_tools"
1409
1410
  | "model_prepare_mcp_tools_snapshot"
1410
1411
  | "model_prepare_mcp_tools_before_input_filter"
1412
+ | "model_prepare_mcp_tools_before_repository_skill_discovery"
1413
+ | "model_prepare_repository_skill_discovery"
1414
+ | "model_prepare_repository_skill_discovery_before_input_filter"
1411
1415
  | "model_prepare_input_filter_base"
1412
1416
  | "model_prepare_input_filter_genesis"
1413
1417
  | "model_prepare_input_filter_host"
@@ -17,11 +17,13 @@
17
17
  import { sandboxLifecycleTransitionWaitMs, type Settings } from "@opengeni/config";
18
18
  import {
19
19
  adoptConnectedMachineSessionBackgroundCommand,
20
+ adoptManagedSessionBackgroundCommand,
20
21
  advanceWorkspaceGenerationForRetainedProcess,
21
22
  advanceWorkspaceGeneration,
22
23
  getRetainedProcess,
23
24
  retainWorkspaceMutationProcess,
24
25
  retainedProcessSettlementIdentity,
26
+ settleConnectedMachineSessionBackgroundCommand,
25
27
  settleRetainedProcess,
26
28
  verifyRetainedProcessMutationSettlement,
27
29
  verifyWorkspaceMutationSettlement,
@@ -36,10 +38,6 @@ import {
36
38
  type EnrollmentRecord,
37
39
  type SandboxWorkspaceMutationAdmission,
38
40
  } from "@opengeni/db";
39
- import {
40
- settleConnectedMachineSessionBackgroundCommand,
41
- settleSessionBackgroundCommandForRetainedProcess,
42
- } from "@opengeni/db/session-background-commands";
43
41
  import type { EventBus } from "@opengeni/events";
44
42
  import {
45
43
  buildSelfhostedBackendSession,
@@ -515,10 +513,6 @@ function afterPersistableHomeMutation(
515
513
  admittedWorkspaceGeneration: exactAdmission.workspaceGeneration,
516
514
  operation: op,
517
515
  providerBinding: boundAdmission.providerBinding ?? null,
518
- backgroundCommand: {
519
- commandId: retainedProcess.id,
520
- command: op,
521
- },
522
516
  owner: {
523
517
  kind: "turn",
524
518
  turnId: fence.turnId,
@@ -686,14 +680,50 @@ function settleRetainedProcessForTurn(
686
680
  if (settlement.process.state === "active") {
687
681
  throw new Error("Retained-process settlement returned an active durable process");
688
682
  }
689
- await settleSessionBackgroundCommandForRetainedProcess(services.db, {
683
+ if (settlement.backgroundCommandEvents.length > 0 && services.bus) {
684
+ await services.bus
685
+ .publish(ids.workspaceId, ids.sessionId, settlement.backgroundCommandEvents)
686
+ .catch(() => undefined);
687
+ }
688
+ };
689
+ }
690
+
691
+ function adoptRetainedProcessAsBackgroundCommandForTurn(
692
+ services: RoutingWiringServices,
693
+ ids: RoutingWiringIds,
694
+ ):
695
+ | ((input: { backend: ResolvedActiveBackend; process: RoutingRetainedProcess }) => Promise<void>)
696
+ | undefined {
697
+ const fence = ids.workspaceMutationFence;
698
+ if (!fence) return undefined;
699
+ return async ({ backend, process }) => {
700
+ const durable = await getRetainedProcess(services.db, {
701
+ workspaceId: ids.workspaceId,
702
+ sessionId: ids.sessionId,
703
+ processId: process.id,
704
+ });
705
+ if (
706
+ !durable ||
707
+ durable.providerSessionId !== process.providerSessionId ||
708
+ durable.providerBackend !== backend.kind ||
709
+ durable.providerInstanceId !== backend.providerInstanceId ||
710
+ durable.leaseEpoch !== backend.leaseEpoch ||
711
+ durable.routeKind !== (backend.sandboxId === null ? "home" : "active") ||
712
+ durable.routeTargetId !== backend.sandboxId ||
713
+ durable.routeEpoch !== backend.activeEpoch
714
+ ) {
715
+ throw new Error("Background command adoption lost its exact retained-process identity");
716
+ }
717
+ await adoptManagedSessionBackgroundCommand(services.db, {
690
718
  accountId: fence.accountId,
691
719
  workspaceId: ids.workspaceId,
692
720
  sessionId: ids.sessionId,
693
- retainedProcessId: process.id,
694
- outcome: settlement.process.state,
695
- exitCode: settlement.process.exitCode,
696
- reason: settlement.process.settlementReason ?? proof.reason,
721
+ turnId: fence.turnId,
722
+ executionGeneration: fence.executionGeneration,
723
+ attemptId: fence.attemptId,
724
+ processId: process.id,
725
+ expected: retainedProcessSettlementIdentity(durable),
726
+ command: "execCommand",
697
727
  });
698
728
  };
699
729
  }
@@ -736,6 +766,10 @@ export function wrapTurnBoxWithRouting(
736
766
  const beforeProcessMutation = beforeRetainedProcessMutation(services, ids);
737
767
  const afterProcessMutation = afterRetainedProcessMutation(services, ids);
738
768
  const settleProcess = settleRetainedProcessForTurn(services, ids);
769
+ const adoptProcessAsBackgroundCommand = adoptRetainedProcessAsBackgroundCommandForTurn(
770
+ services,
771
+ ids,
772
+ );
739
773
  const resolver = makeActiveBackendResolver({
740
774
  workspaceId: ids.workspaceId,
741
775
  defaultBackend: established.session as RoutableBackendSession,
@@ -794,7 +828,7 @@ export function wrapTurnBoxWithRouting(
794
828
  return { commandId: adopted.id };
795
829
  },
796
830
  selfhostedSettleBackgroundCommand: async (command) => {
797
- await settleConnectedMachineSessionBackgroundCommand(db, {
831
+ const settlement = await settleConnectedMachineSessionBackgroundCommand(db, {
798
832
  accountId: backgroundCommandAccountId,
799
833
  workspaceId: ids.workspaceId,
800
834
  sessionId: ids.sessionId,
@@ -807,6 +841,11 @@ export function wrapTurnBoxWithRouting(
807
841
  exitCode: command.exitCode,
808
842
  reason: command.reason,
809
843
  });
844
+ if (settlement && bus) {
845
+ await bus
846
+ .publish(ids.workspaceId, ids.sessionId, settlement.events)
847
+ .catch(() => undefined);
848
+ }
810
849
  },
811
850
  }
812
851
  : {}),
@@ -892,6 +931,7 @@ export function wrapTurnBoxWithRouting(
892
931
  ...(beforeProcessMutation ? { beforeProcessMutation } : {}),
893
932
  ...(afterProcessMutation ? { afterProcessMutation } : {}),
894
933
  ...(settleProcess ? { settleProcess } : {}),
934
+ ...(adoptProcessAsBackgroundCommand ? { adoptProcessAsBackgroundCommand } : {}),
895
935
  ...(ids.homeLease
896
936
  ? {
897
937
  onDefaultBackendError: async ({
@@ -970,6 +1010,10 @@ export function wrapLazyTurnBoxWithRouting(
970
1010
  const beforeProcessMutation = beforeRetainedProcessMutation(services, ids);
971
1011
  const afterProcessMutation = afterRetainedProcessMutation(services, ids);
972
1012
  const settleProcess = settleRetainedProcessForTurn(services, ids);
1013
+ const adoptProcessAsBackgroundCommand = adoptRetainedProcessAsBackgroundCommandForTurn(
1014
+ services,
1015
+ ids,
1016
+ );
973
1017
  const defaultBackend = sandboxBackendForSdkBackendId(args.backendId);
974
1018
  const defaultSupportsPty = defaultBackend
975
1019
  ? selectBackend(defaultBackend).capabilities.Terminal.pty
@@ -1038,7 +1082,7 @@ export function wrapLazyTurnBoxWithRouting(
1038
1082
  return { commandId: adopted.id };
1039
1083
  },
1040
1084
  selfhostedSettleBackgroundCommand: async (command) => {
1041
- await settleConnectedMachineSessionBackgroundCommand(db, {
1085
+ const settlement = await settleConnectedMachineSessionBackgroundCommand(db, {
1042
1086
  accountId: backgroundCommandAccountId,
1043
1087
  workspaceId: ids.workspaceId,
1044
1088
  sessionId: ids.sessionId,
@@ -1051,6 +1095,11 @@ export function wrapLazyTurnBoxWithRouting(
1051
1095
  exitCode: command.exitCode,
1052
1096
  reason: command.reason,
1053
1097
  });
1098
+ if (settlement && bus) {
1099
+ await bus
1100
+ .publish(ids.workspaceId, ids.sessionId, settlement.events)
1101
+ .catch(() => undefined);
1102
+ }
1054
1103
  },
1055
1104
  }
1056
1105
  : {}),
@@ -1105,6 +1154,7 @@ export function wrapLazyTurnBoxWithRouting(
1105
1154
  ...(beforeProcessMutation ? { beforeProcessMutation } : {}),
1106
1155
  ...(afterProcessMutation ? { afterProcessMutation } : {}),
1107
1156
  ...(settleProcess ? { settleProcess } : {}),
1157
+ ...(adoptProcessAsBackgroundCommand ? { adoptProcessAsBackgroundCommand } : {}),
1108
1158
  ...(args.homeLeaseIdentity
1109
1159
  ? {
1110
1160
  onDefaultBackendError: async ({
@@ -1383,7 +1433,7 @@ export async function establishSelfhostedTurnSession(
1383
1433
  }
1384
1434
  : {}),
1385
1435
  settleBackgroundCommand: async (command) => {
1386
- await settleConnectedMachineSessionBackgroundCommand(db, {
1436
+ const settlement = await settleConnectedMachineSessionBackgroundCommand(db, {
1387
1437
  accountId: args.accountId,
1388
1438
  workspaceId: args.workspaceId,
1389
1439
  sessionId: args.sessionId,
@@ -1396,6 +1446,11 @@ export async function establishSelfhostedTurnSession(
1396
1446
  exitCode: command.exitCode,
1397
1447
  reason: command.reason,
1398
1448
  });
1449
+ if (settlement && bus) {
1450
+ await bus
1451
+ .publish(args.workspaceId, args.sessionId, settlement.events)
1452
+ .catch(() => undefined);
1453
+ }
1399
1454
  },
1400
1455
  // Meter every control op (out-of-band telemetry) — no-op when unwired.
1401
1456
  ...(onOp !== undefined ? { onOp } : {}),
@@ -20,6 +20,7 @@ type WorkflowControlActivities = Pick<
20
20
  | "recoverDispatch"
21
21
  | "recoverEscapedMcpTimeout"
22
22
  | "settleSessionInterruptions"
23
+ | "settleSessionInputWait"
23
24
  >;
24
25
 
25
26
  /**
@@ -95,6 +95,14 @@ export function deferredResultMayContinue(entryWakeups: number, currentWakeups:
95
95
  return currentWakeups !== entryWakeups;
96
96
  }
97
97
 
98
+ /** A typed activity cancellation is recoverable unless its exact-attempt
99
+ * redispatch budget was atomically exhausted. */
100
+ export function cancelledAttemptRecoveryMayContinue(
101
+ action: activities.RecoverDispatchResult["action"],
102
+ ): boolean {
103
+ return action !== "exceeded";
104
+ }
105
+
98
106
  /**
99
107
  * Bound repeated failures that happen before an attempt row exists. The
100
108
  * activity mirrors this deterministic delay into the durable wake outbox, so
@@ -342,6 +350,10 @@ export async function sessionWorkflow(input: SessionWorkflowInput): Promise<void
342
350
  const writerSetQuiescenceRecovery = patched("session-attempt-writer-set-quiescence-v1");
343
351
  const staleControlSignalIsOnlyWakeHint = patched("session-control-stale-wake-v1");
344
352
  const unclaimedAttemptRecovery = patched("session-unclaimed-attempt-recovery-v1");
353
+ // PR #2208 changed a typed-cancelled result from a plain re-peek into a
354
+ // recoverDispatch activity. Version that new command so histories which
355
+ // already recorded the legacy re-peek remain deterministic on replay.
356
+ const cancelledAttemptRecovery = patched("session-cancelled-attempt-recovery-v1");
345
357
  const turnActivity = turnActivityForTaskQueue(workflowInfo().taskQueue, receiptGatedCancellation);
346
358
  let approvalWakeups = 0;
347
359
  let interruptionWakeups = 0;
@@ -644,6 +656,48 @@ export async function sessionWorkflow(input: SessionWorkflowInput): Promise<void
644
656
  }
645
657
  continue;
646
658
  }
659
+ if (peek.kind === "input-wait") {
660
+ const settlement = await activity.settleSessionInputWait({
661
+ accountId: input.accountId,
662
+ workspaceId: input.workspaceId,
663
+ sessionId: input.sessionId,
664
+ waitTurnId: peek.waitTurnId,
665
+ disposition: peek.disposition,
666
+ });
667
+ if (settlement.action !== "held") continue;
668
+
669
+ // The durable outbox owns the long deadline. Keep this workflow run open
670
+ // only for the same bounded close-race window used by ordinary idle; any
671
+ // signal is a hint to re-peek PostgreSQL truth.
672
+ const seenWakeups = wakeups;
673
+ const seenApprovalWakeups = approvalWakeups;
674
+ const seenInterruptionWakeups = interruptionWakeups;
675
+ const woke = await condition(
676
+ () =>
677
+ interruptionWakeups !== seenInterruptionWakeups ||
678
+ wakeups !== seenWakeups ||
679
+ approvalWakeups !== seenApprovalWakeups,
680
+ "5s",
681
+ );
682
+ if (woke) continue;
683
+ const finalPeek = await activity.peekSessionWork({
684
+ workspaceId: input.workspaceId,
685
+ sessionId: input.sessionId,
686
+ });
687
+ if (
688
+ finalPeek.kind !== "input-wait" ||
689
+ finalPeek.disposition !== "held" ||
690
+ finalPeek.waitTurnId !== peek.waitTurnId
691
+ ) {
692
+ continue;
693
+ }
694
+ await activity.markSessionIdle({
695
+ workspaceId: input.workspaceId,
696
+ sessionId: input.sessionId,
697
+ });
698
+ if (signalVersion !== closeSignalVersion) continue;
699
+ return;
700
+ }
647
701
  if (peek.kind === "idle") {
648
702
  let continuation: activities.MaybeContinueGoalResult = { action: "none" };
649
703
  try {
@@ -663,11 +717,10 @@ export async function sessionWorkflow(input: SessionWorkflowInput): Promise<void
663
717
  });
664
718
  }
665
719
  if (continuation.action === "continue" || continuation.action === "queue") continue;
666
- // `none`, `paused`, `held`, and `deferred` all close this run below. A
667
- // held or deferred (idle-backoff) goal keeps its durable obligation
668
- // armed; the delayed wake-outbox row at the hold/pacing deadline, pending
669
- // machine input, a human prompt, or any producer's signalWithStart
670
- // restarts the workflow. No Temporal timer is used for pacing.
720
+ // `none`, `paused`, and `deferred` all close this run below. A deferred
721
+ // idle-backoff goal keeps its durable obligation armed; the delayed
722
+ // wake-outbox row at the pacing deadline or any producer signal restarts
723
+ // the workflow. No Temporal timer is used for pacing.
671
724
  const seenWakeups = wakeups;
672
725
  const seenApprovalWakeups = approvalWakeups;
673
726
  const seenInterruptionWakeups = interruptionWakeups;
@@ -1052,8 +1105,33 @@ export async function sessionWorkflow(input: SessionWorkflowInput): Promise<void
1052
1105
  return true;
1053
1106
  }
1054
1107
 
1055
- if (outcome.result.status === "failed" || outcome.result.status === "cancelled") {
1056
- return outcome.result.status === "cancelled";
1108
+ if (outcome.result.status === "failed") {
1109
+ return false;
1110
+ }
1111
+
1112
+ if (outcome.result.status === "cancelled") {
1113
+ // Histories created before session-cancelled-attempt-recovery-v1 must
1114
+ // preserve the old command sequence. Their durable state is still safe:
1115
+ // operator recovery or a later fresh workflow run can close a stranded
1116
+ // owner, while new histories use the bounded exact-attempt transaction.
1117
+ if (!cancelledAttemptRecovery) return true;
1118
+ // A typed cancellation is normally observed through the control-signal
1119
+ // branch above, after Pause/Steer has durably fenced the attempt. A
1120
+ // worker can nevertheless return the same shape after a shutdown or a
1121
+ // stale settlement race without closing its attempt row. Blindly
1122
+ // re-peeking then retries forever against `turn.status = running` and
1123
+ // strands every later prompt. Reconcile the exact attempt through the
1124
+ // same bounded, generation-fenced redispatch transaction used after an
1125
+ // activity heartbeat loss. If the attempt actually settled meanwhile,
1126
+ // the transaction is a stale no-op and the next peek observes truth.
1127
+ const recovery = await activity.recoverDispatch({
1128
+ accountId,
1129
+ workspaceId,
1130
+ sessionId,
1131
+ attemptId: outcome.result.attemptId,
1132
+ timeoutType: "HEARTBEAT",
1133
+ });
1134
+ return cancelledAttemptRecoveryMayContinue(recovery.action);
1057
1135
  }
1058
1136
 
1059
1137
  if (outcome.result.capacityWait) {
@@ -1,21 +0,0 @@
1
- import { type IntegrationInvocationAuthority } from "@opengeni/capabilities";
2
- import type { Settings } from "@opengeni/config";
3
- import type { ToolAuthNeededPayload } from "@opengeni/contracts";
4
- import type { ApiIntegrationRuntime, ResolveConnectionCredentialInput, ResolveConnectionCredentialResult } from "@opengeni/db";
5
- import type { LocalMcpServerRegistration } from "@opengeni/runtime";
6
- import type { FetchLike } from "@opengeni/network";
7
- export type BuildApiIntegrationServersInput = {
8
- settings: Settings;
9
- integrations: readonly ApiIntegrationRuntime[];
10
- authority: Omit<IntegrationInvocationAuthority, "connectionRef">;
11
- resolveCredential: (input: ResolveConnectionCredentialInput) => Promise<ResolveConnectionCredentialResult>;
12
- onAuthNeeded?: (payload: ToolAuthNeededPayload) => Promise<void> | void;
13
- fetchImpl?: FetchLike;
14
- };
15
- /**
16
- * Compile active persisted API facets into ordinary in-process MCP servers for
17
- * one exact attempt. Connection resolution remains request-time, destination-
18
- * bound, personal-delegation-fenced, and refreshable through the same worker
19
- * resolver used by remote MCP servers.
20
- */
21
- export declare function buildApiIntegrationServersForTurn(input: BuildApiIntegrationServersInput): LocalMcpServerRegistration[];