@opengeni/worker-bundle 1.0.0-canary.1 → 1.0.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 (244) hide show
  1. package/dist/activities/agent-run-admission.d.ts +3 -1
  2. package/dist/activities/agent-turn/admission.d.ts +24 -3
  3. package/dist/activities/agent-turn/agent-build.d.ts +4 -0
  4. package/dist/activities/agent-turn/claude-usage-observer.d.ts +58 -0
  5. package/dist/activities/agent-turn/code-search.d.ts +60 -0
  6. package/dist/activities/agent-turn/codex-capacity.d.ts +13 -0
  7. package/dist/activities/agent-turn/codex-plan-entitlement.d.ts +105 -0
  8. package/dist/activities/agent-turn/codex.d.ts +3 -2
  9. package/dist/activities/agent-turn/compaction-prep.d.ts +21 -5
  10. package/dist/activities/agent-turn/credential-leases.d.ts +19 -33
  11. package/dist/activities/agent-turn/credential-restriction.d.ts +3 -0
  12. package/dist/activities/agent-turn/errors.d.ts +82 -11
  13. package/dist/activities/agent-turn/failure-settlement.d.ts +6 -3
  14. package/dist/activities/agent-turn/final-reply.d.ts +18 -0
  15. package/dist/activities/agent-turn/finalization-monitor.d.ts +17 -0
  16. package/dist/activities/agent-turn/finalization.d.ts +4 -2
  17. package/dist/activities/agent-turn/github-repository-bindings.d.ts +2 -0
  18. package/dist/activities/agent-turn/governance-model.d.ts +9 -2
  19. package/dist/activities/agent-turn/history-sink.d.ts +2 -0
  20. package/dist/activities/agent-turn/history.d.ts +2 -0
  21. package/dist/activities/agent-turn/input-wait-reply.d.ts +41 -0
  22. package/dist/activities/agent-turn/media-artifacts.d.ts +5 -3
  23. package/dist/activities/agent-turn/model-call-admission.d.ts +15 -0
  24. package/dist/activities/agent-turn/model-usage.d.ts +6 -0
  25. package/dist/activities/agent-turn/model-wire-dispatch.d.ts +15 -0
  26. package/dist/activities/agent-turn/optional-repositories.d.ts +59 -0
  27. package/dist/activities/agent-turn/provider-dispatch-barrier.d.ts +12 -1
  28. package/dist/activities/agent-turn/quiescence.d.ts +7 -7
  29. package/dist/activities/agent-turn/recovery-warning.d.ts +9 -0
  30. package/dist/activities/agent-turn/refresh-credentials.d.ts +6 -0
  31. package/dist/activities/agent-turn/run-credentials.d.ts +8 -3
  32. package/dist/activities/agent-turn/sandbox-establish.d.ts +2 -1
  33. package/dist/activities/agent-turn/sandbox-provision.d.ts +3 -1
  34. package/dist/activities/agent-turn/sandbox-route.d.ts +3 -20
  35. package/dist/activities/agent-turn/sandbox-runtime.d.ts +2 -2
  36. package/dist/activities/agent-turn/session-title.d.ts +34 -2
  37. package/dist/activities/agent-turn/skill-checkout.d.ts +25 -6
  38. package/dist/activities/agent-turn/skill-read.d.ts +70 -2
  39. package/dist/activities/agent-turn/skill-remove.d.ts +14 -0
  40. package/dist/activities/agent-turn/skill-search.d.ts +3 -1
  41. package/dist/activities/agent-turn/skill-tools.d.ts +15 -2
  42. package/dist/activities/agent-turn/skill-transfer.d.ts +18 -6
  43. package/dist/activities/agent-turn/stream-attempt.d.ts +7 -3
  44. package/dist/activities/agent-turn/subscription-lease.d.ts +38 -0
  45. package/dist/activities/agent-turn/tool-environment.d.ts +56 -6
  46. package/dist/activities/agent-turn/tool-policy.d.ts +43 -0
  47. package/dist/activities/agent-turn/turn-context.d.ts +29 -0
  48. package/dist/activities/agent-turn/turn-sandbox-access.d.ts +3 -0
  49. package/dist/activities/agent-turn/xai-capacity.d.ts +2 -1
  50. package/dist/activities/automations.d.ts +3 -1
  51. package/dist/activities/browser-deadline-checkpoint.d.ts +29 -0
  52. package/dist/activities/codemode-dispatcher.d.ts +9 -2
  53. package/dist/activities/codex-capacity.d.ts +18 -2
  54. package/dist/activities/codex-rotation.d.ts +7 -1
  55. package/dist/activities/context-compaction.d.ts +16 -2
  56. package/dist/activities/gmail-files.d.ts +32 -0
  57. package/dist/activities/goals.d.ts +8 -0
  58. package/dist/activities/knowledge-indexing.d.ts +19 -0
  59. package/dist/activities/mcp-account-routes.d.ts +3 -0
  60. package/dist/activities/mcp-credentials.d.ts +12 -13
  61. package/dist/activities/mcp-operation-authority.d.ts +0 -5
  62. package/dist/activities/model-call-fact-reconciler.d.ts +34 -0
  63. package/dist/activities/open-suffix-resume.d.ts +13 -0
  64. package/dist/activities/parent-wake.d.ts +6 -12
  65. package/dist/activities/retained-screenshots.d.ts +7 -2
  66. package/dist/activities/rig-verification.d.ts +2 -3
  67. package/dist/activities/run-credential-renewal.d.ts +1 -0
  68. package/dist/activities/run-credentials.d.ts +15 -3
  69. package/dist/activities/sandbox-images.d.ts +1 -1
  70. package/dist/activities/sandbox-lease.d.ts +47 -9
  71. package/dist/activities/scheduled-tasks.d.ts +4 -35
  72. package/dist/activities/session-state.d.ts +70 -3
  73. package/dist/activities/types.d.ts +55 -6
  74. package/dist/activities/workspace-capture.d.ts +2 -0
  75. package/dist/activities/workspace-credential-provider.d.ts +46 -0
  76. package/dist/{activities-control-HMFGSKC5.js → activities-control-BNPTRTOE.js} +1896 -418
  77. package/dist/activities-control-BNPTRTOE.js.map +1 -0
  78. package/dist/activities-control.d.ts +182 -4
  79. package/dist/{activities-turn-AP67JADS.js → activities-turn-5LGZOSVU.js} +4476 -1327
  80. package/dist/activities-turn-5LGZOSVU.js.map +1 -0
  81. package/dist/activities.d.ts +182 -4
  82. package/dist/artifact-materializer-entry.js +5 -2
  83. package/dist/artifact-materializer-entry.js.map +1 -1
  84. package/dist/artifact-outbox-entry.js +5 -2
  85. package/dist/artifact-outbox-entry.js.map +1 -1
  86. package/dist/browser-deadline-checkpoint-contract.d.ts +2 -0
  87. package/dist/{chunk-A4XQWVZK.js → chunk-3ZTRWDMN.js} +307 -4
  88. package/dist/chunk-3ZTRWDMN.js.map +1 -0
  89. package/dist/{chunk-RAMNYSAW.js → chunk-4ER3YXOT.js} +22 -4
  90. package/dist/chunk-4ER3YXOT.js.map +1 -0
  91. package/dist/{chunk-CYITU5UH.js → chunk-LJX7Z2KP.js} +1445 -343
  92. package/dist/chunk-LJX7Z2KP.js.map +1 -0
  93. package/dist/editable-artifact-materializer-service.d.ts +2 -2
  94. package/dist/editable-artifact-outbox-service.d.ts +2 -2
  95. package/dist/host-export-pump.d.ts +3 -1
  96. package/dist/host-export.d.ts +1 -1
  97. package/dist/host-export.js +1 -1
  98. package/dist/http.d.ts +1 -1
  99. package/dist/index.d.ts +95 -3
  100. package/dist/index.js +137 -43
  101. package/dist/index.js.map +1 -1
  102. package/dist/observability-metrics.d.ts +118 -8
  103. package/dist/retained-process-diagnostics.d.ts +4 -0
  104. package/dist/retained-process-retry.d.ts +7 -0
  105. package/dist/sandbox-resume.d.ts +55 -13
  106. package/dist/sandbox-routing.d.ts +5 -3
  107. package/dist/sandbox-snapshot-diagnostics.d.ts +20 -0
  108. package/dist/session-event-fanout.d.ts +6 -0
  109. package/dist/warm-capture-holder.d.ts +3 -0
  110. package/dist/worker-service-lifecycle.d.ts +12 -0
  111. package/dist/workflow-bundle.js +273 -41
  112. package/dist/workflows/activities.d.ts +1 -1
  113. package/dist/workflows/browser-deadline-checkpoint.d.ts +9 -0
  114. package/dist/workflows/scheduled-tasks.d.ts +4 -0
  115. package/dist/workflows/session.d.ts +36 -0
  116. package/dist/workflows.d.ts +1 -0
  117. package/package.json +21 -19
  118. package/src/activities/agent-run-admission.ts +17 -1
  119. package/src/activities/agent-turn/admission.ts +66 -3
  120. package/src/activities/agent-turn/agent-build.ts +84 -10
  121. package/src/activities/agent-turn/claim.ts +186 -43
  122. package/src/activities/agent-turn/claude-usage-observer.ts +221 -0
  123. package/src/activities/agent-turn/code-search.ts +275 -0
  124. package/src/activities/agent-turn/codex-capacity.ts +172 -8
  125. package/src/activities/agent-turn/codex-plan-entitlement.ts +254 -0
  126. package/src/activities/agent-turn/codex.ts +13 -5
  127. package/src/activities/agent-turn/compaction-prep.ts +170 -102
  128. package/src/activities/agent-turn/credential-leases.ts +122 -216
  129. package/src/activities/agent-turn/credential-restriction.ts +14 -0
  130. package/src/activities/agent-turn/errors.ts +647 -48
  131. package/src/activities/agent-turn/failure-settlement.ts +682 -130
  132. package/src/activities/agent-turn/final-reply.ts +46 -0
  133. package/src/activities/agent-turn/finalization-monitor.ts +120 -0
  134. package/src/activities/agent-turn/finalization.ts +146 -43
  135. package/src/activities/agent-turn/github-repository-bindings.ts +3 -1
  136. package/src/activities/agent-turn/governance-model.ts +69 -28
  137. package/src/activities/agent-turn/history-sink.ts +16 -2
  138. package/src/activities/agent-turn/history.ts +38 -11
  139. package/src/activities/agent-turn/input-wait-reply.ts +103 -0
  140. package/src/activities/agent-turn/knowledge-source-tools.ts +2 -0
  141. package/src/activities/agent-turn/media-artifacts.ts +2 -1
  142. package/src/activities/agent-turn/model-call-admission.ts +94 -0
  143. package/src/activities/agent-turn/model-usage.ts +64 -3
  144. package/src/activities/agent-turn/model-wire-dispatch.ts +27 -0
  145. package/src/activities/agent-turn/optional-repositories.ts +224 -0
  146. package/src/activities/agent-turn/provider-dispatch-barrier.ts +22 -0
  147. package/src/activities/agent-turn/quiescence.ts +10 -7
  148. package/src/activities/agent-turn/recovery-warning.ts +16 -0
  149. package/src/activities/agent-turn/refresh-credentials.ts +44 -0
  150. package/src/activities/agent-turn/run-credentials.ts +116 -55
  151. package/src/activities/agent-turn/run.ts +320 -93
  152. package/src/activities/agent-turn/sandbox-establish.ts +84 -8
  153. package/src/activities/agent-turn/sandbox-provision.ts +3 -1
  154. package/src/activities/agent-turn/sandbox-route.ts +4 -21
  155. package/src/activities/agent-turn/sandbox-runtime.ts +343 -18
  156. package/src/activities/agent-turn/session-title.ts +81 -5
  157. package/src/activities/agent-turn/skill-checkout.ts +111 -24
  158. package/src/activities/agent-turn/skill-install.ts +1 -1
  159. package/src/activities/agent-turn/skill-read.ts +374 -28
  160. package/src/activities/agent-turn/skill-remove.ts +46 -0
  161. package/src/activities/agent-turn/skill-save.ts +1 -1
  162. package/src/activities/agent-turn/skill-search.ts +10 -1
  163. package/src/activities/agent-turn/skill-selection.ts +4 -0
  164. package/src/activities/agent-turn/skill-tools.ts +112 -18
  165. package/src/activities/agent-turn/skill-transfer.ts +68 -23
  166. package/src/activities/agent-turn/stream-attempt.ts +313 -77
  167. package/src/activities/agent-turn/subscription-lease.ts +115 -0
  168. package/src/activities/agent-turn/tool-environment.ts +316 -167
  169. package/src/activities/agent-turn/tool-policy.ts +80 -1
  170. package/src/activities/agent-turn/turn-context.ts +35 -0
  171. package/src/activities/agent-turn/turn-sandbox-access.ts +7 -1
  172. package/src/activities/agent-turn/xai-capacity.ts +94 -51
  173. package/src/activities/automations.ts +76 -4
  174. package/src/activities/browser-deadline-checkpoint.ts +279 -0
  175. package/src/activities/capabilities.ts +108 -11
  176. package/src/activities/codemode-dispatcher.ts +36 -8
  177. package/src/activities/codex-capacity.ts +60 -25
  178. package/src/activities/codex-rotation.ts +39 -17
  179. package/src/activities/context-compaction.ts +75 -18
  180. package/src/activities/gmail-files.ts +88 -0
  181. package/src/activities/goals.ts +116 -121
  182. package/src/activities/google-drive-publication.ts +1 -3
  183. package/src/activities/image-generation-operation.ts +1 -1
  184. package/src/activities/knowledge-indexing.ts +269 -15
  185. package/src/activities/knowledge-source-sync.ts +10 -0
  186. package/src/activities/mcp-account-routes.ts +17 -0
  187. package/src/activities/mcp-credentials.ts +83 -194
  188. package/src/activities/mcp-operation-authority.ts +16 -41
  189. package/src/activities/model-call-fact-reconciler.ts +112 -0
  190. package/src/activities/open-suffix-resume.ts +15 -2
  191. package/src/activities/parent-wake.ts +46 -21
  192. package/src/activities/retained-screenshots.ts +82 -11
  193. package/src/activities/rig-verification.ts +38 -37
  194. package/src/activities/run-credential-renewal.ts +13 -1
  195. package/src/activities/run-credentials.ts +59 -17
  196. package/src/activities/run-input.ts +25 -16
  197. package/src/activities/sandbox-images.ts +0 -1
  198. package/src/activities/sandbox-lease.ts +798 -82
  199. package/src/activities/scheduled-tasks.ts +550 -178
  200. package/src/activities/session-state.ts +245 -6
  201. package/src/activities/site-auth-maintenance.ts +3 -0
  202. package/src/activities/types.ts +72 -5
  203. package/src/activities/workflow-wake.ts +2 -17
  204. package/src/activities/workspace-capture.ts +13 -2
  205. package/src/activities/workspace-credential-provider.ts +283 -0
  206. package/src/activities-control.ts +4 -0
  207. package/src/activities-turn.ts +5 -0
  208. package/src/activities.ts +13 -0
  209. package/src/activity-services.ts +16 -4
  210. package/src/browser-deadline-checkpoint-contract.ts +5 -0
  211. package/src/editable-artifact-hint-broker.ts +3 -0
  212. package/src/editable-artifact-materializer-service.ts +7 -3
  213. package/src/editable-artifact-outbox-service.ts +4 -4
  214. package/src/github-rest-mcp.ts +1 -2
  215. package/src/host-export-pump.ts +26 -4
  216. package/src/host-export.ts +3 -0
  217. package/src/http.ts +4 -2
  218. package/src/index.ts +99 -37
  219. package/src/observability-metrics.ts +510 -5
  220. package/src/personal-github-git-credentials.ts +2 -1
  221. package/src/pr-review-credentials.ts +1 -3
  222. package/src/retained-process-diagnostics.ts +50 -0
  223. package/src/retained-process-retry.ts +36 -0
  224. package/src/sandbox-resume.ts +388 -101
  225. package/src/sandbox-routing.ts +150 -25
  226. package/src/sandbox-snapshot-diagnostics.ts +112 -0
  227. package/src/session-event-fanout.ts +23 -0
  228. package/src/warm-capture-holder.ts +15 -0
  229. package/src/worker-service-lifecycle.ts +53 -0
  230. package/src/workflows/activities.ts +16 -1
  231. package/src/workflows/browser-deadline-checkpoint.ts +50 -0
  232. package/src/workflows/file-upload-reaper.ts +2 -0
  233. package/src/workflows/scheduled-tasks.ts +26 -13
  234. package/src/workflows/session.ts +242 -22
  235. package/src/workflows.ts +4 -0
  236. package/dist/activities/agent-turn/knowledge-sources.d.ts +0 -20
  237. package/dist/activities/packs.d.ts +0 -55
  238. package/dist/activities-control-HMFGSKC5.js.map +0 -1
  239. package/dist/activities-turn-AP67JADS.js.map +0 -1
  240. package/dist/chunk-A4XQWVZK.js.map +0 -1
  241. package/dist/chunk-CYITU5UH.js.map +0 -1
  242. package/dist/chunk-RAMNYSAW.js.map +0 -1
  243. package/src/activities/agent-turn/knowledge-sources.ts +0 -86
  244. package/src/activities/packs.ts +0 -166
@@ -4,11 +4,17 @@ import {
4
4
  appendSessionInstructions,
5
5
  appendWorkspaceGovernance,
6
6
  appendWorkspaceMemory,
7
+ agentPromptResourcesFor,
7
8
  composeAgentInstructions,
9
+ inspectPersistentAgentInstructions,
8
10
  requestRemoteCompactionV2,
9
- serializedToolsForRemoteCompaction,
10
- EmptyCompactionSummaryError,
11
- SUMMARY_BUFFER_TOKENS,
11
+ preparedCompactionRequest,
12
+ queuePreparedCompaction,
13
+ compactionThresholdTokens,
14
+ CompactionNeededError,
15
+ compactionProviderRejection,
16
+ estimateSerializedValueTokens,
17
+ compactionSummaryOutputTokens,
12
18
  type ModelResponseUsage,
13
19
  } from "@opengeni/runtime";
14
20
  import { type Settings } from "@opengeni/config";
@@ -31,7 +37,7 @@ import { type SessionEvent } from "@opengeni/contracts";
31
37
  import { acceptsPromptCacheKeyForTurn } from "./codex";
32
38
  import {
33
39
  safeErrorDiagnostic,
34
- compactionFailureReasonFromError,
40
+ compactionFailureTurnEventPayload,
35
41
  isCompactionSummaryFailure,
36
42
  shouldRecoverCompactionProviderFailure,
37
43
  } from "./errors";
@@ -53,10 +59,7 @@ import type {
53
59
  } from "./turn-context";
54
60
 
55
61
  export type RemoteCompactionPrefix = {
56
- tools: Awaited<ReturnType<typeof serializedToolsForRemoteCompaction>>;
57
- instructions: string;
58
- toolsReady: boolean;
59
- agent: Parameters<typeof serializedToolsForRemoteCompaction>[0] | null;
62
+ agent: ReturnType<ActivityServices["runtime"]["buildAgent"]> | null;
60
63
  };
61
64
 
62
65
  export type CompactionPrepDeps = {
@@ -85,6 +88,7 @@ export type CompactionPrepDeps = {
85
88
  turnExecutionPolicy: ClaimTurnOk["turnExecutionPolicy"];
86
89
  resolvedModel: GovernanceModelOk["resolvedModel"];
87
90
  workspaceAgentInstructions: GovernanceModelOk["workspaceAgentInstructions"];
91
+ workspaceAgentIdentity: GovernanceModelOk["workspaceAgentIdentity"];
88
92
  workspaceGovernance: GovernanceModelOk["workspaceGovernance"];
89
93
  structuredWorkspacePolicyActive: GovernanceModelOk["structuredWorkspacePolicyActive"];
90
94
  workspaceMemory: GovernanceModelOk["workspaceMemory"];
@@ -130,6 +134,59 @@ export type PostAgentCompactionOutcome =
130
134
  | { exit: RunAgentTurnResult }
131
135
  | { ok: PostAgentCompactionOk };
132
136
 
137
+ /**
138
+ * System instructions for the standalone (chat-provider) compaction request.
139
+ * A session with an agent configuration uses the same modular composer and
140
+ * module selection as its turns; a legacy session keeps the historical
141
+ * persona + CORE + governance + session + memory string byte-for-byte.
142
+ */
143
+ export function standaloneCompactionInstructions(input: {
144
+ settings: Settings;
145
+ session: Pick<ClaimTurnOk["session"], "agent" | "instructions" | "resources">;
146
+ workspaceAgentInstructions: string | null | undefined;
147
+ workspaceAgentIdentity: string | null;
148
+ workspaceGovernance: string | null | undefined;
149
+ structuredWorkspacePolicyActive: boolean;
150
+ workspaceMemory: string | null | undefined;
151
+ rig: { name: string; version: number } | undefined;
152
+ }): string {
153
+ if (input.session.agent) {
154
+ return inspectPersistentAgentInstructions(input.settings, {
155
+ agentConfig: input.session.agent,
156
+ ...(input.workspaceAgentIdentity
157
+ ? { workspaceAgentIdentity: input.workspaceAgentIdentity }
158
+ : {}),
159
+ ...(input.workspaceGovernance ? { workspaceGovernance: input.workspaceGovernance } : {}),
160
+ ...(input.workspaceMemory ? { workspaceMemory: input.workspaceMemory } : {}),
161
+ ...(input.session.instructions ? { sessionInstructions: input.session.instructions } : {}),
162
+ ...(input.rig ? { rig: input.rig } : {}),
163
+ // Session-level facts only: per-turn attachments do not apply to a
164
+ // standalone compaction request.
165
+ agentPromptResources: agentPromptResourcesFor(
166
+ input.settings,
167
+ input.session.resources.filter((resource) => resource.kind !== "file"),
168
+ input.rig ? { rig: input.rig } : {},
169
+ ),
170
+ }).composed;
171
+ }
172
+ return appendWorkspaceMemory(
173
+ appendSessionInstructions(
174
+ appendWorkspaceGovernance(
175
+ composeAgentInstructions(
176
+ input.structuredWorkspacePolicyActive
177
+ ? input.settings.agentInstructionsTemplate
178
+ : (input.workspaceAgentInstructions ?? input.settings.agentInstructionsTemplate),
179
+ undefined,
180
+ input.rig,
181
+ ),
182
+ input.workspaceGovernance ?? undefined,
183
+ ),
184
+ input.session.instructions ?? undefined,
185
+ ),
186
+ input.workspaceMemory ?? undefined,
187
+ );
188
+ }
189
+
133
190
  export async function prepareCompaction(deps: CompactionPrepDeps): Promise<CompactionPrepOutcome> {
134
191
  const {
135
192
  input,
@@ -154,6 +211,7 @@ export async function prepareCompaction(deps: CompactionPrepDeps): Promise<Compa
154
211
  turnExecutionPolicy,
155
212
  resolvedModel,
156
213
  workspaceAgentInstructions,
214
+ workspaceAgentIdentity,
157
215
  workspaceGovernance,
158
216
  structuredWorkspacePolicyActive,
159
217
  workspaceMemory,
@@ -166,11 +224,15 @@ export async function prepareCompaction(deps: CompactionPrepDeps): Promise<Compa
166
224
  } = deps;
167
225
 
168
226
  const remotePrefix: RemoteCompactionPrefix = {
169
- tools: [],
170
- instructions: "",
171
- toolsReady: false,
172
227
  agent: null,
173
228
  };
229
+ const portableResponsesNeedsAgentPrefix =
230
+ resolvedModel?.provider.api === "responses" &&
231
+ !(billingState.isCodexTurn && session.codexCompactionMode === "remote_v2");
232
+ const preparedPortableRequest = () => {
233
+ if (!remotePrefix.agent) throw new Error("Compaction agent is unavailable");
234
+ return preparedCompactionRequest(remotePrefix.agent);
235
+ };
174
236
 
175
237
  const promptCacheKey = acceptsPromptCacheKeyForTurn(resolvedModel) ? input.sessionId : undefined;
176
238
  const compactionUsageState = createCompactionModelUsageEventState(claimedModelUsageSourceKeys);
@@ -203,8 +265,8 @@ export async function prepareCompaction(deps: CompactionPrepDeps): Promise<Compa
203
265
  contextContributions: eventing.companyBrainContextContributions,
204
266
  });
205
267
  };
206
- const compactionSummarizerFor = (systemInstructions?: string) =>
207
- resolvedModel
268
+ const compactionSummarizerFor = (systemInstructions?: string): CompactionSummarizer => {
269
+ const summarize: CompactionSummarizer = resolvedModel
208
270
  ? (s: Settings, m: Array<Record<string, unknown>>) =>
209
271
  withProviderRequestContext(() =>
210
272
  summarizeContextForCompaction(s, m, {
@@ -212,20 +274,37 @@ export async function prepareCompaction(deps: CompactionPrepDeps): Promise<Compa
212
274
  provider: resolvedModel.provider,
213
275
  api: resolvedModel.provider.api,
214
276
  model: turnExecutionPolicy.upstreamModelId,
215
- maxOutputTokens: SUMMARY_BUFFER_TOKENS,
277
+ maxOutputTokens: compactionSummaryOutputTokens(s.contextWindowTokens),
278
+ ...(cancellationSignal ? { signal: cancellationSignal } : {}),
216
279
  onUsage: recordCompactionUsage,
217
280
  ...(systemInstructions ? { systemInstructions } : {}),
218
281
  ...(promptCacheKey ? { promptCacheKey } : {}),
282
+ ...(portableResponsesNeedsAgentPrefix
283
+ ? { preparedRequest: preparedPortableRequest() }
284
+ : {}),
219
285
  }),
220
286
  )
221
287
  : (s: Settings, m: Array<Record<string, unknown>>) =>
222
288
  summarizeContextForCompaction(s, m, {
223
289
  model: turnExecutionPolicy.upstreamModelId,
224
- maxOutputTokens: SUMMARY_BUFFER_TOKENS,
290
+ maxOutputTokens: compactionSummaryOutputTokens(s.contextWindowTokens),
291
+ ...(cancellationSignal ? { signal: cancellationSignal } : {}),
225
292
  onUsage: recordCompactionUsage,
226
293
  ...(systemInstructions ? { systemInstructions } : {}),
227
294
  ...(promptCacheKey ? { promptCacheKey } : {}),
228
295
  });
296
+ summarize.estimatePrefixTokens = () => {
297
+ if (resolvedModel?.provider.api === "chat") {
298
+ return estimateSerializedValueTokens(systemInstructions ?? "");
299
+ }
300
+ const prepared = portableResponsesNeedsAgentPrefix ? preparedPortableRequest() : null;
301
+ return (
302
+ estimateSerializedValueTokens(prepared?.systemInstructions ?? systemInstructions ?? "") +
303
+ (prepared ? estimateSerializedValueTokens(prepared.tools) : 0)
304
+ );
305
+ };
306
+ return summarize;
307
+ };
229
308
  // Prompt-cache prefix for remote_v2 MUST match ordinary turns:
230
309
  // tools → instructions → history. Filled after buildAgent for every
231
310
  // compact path (including operator /compact, which now builds the agent
@@ -234,45 +313,16 @@ export async function prepareCompaction(deps: CompactionPrepDeps): Promise<Compa
234
313
  resolvedModel && billingState.isCodexTurn
235
314
  ? (s: Settings, m: Array<Record<string, unknown>>) =>
236
315
  withCodexRemoteCompaction(async () => {
237
- // Lazily serialize tools here so EmptyCompactionSummaryError is
238
- // thrown inside the compaction try/settlement handlers, not as a
239
- // raw activity failure before maybeCompactContext runs.
240
- if (!remotePrefix.instructions.trim()) {
241
- throw new EmptyCompactionSummaryError({
242
- stage: "remote_v2_instructions",
243
- reason: "agent_missing_system_instructions",
244
- });
245
- }
246
- if (!remotePrefix.toolsReady) {
247
- if (!remotePrefix.agent) {
248
- throw new EmptyCompactionSummaryError({
249
- stage: "remote_v2_tools",
250
- reason: "agent_missing_for_tools",
251
- });
252
- }
253
- try {
254
- remotePrefix.tools = await serializedToolsForRemoteCompaction(remotePrefix.agent);
255
- } catch (error) {
256
- // Tool schemas sit before instructions in the cache prefix.
257
- // Failing open to [] would reintroduce a massive pre-compact
258
- // cache bust — fail closed so we never send a tools mismatch
259
- // on purpose.
260
- throw new EmptyCompactionSummaryError({
261
- stage: "remote_v2_tools",
262
- reason: "serialize_tools_failed",
263
- error: String(error),
264
- });
265
- }
266
- remotePrefix.toolsReady = true;
267
- }
316
+ if (!remotePrefix.agent) throw new Error("Compaction agent is unavailable");
317
+ const preparedRequest = preparedCompactionRequest(remotePrefix.agent);
268
318
  return requestRemoteCompactionV2(s, m, {
269
319
  client: resolvedModel.client,
270
320
  provider: resolvedModel.provider,
271
321
  model: turnExecutionPolicy.upstreamModelId,
272
- systemInstructions: remotePrefix.instructions,
322
+ preparedRequest,
323
+ captureAgent: remotePrefix.agent,
324
+ signal: cancellationSignal,
273
325
  onUsage: recordCompactionUsage,
274
- tools: remotePrefix.tools,
275
- ...(promptCacheKey ? { promptCacheKey } : {}),
276
326
  });
277
327
  })
278
328
  : undefined;
@@ -297,13 +347,9 @@ export async function prepareCompaction(deps: CompactionPrepDeps): Promise<Compa
297
347
  ...(remoteCompactionRequester ? { requestRemoteCompactionV2: remoteCompactionRequester } : {}),
298
348
  } as const;
299
349
 
300
- // Operator /compact:
301
- // - portable (incl. Codex portable): early maintenance path — no
302
- // prepareTools/sandbox; summarizer only needs composed instructions.
303
- // - remote_v2: fall through to prepareTools/buildAgent so the compact
304
- // request reuses the ordinary tools→instructions cache prefix, then
305
- // settle without inference. (Requester is also wired for Codex portable
306
- // turns but unused there — gate on the frozen session mode.)
350
+ // Responses compaction, portable or remote, prepares the ordinary agent
351
+ // request first so tool schemas and instructions match the warm cache prefix.
352
+ // Chat providers keep the standalone portable maintenance path.
307
353
  const compactionOnlyTurn = turn.source === "compaction";
308
354
  const remoteV2CompactionNeedsAgentPrefix =
309
355
  Boolean(remoteCompactionRequester) && session.codexCompactionMode === "remote_v2";
@@ -340,23 +386,21 @@ export async function prepareCompaction(deps: CompactionPrepDeps): Promise<Compa
340
386
  control.activityStatus = "idle";
341
387
  return claimedResult({ status: "idle" });
342
388
  };
343
- if (compactionOnlyTurn && !remoteV2CompactionNeedsAgentPrefix) {
344
- const compactionInstructions = appendWorkspaceMemory(
345
- appendSessionInstructions(
346
- appendWorkspaceGovernance(
347
- composeAgentInstructions(
348
- structuredWorkspacePolicyActive
349
- ? eventing.modelRunSettings.agentInstructionsTemplate
350
- : (workspaceAgentInstructions ?? eventing.modelRunSettings.agentInstructionsTemplate),
351
- undefined,
352
- rigVersion && rigName ? { name: rigName, version: rigVersion.version } : undefined,
353
- ),
354
- workspaceGovernance ?? undefined,
355
- ),
356
- session.instructions ?? undefined,
357
- ),
358
- workspaceMemory ?? undefined,
359
- );
389
+ if (
390
+ compactionOnlyTurn &&
391
+ !remoteV2CompactionNeedsAgentPrefix &&
392
+ !portableResponsesNeedsAgentPrefix
393
+ ) {
394
+ const compactionInstructions = standaloneCompactionInstructions({
395
+ settings: eventing.modelRunSettings,
396
+ session,
397
+ workspaceAgentInstructions,
398
+ workspaceAgentIdentity,
399
+ workspaceGovernance,
400
+ structuredWorkspacePolicyActive,
401
+ workspaceMemory,
402
+ rig: rigVersion && rigName ? { name: rigName, version: rigVersion.version } : undefined,
403
+ });
360
404
  const requested = await isSessionCompactionRequested(db, input.workspaceId, input.sessionId);
361
405
  let outcome: Awaited<ReturnType<typeof maybeCompactContext>> | null = null;
362
406
  if (requested) {
@@ -409,22 +453,16 @@ export async function prepareCompaction(deps: CompactionPrepDeps): Promise<Compa
409
453
  {
410
454
  clearRequestedCompaction: true,
411
455
  publishLiveEvents: publishCompactionLiveEvents,
456
+ providerRejection: compactionProviderRejection(error),
412
457
  },
413
458
  );
414
459
  if (!isCompactionSummaryFailure(error)) throw error;
415
- const errorMessage = String(compactionFailureReasonFromError(error));
416
460
  if (
417
461
  !(await eventing.settle!({
418
462
  events: [
419
463
  {
420
464
  type: "turn.failed",
421
- payload: {
422
- error: errorMessage,
423
- code: "context_compaction_failed",
424
- retryable: false,
425
- recovery: "user_message",
426
- compacted: false,
427
- },
465
+ payload: compactionFailureTurnEventPayload(error),
428
466
  },
429
467
  {
430
468
  type: "session.status.changed",
@@ -504,6 +542,7 @@ export async function runPostAgentCompaction(
504
542
  claimedResult,
505
543
  turn,
506
544
  session,
545
+ resolvedModel,
507
546
  remotePrefix,
508
547
  remoteCompactionRequester,
509
548
  publishCompactionLiveEvents,
@@ -518,20 +557,36 @@ export async function runPostAgentCompaction(
518
557
  } = deps;
519
558
 
520
559
  const agentInstructions = typeof agent.instructions === "string" ? agent.instructions : "";
560
+ const preparedPortable =
561
+ resolvedModel?.provider.api === "responses" &&
562
+ !(remoteCompactionRequester && session.codexCompactionMode === "remote_v2");
521
563
  const compactSummarizer = compactionSummarizerFor(
522
564
  agentInstructions.trim() ? agentInstructions : undefined,
523
565
  );
524
- if (remoteCompactionRequester) {
525
- // Exact byte match with the ordinary turn prefix (CLI base_instructions).
526
- // Tools serialize lazily inside the requester so setup failures settle as
527
- // compaction failures rather than raw activity crashes.
528
- remotePrefix.instructions = agentInstructions;
566
+ if (remoteCompactionRequester || preparedPortable) {
567
+ // The prefix is captured only after this agent passes normal SDK preparation.
529
568
  remotePrefix.agent = agent;
530
569
  }
531
570
 
532
571
  if (compactionOnlyTurn) {
533
572
  const requested = await isSessionCompactionRequested(db, input.workspaceId, input.sessionId);
534
573
  let outcome: Awaited<ReturnType<typeof maybeCompactContext>> | null = null;
574
+ if (
575
+ requested &&
576
+ (preparedPortable ||
577
+ (remoteCompactionRequester && session.codexCompactionMode === "remote_v2"))
578
+ ) {
579
+ queuePreparedCompaction(
580
+ agent,
581
+ new CompactionNeededError({
582
+ trigger: "operator",
583
+ signalSource: "operator",
584
+ signalTokens: session.lastInputTokens ?? 0,
585
+ thresholdTokens: compactionThresholdTokens(eventing.modelRunSettings),
586
+ }),
587
+ );
588
+ return { ok: { compactSummarizer } };
589
+ }
535
590
  if (requested) {
536
591
  try {
537
592
  outcome = await waitForTurnOperation(
@@ -579,22 +634,16 @@ export async function runPostAgentCompaction(
579
634
  {
580
635
  clearRequestedCompaction: true,
581
636
  publishLiveEvents: publishCompactionLiveEvents,
637
+ providerRejection: compactionProviderRejection(error),
582
638
  },
583
639
  );
584
640
  if (!isCompactionSummaryFailure(error)) throw error;
585
- const errorMessage = String(compactionFailureReasonFromError(error));
586
641
  if (
587
642
  !(await eventing.settle!({
588
643
  events: [
589
644
  {
590
645
  type: "turn.failed",
591
- payload: {
592
- error: errorMessage,
593
- code: "context_compaction_failed",
594
- retryable: false,
595
- recovery: "user_message",
596
- compacted: false,
597
- },
646
+ payload: compactionFailureTurnEventPayload(error),
598
647
  },
599
648
  {
600
649
  type: "session.status.changed",
@@ -645,6 +694,31 @@ export async function runPostAgentCompaction(
645
694
  return { exit: claimedResult({ status: "idle" }) };
646
695
  }
647
696
 
697
+ if (
698
+ preparedPortable ||
699
+ (remoteCompactionRequester && session.codexCompactionMode === "remote_v2")
700
+ ) {
701
+ const forced = await isSessionCompactionRequested(db, input.workspaceId, input.sessionId);
702
+ const thresholdTokens = compactionThresholdTokens(eventing.modelRunSettings);
703
+ if (
704
+ forced ||
705
+ ((attempt.triggerType === "user.message" ||
706
+ attempt.triggerType === "system.update.delivered") &&
707
+ (session.lastInputTokens ?? 0) >= thresholdTokens)
708
+ ) {
709
+ queuePreparedCompaction(
710
+ agent,
711
+ new CompactionNeededError({
712
+ trigger: forced ? "operator" : "threshold",
713
+ signalSource: forced ? "operator" : "provider",
714
+ signalTokens: session.lastInputTokens ?? 0,
715
+ thresholdTokens,
716
+ }),
717
+ );
718
+ }
719
+ return { ok: { compactSummarizer } };
720
+ }
721
+
648
722
  // Pre-turn durable context compaction. When the single Codex-parity
649
723
  // threshold is crossed, this summarizes active history and rebuilds active
650
724
  // history as [user messages..., summary] BEFORE the model input is read.
@@ -731,12 +805,12 @@ export async function runPostAgentCompaction(
731
805
  {
732
806
  clearRequestedCompaction: forced,
733
807
  publishLiveEvents: publishCompactionLiveEvents,
808
+ providerRejection: compactionProviderRejection(compactError),
734
809
  },
735
810
  );
736
811
  if (!isCompactionSummaryFailure(compactError)) throw compactError;
737
812
  const deferredSteer = await settleDeferredSteerAfterCompaction();
738
813
  if (deferredSteer) return { exit: deferredSteer };
739
- const errorMessage = String(compactionFailureReasonFromError(compactError));
740
814
  observability.error("context compaction failed", {
741
815
  sessionId: input.sessionId,
742
816
  turnId: attempt.turnId,
@@ -747,13 +821,7 @@ export async function runPostAgentCompaction(
747
821
  events: [
748
822
  {
749
823
  type: "turn.failed",
750
- payload: {
751
- error: errorMessage,
752
- code: "context_compaction_failed",
753
- retryable: false,
754
- recovery: "user_message",
755
- compacted: false,
756
- },
824
+ payload: compactionFailureTurnEventPayload(compactError),
757
825
  },
758
826
  { type: "session.status.changed", payload: { status: "idle" } },
759
827
  ],