@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
@@ -0,0 +1,722 @@
1
+ import { isSessionCompactionRequested } from "@opengeni/db";
2
+ import { publishDurableSessionEvents } from "@opengeni/events";
3
+ import {
4
+ appendSessionInstructions,
5
+ appendWorkspaceGovernance,
6
+ appendWorkspaceMemory,
7
+ composeAgentInstructions,
8
+ requestRemoteCompactionV2,
9
+ serializedToolsForRemoteCompaction,
10
+ EmptyCompactionSummaryError,
11
+ SUMMARY_BUFFER_TOKENS,
12
+ type ModelResponseUsage,
13
+ } from "@opengeni/runtime";
14
+ import { type Settings } from "@opengeni/config";
15
+ import { maybeCompactContext, settleFailedContextCompactionLandmark } from "../context-compaction";
16
+ import type { CompactionSummarizer, RemoteCompactionV2Requester } from "../context-compaction";
17
+ import { TurnAttemptFencedError } from "../turn-attempt-fenced";
18
+ import type {
19
+ TurnActivityServices as ActivityServices,
20
+ RunAgentTurnInput,
21
+ RunAgentTurnResult,
22
+ } from "../types";
23
+ import { recordContextCompaction } from "../../observability-metrics";
24
+ import { createTurnCredentialLeases } from "./credential-leases";
25
+ import { createTurnMediaArtifacts } from "./media-artifacts";
26
+ import { type SessionEvent } from "@opengeni/contracts";
27
+
28
+ import { acceptsPromptCacheKeyForTurn } from "./codex";
29
+ import {
30
+ safeErrorDiagnostic,
31
+ compactionFailureReasonFromError,
32
+ isCompactionSummaryFailure,
33
+ shouldRecoverCompactionProviderFailure,
34
+ } from "./errors";
35
+ import {
36
+ createCompactionModelUsageEventState,
37
+ processCompactionModelUsageEvent,
38
+ } from "./model-usage";
39
+ import { waitForTurnOperation } from "./sandbox-provision";
40
+
41
+ import type { ClaimTurnOk } from "./claim";
42
+ import type { GovernanceModelOk } from "./governance-model";
43
+ import type {
44
+ AttemptIdentityState,
45
+ BillingState,
46
+ ClaimedResult,
47
+ EventingState,
48
+ ProviderTurnState,
49
+ TurnControlState,
50
+ } from "./turn-context";
51
+
52
+ export type RemoteCompactionPrefix = {
53
+ tools: Awaited<ReturnType<typeof serializedToolsForRemoteCompaction>>;
54
+ instructions: string;
55
+ toolsReady: boolean;
56
+ agent: Parameters<typeof serializedToolsForRemoteCompaction>[0] | null;
57
+ };
58
+
59
+ export type CompactionPrepDeps = {
60
+ input: RunAgentTurnInput;
61
+ settings: Settings;
62
+ db: ActivityServices["db"];
63
+ bus: ActivityServices["bus"];
64
+ observability: ActivityServices["observability"];
65
+ cancellationSignal: AbortSignal | undefined;
66
+ control: TurnControlState;
67
+ attempt: AttemptIdentityState;
68
+ billingState: BillingState;
69
+ eventing: EventingState & {
70
+ publish: NonNullable<EventingState["publish"]>;
71
+ settle: NonNullable<EventingState["settle"]>;
72
+ };
73
+ providerTurn: ProviderTurnState;
74
+ leases: ReturnType<typeof createTurnCredentialLeases>;
75
+ media: ReturnType<typeof createTurnMediaArtifacts>;
76
+ claimedResult: ClaimedResult;
77
+ claimedModelUsageSourceKeys: Set<string>;
78
+ emittedModelUsageSourceKeys: Set<string>;
79
+ modelUsageDispatchId: string;
80
+ turn: ClaimTurnOk["turn"];
81
+ session: ClaimTurnOk["session"];
82
+ turnExecutionPolicy: ClaimTurnOk["turnExecutionPolicy"];
83
+ resolvedModel: GovernanceModelOk["resolvedModel"];
84
+ workspaceAgentInstructions: GovernanceModelOk["workspaceAgentInstructions"];
85
+ workspaceGovernance: GovernanceModelOk["workspaceGovernance"];
86
+ structuredWorkspacePolicyActive: GovernanceModelOk["structuredWorkspacePolicyActive"];
87
+ workspaceMemory: GovernanceModelOk["workspaceMemory"];
88
+ rigVersion: GovernanceModelOk["rigVersion"];
89
+ rigName: GovernanceModelOk["rigName"];
90
+ compactionModelHistoryProjector: GovernanceModelOk["compactionModelHistoryProjector"];
91
+ summarizeContextForCompaction: ActivityServices["summarizeContextForCompaction"];
92
+ withProviderRequestContext: <T>(fn: () => Promise<T>) => Promise<T>;
93
+ withCodexRemoteCompaction: <T>(fn: () => Promise<T>) => Promise<T>;
94
+ };
95
+
96
+ export type CompactionPrepOk = {
97
+ promptCacheKey: string | undefined;
98
+ remotePrefix: RemoteCompactionPrefix;
99
+ remoteCompactionRequester: RemoteCompactionV2Requester | undefined;
100
+ publishCompactionLiveEvents: (events: SessionEvent[]) => Promise<void>;
101
+ publishCompactionOutcomeEvents: (events: SessionEvent[]) => Promise<void>;
102
+ compactionModeOptions: NonNullable<Parameters<typeof maybeCompactContext>[5]>;
103
+ compactionOnlyTurn: boolean;
104
+ compactionSummarizerFor: (systemInstructions?: string) => CompactionSummarizer;
105
+ };
106
+
107
+ export type CompactionPrepOutcome = { exit: RunAgentTurnResult } | { ok: CompactionPrepOk };
108
+
109
+ export type PostAgentCompactionDeps = CompactionPrepDeps & {
110
+ remotePrefix: RemoteCompactionPrefix;
111
+ remoteCompactionRequester: CompactionPrepOk["remoteCompactionRequester"];
112
+ publishCompactionLiveEvents: CompactionPrepOk["publishCompactionLiveEvents"];
113
+ publishCompactionOutcomeEvents: CompactionPrepOk["publishCompactionOutcomeEvents"];
114
+ compactionModeOptions: CompactionPrepOk["compactionModeOptions"];
115
+ compactionOnlyTurn: boolean;
116
+ compactionSummarizerFor: CompactionPrepOk["compactionSummarizerFor"];
117
+ agent: ReturnType<ActivityServices["runtime"]["buildAgent"]>;
118
+ };
119
+
120
+ export type PostAgentCompactionOk = {
121
+ compactSummarizer: ReturnType<CompactionPrepOk["compactionSummarizerFor"]>;
122
+ };
123
+
124
+ export type PostAgentCompactionOutcome =
125
+ | { exit: RunAgentTurnResult }
126
+ | { ok: PostAgentCompactionOk };
127
+
128
+ export async function prepareCompaction(deps: CompactionPrepDeps): Promise<CompactionPrepOutcome> {
129
+ const {
130
+ input,
131
+ settings,
132
+ db,
133
+ bus,
134
+ observability,
135
+ cancellationSignal,
136
+ control,
137
+ attempt,
138
+ billingState,
139
+ eventing,
140
+ providerTurn,
141
+ leases,
142
+ media,
143
+ claimedResult,
144
+ claimedModelUsageSourceKeys,
145
+ emittedModelUsageSourceKeys,
146
+ modelUsageDispatchId,
147
+ turn,
148
+ session,
149
+ turnExecutionPolicy,
150
+ resolvedModel,
151
+ workspaceAgentInstructions,
152
+ workspaceGovernance,
153
+ structuredWorkspacePolicyActive,
154
+ workspaceMemory,
155
+ rigVersion,
156
+ rigName,
157
+ compactionModelHistoryProjector,
158
+ summarizeContextForCompaction,
159
+ withProviderRequestContext,
160
+ withCodexRemoteCompaction,
161
+ } = deps;
162
+
163
+ const remotePrefix: RemoteCompactionPrefix = {
164
+ tools: [],
165
+ instructions: "",
166
+ toolsReady: false,
167
+ agent: null,
168
+ };
169
+
170
+ const promptCacheKey = acceptsPromptCacheKeyForTurn(resolvedModel) ? input.sessionId : undefined;
171
+ const compactionUsageState = createCompactionModelUsageEventState(claimedModelUsageSourceKeys);
172
+ const recordCompactionUsage = async (usage: ModelResponseUsage) => {
173
+ await processCompactionModelUsageEvent({
174
+ usage,
175
+ state: compactionUsageState,
176
+ dispatchId: modelUsageDispatchId,
177
+ settings,
178
+ db,
179
+ observability,
180
+ publish: eventing.publish,
181
+ accountId: input.accountId,
182
+ workspaceId: input.workspaceId,
183
+ sessionId: input.sessionId,
184
+ turnId: turn.id,
185
+ provider: resolvedModel?.provider.id ?? settings.openaiProvider,
186
+ providerApi: resolvedModel?.provider.api ?? "responses",
187
+ model: resolvedModel?.configured.id ?? turn.model,
188
+ externallyBilled: billingState.isExternallyBilledTurn,
189
+ turnAttemptId: input.attemptId,
190
+ servingCredentialId: providerTurn.effectiveCodexCredentialId,
191
+ priorSessionCredentialId: providerTurn.priorSessionCodexCredentialId,
192
+ emittedSourceKeys: emittedModelUsageSourceKeys,
193
+ renewLease: () => leases.renewServing("model_usage"),
194
+ leaseLost: leases.servingLost,
195
+ leaseLostMessage: "Provider credential lease expired during context compaction",
196
+ contextContributions: eventing.companyBrainContextContributions,
197
+ });
198
+ };
199
+ const compactionSummarizerFor = (systemInstructions?: string) =>
200
+ resolvedModel
201
+ ? (s: Settings, m: Array<Record<string, unknown>>) =>
202
+ withProviderRequestContext(() =>
203
+ summarizeContextForCompaction(s, m, {
204
+ client: resolvedModel.client,
205
+ provider: resolvedModel.provider,
206
+ api: resolvedModel.provider.api,
207
+ model: turnExecutionPolicy.upstreamModelId,
208
+ maxOutputTokens: SUMMARY_BUFFER_TOKENS,
209
+ onUsage: recordCompactionUsage,
210
+ ...(systemInstructions ? { systemInstructions } : {}),
211
+ ...(promptCacheKey ? { promptCacheKey } : {}),
212
+ }),
213
+ )
214
+ : (s: Settings, m: Array<Record<string, unknown>>) =>
215
+ summarizeContextForCompaction(s, m, {
216
+ model: turnExecutionPolicy.upstreamModelId,
217
+ maxOutputTokens: SUMMARY_BUFFER_TOKENS,
218
+ onUsage: recordCompactionUsage,
219
+ ...(systemInstructions ? { systemInstructions } : {}),
220
+ ...(promptCacheKey ? { promptCacheKey } : {}),
221
+ });
222
+ // Prompt-cache prefix for remote_v2 MUST match ordinary turns:
223
+ // tools → instructions → history. Filled after buildAgent for every
224
+ // compact path (including operator /compact, which now builds the agent
225
+ // first so it does not send empty tools/instructions).
226
+ const remoteCompactionRequester =
227
+ resolvedModel && billingState.isCodexTurn
228
+ ? (s: Settings, m: Array<Record<string, unknown>>) =>
229
+ withCodexRemoteCompaction(async () => {
230
+ // Lazily serialize tools here so EmptyCompactionSummaryError is
231
+ // thrown inside the compaction try/settlement handlers, not as a
232
+ // raw activity failure before maybeCompactContext runs.
233
+ if (!remotePrefix.instructions.trim()) {
234
+ throw new EmptyCompactionSummaryError({
235
+ stage: "remote_v2_instructions",
236
+ reason: "agent_missing_system_instructions",
237
+ });
238
+ }
239
+ if (!remotePrefix.toolsReady) {
240
+ if (!remotePrefix.agent) {
241
+ throw new EmptyCompactionSummaryError({
242
+ stage: "remote_v2_tools",
243
+ reason: "agent_missing_for_tools",
244
+ });
245
+ }
246
+ try {
247
+ remotePrefix.tools = await serializedToolsForRemoteCompaction(remotePrefix.agent);
248
+ } catch (error) {
249
+ // Tool schemas sit before instructions in the cache prefix.
250
+ // Failing open to [] would reintroduce a massive pre-compact
251
+ // cache bust — fail closed so we never send a tools mismatch
252
+ // on purpose.
253
+ throw new EmptyCompactionSummaryError({
254
+ stage: "remote_v2_tools",
255
+ reason: "serialize_tools_failed",
256
+ error: String(error),
257
+ });
258
+ }
259
+ remotePrefix.toolsReady = true;
260
+ }
261
+ return requestRemoteCompactionV2(s, m, {
262
+ client: resolvedModel.client,
263
+ provider: resolvedModel.provider,
264
+ model: turnExecutionPolicy.upstreamModelId,
265
+ systemInstructions: remotePrefix.instructions,
266
+ onUsage: recordCompactionUsage,
267
+ tools: remotePrefix.tools,
268
+ ...(promptCacheKey ? { promptCacheKey } : {}),
269
+ });
270
+ })
271
+ : undefined;
272
+ const publishCompactionLiveEvents = async (events: SessionEvent[]) => {
273
+ await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, events);
274
+ };
275
+ const publishCompactionOutcomeEvents = async (events: SessionEvent[]) => {
276
+ // `compaction.started` was already fanout via publishCompactionLiveEvents.
277
+ await publishDurableSessionEvents(
278
+ bus,
279
+ input.workspaceId,
280
+ input.sessionId,
281
+ events.filter((event) => event.type !== "session.context.compaction.started"),
282
+ );
283
+ };
284
+ const compactionModeOptions = {
285
+ codexCompactionMode: session.codexCompactionMode,
286
+ isCodexSubscriptionTurn: billingState.isCodexTurn,
287
+ publishLiveEvents: publishCompactionLiveEvents,
288
+ ...(remoteCompactionRequester ? { requestRemoteCompactionV2: remoteCompactionRequester } : {}),
289
+ } as const;
290
+
291
+ // Operator /compact:
292
+ // - portable (incl. Codex portable): early maintenance path — no
293
+ // prepareTools/sandbox; summarizer only needs composed instructions.
294
+ // - remote_v2: fall through to prepareTools/buildAgent so the compact
295
+ // request reuses the ordinary tools→instructions cache prefix, then
296
+ // settle without inference. (Requester is also wired for Codex portable
297
+ // turns but unused there — gate on the frozen session mode.)
298
+ const compactionOnlyTurn = turn.source === "compaction";
299
+ const remoteV2CompactionNeedsAgentPrefix =
300
+ Boolean(remoteCompactionRequester) && session.codexCompactionMode === "remote_v2";
301
+ if (compactionOnlyTurn && !remoteV2CompactionNeedsAgentPrefix) {
302
+ const compactionInstructions = appendWorkspaceMemory(
303
+ appendSessionInstructions(
304
+ appendWorkspaceGovernance(
305
+ composeAgentInstructions(
306
+ structuredWorkspacePolicyActive
307
+ ? eventing.modelRunSettings.agentInstructionsTemplate
308
+ : (workspaceAgentInstructions ?? eventing.modelRunSettings.agentInstructionsTemplate),
309
+ undefined,
310
+ rigVersion && rigName ? { name: rigName, version: rigVersion.version } : undefined,
311
+ ),
312
+ workspaceGovernance ?? undefined,
313
+ ),
314
+ session.instructions ?? undefined,
315
+ ),
316
+ workspaceMemory ?? undefined,
317
+ );
318
+ const requested = await isSessionCompactionRequested(db, input.workspaceId, input.sessionId);
319
+ let outcome: Awaited<ReturnType<typeof maybeCompactContext>> | null = null;
320
+ if (requested) {
321
+ try {
322
+ outcome = await waitForTurnOperation(
323
+ maybeCompactContext(
324
+ db,
325
+ eventing.modelRunSettings,
326
+ {
327
+ accountId: input.accountId,
328
+ workspaceId: input.workspaceId,
329
+ sessionId: input.sessionId,
330
+ turnId: turn.id,
331
+ executionGeneration: attempt.executionGeneration,
332
+ attemptId: input.attemptId,
333
+ },
334
+ session.lastInputTokens,
335
+ compactionSummarizerFor(compactionInstructions),
336
+ {
337
+ force: true,
338
+ clearRequestedCompaction: true,
339
+ trigger: "operator",
340
+ materializeHistory: media.materializeScreenshotHistory,
341
+ projectModelInput: compactionModelHistoryProjector,
342
+ ...compactionModeOptions,
343
+ },
344
+ ),
345
+ cancellationSignal,
346
+ undefined,
347
+ );
348
+ } catch (error) {
349
+ // Codex retries retryable checkpoint-provider failures rather than
350
+ // treating them as a semantic compaction result. Keep the operator
351
+ // request pending and let the ordinary same-turn provider/capacity
352
+ // recovery path re-dispatch this exact maintenance execution.
353
+ if (shouldRecoverCompactionProviderFailure(error)) throw error;
354
+ if (error instanceof TurnAttemptFencedError) throw error;
355
+ // `compaction.started` may already be live — settle skipped before
356
+ // failing the turn so the timeline cannot stick on Compacting…
357
+ const landmark = await settleFailedContextCompactionLandmark(
358
+ db,
359
+ {
360
+ accountId: input.accountId,
361
+ workspaceId: input.workspaceId,
362
+ sessionId: input.sessionId,
363
+ turnId: turn.id,
364
+ executionGeneration: attempt.executionGeneration,
365
+ attemptId: input.attemptId,
366
+ },
367
+ {
368
+ clearRequestedCompaction: true,
369
+ publishLiveEvents: publishCompactionLiveEvents,
370
+ },
371
+ );
372
+ if (!isCompactionSummaryFailure(error)) throw error;
373
+ const errorMessage = String(compactionFailureReasonFromError(error));
374
+ if (
375
+ !(await eventing.settle!({
376
+ events: [
377
+ {
378
+ type: "turn.failed",
379
+ payload: {
380
+ error: errorMessage,
381
+ code: "context_compaction_failed",
382
+ retryable: false,
383
+ recovery: "user_message",
384
+ compacted: false,
385
+ },
386
+ },
387
+ {
388
+ type: "session.status.changed",
389
+ payload: { status: "idle" },
390
+ },
391
+ ],
392
+ turnStatus: "failed",
393
+ sessionStatus: "idle",
394
+ activeTurnId: null,
395
+ ...(landmark.requestConsumed ? {} : { consumeRequestedCompactionFailure: true }),
396
+ }))
397
+ ) {
398
+ return { exit: claimedResult({ status: "cancelled" }) };
399
+ }
400
+ control.turnMetricOutcome = "failed";
401
+ control.activityStatus = "idle";
402
+ control.activityError = error;
403
+ return { exit: claimedResult({ status: "idle" }) };
404
+ }
405
+ if (outcome.events.length > 0) {
406
+ if (outcome.compacted) {
407
+ recordContextCompaction(observability, "operator");
408
+ }
409
+ await publishCompactionOutcomeEvents(outcome.events);
410
+ }
411
+ }
412
+ if (
413
+ !(await eventing.settle!({
414
+ events: [
415
+ {
416
+ type: "turn.completed",
417
+ payload: {
418
+ maintenance: "context_compaction",
419
+ result: outcome?.compacted ? "compacted" : (outcome?.reason ?? "already_applied"),
420
+ },
421
+ },
422
+ { type: "session.status.changed", payload: { status: "idle" } },
423
+ ],
424
+ turnStatus: "completed",
425
+ sessionStatus: "idle",
426
+ activeTurnId: null,
427
+ }))
428
+ ) {
429
+ return { exit: claimedResult({ status: "cancelled" }) };
430
+ }
431
+ control.turnMetricOutcome = "completed";
432
+ control.activityStatus = "idle";
433
+ return { exit: claimedResult({ status: "idle" }) };
434
+ }
435
+
436
+ return {
437
+ ok: {
438
+ promptCacheKey,
439
+ remotePrefix,
440
+ remoteCompactionRequester,
441
+ publishCompactionLiveEvents,
442
+ publishCompactionOutcomeEvents,
443
+ compactionModeOptions,
444
+ compactionOnlyTurn,
445
+ compactionSummarizerFor,
446
+ },
447
+ };
448
+ }
449
+
450
+ export async function runPostAgentCompaction(
451
+ deps: PostAgentCompactionDeps,
452
+ ): Promise<PostAgentCompactionOutcome> {
453
+ const {
454
+ input,
455
+ db,
456
+ observability,
457
+ cancellationSignal,
458
+ control,
459
+ attempt,
460
+ eventing,
461
+ claimedResult,
462
+ turn,
463
+ session,
464
+ remotePrefix,
465
+ remoteCompactionRequester,
466
+ publishCompactionLiveEvents,
467
+ publishCompactionOutcomeEvents,
468
+ compactionModeOptions,
469
+ compactionOnlyTurn,
470
+ compactionSummarizerFor,
471
+ compactionModelHistoryProjector,
472
+ media,
473
+ agent,
474
+ } = deps;
475
+
476
+ const agentInstructions = typeof agent.instructions === "string" ? agent.instructions : "";
477
+ const compactSummarizer = compactionSummarizerFor(
478
+ agentInstructions.trim() ? agentInstructions : undefined,
479
+ );
480
+ if (remoteCompactionRequester) {
481
+ // Exact byte match with the ordinary turn prefix (CLI base_instructions).
482
+ // Tools serialize lazily inside the requester so setup failures settle as
483
+ // compaction failures rather than raw activity crashes.
484
+ remotePrefix.instructions = agentInstructions;
485
+ remotePrefix.agent = agent;
486
+ }
487
+
488
+ if (compactionOnlyTurn) {
489
+ const requested = await isSessionCompactionRequested(db, input.workspaceId, input.sessionId);
490
+ let outcome: Awaited<ReturnType<typeof maybeCompactContext>> | null = null;
491
+ if (requested) {
492
+ try {
493
+ outcome = await waitForTurnOperation(
494
+ maybeCompactContext(
495
+ db,
496
+ eventing.modelRunSettings,
497
+ {
498
+ accountId: input.accountId,
499
+ workspaceId: input.workspaceId,
500
+ sessionId: input.sessionId,
501
+ turnId: turn.id,
502
+ executionGeneration: attempt.executionGeneration,
503
+ attemptId: input.attemptId,
504
+ },
505
+ session.lastInputTokens,
506
+ compactSummarizer,
507
+ {
508
+ force: true,
509
+ clearRequestedCompaction: true,
510
+ trigger: "operator",
511
+ projectModelInput: compactionModelHistoryProjector,
512
+ ...compactionModeOptions,
513
+ },
514
+ ),
515
+ cancellationSignal,
516
+ undefined,
517
+ );
518
+ } catch (error) {
519
+ // Codex retries retryable checkpoint-provider failures rather than
520
+ // treating them as a semantic compaction result. Keep the operator
521
+ // request pending and let the ordinary same-turn provider/capacity
522
+ // recovery path re-dispatch this exact maintenance execution.
523
+ if (shouldRecoverCompactionProviderFailure(error)) throw error;
524
+ if (error instanceof TurnAttemptFencedError) throw error;
525
+ const landmark = await settleFailedContextCompactionLandmark(
526
+ db,
527
+ {
528
+ accountId: input.accountId,
529
+ workspaceId: input.workspaceId,
530
+ sessionId: input.sessionId,
531
+ turnId: turn.id,
532
+ executionGeneration: attempt.executionGeneration,
533
+ attemptId: input.attemptId,
534
+ },
535
+ {
536
+ clearRequestedCompaction: true,
537
+ publishLiveEvents: publishCompactionLiveEvents,
538
+ },
539
+ );
540
+ if (!isCompactionSummaryFailure(error)) throw error;
541
+ const errorMessage = String(compactionFailureReasonFromError(error));
542
+ if (
543
+ !(await eventing.settle!({
544
+ events: [
545
+ {
546
+ type: "turn.failed",
547
+ payload: {
548
+ error: errorMessage,
549
+ code: "context_compaction_failed",
550
+ retryable: false,
551
+ recovery: "user_message",
552
+ compacted: false,
553
+ },
554
+ },
555
+ {
556
+ type: "session.status.changed",
557
+ payload: { status: "idle" },
558
+ },
559
+ ],
560
+ turnStatus: "failed",
561
+ sessionStatus: "idle",
562
+ activeTurnId: null,
563
+ ...(landmark.requestConsumed ? {} : { consumeRequestedCompactionFailure: true }),
564
+ }))
565
+ ) {
566
+ return { exit: claimedResult({ status: "cancelled" }) };
567
+ }
568
+ control.turnMetricOutcome = "failed";
569
+ control.activityStatus = "idle";
570
+ control.activityError = error;
571
+ return { exit: claimedResult({ status: "idle" }) };
572
+ }
573
+ if (outcome.events.length > 0) {
574
+ if (outcome.compacted) {
575
+ recordContextCompaction(observability, "operator");
576
+ }
577
+ await publishCompactionOutcomeEvents(outcome.events);
578
+ }
579
+ }
580
+ if (
581
+ !(await eventing.settle!({
582
+ events: [
583
+ {
584
+ type: "turn.completed",
585
+ payload: {
586
+ maintenance: "context_compaction",
587
+ result: outcome?.compacted ? "compacted" : (outcome?.reason ?? "already_applied"),
588
+ },
589
+ },
590
+ { type: "session.status.changed", payload: { status: "idle" } },
591
+ ],
592
+ turnStatus: "completed",
593
+ sessionStatus: "idle",
594
+ activeTurnId: null,
595
+ }))
596
+ ) {
597
+ return { exit: claimedResult({ status: "cancelled" }) };
598
+ }
599
+ control.turnMetricOutcome = "completed";
600
+ control.activityStatus = "idle";
601
+ return { exit: claimedResult({ status: "idle" }) };
602
+ }
603
+
604
+ // Pre-turn durable context compaction. When the single Codex-parity
605
+ // threshold is crossed, this summarizes active history and rebuilds active
606
+ // history as [user messages..., summary] BEFORE the model input is read.
607
+ // Summarizer context overflows drop one oldest summarizer-input item and
608
+ // retry, exactly like Codex. Other failures end this turn honestly.
609
+ // Run before every fresh inference. Approval resumes replay their frozen
610
+ // RunState verbatim and recovering attempts already compacted, if needed,
611
+ // before the first attempt's model boundary.
612
+ if (attempt.triggerType === "user.message" || attempt.triggerType === "system.update.delivered") {
613
+ let forced = false;
614
+ try {
615
+ // Operator /compact (the slash command) sets a durable request flag;
616
+ // observe it without consuming it so a failed/stale attempt cannot
617
+ // lose the request. The replacement transaction clears it on success.
618
+ forced = await isSessionCompactionRequested(db, input.workspaceId, input.sessionId);
619
+ const outcome = await waitForTurnOperation(
620
+ maybeCompactContext(
621
+ db,
622
+ eventing.modelRunSettings,
623
+ {
624
+ accountId: input.accountId,
625
+ workspaceId: input.workspaceId,
626
+ sessionId: input.sessionId,
627
+ turnId: attempt.turnId!,
628
+ executionGeneration: attempt.executionGeneration,
629
+ attemptId: input.attemptId,
630
+ },
631
+ session.lastInputTokens,
632
+ // Provider-aware summarizer: when the turn's model resolved to a
633
+ // registry provider, summarize on THAT provider's client + wire API
634
+ // (a chat provider can't summarize through OpenAI/Azure). Null
635
+ // resolution uses the built-in Responses summarizer with the same
636
+ // session prompt-cache key as the main model calls.
637
+ compactSummarizer,
638
+ forced
639
+ ? {
640
+ force: true,
641
+ clearRequestedCompaction: true,
642
+ trigger: "operator",
643
+ materializeHistory: media.materializeScreenshotHistory,
644
+ projectModelInput: compactionModelHistoryProjector,
645
+ ...compactionModeOptions,
646
+ }
647
+ : {
648
+ trigger: "auto",
649
+ materializeHistory: media.materializeScreenshotHistory,
650
+ projectModelInput: compactionModelHistoryProjector,
651
+ ...compactionModeOptions,
652
+ },
653
+ ),
654
+ cancellationSignal,
655
+ undefined,
656
+ );
657
+ if (outcome.events.length > 0) {
658
+ if (outcome.compacted) {
659
+ const compactionTrigger = forced ? "operator" : undefined;
660
+ recordContextCompaction(observability, compactionTrigger ?? "auto");
661
+ }
662
+ await publishCompactionOutcomeEvents(outcome.events);
663
+ }
664
+ } catch (compactError) {
665
+ if (shouldRecoverCompactionProviderFailure(compactError)) throw compactError;
666
+ if (compactError instanceof TurnAttemptFencedError) throw compactError;
667
+ const landmark = await settleFailedContextCompactionLandmark(
668
+ db,
669
+ {
670
+ accountId: input.accountId,
671
+ workspaceId: input.workspaceId,
672
+ sessionId: input.sessionId,
673
+ turnId: attempt.turnId!,
674
+ executionGeneration: attempt.executionGeneration,
675
+ attemptId: input.attemptId,
676
+ },
677
+ {
678
+ clearRequestedCompaction: forced,
679
+ publishLiveEvents: publishCompactionLiveEvents,
680
+ },
681
+ );
682
+ if (!isCompactionSummaryFailure(compactError)) throw compactError;
683
+ const errorMessage = String(compactionFailureReasonFromError(compactError));
684
+ observability.error("context compaction failed", {
685
+ sessionId: input.sessionId,
686
+ turnId: attempt.turnId,
687
+ ...safeErrorDiagnostic(compactError),
688
+ });
689
+ if (
690
+ !(await eventing.settle!({
691
+ events: [
692
+ {
693
+ type: "turn.failed",
694
+ payload: {
695
+ error: errorMessage,
696
+ code: "context_compaction_failed",
697
+ retryable: false,
698
+ recovery: "user_message",
699
+ compacted: false,
700
+ },
701
+ },
702
+ { type: "session.status.changed", payload: { status: "idle" } },
703
+ ],
704
+ turnStatus: "failed",
705
+ sessionStatus: "idle",
706
+ activeTurnId: null,
707
+ ...(forced && !landmark.requestConsumed
708
+ ? { consumeRequestedCompactionFailure: true }
709
+ : {}),
710
+ }))
711
+ ) {
712
+ return { exit: claimedResult({ status: "cancelled" }) };
713
+ }
714
+ control.turnMetricOutcome = "failed";
715
+ control.activityStatus = "idle";
716
+ control.activityError = compactError;
717
+ return { exit: claimedResult({ status: "idle" }) };
718
+ }
719
+ }
720
+
721
+ return { ok: { compactSummarizer } };
722
+ }