@opengeni/worker-bundle 0.16.14 → 0.16.17

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.
@@ -15,7 +15,6 @@ import {
15
15
  getSessionEvent,
16
16
  getSessionRootId,
17
17
  getSessionGoal,
18
- getLatestRunState,
19
18
  getHumanInputResumeForEvent,
20
19
  getSessionHumanInputRequest,
21
20
  installOrReadTurnExecutionPolicyForAttempt,
@@ -34,7 +33,6 @@ import {
34
33
  recordSessionActiveCodexCredential,
35
34
  setSessionCodexPin,
36
35
  recordCodexAccountUsageWithWakeTargets,
37
- recordCodexAccountConnectors,
38
36
  quarantineCodexCredentialForLease,
39
37
  setActiveCodexCredential,
40
38
  resolveWorkspaceMemoryBlock,
@@ -76,6 +74,7 @@ import {
76
74
  beginConnectorActionExecution,
77
75
  completeConnectorActionExecution,
78
76
  prepareConnectorActionApproval,
77
+ withCodexAppsRequestAuthorization,
79
78
  type AppendEventInput,
80
79
  type ActiveSandboxPointer,
81
80
  type SandboxRecord,
@@ -93,6 +92,7 @@ import {
93
92
  modelResponseUsageFromSdkEvent,
94
93
  normalizeModelCallUsage,
95
94
  normalizeSdkEvent,
95
+ projectHistoryForProvider,
96
96
  sanitizeHistoryItemsForModel,
97
97
  projectModelInputForCapabilities,
98
98
  appendPersistentSessionSettings,
@@ -122,6 +122,7 @@ import {
122
122
  sandboxFileDownloadFailureNote,
123
123
  SUMMARY_BUFFER_TOKENS,
124
124
  isMcpRequestTimeoutError,
125
+ isMcpTransportConnectivityError,
125
126
  runOwnedSandboxSetup,
126
127
  RoutingMutationOutcomeUnknownError,
127
128
  WorkspaceArchiveIntegrityError,
@@ -210,6 +211,7 @@ import {
210
211
  classifyCodexUsageLimitError,
211
212
  codexRequestStorage,
212
213
  isCodexTransportError,
214
+ opaqueProviderArtifactFingerprint,
213
215
  withCodexRequestOverrides,
214
216
  selectCodexCredentialId,
215
217
  type CodexRequestContext,
@@ -220,6 +222,7 @@ import {
220
222
  assertSessionAllowsProductModel,
221
223
  defaultSessionMcpServerIds,
222
224
  directPersonalConnectionSubjectId,
225
+ resolveCodexAppsCredentialIdForRun,
223
226
  withFrozenPersonalConnectionDelegations,
224
227
  resolveSessionToolPolicy,
225
228
  } from "@opengeni/core";
@@ -273,11 +276,9 @@ import {
273
276
  type SecretForRedaction,
274
277
  } from "./redaction";
275
278
  import {
276
- applyCodexHistoryStrip,
277
279
  createModelHistoryAttachmentProjector,
278
280
  turnInput,
279
281
  type ModelAttachmentInputPolicy,
280
- type TurnCodexAccount,
281
282
  } from "./run-input";
282
283
  import {
283
284
  createRuntimeBatcher,
@@ -463,7 +464,8 @@ export function providerRecoveryResult(input: {
463
464
  input.failureCode === "provider_rate_limited"
464
465
  ? (providerDelay ?? PROVIDER_BACKPRESSURE_DELAY_MS)
465
466
  : input.failureCode === "provider_unavailable" ||
466
- input.failureCode === "upstream_connectivity_unavailable"
467
+ input.failureCode === "upstream_connectivity_unavailable" ||
468
+ input.failureCode === "mcp_transport_unavailable"
467
469
  ? Math.max(
468
470
  providerDelay ?? 0,
469
471
  PROVIDER_CONNECTIVITY_BACKOFF_MS[
@@ -1611,6 +1613,42 @@ export function historyRowsToAppend(
1611
1613
  };
1612
1614
  }
1613
1615
 
1616
+ /** Select only opaque rows that participated in the provider's rejected wire request. */
1617
+ export function selectRejectedProviderArtifactHistoryIds(
1618
+ activeHistory: ReadonlyArray<{
1619
+ id: string;
1620
+ item: Record<string, unknown>;
1621
+ providerArtifactInvalidatedAt: Date | null;
1622
+ }>,
1623
+ candidates: {
1624
+ knownHistoryItemIds: readonly string[];
1625
+ historyItemIds: readonly string[];
1626
+ },
1627
+ wireFingerprints: readonly string[],
1628
+ ): string[] {
1629
+ const remainingWireArtifacts = new Map<string, number>();
1630
+ for (const fingerprint of wireFingerprints) {
1631
+ remainingWireArtifacts.set(fingerprint, (remainingWireArtifacts.get(fingerprint) ?? 0) + 1);
1632
+ }
1633
+ const knownHistoryItemIds = new Set(candidates.knownHistoryItemIds);
1634
+ const initialCandidateIds = new Set(candidates.historyItemIds);
1635
+ const selected: string[] = [];
1636
+ for (const row of activeHistory) {
1637
+ if (row.providerArtifactInvalidatedAt !== null) continue;
1638
+ // A row present before this attempt is eligible only when the exact
1639
+ // model-facing projection retained it. Rows appended during this run are
1640
+ // eligible after durable reconciliation.
1641
+ if (knownHistoryItemIds.has(row.id) && !initialCandidateIds.has(row.id)) continue;
1642
+ const fingerprint = opaqueProviderArtifactFingerprint(row.item);
1643
+ if (!fingerprint) continue;
1644
+ const remaining = remainingWireArtifacts.get(fingerprint) ?? 0;
1645
+ if (remaining === 0) continue;
1646
+ selected.push(row.id);
1647
+ remainingWireArtifacts.set(fingerprint, remaining - 1);
1648
+ }
1649
+ return selected;
1650
+ }
1651
+
1614
1652
  /** Literal final per-call boundary for replayed and current-turn model input. */
1615
1653
  export function secretRedactionModelInputFilter(
1616
1654
  redactValue: (value: unknown) => unknown,
@@ -1634,49 +1672,6 @@ function isModelOrToolProgressHistoryItem(item: Record<string, unknown>): boolea
1634
1672
  return false;
1635
1673
  }
1636
1674
 
1637
- /**
1638
- * Seed the turn-end reconcile watermark (`persistedHistoryCount`) from EXACTLY the
1639
- * view `state.history` was seeded from, so the model-input length and the watermark
1640
- * can NEVER disagree. The watermark is the slice index the reconcile cuts the
1641
- * (re-sanitized) `state.history` at to find this turn's genuinely-new items, so it
1642
- * must equal the length of `state.history`'s already-persisted leading prefix.
1643
- *
1644
- * The cross-account reasoning strip drops foreign reasoning items, so the prefix
1645
- * length is PATH-DEPENDENT, captured by `modelHistoryFromItems`:
1646
- *
1647
- * - items read path (`modelHistoryFromItems === true`) — `state.history` was seeded
1648
- * from the cross-account-STRIPPED active items (foreign reasoning DROPPED), so it
1649
- * starts K shorter than the raw active-row count. Seed from the SAME strip
1650
- * (HOLE D); seeding from the un-stripped count would slice K genuinely-new items
1651
- * off the reconcile and silently lose them (incl. the user's switch-turn message).
1652
- *
1653
- * - approval RunState path (`modelHistoryFromItems === false`) — `state.history` was seeded
1654
- * from the blob, where foreign reasoning is NEUTRALIZED-IN-PLACE (the item is
1655
- * KEPT, only its id/encrypted_content go — see resumeRunStateForCodexAccount), so
1656
- * the blob's history length still COUNTS those items. Applying the strip here
1657
- * under-counts by K and the reconcile re-appends K already-persisted items at
1658
- * fresh positions — HOLE E. So the blob path must NOT strip: count the raw
1659
- * sanitized active length, which mirrors the blob's completed prefix.
1660
- *
1661
- * On a same-account / non-codex turn the strip is a no-op, so both branches reduce
1662
- * to the same raw sanitized count (byte-identical to the pre-strip behaviour).
1663
- * Pure; exported for unit testing the D/E seed invariant.
1664
- */
1665
- export function reconcileSeedCount(
1666
- activeSeedRows: ReadonlyArray<{
1667
- item: Record<string, unknown>;
1668
- producerCodexCredentialId: string | null;
1669
- }>,
1670
- modelHistoryFromItems: boolean,
1671
- current: TurnCodexAccount,
1672
- ): number {
1673
- return sanitizeHistoryItemsForModel(
1674
- modelHistoryFromItems
1675
- ? applyCodexHistoryStrip(activeSeedRows, current)
1676
- : activeSeedRows.map((row) => row.item),
1677
- ).length;
1678
- }
1679
-
1680
1675
  /**
1681
1676
  * Resolve the EFFECTIVE/active compute backend a turn should gate
1682
1677
  * filesystem-touching agent lifecycle hooks on (today: the repository clone).
@@ -3103,6 +3098,12 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
3103
3098
  // stable and this scalar append watermark is valid again. The sanitizer
3104
3099
  // remains the final call/result pairing guard for every other reconcile.
3105
3100
  let persistedHistoryCount = 0;
3101
+ let providerArtifactCandidates: Awaited<
3102
+ ReturnType<typeof turnInput>
3103
+ >["providerArtifactCandidates"] = {
3104
+ knownHistoryItemIds: [],
3105
+ historyItemIds: [],
3106
+ };
3106
3107
  // Next free WHOLE-NUMBER absolute position to append at. Tracked separately
3107
3108
  // from persistedHistoryCount (the in-memory slice index) because a compaction
3108
3109
  // inserts a fractional summary position, so total rows no longer equal
@@ -3137,11 +3138,6 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
3137
3138
  turnId,
3138
3139
  expectedExecutionGeneration: executionGeneration,
3139
3140
  expectedAttemptId: input.attemptId,
3140
- // Tag each row with the codex account that produced it (null on the
3141
- // non-codex path). Resolved at line ~504 before any reconcile pass
3142
- // runs, so this is the turn's effective account. The read path uses
3143
- // it to strip cross-account reasoning.encrypted_content next turn.
3144
- producerCodexCredentialId: effectiveCodexCredentialId,
3145
3141
  modelToolOutputTruncationTokens: modelRunSettings.modelToolOutputTruncationTokens,
3146
3142
  items: rows,
3147
3143
  });
@@ -3202,7 +3198,7 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
3202
3198
  // a per-call usage log can report whether the serving account CHANGED since the
3203
3199
  // session's previous call (the prompt-cache account-switch hypothesis).
3204
3200
  let priorSessionCodexCredentialId: string | null = null;
3205
- // Multi-account P4 (Part A): the latest usage-header snapshot scraped FOR FREE
3201
+ // The latest usage-header snapshot scraped for free
3206
3202
  // off this turn's `/codex/responses` responses (a turn issues many model calls;
3207
3203
  // latest wins). Flushed ONCE into the P2 usage cache for the serving account in
3208
3204
  // the `finally` — cheaper than a /wham/usage poll AND it self-heals P3 rotation
@@ -3210,6 +3206,7 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
3210
3206
  // Hoisted to activity scope so the finally flush (below) sees it. The sink is
3211
3207
  // wired into codexContext.onUsageHeaders inside the try.
3212
3208
  let latestCodexUsage: CodexUsageHeaderSnapshot | null = null;
3209
+ let lastCodexRequestOpaqueArtifacts: readonly string[] = [];
3213
3210
  // Hoisted for same-turn recovery: an approval-decision rerun must
3214
3211
  // re-enter through the approval resume path (its frozen mid-flight state
3215
3212
  // only exists in the RunState blob), never through a swapped trigger.
@@ -3239,6 +3236,9 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
3239
3236
  input.workspaceId,
3240
3237
  codexSettings,
3241
3238
  );
3239
+ const codexAppsCredentialId = capabilitySettings.codexConnectedAppsEnabled
3240
+ ? await resolveCodexAppsCredentialIdForRun(db, input.workspaceId)
3241
+ : null;
3242
3242
  runtime.configure(capabilitySettings);
3243
3243
  const session = await requireSession(db, input.workspaceId, input.sessionId);
3244
3244
  const claim = await claimSessionWorkForAttempt(db, input.workspaceId, {
@@ -3302,9 +3302,6 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
3302
3302
  trigger,
3303
3303
  );
3304
3304
  triggerType = trigger.type;
3305
- const latestTurnState = await getLatestRunState(db, input.workspaceId, input.sessionId);
3306
- const continuationCodexCredentialId =
3307
- latestTurnState?.turnId === turnId ? latestTurnState.frozenCodexCredentialId : null;
3308
3305
  redispatchesAtDispatch = Number(
3309
3306
  (turn.metadata as { workerDeathRedispatches?: number } | null)?.workerDeathRedispatches ??
3310
3307
  0,
@@ -3548,7 +3545,6 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
3548
3545
  sessionPinnedCredentialId: sessionPin,
3549
3546
  sessionPinSource,
3550
3547
  sessionLastCredentialId: sessionCodex?.lastCredentialId ?? null,
3551
- continuationCredentialId: continuationCodexCredentialId,
3552
3548
  now: new Date(),
3553
3549
  });
3554
3550
 
@@ -3567,7 +3563,6 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
3567
3563
  turnId,
3568
3564
  holderId: codexLeaseHolderId,
3569
3565
  advanceActivePointer: sessionPin === null,
3570
- continuationCredentialId: continuationCodexCredentialId,
3571
3566
  },
3572
3567
  selectForTurn,
3573
3568
  );
@@ -3623,7 +3618,6 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
3623
3618
  turnId,
3624
3619
  holderId: codexLeaseHolderId,
3625
3620
  advanceActivePointer: sessionPin === null,
3626
- continuationCredentialId: continuationCodexCredentialId,
3627
3621
  },
3628
3622
  selectForTurn,
3629
3623
  );
@@ -3773,10 +3767,7 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
3773
3767
  : rotationDecision.kind === "allCapped"
3774
3768
  ? "all_capped"
3775
3769
  : "none";
3776
- const fencedInFlight =
3777
- leased.reused ||
3778
- (continuationCodexCredentialId !== null &&
3779
- continuationCodexCredentialId === effectiveCodexCredentialId);
3770
+ const fencedInFlight = leased.reused;
3780
3771
  const shadowResult = await publishCodexFleetShadowDecisionV1({
3781
3772
  enabled: settings.codexFleetPolicyShadowEnabled,
3782
3773
  decision: {
@@ -4090,11 +4081,6 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
4090
4081
  );
4091
4082
  if (priorAccountId !== effectiveCodexCredentialId) {
4092
4083
  const rotated = rotationDecision.kind === "active" && rotationDecision.moved;
4093
- // P4: surface the dropped-connector note when this rotation pick couldn't
4094
- // cover the session's used connectors (a Tier-2/unknown failover); the pill
4095
- // renders the badge. Omitted when the switch covered everything (the norm).
4096
- const droppedConnectors =
4097
- rotationDecision.kind === "active" ? rotationDecision.droppedConnectors : undefined;
4098
4084
  await publish([
4099
4085
  {
4100
4086
  type: "codex.account.switched",
@@ -4102,9 +4088,6 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
4102
4088
  fromAccountId: priorAccountId,
4103
4089
  toAccountId: effectiveCodexCredentialId,
4104
4090
  reason: rotated ? "rotation" : "manual",
4105
- ...(droppedConnectors && droppedConnectors.length > 0
4106
- ? { droppedConnectors }
4107
- : {}),
4108
4091
  },
4109
4092
  },
4110
4093
  ]);
@@ -4262,6 +4245,7 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
4262
4245
  turnExecutionPolicy.productModelId,
4263
4246
  );
4264
4247
  const supportsImageInput = modelSupportsImageInputForTurn(resolvedModel);
4248
+ const providerApi = resolvedModel?.provider.api ?? "responses";
4265
4249
  const modelInputPolicy = modelAttachmentInputPolicyForTurn(resolvedModel);
4266
4250
  const attachmentProjector = createModelHistoryAttachmentProjector(
4267
4251
  db,
@@ -4271,6 +4255,8 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
4271
4255
  );
4272
4256
  const modelHistoryProjector = async (items: Array<Record<string, unknown>>) =>
4273
4257
  projectModelInputForCapabilities(await attachmentProjector(items), modelInputPolicy);
4258
+ const compactionModelHistoryProjector = async (items: Array<Record<string, unknown>>) =>
4259
+ await modelHistoryProjector(projectHistoryForProvider(items, providerApi));
4274
4260
  const selectedProvider = resolvedModel?.provider;
4275
4261
  const publicProviderHeaders = new Set(
4276
4262
  selectedProvider?.publicDefaultHeaderNames?.map((name) => name.toLowerCase()) ?? [],
@@ -4395,6 +4381,9 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
4395
4381
  onUsageHeaders: (snapshot) => {
4396
4382
  latestCodexUsage = snapshot;
4397
4383
  }, // latest wins; flushed once in finally
4384
+ onRequestOpaqueArtifacts: ({ fingerprints }) => {
4385
+ lastCodexRequestOpaqueArtifacts = fingerprints;
4386
+ },
4398
4387
  nextRequestId: () => `${dispatchId}:${++codexModelRequestSequence}`,
4399
4388
  onModelRequestEvent: async (event) => {
4400
4389
  if (!publish || !turnId) {
@@ -4564,9 +4553,6 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
4564
4553
  ...(remoteCompactionRequester
4565
4554
  ? { requestRemoteCompactionV2: remoteCompactionRequester }
4566
4555
  : {}),
4567
- ...(effectiveCodexCredentialId
4568
- ? { producerCodexCredentialId: effectiveCodexCredentialId }
4569
- : {}),
4570
4556
  } as const;
4571
4557
 
4572
4558
  // Operator /compact:
@@ -4630,10 +4616,7 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
4630
4616
  force: true,
4631
4617
  clearRequestedCompaction: true,
4632
4618
  trigger: "operator",
4633
- codexAccount: {
4634
- currentCodexCredentialId: effectiveCodexCredentialId,
4635
- },
4636
- projectModelInput: modelHistoryProjector,
4619
+ projectModelInput: compactionModelHistoryProjector,
4637
4620
  ...compactionModeOptions,
4638
4621
  },
4639
4622
  ),
@@ -5608,10 +5591,8 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
5608
5591
  connectionCredentials?.mcpCredentials && hostCredentialRootSessionId
5609
5592
  ? hostCredentialRootSessionId
5610
5593
  : input.sessionId;
5611
- // Wrap MCP prep in the codex ALS so the codex_apps connect handshake
5612
- // (initialize + tools/list) can resolve the per-workspace bearer from
5613
- // codexRequestStorage (runtime/codexAppsMcpRequestInit). withCodex is the
5614
- // identity on every non-codex turn, so this is a no-op for existing paths.
5594
+ // Connection credentials and the optional Apps credential are resolved
5595
+ // independently. Inference auth is never an Apps fallback.
5615
5596
  const rawResolveCredential = connectionTokenResolverForTurn({
5616
5597
  db,
5617
5598
  settings: runSettings,
@@ -5648,36 +5629,64 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
5648
5629
  return result;
5649
5630
  };
5650
5631
  const credentialSubjectId = credentialSubjectIdForTurnInitiator(turn);
5632
+ const codexAppsAuth = codexAppsCredentialId
5633
+ ? (() => {
5634
+ const resolver = buildCodexTokenResolver(
5635
+ db,
5636
+ runSettings,
5637
+ input.workspaceId,
5638
+ codexAppsCredentialId,
5639
+ );
5640
+ return {
5641
+ clientVersion: CODEX_CLIENT_VERSION,
5642
+ withAuthorization: async <T>(
5643
+ use: (token: {
5644
+ accessToken: string;
5645
+ chatgptAccountId: string | null;
5646
+ }) => Promise<T>,
5647
+ ): Promise<T> => {
5648
+ const snapshot = await resolver.getToken();
5649
+ registerSecretRedactions([
5650
+ { name: "CODEX_APPS_ACCESS_TOKEN", value: snapshot.accessToken },
5651
+ ]);
5652
+ return await withCodexAppsRequestAuthorization(
5653
+ db,
5654
+ { workspaceId: input.workspaceId, credentialId: codexAppsCredentialId },
5655
+ async () => await use(snapshot),
5656
+ );
5657
+ },
5658
+ };
5659
+ })()
5660
+ : undefined;
5651
5661
  preparedTools = await waitForTurnOperation(
5652
- withCodex(() =>
5653
- runtime.prepareTools(runSettings, turnTools, {
5654
- accountId: input.accountId,
5655
- workspaceId: input.workspaceId,
5656
- sessionId: input.sessionId,
5657
- // Sign the calling turn into the first-party token so tools classify
5658
- // the caller by its own identity (sacred-pause guard), not the racy
5659
- // live active pointer.
5660
- ...(turnId ? { turnId } : {}),
5661
- attemptId: input.attemptId,
5662
- executionGeneration,
5663
- subjectId: "worker:first-party-mcp",
5664
- subjectLabel: "OpenGeni worker",
5665
- ...(credentialSubjectId ? { credentialSubjectId } : {}),
5666
- resolveCredential,
5667
- onAuthNeeded: async (payload) => {
5668
- if (!shouldPublishToolAuthNeededForTurn(payload, trigger, turn)) {
5669
- return;
5670
- }
5671
- await publish!([{ type: "tool.auth_needed", payload }], true);
5672
- },
5673
- // Manager-style sessions carry a creation-validated permission set
5674
- // for their first-party MCP token; null keeps the fixed default.
5675
- ...(session.firstPartyMcpPermissions?.length
5676
- ? { firstPartyPermissions: session.firstPartyMcpPermissions }
5677
- : {}),
5678
- firstPartyTools: session.firstPartyMcpTools ?? [...DEFAULT_FIRST_PARTY_MCP_TOOLS],
5679
- }),
5680
- ),
5662
+ runtime.prepareTools(runSettings, turnTools, {
5663
+ accountId: input.accountId,
5664
+ workspaceId: input.workspaceId,
5665
+ sessionId: input.sessionId,
5666
+ // Sign the calling turn into the first-party token so tools classify
5667
+ // the caller by its own identity (sacred-pause guard), not the racy
5668
+ // live active pointer.
5669
+ ...(turnId ? { turnId } : {}),
5670
+ attemptId: input.attemptId,
5671
+ executionGeneration,
5672
+ subjectId: "worker:first-party-mcp",
5673
+ subjectLabel: "OpenGeni worker",
5674
+ ...(credentialSubjectId ? { credentialSubjectId } : {}),
5675
+ ...(codexAppsAuth ? { codexAppsAuth } : {}),
5676
+ resolveCredential,
5677
+ onAuthNeeded: async (payload) => {
5678
+ if (!shouldPublishToolAuthNeededForTurn(payload, trigger, turn)) {
5679
+ return;
5680
+ }
5681
+ await publish!([{ type: "tool.auth_needed", payload }], true);
5682
+ },
5683
+ // Manager-style sessions carry a creation-validated permission set
5684
+ // for their first-party MCP token; null keeps the fixed default.
5685
+ ...(session.firstPartyMcpPermissions?.length
5686
+ ? { firstPartyPermissions: session.firstPartyMcpPermissions }
5687
+ : {}),
5688
+ firstPartyTools: session.firstPartyMcpTools ?? [...DEFAULT_FIRST_PARTY_MCP_TOOLS],
5689
+ }),
5681
5690
  cancellationSignal,
5682
5691
  async (latePreparedTools) => await latePreparedTools.close().catch(() => undefined),
5683
5692
  );
@@ -6161,10 +6170,7 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
6161
6170
  force: true,
6162
6171
  clearRequestedCompaction: true,
6163
6172
  trigger: "operator",
6164
- codexAccount: {
6165
- currentCodexCredentialId: effectiveCodexCredentialId,
6166
- },
6167
- projectModelInput: modelHistoryProjector,
6173
+ projectModelInput: compactionModelHistoryProjector,
6168
6174
  ...compactionModeOptions,
6169
6175
  },
6170
6176
  ),
@@ -6296,18 +6302,12 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
6296
6302
  force: true,
6297
6303
  clearRequestedCompaction: true,
6298
6304
  trigger: "operator",
6299
- codexAccount: {
6300
- currentCodexCredentialId: effectiveCodexCredentialId,
6301
- },
6302
- projectModelInput: modelHistoryProjector,
6305
+ projectModelInput: compactionModelHistoryProjector,
6303
6306
  ...compactionModeOptions,
6304
6307
  }
6305
6308
  : {
6306
6309
  trigger: "auto",
6307
- codexAccount: {
6308
- currentCodexCredentialId: effectiveCodexCredentialId,
6309
- },
6310
- projectModelInput: modelHistoryProjector,
6310
+ projectModelInput: compactionModelHistoryProjector,
6311
6311
  ...compactionModeOptions,
6312
6312
  },
6313
6313
  ),
@@ -6444,35 +6444,25 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
6444
6444
  const unavailableSandboxFilesNote = sandboxFileDownloadFailureNote(
6445
6445
  fileMaterializationFailures,
6446
6446
  );
6447
- // Cross-account reasoning strip: pass THIS turn's codex account so every
6448
- // history read path (items + run-state replay) drops reasoning produced by
6449
- // a DIFFERENT codex account. effectiveCodexCredentialId is the resolved
6450
- // codex credential on a codex turn (pin > workspace-active) and null on a
6451
- // non-codex turn OR a codex turn with no usable account — exactly the
6452
- // "current account" the single strip rule compares against (null is the
6453
- // built-in/Azure account, so a non-codex turn still drops codex-produced
6454
- // reasoning, and a no-codex-history session is a byte-for-byte no-op).
6447
+ // Build one attempt from canonical history. The provider adapter creates
6448
+ // only the temporary wire view required by this turn's selected API;
6449
+ // subscription identity never edits or filters durable history.
6455
6450
  const activeTurnId = turnId;
6456
6451
  if (!activeTurnId) {
6457
6452
  throw new Error("Turn id was not initialized");
6458
6453
  }
6459
6454
  let runInput: Awaited<ReturnType<typeof turnInput>>["input"] | null = null;
6460
6455
  const prepareRunAttemptInput = async () => {
6461
- const prepared = await turnInput(
6462
- db,
6463
- runtime,
6464
- agent,
6465
- trigger,
6466
- { currentCodexCredentialId: effectiveCodexCredentialId },
6467
- {
6468
- turnId: activeTurnId,
6469
- recovering: turn.executionGeneration > 1,
6470
- ...(unavailableSandboxFilesNote ? { unavailableSandboxFilesNote } : {}),
6471
- ...(runCredentialsNote ? { runCredentialsNote } : {}),
6472
- projectModelHistory: modelHistoryProjector,
6473
- },
6474
- );
6456
+ const prepared = await turnInput(db, runtime, agent, trigger, {
6457
+ turnId: activeTurnId,
6458
+ recovering: turn.executionGeneration > 1,
6459
+ ...(unavailableSandboxFilesNote ? { unavailableSandboxFilesNote } : {}),
6460
+ ...(runCredentialsNote ? { runCredentialsNote } : {}),
6461
+ providerApi,
6462
+ projectModelHistory: modelHistoryProjector,
6463
+ });
6475
6464
  runInput = prepared.input;
6465
+ providerArtifactCandidates = prepared.providerArtifactCandidates;
6476
6466
  // Slice index = the length of the model-facing (active) history this turn
6477
6467
  // is seeded from; new items beyond it (the trigger message + this turn's
6478
6468
  // generated items) are the ones to persist. After a compaction this is the
@@ -6494,18 +6484,7 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
6494
6484
  // and bricks the session (issue-61). The sanitized seed is already
6495
6485
  // orphan-free, so it is a stable prefix of the re-sanitized history and the
6496
6486
  // slice begins exactly at the first genuinely-new item.
6497
- const activeSeedRows = await getActiveSessionHistoryItems(
6498
- db,
6499
- input.workspaceId,
6500
- input.sessionId,
6501
- );
6502
- // Seed the reconcile watermark from EXACTLY the view the model's
6503
- // `state.history` was seeded from (items strip on the items path = HOLE D; NO
6504
- // strip on the run-state blob path, where foreign reasoning is neutralized but
6505
- // KEPT = HOLE E), so the model-input length and the watermark never disagree.
6506
- persistedHistoryCount = reconcileSeedCount(activeSeedRows, prepared.modelHistoryFromItems, {
6507
- currentCodexCredentialId: effectiveCodexCredentialId,
6508
- });
6487
+ persistedHistoryCount = prepared.persistedHistoryCount;
6509
6488
  nextHistoryPosition = await nextSessionHistoryPosition(
6510
6489
  db,
6511
6490
  input.workspaceId,
@@ -6540,10 +6519,7 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
6540
6519
  force: true,
6541
6520
  ...(triggerLabel === "operator" ? { clearRequestedCompaction: true } : {}),
6542
6521
  trigger: triggerLabel,
6543
- codexAccount: {
6544
- currentCodexCredentialId: effectiveCodexCredentialId,
6545
- },
6546
- projectModelInput: modelHistoryProjector,
6522
+ projectModelInput: compactionModelHistoryProjector,
6547
6523
  ...compactionModeOptions,
6548
6524
  },
6549
6525
  ),
@@ -7071,7 +7047,6 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
7071
7047
  runState: {
7072
7048
  serializedRunState: stream.state.toString(),
7073
7049
  pendingApprovals: approvals,
7074
- frozenCodexCredentialId: effectiveCodexCredentialId,
7075
7050
  humanInputRequests: humanInputRequests.map(
7076
7051
  ({ isNew: _isNew, ...request }) => request,
7077
7052
  ),
@@ -7735,7 +7710,6 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
7735
7710
  priorCredentialId: effectiveCodexCredentialId,
7736
7711
  accounts,
7737
7712
  now: new Date(),
7738
- usedConnectors: serving?.connectorNamespaces ?? [],
7739
7713
  })
7740
7714
  : ({ kind: "none" } as const);
7741
7715
  const candidateAvailable =
@@ -7951,9 +7925,6 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
7951
7925
  priorCredentialId: effectiveCodexCredentialId,
7952
7926
  accounts: fresh,
7953
7927
  now: new Date(),
7954
- // P4: the just-capped serving account's connector set is the proxy for
7955
- // "what this session has access to" — prefer a covering failover target.
7956
- usedConnectors: serving?.connectorNamespaces ?? [],
7957
7928
  });
7958
7929
  if (decision.kind === "active") {
7959
7930
  rotated = true;
@@ -8164,8 +8135,9 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
8164
8135
  // credential-row UUID is unchanged. HTTP 400 + the exact provider
8165
8136
  // semantic proves this request never entered inference. Atomically mark
8166
8137
  // the active opaque artifacts rejected and recover the SAME logical turn
8167
- // from durable history; messages, tool calls/results, summaries, and the
8168
- // original audit rows remain intact. If no artifact can be invalidated,
8138
+ // from durable history; messages, tool calls/results, readable reasoning,
8139
+ // and the original audit rows remain intact. Opaque remote compaction has
8140
+ // no portable plaintext representation. If no artifact can be invalidated,
8169
8141
  // fall through to the terminal path rather than resend an equivalent
8170
8142
  // request forever.
8171
8143
  const encryptedArtifactRejection =
@@ -8181,6 +8153,20 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
8181
8153
  ) {
8182
8154
  await flushRuntimeBatcher();
8183
8155
  await reconcileConversationTruth({ requireDurable: true });
8156
+ const activeHistory = await getActiveSessionHistoryItems(
8157
+ db,
8158
+ input.workspaceId,
8159
+ input.sessionId,
8160
+ );
8161
+ const rejectedHistoryItemIds = selectRejectedProviderArtifactHistoryIds(
8162
+ activeHistory,
8163
+ providerArtifactCandidates,
8164
+ lastCodexRequestOpaqueArtifacts,
8165
+ );
8166
+ const rejectedRunStateId =
8167
+ providerArtifactCandidates.runStateId && lastCodexRequestOpaqueArtifacts.length > 0
8168
+ ? providerArtifactCandidates.runStateId
8169
+ : undefined;
8184
8170
  const recovery = await requestSessionTurnRecovery(db, input.workspaceId, {
8185
8171
  sessionId: input.sessionId,
8186
8172
  turnId,
@@ -8192,7 +8178,8 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
8192
8178
  retryable: true,
8193
8179
  },
8194
8180
  providerArtifactInvalidation: {
8195
- codexCredentialId: effectiveCodexCredentialId,
8181
+ historyItemIds: rejectedHistoryItemIds,
8182
+ ...(rejectedRunStateId ? { runStateId: rejectedRunStateId } : {}),
8196
8183
  reason: encryptedArtifactRejection.kind,
8197
8184
  },
8198
8185
  });
@@ -8543,19 +8530,6 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
8543
8530
  );
8544
8531
  }
8545
8532
  }
8546
- // Part B.1: the connector namespaces codex_apps listed this turn → the
8547
- // connector-set cache. NON-EMPTY-only: a flaky/empty tools/list must never
8548
- // overwrite a known set with [] (false coverage drop). Read by reference
8549
- // AFTER the run, so every tools/list this turn has accumulated.
8550
- const connectorNamespaces = preparedTools?.codexConnectorNamespaces;
8551
- if (connectorNamespaces && connectorNamespaces.size > 0) {
8552
- await waitForTurnFinalizerStep(
8553
- recordCodexAccountConnectors(db, input.workspaceId, effectiveCodexCredentialId, [
8554
- ...connectorNamespaces,
8555
- ]).catch(() => undefined),
8556
- finalizerSignal,
8557
- );
8558
- }
8559
8533
  }
8560
8534
  if (codexLeaseHeartbeatTimer) {
8561
8535
  clearInterval(codexLeaseHeartbeatTimer);
@@ -9032,6 +9006,14 @@ export function agentRunFailurePayload(
9032
9006
  : {}),
9033
9007
  };
9034
9008
  }
9009
+ if (isMcpTransportConnectivityError(error)) {
9010
+ return {
9011
+ error:
9012
+ "A required MCP server was temporarily unreachable. The same turn will retry after a short delay.",
9013
+ code: "mcp_transport_unavailable",
9014
+ retryable: true,
9015
+ };
9016
+ }
9035
9017
  if (
9036
9018
  status === 429 ||
9037
9019
  code === "rate_limit_exceeded" ||
@@ -94,7 +94,6 @@ export function codexCapacityDecision(
94
94
  sessionPinnedCredentialId: context.sessionPinnedCredentialId,
95
95
  sessionPinSource: context.sessionPinSource,
96
96
  sessionLastCredentialId: context.sessionLastCredentialId,
97
- continuationCredentialId: null,
98
97
  now,
99
98
  });
100
99
  if (selected.credentialId) {