@opengeni/worker-bundle 0.20.3 → 0.22.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 (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
@@ -0,0 +1,422 @@
1
+ import type { Agent } from "@openai/agents";
2
+ import {
3
+ OPEN_SUFFIX_RUN_STATE_BLOB,
4
+ approvalIdentifier,
5
+ type HumanInputResponse,
6
+ type SessionEvent,
7
+ } from "@opengeni/contracts";
8
+ import {
9
+ appendSessionHistoryItems,
10
+ getActiveSessionHistoryItems,
11
+ interruptedToolCallResult,
12
+ listTurnOpenSuffixToolCalls,
13
+ nextSessionHistoryPosition,
14
+ recordPendingSessionToolCallResult,
15
+ type Database,
16
+ type OpenSuffixPendingToolCall,
17
+ } from "@opengeni/db";
18
+ import {
19
+ functionCallResultItem,
20
+ invokePreparedAgentTool,
21
+ sanitizeHistoryItemsForModel,
22
+ } from "@opengeni/runtime";
23
+
24
+ export type OpenSuffixResumeOutcome =
25
+ | { action: "continue" }
26
+ | { action: "requires_action" }
27
+ | { action: "cancelled" };
28
+
29
+ type OpenSuffixSettle = (input: {
30
+ events: Array<
31
+ | { type: "session.requiresAction"; payload: { approvals: unknown[] } }
32
+ | { type: "session.status.changed"; payload: { status: "requires_action" } }
33
+ >;
34
+ turnStatus: "requires_action";
35
+ sessionStatus: "requires_action";
36
+ activeTurnId: string;
37
+ runState: {
38
+ serializedRunState: string;
39
+ pendingApprovals: unknown[];
40
+ };
41
+ }) => Promise<boolean>;
42
+
43
+ function argumentsJsonFromCallItem(callItem: Record<string, unknown>): string {
44
+ const raw = callItem.arguments;
45
+ if (typeof raw === "string") {
46
+ return raw;
47
+ }
48
+ return JSON.stringify(raw ?? {});
49
+ }
50
+
51
+ function toolNameFromCallItem(callItem: Record<string, unknown>): string {
52
+ return typeof callItem.name === "string" && callItem.name.length > 0 ? callItem.name : "tool";
53
+ }
54
+
55
+ function pendingApprovalProjection(row: OpenSuffixPendingToolCall): unknown {
56
+ return {
57
+ id: row.callId,
58
+ name: toolNameFromCallItem(row.callItem),
59
+ arguments: row.callItem.arguments ?? null,
60
+ raw: row.callItem,
61
+ };
62
+ }
63
+
64
+ function remainingSuffixApprovals(
65
+ rows: readonly OpenSuffixPendingToolCall[],
66
+ kinds: ReadonlySet<OpenSuffixPendingToolCall["interruptionKind"]>,
67
+ ): unknown[] {
68
+ return rows
69
+ .filter((row) => row.resultItem == null && kinds.has(row.interruptionKind))
70
+ .map(pendingApprovalProjection);
71
+ }
72
+
73
+ /** Matches the original pause `session.requiresAction` payload: ordinary approvals only. */
74
+ export function remainingPendingApprovalsFromSuffix(
75
+ rows: readonly OpenSuffixPendingToolCall[],
76
+ ): unknown[] {
77
+ return remainingSuffixApprovals(rows, new Set(["approval"]));
78
+ }
79
+
80
+ /** Leftover `pendingApprovals` snapshot includes interaction interventions. */
81
+ export function remainingRunStatePendingApprovalsFromSuffix(
82
+ rows: readonly OpenSuffixPendingToolCall[],
83
+ ): unknown[] {
84
+ return remainingSuffixApprovals(rows, new Set(["approval", "interaction_intervention"]));
85
+ }
86
+
87
+ export function openSuffixHistoryItems(
88
+ row: OpenSuffixPendingToolCall,
89
+ resultItem: Record<string, unknown>,
90
+ ): Record<string, unknown>[] {
91
+ return sanitizeHistoryItemsForModel([
92
+ ...row.tiedReasoningItems,
93
+ row.callItem,
94
+ resultItem,
95
+ ]) as Record<string, unknown>[];
96
+ }
97
+
98
+ export function matchingOpenSuffixCallId(input: {
99
+ trigger: Pick<SessionEvent, "type" | "payload">;
100
+ humanInputToolCallId?: string | undefined;
101
+ }): string | null {
102
+ if (input.trigger.type === "user.humanInputResponse") {
103
+ return input.humanInputToolCallId ?? null;
104
+ }
105
+ if (input.trigger.type === "user.approvalDecision") {
106
+ const payload = input.trigger.payload as { approvalId?: unknown };
107
+ return typeof payload.approvalId === "string" ? payload.approvalId : null;
108
+ }
109
+ return null;
110
+ }
111
+
112
+ function historyItemCallId(item: Record<string, unknown>): string | null {
113
+ const value = item.callId ?? item.call_id ?? item.id;
114
+ return typeof value === "string" && value.length > 0 ? value : null;
115
+ }
116
+
117
+ export function resolveOpenSuffixResumeTarget(
118
+ rows: readonly OpenSuffixPendingToolCall[],
119
+ callId: string | null,
120
+ ): OpenSuffixPendingToolCall | null {
121
+ if (!callId) {
122
+ return null;
123
+ }
124
+ return rows.find((row) => row.callId === callId) ?? null;
125
+ }
126
+
127
+ /** True when the paired call and result already exist in durable history. */
128
+ export function openSuffixPairPresentInHistory(
129
+ items: readonly Record<string, unknown>[],
130
+ callId: string,
131
+ ): boolean {
132
+ let sawCall = false;
133
+ for (const item of items) {
134
+ if (historyItemCallId(item) !== callId) {
135
+ continue;
136
+ }
137
+ const type = typeof item.type === "string" ? item.type : null;
138
+ if (type === "function_call" || type === "computer_call") {
139
+ sawCall = true;
140
+ continue;
141
+ }
142
+ if (sawCall && (type === "function_call_result" || type === "computer_call_result")) {
143
+ return true;
144
+ }
145
+ }
146
+ return false;
147
+ }
148
+
149
+ function memberResult(input: {
150
+ callId: string;
151
+ name: string;
152
+ output: unknown;
153
+ resultItem?: Record<string, unknown>;
154
+ }): { resultItem: Record<string, unknown>; eventOutput: unknown } {
155
+ return {
156
+ resultItem:
157
+ input.resultItem ??
158
+ functionCallResultItem({
159
+ callId: input.callId,
160
+ name: input.name,
161
+ output: input.output,
162
+ }),
163
+ eventOutput: input.output,
164
+ };
165
+ }
166
+
167
+ async function resultItemForOpenSuffixMember(input: {
168
+ agent: Agent<any, any>;
169
+ row: OpenSuffixPendingToolCall;
170
+ trigger: Pick<SessionEvent, "type" | "payload">;
171
+ humanInputResume: {
172
+ requestId: string;
173
+ toolCallId: string;
174
+ response: HumanInputResponse;
175
+ } | null;
176
+ }): Promise<{ resultItem: Record<string, unknown>; eventOutput: unknown }> {
177
+ const name = toolNameFromCallItem(input.row.callItem);
178
+ const rejected = (): { resultItem: Record<string, unknown>; eventOutput: unknown } => {
179
+ const payload = input.trigger.payload as { message?: unknown; decision?: unknown };
180
+ const message =
181
+ typeof payload.message === "string" && payload.message.trim().length > 0
182
+ ? payload.message
183
+ : "Tool approval was rejected.";
184
+ const interrupted = interruptedToolCallResult({
185
+ callType: input.row.callType,
186
+ callId: input.row.callId,
187
+ callItem: input.row.callItem,
188
+ reason: message,
189
+ });
190
+ return memberResult({
191
+ callId: input.row.callId,
192
+ name,
193
+ output: message,
194
+ ...(interrupted ? { resultItem: interrupted } : {}),
195
+ });
196
+ };
197
+ if (input.row.interruptionKind === "human_input") {
198
+ if (!input.humanInputResume || input.humanInputResume.toolCallId !== input.row.callId) {
199
+ throw new Error("Human-input open suffix is missing its durable response");
200
+ }
201
+ const output = JSON.stringify({
202
+ requestId: input.humanInputResume.requestId,
203
+ ...input.humanInputResume.response,
204
+ });
205
+ return memberResult({
206
+ callId: input.row.callId,
207
+ name,
208
+ output,
209
+ });
210
+ }
211
+ const payload = input.trigger.payload as { decision?: unknown };
212
+ if (payload.decision !== "approve") {
213
+ return rejected();
214
+ }
215
+ try {
216
+ const output = await invokePreparedAgentTool({
217
+ agent: input.agent,
218
+ toolName: name,
219
+ argumentsJson: argumentsJsonFromCallItem(input.row.callItem),
220
+ callId: input.row.callId,
221
+ });
222
+ return memberResult({
223
+ callId: input.row.callId,
224
+ name,
225
+ output,
226
+ });
227
+ } catch (error) {
228
+ const message = error instanceof Error ? error.message : String(error);
229
+ return memberResult({
230
+ callId: input.row.callId,
231
+ name,
232
+ output: message,
233
+ });
234
+ }
235
+ }
236
+
237
+ export async function settleOpenSuffixResumeIfNeeded(input: {
238
+ db: Database;
239
+ agent: Agent<any, any>;
240
+ accountId: string;
241
+ workspaceId: string;
242
+ sessionId: string;
243
+ turnId: string;
244
+ executionGeneration: number;
245
+ attemptId: string;
246
+ trigger: Pick<SessionEvent, "type" | "payload">;
247
+ humanInputResume: {
248
+ requestId: string;
249
+ toolCallId: string;
250
+ response: HumanInputResponse;
251
+ } | null;
252
+ modelToolOutputTruncationTokens?: number;
253
+ settle: OpenSuffixSettle;
254
+ publish?: (
255
+ events: Array<{ type: "agent.toolCall.output"; payload: { id: string; output: unknown } }>,
256
+ ) => Promise<unknown>;
257
+ }): Promise<OpenSuffixResumeOutcome> {
258
+ if (
259
+ input.trigger.type !== "user.approvalDecision" &&
260
+ input.trigger.type !== "user.humanInputResponse"
261
+ ) {
262
+ return { action: "continue" };
263
+ }
264
+ const rows = await listTurnOpenSuffixToolCalls(
265
+ input.db,
266
+ input.workspaceId,
267
+ input.sessionId,
268
+ input.turnId,
269
+ );
270
+ if (rows.length === 0) {
271
+ return { action: "continue" };
272
+ }
273
+ const callId = matchingOpenSuffixCallId({
274
+ trigger: input.trigger,
275
+ humanInputToolCallId: input.humanInputResume?.toolCallId,
276
+ });
277
+ const target = resolveOpenSuffixResumeTarget(rows, callId);
278
+ if (!target || !callId) {
279
+ throw new Error("Open suffix resume event does not match an interruption");
280
+ }
281
+ const truncationTokens =
282
+ input.modelToolOutputTruncationTokens ?? target.modelToolOutputTruncationTokens ?? undefined;
283
+ let resultItem = target.resultItem;
284
+ let eventOutput: unknown = resultItem?.output;
285
+ if (!resultItem) {
286
+ const member = await resultItemForOpenSuffixMember({
287
+ agent: input.agent,
288
+ row: target,
289
+ trigger: input.trigger,
290
+ humanInputResume: input.humanInputResume,
291
+ });
292
+ resultItem = member.resultItem;
293
+ eventOutput = member.eventOutput;
294
+ const recorded = await recordPendingSessionToolCallResult(input.db, {
295
+ accountId: input.accountId,
296
+ workspaceId: input.workspaceId,
297
+ sessionId: input.sessionId,
298
+ turnId: input.turnId,
299
+ executionGeneration: input.executionGeneration,
300
+ attemptId: input.attemptId,
301
+ callId: target.callId,
302
+ ...(truncationTokens !== undefined
303
+ ? { modelToolOutputTruncationTokens: truncationTokens }
304
+ : {}),
305
+ resultItem,
306
+ eventOutput,
307
+ });
308
+ if (!recorded.accepted) {
309
+ return { action: "cancelled" };
310
+ }
311
+ if (!recorded.recorded) {
312
+ const latest = resolveOpenSuffixResumeTarget(
313
+ await listTurnOpenSuffixToolCalls(
314
+ input.db,
315
+ input.workspaceId,
316
+ input.sessionId,
317
+ input.turnId,
318
+ ),
319
+ callId,
320
+ );
321
+ resultItem = latest?.resultItem ?? resultItem;
322
+ } else if (input.publish) {
323
+ await input.publish([
324
+ {
325
+ type: "agent.toolCall.output",
326
+ payload: { id: target.callId, output: eventOutput },
327
+ },
328
+ ]);
329
+ }
330
+ }
331
+ if (!resultItem) {
332
+ throw new Error(`Open suffix resume for ${target.callId} has no result item`);
333
+ }
334
+ const history = await getActiveSessionHistoryItems(input.db, input.workspaceId, input.sessionId);
335
+ if (
336
+ !openSuffixPairPresentInHistory(
337
+ history.map((row) => row.item),
338
+ callId,
339
+ )
340
+ ) {
341
+ const historyItems = openSuffixHistoryItems(target, resultItem);
342
+ if (historyItems.length === 0) {
343
+ throw new Error(`Open suffix resume for ${target.callId} produced no paired history`);
344
+ }
345
+ const nextPosition = await nextSessionHistoryPosition(
346
+ input.db,
347
+ input.workspaceId,
348
+ input.sessionId,
349
+ );
350
+ const appended = await appendSessionHistoryItems(input.db, {
351
+ accountId: input.accountId,
352
+ workspaceId: input.workspaceId,
353
+ sessionId: input.sessionId,
354
+ turnId: input.turnId,
355
+ expectedExecutionGeneration: input.executionGeneration,
356
+ expectedAttemptId: input.attemptId,
357
+ ...(truncationTokens !== undefined
358
+ ? { modelToolOutputTruncationTokens: truncationTokens }
359
+ : {}),
360
+ items: historyItems.map((item, offset) => ({
361
+ position: nextPosition + offset,
362
+ item,
363
+ })),
364
+ });
365
+ if (!appended) {
366
+ return { action: "cancelled" };
367
+ }
368
+ }
369
+ const remaining = (
370
+ await listTurnOpenSuffixToolCalls(input.db, input.workspaceId, input.sessionId, input.turnId)
371
+ ).filter((row) => row.resultItem == null);
372
+ if (remaining.length === 0) {
373
+ return { action: "continue" };
374
+ }
375
+ const requiresActionApprovals = remainingPendingApprovalsFromSuffix(remaining);
376
+ const pendingApprovals = remainingRunStatePendingApprovalsFromSuffix(remaining);
377
+ const settled = await input.settle({
378
+ events: [
379
+ ...(requiresActionApprovals.length > 0
380
+ ? [
381
+ {
382
+ type: "session.requiresAction" as const,
383
+ payload: { approvals: requiresActionApprovals },
384
+ },
385
+ ]
386
+ : []),
387
+ {
388
+ type: "session.status.changed" as const,
389
+ payload: { status: "requires_action" as const },
390
+ },
391
+ ],
392
+ turnStatus: "requires_action",
393
+ sessionStatus: "requires_action",
394
+ activeTurnId: input.turnId,
395
+ runState: {
396
+ serializedRunState: OPEN_SUFFIX_RUN_STATE_BLOB,
397
+ pendingApprovals,
398
+ },
399
+ });
400
+ return settled ? { action: "requires_action" } : { action: "cancelled" };
401
+ }
402
+
403
+ export function interruptionCallIdsFromPause(input: {
404
+ humanInputRequests: Array<{ toolCallId: string }>;
405
+ interactionInterventionRequests: Array<{ toolCallId: string }>;
406
+ pendingApprovals: unknown[];
407
+ }): string[] {
408
+ const ids = new Set<string>();
409
+ for (const request of input.humanInputRequests) {
410
+ ids.add(request.toolCallId);
411
+ }
412
+ for (const request of input.interactionInterventionRequests) {
413
+ ids.add(request.toolCallId);
414
+ }
415
+ for (const approval of input.pendingApprovals) {
416
+ const id = approvalIdentifier(approval);
417
+ if (id) {
418
+ ids.add(id);
419
+ }
420
+ }
421
+ return [...ids];
422
+ }
@@ -1,11 +1,10 @@
1
- import { CapabilityPack, type PackInstallation } from "@opengeni/contracts";
1
+ import { CapabilityPack } from "@opengeni/contracts";
2
+ import { getWorkspace, listInstalledPortableSkills, type Database } from "@opengeni/db";
2
3
  import {
3
- getWorkspace,
4
- getWorkspacePack,
5
- listInstalledPortableSkills,
6
- listPackInstallations,
7
- type Database,
8
- } from "@opengeni/db";
4
+ legacySandboxRuntimeFromPacks,
5
+ packInstallationUsesLegacyRuntime,
6
+ resolveWorkspaceLegacyRuntimePacks,
7
+ } from "@opengeni/core";
9
8
  import {
10
9
  buildPortableSkillArtifact,
11
10
  type InstalledSkillActivation,
@@ -19,6 +18,7 @@ export {
19
18
  settingsWithRigImage,
20
19
  settingsWithRigProviderImage,
21
20
  } from "./sandbox-images";
21
+ export { packInstallationUsesLegacyRuntime };
22
22
 
23
23
  /**
24
24
  * Legacy pack-scoped runtime compatibility. V2 Pack installations own ordinary
@@ -51,34 +51,11 @@ export async function resolveWorkspacePackRuntime(
51
51
  db: Database,
52
52
  workspaceId: string,
53
53
  ): Promise<WorkspacePackRuntime> {
54
- const installations = await listPackInstallations(db, workspaceId);
55
- const active = installations.filter((installation) => installation.status === "active");
56
- if (active.length === 0) {
57
- return emptyPackRuntime;
58
- }
59
- const packs: CapabilityPack[] = [];
60
- for (const installation of active) {
61
- if (!packInstallationUsesLegacyRuntime(installation)) {
62
- continue;
63
- }
64
- const registration = await getWorkspacePack(db, workspaceId, installation.packId);
65
- if (!registration) {
66
- continue;
67
- }
68
- const parsed = CapabilityPack.safeParse(registration.pack);
69
- if (parsed.success) {
70
- packs.push(parsed.data);
71
- }
72
- }
54
+ const packs = await resolveWorkspaceLegacyRuntimePacks(db, workspaceId);
55
+ if (packs.length === 0) return emptyPackRuntime;
73
56
  return workspacePackRuntimeFromPacks(packs);
74
57
  }
75
58
 
76
- export function packInstallationUsesLegacyRuntime(
77
- installation: Pick<PackInstallation, "manifestSnapshot" | "manifestDigest">,
78
- ): boolean {
79
- return installation.manifestSnapshot === null && installation.manifestDigest === null;
80
- }
81
-
82
59
  /**
83
60
  * Resolves every active immutable Skill through the normalized Plugin/Skill-
84
61
  * Facet ledger. The data layer has already filtered ineffective owner edges;
@@ -128,18 +105,7 @@ export async function resolveWorkspaceInstalledSkillRuntime(
128
105
  * unique. V2 rows never reach this function through runtime resolution.
129
106
  */
130
107
  export function workspacePackRuntimeFromPacks(packs: CapabilityPack[]): WorkspacePackRuntime {
131
- const imagePacks = packs.filter(
132
- (pack) => typeof pack.sandboxImage === "string" && pack.sandboxImage.trim().length > 0,
133
- );
134
- if (imagePacks.length > 1) {
135
- const ids = imagePacks
136
- .map((pack) => pack.id)
137
- .sort()
138
- .join(", ");
139
- throw new Error(
140
- `Multiple enabled packs declare a sandbox image (${ids}). Only one enabled pack per workspace may declare sandboxImage; disable the others and retry.`,
141
- );
142
- }
108
+ const sandboxRuntime = legacySandboxRuntimeFromPacks(packs);
143
109
  const skillActivations: PackSkillActivation[] = [];
144
110
  // Keyed case-insensitively to match the per-pack uniqueness rule in the
145
111
  // CapabilityPack contract (and case-insensitive filesystems).
@@ -168,8 +134,8 @@ export function workspacePackRuntimeFromPacks(packs: CapabilityPack[]): Workspac
168
134
  }
169
135
  }
170
136
  return {
171
- sandboxImage: imagePacks[0]?.sandboxImage?.trim() ?? null,
172
- sandboxProviderImages: imagePacks[0]?.sandboxProviderImages ?? null,
137
+ sandboxImage: sandboxRuntime.sandboxImage,
138
+ sandboxProviderImages: sandboxRuntime.sandboxProviderImages,
173
139
  skillActivations,
174
140
  };
175
141
  }
@@ -198,17 +164,3 @@ export async function resolveWorkspaceAgentInstructions(
198
164
  * the settings pass through untouched, so deployments without packs keep the
199
165
  * global OPENGENI_DOCKER_IMAGE / OPENGENI_MODAL_IMAGE_REF behavior exactly.
200
166
  */
201
- /**
202
- * Layers the rig version's default variable sets BELOW the session's own set:
203
- * the session's values WIN on any key collision (explicit precedence). Both maps
204
- * are already the decrypted-and-merged values (rig defaults merged in listed
205
- * order upstream). Pure and deterministic — given the same inputs it returns the
206
- * same env, which is what keeps a session's box-manifest env stable across turns
207
- * (the rig version is frozen per session, so its default-set list is fixed).
208
- */
209
- export function mergeRigDefaultVariableSetEnvironment(
210
- rigDefaultValues: Record<string, string>,
211
- sessionValues: Record<string, string>,
212
- ): Record<string, string> {
213
- return { ...rigDefaultValues, ...sessionValues };
214
- }
@@ -8,11 +8,13 @@ import {
8
8
  addSessionSystemUpdateWithSourceMutation,
9
9
  claimPendingSessionSystemUpdateOutbox,
10
10
  claimPendingSessionWorkflowWakes,
11
+ childRequiresActionDedupeKey,
11
12
  getSessionSystemUpdateOutboxByDedupeKey,
12
13
  getOrCreateSessionSystemUpdateOutbox,
13
14
  markSessionWorkflowWakeFailed,
14
15
  markSessionSystemUpdateOutboxDeliveredInTransaction,
15
16
  markSessionSystemUpdateOutboxFailed,
17
+ sessionSystemUpdateOutboxKindPayload,
16
18
  type Database,
17
19
  type SessionSystemUpdateOutboxDelivery,
18
20
  } from "@opengeni/db";
@@ -103,41 +105,88 @@ export async function notifyParentOfChildIdle(
103
105
  }
104
106
 
105
107
  /**
106
- * Deliver the exact failure row already committed by turn settlement. This
107
- * layer deliberately cannot create or rewrite the row: the settlement
108
- * transaction is the sole owner of the failed turn id, payload, and lineage.
108
+ * Deliver one exact child-lifecycle outbox row already committed by the
109
+ * child's own lifecycle transaction (turn failure, requires_action freeze,
110
+ * ...). This layer deliberately cannot create or rewrite the row: the
111
+ * producing transaction is the sole owner of its payload and lineage, and the
112
+ * global reconciler remains the recovery path if immediate delivery fails.
109
113
  */
110
- export async function deliverFailedChildTurnToParent(
114
+ export async function deliverChildLifecycleOutboxToParent(
111
115
  svc: NotifyServices,
112
116
  workspaceId: string,
113
117
  childSessionId: string,
114
- turnId: string,
118
+ dedupeKey: string,
119
+ options: { requireRow?: boolean } = {},
115
120
  ): Promise<void> {
116
121
  try {
117
122
  const child = await getSession(svc.db, workspaceId, childSessionId);
118
123
  if (!child || !child.parentSessionId) return;
119
- const dedupeKey = `child-completion:${childSessionId}:turn:${turnId}`;
120
124
  const outbox = await getSessionSystemUpdateOutboxByDedupeKey(svc.db, {
121
125
  accountId: child.accountId,
122
126
  workspaceId,
123
127
  dedupeKey,
124
128
  });
125
129
  if (!outbox) {
126
- throw new Error(`Committed failed-child outbox disappeared: ${dedupeKey}`);
130
+ if (options.requireRow === false) return;
131
+ throw new Error(`Committed child-lifecycle outbox disappeared: ${dedupeKey}`);
127
132
  }
128
133
  if (outbox.status === "delivered") return;
129
134
  await deliverParentSystemUpdateOutbox(svc, outbox);
130
135
  } catch (error) {
131
- // Settlement already committed the retryable outbox row. The global
132
- // reconciler remains the recovery path if immediate delivery fails.
133
- svc.observability.error("Failed to deliver committed child-turn failure", {
136
+ svc.observability.error("Failed to deliver committed child-lifecycle notice", {
134
137
  childSessionId,
135
- turnId,
138
+ dedupeKey,
136
139
  error: error instanceof Error ? error.message : String(error),
137
140
  });
138
141
  }
139
142
  }
140
143
 
144
+ /**
145
+ * Deliver the exact failure row already committed by turn settlement. This
146
+ * layer deliberately cannot create or rewrite the row: the settlement
147
+ * transaction is the sole owner of the failed turn id, payload, and lineage.
148
+ */
149
+ export async function deliverFailedChildTurnToParent(
150
+ svc: NotifyServices,
151
+ workspaceId: string,
152
+ childSessionId: string,
153
+ turnId: string,
154
+ ): Promise<void> {
155
+ await deliverChildLifecycleOutboxToParent(
156
+ svc,
157
+ workspaceId,
158
+ childSessionId,
159
+ `child-completion:${childSessionId}:turn:${turnId}`,
160
+ );
161
+ }
162
+
163
+ /**
164
+ * Deliver the child_requires_action notice a requires_action settlement
165
+ * committed for this exact (child, turn, generation). When the rollout flag is
166
+ * off no row exists and this is a no-op; the reaper covers crashes after commit.
167
+ */
168
+ export async function deliverChildRequiresActionToParent(
169
+ svc: NotifyServices,
170
+ workspaceId: string,
171
+ childSessionId: string,
172
+ input: { turnId: string; turnGeneration: number },
173
+ ): Promise<void> {
174
+ if (!svc.settings.childLifecycleNoticesEnabled) return;
175
+ await deliverChildLifecycleOutboxToParent(
176
+ svc,
177
+ workspaceId,
178
+ childSessionId,
179
+ childRequiresActionDedupeKey({
180
+ childSessionId,
181
+ turnId: input.turnId,
182
+ turnGeneration: input.turnGeneration,
183
+ }),
184
+ // A requires_action freeze without any human-input/approval request (or a
185
+ // child without a parent) commits no row; that is not an error.
186
+ { requireRow: false },
187
+ );
188
+ }
189
+
141
190
  async function deliverParentSystemUpdateOutbox(
142
191
  svc: NotifyServices,
143
192
  outbox: SessionSystemUpdateOutboxDelivery,
@@ -149,12 +198,11 @@ async function deliverParentSystemUpdateOutbox(
149
198
  accountId: outbox.accountId,
150
199
  workspaceId: outbox.workspaceId,
151
200
  sessionId: outbox.targetSessionId,
152
- kind: outbox.kind,
201
+ ...sessionSystemUpdateOutboxKindPayload(outbox),
153
202
  classification: outbox.classification,
154
203
  sourceId: outbox.sourceId,
155
204
  dedupeKey: outbox.dedupeKey,
156
205
  summary: outbox.summary,
157
- payload: outbox.payload,
158
206
  lineage: outbox.lineage,
159
207
  personalConnectionDelegations: outbox.personalConnectionDelegations,
160
208
  xaiProviderAccountAuthoritySnapshot: outbox.xaiProviderAccountAuthoritySnapshot,
@@ -181,10 +229,12 @@ async function deliverParentSystemUpdateOutbox(
181
229
  wakeRevision: result.workflowWakeRevision,
182
230
  });
183
231
  }
184
- svc.observability.info("Woke parent session on worker completion", {
232
+ svc.observability.info("Delivered child lifecycle notice to parent session", {
185
233
  childSessionId: outbox.sourceSessionId,
186
234
  parentSessionId: outbox.targetSessionId,
235
+ kind: outbox.kind,
187
236
  dedupeKey: outbox.dedupeKey,
237
+ woke: result.shouldWake,
188
238
  });
189
239
  } catch (error) {
190
240
  await markSessionSystemUpdateOutboxFailed(
@@ -5,7 +5,7 @@ import {
5
5
  promoteRetainedScreenshotMaintenanceCleanup,
6
6
  type RetainedScreenshotMaintenanceClaim,
7
7
  } from "@opengeni/db";
8
- import type { ObjectHead, ObjectStorage } from "@opengeni/storage";
8
+ import { retryWhileMissing, type ObjectHead, type ObjectStorage } from "@opengeni/storage";
9
9
  import type { ControlActivityServices } from "./types";
10
10
 
11
11
  export const RETAINED_SCREENSHOT_PENDING_GRACE_MS = 15 * 60 * 1_000;
@@ -168,8 +168,11 @@ async function observeClaimObject(
168
168
  provider: Required<Pick<RetainedScreenshotMaintenanceActivityOptions, "fileExists" | "headFile">>,
169
169
  ): Promise<"matches" | "mismatch" | "missing"> {
170
170
  const file = claimFile(storage, claim);
171
- if (!(await provider.fileExists(storage, file))) return "missing";
172
- const head = await provider.headFile(storage, file);
171
+ const head = await retryWhileMissing(async () => {
172
+ if (!(await provider.fileExists(storage, file))) return null;
173
+ return await provider.headFile(storage, file);
174
+ });
175
+ if (!head) return "missing";
173
176
  return head.ContentLength === claim.sizeBytes &&
174
177
  head.ContentType === claim.mediaType &&
175
178
  head.Metadata?.sha256 === claim.sha256