@opengeni/worker-bundle 0.16.13 → 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.
package/dist/index.js CHANGED
@@ -60,7 +60,6 @@ import {
60
60
  getSessionEvent as getSessionEvent2,
61
61
  getSessionRootId as getSessionRootId2,
62
62
  getSessionGoal as getSessionGoal3,
63
- getLatestRunState as getLatestRunState2,
64
63
  getHumanInputResumeForEvent as getHumanInputResumeForEvent2,
65
64
  getSessionHumanInputRequest,
66
65
  installOrReadTurnExecutionPolicyForAttempt,
@@ -79,7 +78,6 @@ import {
79
78
  recordSessionActiveCodexCredential,
80
79
  setSessionCodexPin,
81
80
  recordCodexAccountUsageWithWakeTargets,
82
- recordCodexAccountConnectors,
83
81
  quarantineCodexCredentialForLease,
84
82
  setActiveCodexCredential,
85
83
  resolveWorkspaceMemoryBlock,
@@ -120,7 +118,8 @@ import {
120
118
  PreferenceRegistryInitiatorError,
121
119
  beginConnectorActionExecution,
122
120
  completeConnectorActionExecution,
123
- prepareConnectorActionApproval
121
+ prepareConnectorActionApproval,
122
+ withCodexAppsRequestAuthorization
124
123
  } from "@opengeni/db";
125
124
  import { appendAndPublishTurnEventsFenced, publishDurableSessionEvents } from "@opengeni/events";
126
125
  import { sandboxOperationMetricObserver } from "@opengeni/observability";
@@ -131,6 +130,7 @@ import {
131
130
  modelResponseUsageFromSdkEvent,
132
131
  normalizeModelCallUsage,
133
132
  normalizeSdkEvent,
133
+ projectHistoryForProvider as projectHistoryForProvider2,
134
134
  sanitizeHistoryItemsForModel as sanitizeHistoryItemsForModel2,
135
135
  projectModelInputForCapabilities,
136
136
  appendPersistentSessionSettings,
@@ -160,6 +160,7 @@ import {
160
160
  sandboxFileDownloadFailureNote,
161
161
  SUMMARY_BUFFER_TOKENS as SUMMARY_BUFFER_TOKENS2,
162
162
  isMcpRequestTimeoutError,
163
+ isMcpTransportConnectivityError,
163
164
  runOwnedSandboxSetup,
164
165
  RoutingMutationOutcomeUnknownError,
165
166
  WorkspaceArchiveIntegrityError as WorkspaceArchiveIntegrityError2,
@@ -326,28 +327,6 @@ function bindingRemaining(acct, now) {
326
327
  function cooling(acct, now) {
327
328
  return acct.exhaustedUntil != null && acct.exhaustedUntil.getTime() > now.getTime();
328
329
  }
329
- function covers(acct, usedConnectors) {
330
- if (usedConnectors.length === 0) {
331
- return true;
332
- }
333
- const owned = acct.connectorNamespaces;
334
- if (owned === null) {
335
- return false;
336
- }
337
- const ownedSet = new Set(owned);
338
- return usedConnectors.every((connector) => ownedSet.has(connector));
339
- }
340
- function droppedConnectorsFor(acct, usedConnectors) {
341
- if (usedConnectors.length === 0) {
342
- return [];
343
- }
344
- const owned = acct.connectorNamespaces;
345
- if (owned === null) {
346
- return [...usedConnectors];
347
- }
348
- const ownedSet = new Set(owned);
349
- return usedConnectors.filter((connector) => !ownedSet.has(connector));
350
- }
351
330
  function isCodexCredentialHealthy(acct, now) {
352
331
  return acct.status === "active" && !cooling(acct, now) && bindingUsedPct(acct, now) < CODEX_USAGE_EXHAUSTED_PCT;
353
332
  }
@@ -454,7 +433,6 @@ function chooseRotationActive(args) {
454
433
  const { activeCredentialId, priorCredentialId, accounts, now } = args;
455
434
  const rotationStrategy = effectiveRotationStrategy(args.rotationStrategy);
456
435
  const allocatableAccounts = accounts.filter((account) => account.allocatorEnabled);
457
- const usedConnectors = args.usedConnectors ?? [];
458
436
  if (allocatableAccounts.length === 0) {
459
437
  return { kind: "none" };
460
438
  }
@@ -466,12 +444,10 @@ function chooseRotationActive(args) {
466
444
  earliestResetAt: earliestReset(allocatableAccounts, now)
467
445
  };
468
446
  }
469
- const dropped = droppedConnectorsFor(chosen2, usedConnectors);
470
447
  return {
471
448
  kind: "active",
472
449
  credentialId: chosen2.id,
473
- moved: chosen2.id !== activeCredentialId,
474
- ...dropped.length > 0 ? { droppedConnectors: dropped } : {}
450
+ moved: chosen2.id !== activeCredentialId
475
451
  };
476
452
  };
477
453
  if (rotationStrategy === "round_robin") {
@@ -496,12 +472,10 @@ function chooseRotationActive(args) {
496
472
  }
497
473
  return decide(eligibles[0]);
498
474
  }
499
- const covering = eligibles.filter((acct) => covers(acct, usedConnectors));
500
- const pool = covering.length > 0 ? covering : eligibles;
501
475
  const activeLeases = (acct) => "activeLeaseCount" in acct ? acct.activeLeaseCount : 0;
502
476
  const selections = (acct) => "selectionCount" in acct ? acct.selectionCount : 0;
503
477
  const lastSelected = (acct) => "lastSelectedAt" in acct && acct.lastSelectedAt ? acct.lastSelectedAt.getTime() : 0;
504
- const chosen = pool.reduce((best, acct) => {
478
+ const chosen = eligibles.reduce((best, acct) => {
505
479
  if (!best) {
506
480
  return acct;
507
481
  }
@@ -558,18 +532,6 @@ function selectCodexCredentialLeaseForTurn(args) {
558
532
  }
559
533
  };
560
534
  }
561
- const continuation = args.continuationCredentialId ? accounts.find((account) => account.id === args.continuationCredentialId) : void 0;
562
- if (continuation && isCodexCredentialHealthy(continuation, args.now)) {
563
- return {
564
- credentialId: continuation.id,
565
- advanceActivePointer: false,
566
- decision: {
567
- kind: "active",
568
- credentialId: continuation.id,
569
- moved: continuation.id !== activeCredentialId
570
- }
571
- };
572
- }
573
535
  const connectedIds = new Set(
574
536
  accounts.filter((account) => account.allocatorEnabled).map((account) => account.id)
575
537
  );
@@ -650,8 +612,7 @@ function selectCodexCredentialLeaseForTurn(args) {
650
612
  // the workspace pointer is only correct when this session has never run.
651
613
  priorCredentialId: priorId,
652
614
  accounts,
653
- now: args.now,
654
- usedConnectors: accounts.find((account) => account.id === priorId)?.connectorNamespaces ?? []
615
+ now: args.now
655
616
  });
656
617
  return {
657
618
  credentialId: decision.kind === "active" ? decision.credentialId : null,
@@ -908,7 +869,6 @@ function codexCapacityDecision(context, settings) {
908
869
  sessionPinnedCredentialId: context.sessionPinnedCredentialId,
909
870
  sessionPinSource: context.sessionPinSource,
910
871
  sessionLastCredentialId: context.sessionLastCredentialId,
911
- continuationCredentialId: null,
912
872
  now
913
873
  });
914
874
  if (selected.credentialId) {
@@ -1019,6 +979,7 @@ import {
1019
979
  classifyCodexUsageLimitError,
1020
980
  codexRequestStorage,
1021
981
  isCodexTransportError,
982
+ opaqueProviderArtifactFingerprint,
1022
983
  withCodexRequestOverrides,
1023
984
  selectCodexCredentialId
1024
985
  } from "@opengeni/codex";
@@ -1053,6 +1014,7 @@ import {
1053
1014
  assertSessionAllowsProductModel,
1054
1015
  defaultSessionMcpServerIds,
1055
1016
  directPersonalConnectionSubjectId,
1017
+ resolveCodexAppsCredentialIdForRun,
1056
1018
  withFrozenPersonalConnectionDelegations,
1057
1019
  resolveSessionToolPolicy
1058
1020
  } from "@opengeni/core";
@@ -1097,40 +1059,35 @@ import {
1097
1059
  requireFile
1098
1060
  } from "@opengeni/db";
1099
1061
  import {
1100
- stripReasoningEncryptedContent,
1101
- stripReasoningIdentityFromSerializedRunState,
1102
- neutralizeToolSearchItemsInSerializedRunState
1062
+ projectHistoryForProvider,
1063
+ projectRejectedProviderArtifactsFromSerializedRunState,
1064
+ projectRejectedReasoningArtifact,
1065
+ hasOpaqueProviderArtifact
1103
1066
  } from "@opengeni/runtime";
1104
- var NON_CODEX_TURN = { currentCodexCredentialId: null };
1105
- function applyCodexHistoryStrip(rows, current) {
1067
+ function projectRejectedProviderArtifacts(rows) {
1106
1068
  const out = [];
1107
1069
  for (const row of rows) {
1108
- if (row.producerCodexCredentialId === current.currentCodexCredentialId && !row.providerArtifactInvalidatedAt) {
1070
+ if (!row.providerArtifactInvalidatedAt) {
1109
1071
  out.push(row.item);
1110
1072
  continue;
1111
1073
  }
1112
1074
  const type = typeof row.item.type === "string" ? row.item.type : void 0;
1113
1075
  if (type === "reasoning") {
1114
- continue;
1115
- }
1116
- if (type === "tool_search_call" || type === "tool_search_output") {
1076
+ out.push(projectRejectedReasoningArtifact(row.item));
1117
1077
  continue;
1118
1078
  }
1119
1079
  if (type === "compaction") {
1120
- out.push(stripReasoningEncryptedContent(row.item));
1121
1080
  continue;
1122
1081
  }
1123
1082
  out.push(row.item);
1124
1083
  }
1125
1084
  return out;
1126
1085
  }
1127
- function resumeRunStateForCodexAccount(state, current) {
1128
- if (state.frozenCodexCredentialId === current.currentCodexCredentialId && !state.providerArtifactInvalidatedAt) {
1086
+ function resumeRunState(state) {
1087
+ if (!state.providerArtifactInvalidatedAt) {
1129
1088
  return state.serializedRunState;
1130
1089
  }
1131
- return neutralizeToolSearchItemsInSerializedRunState(
1132
- stripReasoningIdentityFromSerializedRunState(state.serializedRunState)
1133
- );
1090
+ return projectRejectedProviderArtifactsFromSerializedRunState(state.serializedRunState);
1134
1091
  }
1135
1092
  var MAX_INLINE_MODEL_ATTACHMENT_BYTES = 20 * 1024 * 1024;
1136
1093
  var MODEL_IMAGE_CONTENT_TYPES = /* @__PURE__ */ new Set(["image/gif", "image/jpeg", "image/png", "image/webp"]);
@@ -1322,7 +1279,7 @@ function withCurrentUserAttachmentRefs(historyItems, refs) {
1322
1279
  }
1323
1280
  return historyItems;
1324
1281
  }
1325
- async function turnInput(db, runtime, agent, trigger, current = NON_CODEX_TURN, options) {
1282
+ async function turnInput(db, runtime, agent, trigger, options) {
1326
1283
  if (!trigger) {
1327
1284
  throw new Error("Missing trigger event");
1328
1285
  }
@@ -1367,8 +1324,8 @@ async function turnInput(db, runtime, agent, trigger, current = NON_CODEX_TURN,
1367
1324
  trigger,
1368
1325
  void 0,
1369
1326
  joinInternalContext(internalContext, attachmentContext),
1370
- current,
1371
1327
  fileAttachments.map((attachment) => attachment.resource),
1328
+ options.providerApi,
1372
1329
  options.projectModelHistory
1373
1330
  );
1374
1331
  }
@@ -1376,7 +1333,17 @@ async function turnInput(db, runtime, agent, trigger, current = NON_CODEX_TURN,
1376
1333
  if (updates.length === 0) {
1377
1334
  throw new Error("Internal update inference has no delivered updates");
1378
1335
  }
1379
- return await messageInput(db, runtime, agent, trigger, void 0, internalContext, current);
1336
+ return await messageInput(
1337
+ db,
1338
+ runtime,
1339
+ agent,
1340
+ trigger,
1341
+ void 0,
1342
+ internalContext,
1343
+ [],
1344
+ options.providerApi,
1345
+ options.projectModelHistory
1346
+ );
1380
1347
  }
1381
1348
  if (trigger.type === "user.approvalDecision") {
1382
1349
  const payload = trigger.payload;
@@ -1384,22 +1351,21 @@ async function turnInput(db, runtime, agent, trigger, current = NON_CODEX_TURN,
1384
1351
  if (!state) {
1385
1352
  throw new Error("No saved run state is available for approval decision");
1386
1353
  }
1354
+ const prepared = await runtime.prepareInput(agent, {
1355
+ kind: "approval",
1356
+ serializedRunState: resumeRunState(state),
1357
+ approvalId: String(payload.approvalId ?? ""),
1358
+ decision: payload.decision === "approve" ? "approve" : "reject",
1359
+ ...typeof payload.message === "string" ? { message: payload.message } : {}
1360
+ });
1387
1361
  return {
1388
- input: await runtime.prepareInput(agent, {
1389
- kind: "approval",
1390
- // Cross-account run-state strip (HOLE C): if the account resuming this
1391
- // frozen approval differs from the one that froze it, neutralize the
1392
- // blob's account-bound reasoning before replay (else byte-for-byte).
1393
- serializedRunState: resumeRunStateForCodexAccount(state, current),
1394
- approvalId: String(payload.approvalId ?? ""),
1395
- decision: payload.decision === "approve" ? "approve" : "reject",
1396
- ...typeof payload.message === "string" ? { message: payload.message } : {}
1397
- }),
1398
- // Model seeded from the run-state BLOB (neutralize-in-place), NOT stripped
1399
- // items: the reconcile watermark must NOT apply the cross-account strip
1400
- // (HOLE E) — else a cross-account approval resume re-appends K
1401
- // already-persisted items at fresh positions.
1402
- modelHistoryFromItems: false
1362
+ input: prepared,
1363
+ persistedHistoryCount: prepared.persistedHistoryCount,
1364
+ providerArtifactCandidates: {
1365
+ knownHistoryItemIds: [],
1366
+ historyItemIds: [],
1367
+ runStateId: state.id
1368
+ }
1403
1369
  };
1404
1370
  }
1405
1371
  if (trigger.type === "user.humanInputResponse") {
@@ -1413,13 +1379,19 @@ async function turnInput(db, runtime, agent, trigger, current = NON_CODEX_TURN,
1413
1379
  if (!resume) {
1414
1380
  throw new Error("Human-input response does not resolve to a durable request");
1415
1381
  }
1382
+ const prepared = await runtime.prepareInput(agent, {
1383
+ kind: "human_input",
1384
+ serializedRunState: resumeRunState(state),
1385
+ toolCallId: resume.toolCallId
1386
+ });
1416
1387
  return {
1417
- input: await runtime.prepareInput(agent, {
1418
- kind: "human_input",
1419
- serializedRunState: resumeRunStateForCodexAccount(state, current),
1420
- toolCallId: resume.toolCallId
1421
- }),
1422
- modelHistoryFromItems: false
1388
+ input: prepared,
1389
+ persistedHistoryCount: prepared.persistedHistoryCount,
1390
+ providerArtifactCandidates: {
1391
+ knownHistoryItemIds: [],
1392
+ historyItemIds: [],
1393
+ runStateId: state.id
1394
+ }
1423
1395
  };
1424
1396
  }
1425
1397
  throw new Error(`Unsupported trigger event type: ${trigger.type}`);
@@ -1428,24 +1400,31 @@ function joinInternalContext(...parts) {
1428
1400
  const content = parts.map((part) => part?.trim()).filter((part) => Boolean(part));
1429
1401
  return content.length > 0 ? content.join("\n\n") : void 0;
1430
1402
  }
1431
- async function messageInput(db, runtime, agent, trigger, text, internalContext, current = NON_CODEX_TURN, currentAttachmentRefs = [], projectModelHistory) {
1403
+ async function messageInput(db, runtime, agent, trigger, text, internalContext, currentAttachmentRefs = [], providerApi = "responses", projectModelHistory) {
1432
1404
  const stored = await getActiveSessionHistoryItems(db, trigger.workspaceId, trigger.sessionId);
1433
1405
  const envelope = await getSandboxSessionEnvelope(db, trigger.workspaceId, trigger.sessionId);
1434
- const referencedHistory = withCurrentUserAttachmentRefs(
1435
- applyCodexHistoryStrip(stored, current),
1436
- currentAttachmentRefs
1437
- );
1406
+ const canonicalView = projectRejectedProviderArtifacts(stored);
1407
+ const providerView = projectHistoryForProvider(canonicalView, providerApi);
1408
+ const referencedHistory = withCurrentUserAttachmentRefs(providerView, currentAttachmentRefs);
1438
1409
  const historyItems = projectModelHistory ? await projectModelHistory(referencedHistory) : referencedHistory;
1410
+ const prepared = await runtime.prepareInput(agent, {
1411
+ kind: "message",
1412
+ ...text ? { text } : {},
1413
+ ...internalContext ? { internalContext } : {},
1414
+ historyItems,
1415
+ sandboxEnvelope: envelope,
1416
+ ...projectModelHistory ? { modelInputAlreadyProjected: true } : {}
1417
+ });
1418
+ const preparedItems = Array.isArray(prepared.input) ? new Set(prepared.input) : /* @__PURE__ */ new Set();
1439
1419
  return {
1440
- input: await runtime.prepareInput(agent, {
1441
- kind: "message",
1442
- ...text ? { text } : {},
1443
- ...internalContext ? { internalContext } : {},
1444
- historyItems,
1445
- sandboxEnvelope: envelope,
1446
- ...projectModelHistory ? { modelInputAlreadyProjected: true } : {}
1447
- }),
1448
- modelHistoryFromItems: true
1420
+ input: prepared,
1421
+ persistedHistoryCount: prepared.persistedHistoryCount,
1422
+ providerArtifactCandidates: {
1423
+ knownHistoryItemIds: stored.map((row) => row.id),
1424
+ historyItemIds: stored.filter(
1425
+ (row) => row.providerArtifactInvalidatedAt === null && hasOpaqueProviderArtifact(row.item) && preparedItems.has(row.item)
1426
+ ).map((row) => row.id)
1427
+ }
1449
1428
  };
1450
1429
  }
1451
1430
  async function resolveUserMessageFileAttachments(db, workspaceId, resources) {
@@ -1510,10 +1489,7 @@ async function maybeCompactContext(db, settings, scope, lastInputTokens, summari
1510
1489
  requestConsumed
1511
1490
  };
1512
1491
  }
1513
- const canonicalItems = applyCodexHistoryStrip(
1514
- active,
1515
- options.codexAccount ?? { currentCodexCredentialId: null }
1516
- );
1492
+ const canonicalItems = projectRejectedProviderArtifacts(active);
1517
1493
  const projectForWire = async (input) => sanitizeHistoryItemsForModel(
1518
1494
  options.projectModelInput ? await options.projectModelInput(input) : input,
1519
1495
  settings.modelToolOutputTruncationTokens
@@ -1641,7 +1617,6 @@ async function compactContextRemoteV2(db, settings, scope, canonicalItems, items
1641
1617
  summaryItem: tailItem,
1642
1618
  replacementInputTokens: estimatedTokensAfter,
1643
1619
  ...options.clearRequestedCompaction ? { clearRequestedCompaction: true } : {},
1644
- ...options.producerCodexCredentialId ? { producerCodexCredentialId: options.producerCodexCredentialId } : {},
1645
1620
  eventPayload: {
1646
1621
  trigger: options.trigger ?? "auto",
1647
1622
  implementation: REMOTE_COMPACTION_V2_IMPLEMENTATION,
@@ -6491,7 +6466,7 @@ function legacyTurnExecutionPolicyInput(turn) {
6491
6466
  }
6492
6467
  function providerRecoveryResult(input) {
6493
6468
  const providerDelay = input.retryAfterMs !== null && input.retryAfterMs !== void 0 && Number.isFinite(input.retryAfterMs) && input.retryAfterMs > 0 ? Math.ceil(input.retryAfterMs) : null;
6494
- const continueDelayMs = input.failureCode === "provider_rate_limited" ? providerDelay ?? PROVIDER_BACKPRESSURE_DELAY_MS : input.failureCode === "provider_unavailable" || input.failureCode === "upstream_connectivity_unavailable" ? Math.max(
6469
+ const continueDelayMs = input.failureCode === "provider_rate_limited" ? providerDelay ?? PROVIDER_BACKPRESSURE_DELAY_MS : input.failureCode === "provider_unavailable" || input.failureCode === "upstream_connectivity_unavailable" || input.failureCode === "mcp_transport_unavailable" ? Math.max(
6495
6470
  providerDelay ?? 0,
6496
6471
  PROVIDER_CONNECTIVITY_BACKOFF_MS[Math.min(
6497
6472
  Math.max(Math.trunc(input.attemptNumber) - 1, 0),
@@ -7114,6 +7089,26 @@ function historyRowsToAppend(rawHistory, persistedHistoryCount, nextPosition = p
7114
7089
  nextPosition: nextPosition + rows.length
7115
7090
  };
7116
7091
  }
7092
+ function selectRejectedProviderArtifactHistoryIds(activeHistory, candidates, wireFingerprints) {
7093
+ const remainingWireArtifacts = /* @__PURE__ */ new Map();
7094
+ for (const fingerprint of wireFingerprints) {
7095
+ remainingWireArtifacts.set(fingerprint, (remainingWireArtifacts.get(fingerprint) ?? 0) + 1);
7096
+ }
7097
+ const knownHistoryItemIds = new Set(candidates.knownHistoryItemIds);
7098
+ const initialCandidateIds = new Set(candidates.historyItemIds);
7099
+ const selected = [];
7100
+ for (const row of activeHistory) {
7101
+ if (row.providerArtifactInvalidatedAt !== null) continue;
7102
+ if (knownHistoryItemIds.has(row.id) && !initialCandidateIds.has(row.id)) continue;
7103
+ const fingerprint = opaqueProviderArtifactFingerprint(row.item);
7104
+ if (!fingerprint) continue;
7105
+ const remaining = remainingWireArtifacts.get(fingerprint) ?? 0;
7106
+ if (remaining === 0) continue;
7107
+ selected.push(row.id);
7108
+ remainingWireArtifacts.set(fingerprint, remaining - 1);
7109
+ }
7110
+ return selected;
7111
+ }
7117
7112
  function secretRedactionModelInputFilter(redactValue) {
7118
7113
  return ({ modelData }) => ({
7119
7114
  ...modelData,
@@ -7132,11 +7127,6 @@ function isModelOrToolProgressHistoryItem(item) {
7132
7127
  }
7133
7128
  return false;
7134
7129
  }
7135
- function reconcileSeedCount(activeSeedRows, modelHistoryFromItems, current) {
7136
- return sanitizeHistoryItemsForModel2(
7137
- modelHistoryFromItems ? applyCodexHistoryStrip(activeSeedRows, current) : activeSeedRows.map((row) => row.item)
7138
- ).length;
7139
- }
7140
7130
  async function resolveActiveSandboxBackend(routingOn, loadPointer, loadSandboxKind) {
7141
7131
  if (!routingOn) {
7142
7132
  return void 0;
@@ -7980,6 +7970,10 @@ function createRunAgentTurnActivity(services) {
7980
7970
  }
7981
7971
  };
7982
7972
  let persistedHistoryCount = 0;
7973
+ let providerArtifactCandidates = {
7974
+ knownHistoryItemIds: [],
7975
+ historyItemIds: []
7976
+ };
7983
7977
  let nextHistoryPosition = 0;
7984
7978
  const reconcileConversationTruth = async (options = {}) => {
7985
7979
  if (!stream || !turnId) {
@@ -8007,11 +8001,6 @@ function createRunAgentTurnActivity(services) {
8007
8001
  turnId,
8008
8002
  expectedExecutionGeneration: executionGeneration,
8009
8003
  expectedAttemptId: input.attemptId,
8010
- // Tag each row with the codex account that produced it (null on the
8011
- // non-codex path). Resolved at line ~504 before any reconcile pass
8012
- // runs, so this is the turn's effective account. The read path uses
8013
- // it to strip cross-account reasoning.encrypted_content next turn.
8014
- producerCodexCredentialId: effectiveCodexCredentialId,
8015
8004
  modelToolOutputTruncationTokens: modelRunSettings.modelToolOutputTruncationTokens,
8016
8005
  items: rows
8017
8006
  });
@@ -8060,6 +8049,7 @@ function createRunAgentTurnActivity(services) {
8060
8049
  let effectiveCodexCredentialId = null;
8061
8050
  let priorSessionCodexCredentialId = null;
8062
8051
  let latestCodexUsage = null;
8052
+ let lastCodexRequestOpaqueArtifacts = [];
8063
8053
  let triggerType = null;
8064
8054
  try {
8065
8055
  const mcpSettings = await settingsWithEnabledCapabilityMcpServers(
@@ -8083,6 +8073,7 @@ function createRunAgentTurnActivity(services) {
8083
8073
  input.workspaceId,
8084
8074
  codexSettings
8085
8075
  );
8076
+ const codexAppsCredentialId = capabilitySettings.codexConnectedAppsEnabled ? await resolveCodexAppsCredentialIdForRun(db, input.workspaceId) : null;
8086
8077
  runtime.configure(capabilitySettings);
8087
8078
  const session = await requireSession2(db, input.workspaceId, input.sessionId);
8088
8079
  const claim = await claimSessionWorkForAttempt(db, input.workspaceId, {
@@ -8143,8 +8134,6 @@ function createRunAgentTurnActivity(services) {
8143
8134
  trigger
8144
8135
  );
8145
8136
  triggerType = trigger.type;
8146
- const latestTurnState = await getLatestRunState2(db, input.workspaceId, input.sessionId);
8147
- const continuationCodexCredentialId = latestTurnState?.turnId === turnId ? latestTurnState.frozenCodexCredentialId : null;
8148
8137
  redispatchesAtDispatch = Number(
8149
8138
  turn.metadata?.workerDeathRedispatches ?? 0
8150
8139
  );
@@ -8327,7 +8316,6 @@ function createRunAgentTurnActivity(services) {
8327
8316
  sessionPinnedCredentialId: sessionPin,
8328
8317
  sessionPinSource,
8329
8318
  sessionLastCredentialId: sessionCodex?.lastCredentialId ?? null,
8330
- continuationCredentialId: continuationCodexCredentialId,
8331
8319
  now: /* @__PURE__ */ new Date()
8332
8320
  });
8333
8321
  let leased;
@@ -8341,8 +8329,7 @@ function createRunAgentTurnActivity(services) {
8341
8329
  workspaceId: input.workspaceId,
8342
8330
  turnId,
8343
8331
  holderId: codexLeaseHolderId,
8344
- advanceActivePointer: sessionPin === null,
8345
- continuationCredentialId: continuationCodexCredentialId
8332
+ advanceActivePointer: sessionPin === null
8346
8333
  },
8347
8334
  selectForTurn
8348
8335
  );
@@ -8396,8 +8383,7 @@ function createRunAgentTurnActivity(services) {
8396
8383
  workspaceId: input.workspaceId,
8397
8384
  turnId,
8398
8385
  holderId: codexLeaseHolderId,
8399
- advanceActivePointer: sessionPin === null,
8400
- continuationCredentialId: continuationCodexCredentialId
8386
+ advanceActivePointer: sessionPin === null
8401
8387
  },
8402
8388
  selectForTurn
8403
8389
  );
@@ -8511,7 +8497,7 @@ function createRunAgentTurnActivity(services) {
8511
8497
  if (codexLeaseHeld) startCodexLeaseHeartbeat();
8512
8498
  const actualOutcome = effectiveCodexCredentialId ? "selected" : rotationDecision.kind === "allCapped" ? "waiting" : "none";
8513
8499
  const actualReason = effectiveCodexCredentialId ? leased.reused ? "lease_reused" : sessionPin === effectiveCodexCredentialId ? "pin" : rotationDecision.kind === "active" && rotationDecision.moved ? "rotation" : "active" : rotationDecision.kind === "allCapped" ? "all_capped" : "none";
8514
- const fencedInFlight = leased.reused || continuationCodexCredentialId !== null && continuationCodexCredentialId === effectiveCodexCredentialId;
8500
+ const fencedInFlight = leased.reused;
8515
8501
  const shadowResult = await publishCodexFleetShadowDecisionV1({
8516
8502
  enabled: settings.codexFleetPolicyShadowEnabled,
8517
8503
  decision: {
@@ -8792,15 +8778,13 @@ function createRunAgentTurnActivity(services) {
8792
8778
  );
8793
8779
  if (priorAccountId !== effectiveCodexCredentialId) {
8794
8780
  const rotated = rotationDecision.kind === "active" && rotationDecision.moved;
8795
- const droppedConnectors = rotationDecision.kind === "active" ? rotationDecision.droppedConnectors : void 0;
8796
8781
  await publish([
8797
8782
  {
8798
8783
  type: "codex.account.switched",
8799
8784
  payload: {
8800
8785
  fromAccountId: priorAccountId,
8801
8786
  toAccountId: effectiveCodexCredentialId,
8802
- reason: rotated ? "rotation" : "manual",
8803
- ...droppedConnectors && droppedConnectors.length > 0 ? { droppedConnectors } : {}
8787
+ reason: rotated ? "rotation" : "manual"
8804
8788
  }
8805
8789
  }
8806
8790
  ]);
@@ -8907,6 +8891,7 @@ function createRunAgentTurnActivity(services) {
8907
8891
  turnExecutionPolicy.productModelId
8908
8892
  );
8909
8893
  const supportsImageInput = modelSupportsImageInputForTurn(resolvedModel);
8894
+ const providerApi = resolvedModel?.provider.api ?? "responses";
8910
8895
  const modelInputPolicy = modelAttachmentInputPolicyForTurn(resolvedModel);
8911
8896
  const attachmentProjector = createModelHistoryAttachmentProjector(
8912
8897
  db,
@@ -8915,6 +8900,7 @@ function createRunAgentTurnActivity(services) {
8915
8900
  objectStorage ? (file) => objectStorage.getFileBytes(file) : void 0
8916
8901
  );
8917
8902
  const modelHistoryProjector = async (items) => projectModelInputForCapabilities(await attachmentProjector(items), modelInputPolicy);
8903
+ const compactionModelHistoryProjector = async (items) => await modelHistoryProjector(projectHistoryForProvider2(items, providerApi));
8918
8904
  const selectedProvider = resolvedModel?.provider;
8919
8905
  const publicProviderHeaders = new Set(
8920
8906
  selectedProvider?.publicDefaultHeaderNames?.map((name) => name.toLowerCase()) ?? []
@@ -8998,6 +8984,9 @@ function createRunAgentTurnActivity(services) {
8998
8984
  latestCodexUsage = snapshot;
8999
8985
  },
9000
8986
  // latest wins; flushed once in finally
8987
+ onRequestOpaqueArtifacts: ({ fingerprints }) => {
8988
+ lastCodexRequestOpaqueArtifacts = fingerprints;
8989
+ },
9001
8990
  nextRequestId: () => `${dispatchId}:${++codexModelRequestSequence}`,
9002
8991
  onModelRequestEvent: async (event) => {
9003
8992
  if (!publish || !turnId) {
@@ -9135,8 +9124,7 @@ function createRunAgentTurnActivity(services) {
9135
9124
  codexCompactionMode: session.codexCompactionMode,
9136
9125
  isCodexSubscriptionTurn: isCodexTurn,
9137
9126
  publishLiveEvents: publishCompactionLiveEvents,
9138
- ...remoteCompactionRequester ? { requestRemoteCompactionV2: remoteCompactionRequester } : {},
9139
- ...effectiveCodexCredentialId ? { producerCodexCredentialId: effectiveCodexCredentialId } : {}
9127
+ ...remoteCompactionRequester ? { requestRemoteCompactionV2: remoteCompactionRequester } : {}
9140
9128
  };
9141
9129
  const compactionOnlyTurn = turn.source === "compaction";
9142
9130
  const remoteV2CompactionNeedsAgentPrefix = Boolean(remoteCompactionRequester) && session.codexCompactionMode === "remote_v2";
@@ -9187,10 +9175,7 @@ function createRunAgentTurnActivity(services) {
9187
9175
  force: true,
9188
9176
  clearRequestedCompaction: true,
9189
9177
  trigger: "operator",
9190
- codexAccount: {
9191
- currentCodexCredentialId: effectiveCodexCredentialId
9192
- },
9193
- projectModelInput: modelHistoryProjector,
9178
+ projectModelInput: compactionModelHistoryProjector,
9194
9179
  ...compactionModeOptions
9195
9180
  }
9196
9181
  ),
@@ -9965,34 +9950,55 @@ function createRunAgentTurnActivity(services) {
9965
9950
  return result;
9966
9951
  };
9967
9952
  const credentialSubjectId = credentialSubjectIdForTurnInitiator(turn);
9953
+ const codexAppsAuth = codexAppsCredentialId ? (() => {
9954
+ const resolver = buildCodexTokenResolver(
9955
+ db,
9956
+ runSettings,
9957
+ input.workspaceId,
9958
+ codexAppsCredentialId
9959
+ );
9960
+ return {
9961
+ clientVersion: CODEX_CLIENT_VERSION,
9962
+ withAuthorization: async (use) => {
9963
+ const snapshot = await resolver.getToken();
9964
+ registerSecretRedactions([
9965
+ { name: "CODEX_APPS_ACCESS_TOKEN", value: snapshot.accessToken }
9966
+ ]);
9967
+ return await withCodexAppsRequestAuthorization(
9968
+ db,
9969
+ { workspaceId: input.workspaceId, credentialId: codexAppsCredentialId },
9970
+ async () => await use(snapshot)
9971
+ );
9972
+ }
9973
+ };
9974
+ })() : void 0;
9968
9975
  preparedTools = await waitForTurnOperation(
9969
- withCodex(
9970
- () => runtime.prepareTools(runSettings, turnTools, {
9971
- accountId: input.accountId,
9972
- workspaceId: input.workspaceId,
9973
- sessionId: input.sessionId,
9974
- // Sign the calling turn into the first-party token so tools classify
9975
- // the caller by its own identity (sacred-pause guard), not the racy
9976
- // live active pointer.
9977
- ...turnId ? { turnId } : {},
9978
- attemptId: input.attemptId,
9979
- executionGeneration,
9980
- subjectId: "worker:first-party-mcp",
9981
- subjectLabel: "OpenGeni worker",
9982
- ...credentialSubjectId ? { credentialSubjectId } : {},
9983
- resolveCredential,
9984
- onAuthNeeded: async (payload) => {
9985
- if (!shouldPublishToolAuthNeededForTurn(payload, trigger, turn)) {
9986
- return;
9987
- }
9988
- await publish([{ type: "tool.auth_needed", payload }], true);
9989
- },
9990
- // Manager-style sessions carry a creation-validated permission set
9991
- // for their first-party MCP token; null keeps the fixed default.
9992
- ...session.firstPartyMcpPermissions?.length ? { firstPartyPermissions: session.firstPartyMcpPermissions } : {},
9993
- firstPartyTools: session.firstPartyMcpTools ?? [...DEFAULT_FIRST_PARTY_MCP_TOOLS]
9994
- })
9995
- ),
9976
+ runtime.prepareTools(runSettings, turnTools, {
9977
+ accountId: input.accountId,
9978
+ workspaceId: input.workspaceId,
9979
+ sessionId: input.sessionId,
9980
+ // Sign the calling turn into the first-party token so tools classify
9981
+ // the caller by its own identity (sacred-pause guard), not the racy
9982
+ // live active pointer.
9983
+ ...turnId ? { turnId } : {},
9984
+ attemptId: input.attemptId,
9985
+ executionGeneration,
9986
+ subjectId: "worker:first-party-mcp",
9987
+ subjectLabel: "OpenGeni worker",
9988
+ ...credentialSubjectId ? { credentialSubjectId } : {},
9989
+ ...codexAppsAuth ? { codexAppsAuth } : {},
9990
+ resolveCredential,
9991
+ onAuthNeeded: async (payload) => {
9992
+ if (!shouldPublishToolAuthNeededForTurn(payload, trigger, turn)) {
9993
+ return;
9994
+ }
9995
+ await publish([{ type: "tool.auth_needed", payload }], true);
9996
+ },
9997
+ // Manager-style sessions carry a creation-validated permission set
9998
+ // for their first-party MCP token; null keeps the fixed default.
9999
+ ...session.firstPartyMcpPermissions?.length ? { firstPartyPermissions: session.firstPartyMcpPermissions } : {},
10000
+ firstPartyTools: session.firstPartyMcpTools ?? [...DEFAULT_FIRST_PARTY_MCP_TOOLS]
10001
+ }),
9996
10002
  cancellationSignal,
9997
10003
  async (latePreparedTools) => await latePreparedTools.close().catch(() => void 0)
9998
10004
  );
@@ -10386,10 +10392,7 @@ function createRunAgentTurnActivity(services) {
10386
10392
  force: true,
10387
10393
  clearRequestedCompaction: true,
10388
10394
  trigger: "operator",
10389
- codexAccount: {
10390
- currentCodexCredentialId: effectiveCodexCredentialId
10391
- },
10392
- projectModelInput: modelHistoryProjector,
10395
+ projectModelInput: compactionModelHistoryProjector,
10393
10396
  ...compactionModeOptions
10394
10397
  }
10395
10398
  ),
@@ -10500,17 +10503,11 @@ function createRunAgentTurnActivity(services) {
10500
10503
  force: true,
10501
10504
  clearRequestedCompaction: true,
10502
10505
  trigger: "operator",
10503
- codexAccount: {
10504
- currentCodexCredentialId: effectiveCodexCredentialId
10505
- },
10506
- projectModelInput: modelHistoryProjector,
10506
+ projectModelInput: compactionModelHistoryProjector,
10507
10507
  ...compactionModeOptions
10508
10508
  } : {
10509
10509
  trigger: "auto",
10510
- codexAccount: {
10511
- currentCodexCredentialId: effectiveCodexCredentialId
10512
- },
10513
- projectModelInput: modelHistoryProjector,
10510
+ projectModelInput: compactionModelHistoryProjector,
10514
10511
  ...compactionModeOptions
10515
10512
  }
10516
10513
  ),
@@ -10638,29 +10635,17 @@ function createRunAgentTurnActivity(services) {
10638
10635
  }
10639
10636
  let runInput = null;
10640
10637
  const prepareRunAttemptInput = async () => {
10641
- const prepared = await turnInput(
10642
- db,
10643
- runtime,
10644
- agent,
10645
- trigger,
10646
- { currentCodexCredentialId: effectiveCodexCredentialId },
10647
- {
10648
- turnId: activeTurnId,
10649
- recovering: turn.executionGeneration > 1,
10650
- ...unavailableSandboxFilesNote ? { unavailableSandboxFilesNote } : {},
10651
- ...runCredentialsNote ? { runCredentialsNote } : {},
10652
- projectModelHistory: modelHistoryProjector
10653
- }
10654
- );
10655
- runInput = prepared.input;
10656
- const activeSeedRows = await getActiveSessionHistoryItems3(
10657
- db,
10658
- input.workspaceId,
10659
- input.sessionId
10660
- );
10661
- persistedHistoryCount = reconcileSeedCount(activeSeedRows, prepared.modelHistoryFromItems, {
10662
- currentCodexCredentialId: effectiveCodexCredentialId
10638
+ const prepared = await turnInput(db, runtime, agent, trigger, {
10639
+ turnId: activeTurnId,
10640
+ recovering: turn.executionGeneration > 1,
10641
+ ...unavailableSandboxFilesNote ? { unavailableSandboxFilesNote } : {},
10642
+ ...runCredentialsNote ? { runCredentialsNote } : {},
10643
+ providerApi,
10644
+ projectModelHistory: modelHistoryProjector
10663
10645
  });
10646
+ runInput = prepared.input;
10647
+ providerArtifactCandidates = prepared.providerArtifactCandidates;
10648
+ persistedHistoryCount = prepared.persistedHistoryCount;
10664
10649
  nextHistoryPosition = await nextSessionHistoryPosition(
10665
10650
  db,
10666
10651
  input.workspaceId,
@@ -10691,10 +10676,7 @@ function createRunAgentTurnActivity(services) {
10691
10676
  force: true,
10692
10677
  ...triggerLabel === "operator" ? { clearRequestedCompaction: true } : {},
10693
10678
  trigger: triggerLabel,
10694
- codexAccount: {
10695
- currentCodexCredentialId: effectiveCodexCredentialId
10696
- },
10697
- projectModelInput: modelHistoryProjector,
10679
+ projectModelInput: compactionModelHistoryProjector,
10698
10680
  ...compactionModeOptions
10699
10681
  }
10700
10682
  ),
@@ -11132,7 +11114,6 @@ function createRunAgentTurnActivity(services) {
11132
11114
  runState: {
11133
11115
  serializedRunState: stream.state.toString(),
11134
11116
  pendingApprovals: approvals,
11135
- frozenCodexCredentialId: effectiveCodexCredentialId,
11136
11117
  humanInputRequests: humanInputRequests.map(
11137
11118
  ({ isNew: _isNew, ...request }) => request
11138
11119
  )
@@ -11642,8 +11623,7 @@ function createRunAgentTurnActivity(services) {
11642
11623
  activeCredentialId: rotation.activeCredentialId,
11643
11624
  priorCredentialId: effectiveCodexCredentialId,
11644
11625
  accounts,
11645
- now: /* @__PURE__ */ new Date(),
11646
- usedConnectors: serving?.connectorNamespaces ?? []
11626
+ now: /* @__PURE__ */ new Date()
11647
11627
  }) : { kind: "none" };
11648
11628
  const candidateAvailable = statePersisted && Boolean(rotation?.rotationEnabled && rotation?.leaseRotationEnabled) && decision.kind === "active" && decision.credentialId !== effectiveCodexCredentialId;
11649
11629
  if (candidateAvailable && codexLeaseHolderId && codexLeaseGeneration !== null) {
@@ -11812,10 +11792,7 @@ function createRunAgentTurnActivity(services) {
11812
11792
  activeCredentialId: rotation.activeCredentialId,
11813
11793
  priorCredentialId: effectiveCodexCredentialId,
11814
11794
  accounts: fresh,
11815
- now: /* @__PURE__ */ new Date(),
11816
- // P4: the just-capped serving account's connector set is the proxy for
11817
- // "what this session has access to" — prefer a covering failover target.
11818
- usedConnectors: serving?.connectorNamespaces ?? []
11795
+ now: /* @__PURE__ */ new Date()
11819
11796
  });
11820
11797
  if (decision.kind === "active") {
11821
11798
  rotated = true;
@@ -11979,6 +11956,17 @@ function createRunAgentTurnActivity(services) {
11979
11956
  if (encryptedArtifactRejection && effectiveCodexCredentialId && publish && turnId && turnStartedPublished) {
11980
11957
  await flushRuntimeBatcher();
11981
11958
  await reconcileConversationTruth({ requireDurable: true });
11959
+ const activeHistory = await getActiveSessionHistoryItems3(
11960
+ db,
11961
+ input.workspaceId,
11962
+ input.sessionId
11963
+ );
11964
+ const rejectedHistoryItemIds = selectRejectedProviderArtifactHistoryIds(
11965
+ activeHistory,
11966
+ providerArtifactCandidates,
11967
+ lastCodexRequestOpaqueArtifacts
11968
+ );
11969
+ const rejectedRunStateId = providerArtifactCandidates.runStateId && lastCodexRequestOpaqueArtifacts.length > 0 ? providerArtifactCandidates.runStateId : void 0;
11982
11970
  const recovery = await requestSessionTurnRecovery(db, input.workspaceId, {
11983
11971
  sessionId: input.sessionId,
11984
11972
  turnId,
@@ -11990,7 +11978,8 @@ function createRunAgentTurnActivity(services) {
11990
11978
  retryable: true
11991
11979
  },
11992
11980
  providerArtifactInvalidation: {
11993
- codexCredentialId: effectiveCodexCredentialId,
11981
+ historyItemIds: rejectedHistoryItemIds,
11982
+ ...rejectedRunStateId ? { runStateId: rejectedRunStateId } : {},
11994
11983
  reason: encryptedArtifactRejection.kind
11995
11984
  }
11996
11985
  });
@@ -12281,15 +12270,6 @@ function createRunAgentTurnActivity(services) {
12281
12270
  );
12282
12271
  }
12283
12272
  }
12284
- const connectorNamespaces = preparedTools?.codexConnectorNamespaces;
12285
- if (connectorNamespaces && connectorNamespaces.size > 0) {
12286
- await waitForTurnFinalizerStep(
12287
- recordCodexAccountConnectors(db, input.workspaceId, effectiveCodexCredentialId, [
12288
- ...connectorNamespaces
12289
- ]).catch(() => void 0),
12290
- finalizerSignal
12291
- );
12292
- }
12293
12273
  }
12294
12274
  if (codexLeaseHeartbeatTimer) {
12295
12275
  clearInterval(codexLeaseHeartbeatTimer);
@@ -12606,6 +12586,13 @@ function agentRunFailurePayload(error, options = {}) {
12606
12586
  ...mcpTimeout.detail || mcpTimeout.message ? { detail: mcpTimeout.detail ?? mcpTimeout.message } : {}
12607
12587
  };
12608
12588
  }
12589
+ if (isMcpTransportConnectivityError(error)) {
12590
+ return {
12591
+ error: "A required MCP server was temporarily unreachable. The same turn will retry after a short delay.",
12592
+ code: "mcp_transport_unavailable",
12593
+ retryable: true
12594
+ };
12595
+ }
12609
12596
  if (status === 429 || code === "rate_limit_exceeded" || /(?:too many requests|rate.?limit|\b429\b)/i.test(message)) {
12610
12597
  return {
12611
12598
  error: "Model provider rate limit hit. Try again in a minute or lower the reasoning effort.",