@opengeni/contracts 0.18.0 → 0.19.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.
package/dist/index.js CHANGED
@@ -864,6 +864,879 @@ function isPlainRecord(value) {
864
864
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
865
865
  }
866
866
 
867
+ // src/codex-fleet-policy.ts
868
+ import { sha256 } from "@noble/hashes/sha256";
869
+ import { bytesToHex } from "@noble/hashes/utils";
870
+ var CODEX_FLEET_POLICY_SCHEMA_VERSION = 1;
871
+ var CODEX_FLEET_POLICY_VERSION = "adaptive-shadow-v1";
872
+ var CODEX_FLEET_POLICY_MAX_CANDIDATES = 32;
873
+ var CODEX_FLEET_POLICY_MAX_OVERLAYS_PER_CANDIDATE = 4;
874
+ var MAX_DURATION_MS = 31 * 24 * 60 * 6e4;
875
+ var MAX_COUNT = 1e6;
876
+ var SCORE_SCALE = 100;
877
+ function compareCodexFleetCanonicalStringsV1(left, right) {
878
+ return left < right ? -1 : left > right ? 1 : 0;
879
+ }
880
+ var DEFAULT_CODEX_FLEET_POLICY_V1 = Object.freeze({
881
+ maxCandidates: CODEX_FLEET_POLICY_MAX_CANDIDATES,
882
+ quotaFreshForMs: 15 * 6e4,
883
+ quotaStaleAfterMs: 60 * 6e4,
884
+ placementUsageCeilingPercent: 90,
885
+ cacheFreshForMs: 30 * 6e4,
886
+ cacheCollapseThreshold: 0.4,
887
+ cacheCollapseRecoveryThreshold: 0.65,
888
+ cacheMinimumSampledTokens: 4096,
889
+ cacheCollapseDwellMs: 5 * 6e4,
890
+ cacheRecoveryDwellMs: 10 * 6e4,
891
+ activeLeaseScore: 8 * SCORE_SCALE,
892
+ unknownQuotaScore: 16 * SCORE_SCALE,
893
+ lowQuotaConfidenceScore: 10 * SCORE_SCALE,
894
+ mediumQuotaConfidenceScore: 4 * SCORE_SCALE,
895
+ inferredBurnScorePerPercentHour: 0.2 * SCORE_SCALE,
896
+ observedBurnScorePerPercentHour: 0.1 * SCORE_SCALE,
897
+ runwayRiskCapHours: 2,
898
+ runwayScorePerAtRiskHour: 8 * SCORE_SCALE,
899
+ healthyCacheAffinityBenefit: 32 * SCORE_SCALE,
900
+ unknownCacheAffinityBenefit: 24 * SCORE_SCALE,
901
+ collapsedCacheAffinityBenefit: 6 * SCORE_SCALE,
902
+ switchHysteresisScore: 8 * SCORE_SCALE,
903
+ admissionPacingEnabled: false,
904
+ managerPriorityEnabled: false,
905
+ managerStandardStarvationMs: 2 * 6e4,
906
+ emergencyFuseEnabled: false,
907
+ overlaysEnabled: false,
908
+ overlayPreferenceScore: 12 * SCORE_SCALE
909
+ });
910
+ function createCodexFleetReplayRecordV1(input, policy = DEFAULT_CODEX_FLEET_POLICY_V1) {
911
+ const normalizedPolicy = normalizePolicy(policy);
912
+ const normalized = normalizeInput(input, normalizedPolicy.maxCandidates);
913
+ const decision = evaluateCodexFleetDecisionV1(normalized.input, normalizedPolicy);
914
+ return {
915
+ schemaVersion: CODEX_FLEET_POLICY_SCHEMA_VERSION,
916
+ policyVersion: CODEX_FLEET_POLICY_VERSION,
917
+ mode: "shadow",
918
+ policy: normalizedPolicy,
919
+ input: normalized.input,
920
+ truncatedCandidateCount: normalized.truncatedCandidateCount,
921
+ policyFingerprint: fingerprint(normalizedPolicy),
922
+ inputFingerprint: fingerprintReplayInput(normalized.input, normalized.truncatedCandidateCount),
923
+ decision,
924
+ decisionFingerprint: fingerprint(decision)
925
+ };
926
+ }
927
+ function replayCodexFleetDecisionV1(value) {
928
+ const record = readCodexFleetReplayRecordV1(value);
929
+ const policyFingerprintMatches = fingerprint(record.policy) === record.policyFingerprint;
930
+ const inputFingerprintMatches = fingerprintReplayInput(record.input, record.truncatedCandidateCount) === record.inputFingerprint;
931
+ const decision = evaluateCodexFleetDecisionV1(record.input, record.policy);
932
+ const replayedDecisionFingerprint = fingerprint(decision);
933
+ const recordedDecisionFingerprintMatches = fingerprint(record.decision) === record.decisionFingerprint;
934
+ const decisionFingerprintMatches = recordedDecisionFingerprintMatches && replayedDecisionFingerprint === record.decisionFingerprint;
935
+ return {
936
+ matches: policyFingerprintMatches && inputFingerprintMatches && decisionFingerprintMatches && canonicalJson(decision) === canonicalJson(record.decision),
937
+ policyFingerprintMatches,
938
+ inputFingerprintMatches,
939
+ decisionFingerprintMatches,
940
+ recordedDecisionFingerprintMatches,
941
+ decision
942
+ };
943
+ }
944
+ function canonicalCodexFleetReplayJsonV1(value) {
945
+ return canonicalJson(value);
946
+ }
947
+ function readCodexFleetReplayRecordV1(value) {
948
+ const record = strictRecord(value, [
949
+ "schemaVersion",
950
+ "policyVersion",
951
+ "mode",
952
+ "policy",
953
+ "input",
954
+ "truncatedCandidateCount",
955
+ "policyFingerprint",
956
+ "inputFingerprint",
957
+ "decision",
958
+ "decisionFingerprint"
959
+ ]);
960
+ if (record.schemaVersion !== CODEX_FLEET_POLICY_SCHEMA_VERSION || record.policyVersion !== CODEX_FLEET_POLICY_VERSION || record.mode !== "shadow") {
961
+ throw new Error("Unsupported Codex fleet replay envelope");
962
+ }
963
+ const policy = normalizePolicy(record.policy);
964
+ if (canonicalJson(policy) !== canonicalJson(record.policy)) {
965
+ throw new Error("Codex fleet replay policy is not in canonical bounded form");
966
+ }
967
+ const normalizedInput = normalizeInput(
968
+ record.input,
969
+ policy.maxCandidates
970
+ );
971
+ if (normalizedInput.truncatedCandidateCount !== 0 || canonicalJson(normalizedInput.input) !== canonicalJson(record.input)) {
972
+ throw new Error("Codex fleet replay input is not in canonical bounded form");
973
+ }
974
+ return {
975
+ schemaVersion: CODEX_FLEET_POLICY_SCHEMA_VERSION,
976
+ policyVersion: CODEX_FLEET_POLICY_VERSION,
977
+ mode: "shadow",
978
+ policy,
979
+ input: normalizedInput.input,
980
+ truncatedCandidateCount: strictInteger(record.truncatedCandidateCount, 0, MAX_COUNT),
981
+ policyFingerprint: strictSha256(record.policyFingerprint),
982
+ inputFingerprint: strictSha256(record.inputFingerprint),
983
+ decision: readCodexFleetDecisionV1(
984
+ record.decision,
985
+ new Set(normalizedInput.input.candidates.map((candidate) => candidate.key))
986
+ ),
987
+ decisionFingerprint: strictSha256(record.decisionFingerprint)
988
+ };
989
+ }
990
+ function evaluateCodexFleetDecisionV1(input, policy = DEFAULT_CODEX_FLEET_POLICY_V1) {
991
+ const admission = evaluateAdmission(input, policy);
992
+ const current = input.request.currentCandidateKey ? input.candidates.find((candidate) => candidate.key === input.request.currentCandidateKey) : void 0;
993
+ if (input.request.placement === "fenced_in_flight") {
994
+ if (!current) {
995
+ return emptyDecision("fenced_candidate_missing", admission, "unknown");
996
+ }
997
+ return {
998
+ outcome: "selected",
999
+ selectedCandidateKey: current.key,
1000
+ reason: "fenced_in_flight",
1001
+ admission,
1002
+ borrowedOverlayCapacity: false,
1003
+ strandedEligibleCount: 0,
1004
+ confidence: candidateConfidence(current, policy),
1005
+ scores: [scoreCandidate(current, input, policy, false)]
1006
+ };
1007
+ }
1008
+ if (admission.outcome === "pace") {
1009
+ return emptyDecision("admission_paced", admission, "unknown");
1010
+ }
1011
+ const scored = input.candidates.map(
1012
+ (candidate) => scoreCandidate(candidate, input, policy, false)
1013
+ );
1014
+ const baseEligibleKeys = new Set(
1015
+ scored.filter((candidate) => candidate.eligible).map((candidate) => candidate.candidateKey)
1016
+ );
1017
+ const overlay = selectOverlayScope(input, policy, baseEligibleKeys);
1018
+ const scopedScores = input.candidates.map(
1019
+ (candidate) => scoreCandidate(
1020
+ candidate,
1021
+ input,
1022
+ policy,
1023
+ overlay.rejectedByIsolation.has(candidate.key),
1024
+ overlay.preferredMembers.has(candidate.key)
1025
+ )
1026
+ ).sort((a, b) => compareCodexFleetCanonicalStringsV1(a.candidateKey, b.candidateKey));
1027
+ const eligible = scopedScores.filter((candidate) => candidate.eligible).sort(
1028
+ (a, b) => a.total - b.total || compareCodexFleetCanonicalStringsV1(a.candidateKey, b.candidateKey)
1029
+ );
1030
+ if (eligible.length === 0) {
1031
+ return {
1032
+ ...emptyDecision(
1033
+ overlay.isolatedEmpty ? "overlay_isolated_empty" : "no_eligible_candidate",
1034
+ admission,
1035
+ aggregateConfidence(scopedScores)
1036
+ ),
1037
+ strandedEligibleCount: overlay.strandedEligibleCount,
1038
+ scores: scopedScores
1039
+ };
1040
+ }
1041
+ let selected = eligible[0];
1042
+ let reason = "best_score";
1043
+ const currentScore = input.request.currentCandidateKey ? eligible.find((candidate) => candidate.candidateKey === input.request.currentCandidateKey) : void 0;
1044
+ if (currentScore) {
1045
+ if (selected.candidateKey === currentScore.candidateKey) {
1046
+ reason = "affinity_best";
1047
+ } else if (selected.total + policy.switchHysteresisScore >= currentScore.total) {
1048
+ selected = currentScore;
1049
+ reason = "hysteresis_hold";
1050
+ }
1051
+ }
1052
+ return {
1053
+ outcome: "selected",
1054
+ selectedCandidateKey: selected.candidateKey,
1055
+ reason,
1056
+ admission,
1057
+ borrowedOverlayCapacity: policy.overlaysEnabled && input.request.overlayMode === "prefer" && input.request.overlayKey !== null && !overlay.preferredMembers.has(selected.candidateKey),
1058
+ strandedEligibleCount: overlay.strandedEligibleCount,
1059
+ confidence: aggregateConfidence(eligible),
1060
+ scores: scopedScores
1061
+ };
1062
+ }
1063
+ function evaluateAdmission(input, policy) {
1064
+ if (input.request.placement === "fenced_in_flight") {
1065
+ return {
1066
+ outcome: "admit",
1067
+ reason: "fenced_in_flight",
1068
+ borrowedIdleCapacity: false
1069
+ };
1070
+ }
1071
+ if (policy.emergencyFuseEnabled && input.admission.emergencyFuseActive) {
1072
+ return {
1073
+ outcome: "pace",
1074
+ reason: "emergency_fuse",
1075
+ borrowedIdleCapacity: false
1076
+ };
1077
+ }
1078
+ if (!policy.admissionPacingEnabled) {
1079
+ return {
1080
+ outcome: "admit",
1081
+ reason: "pacing_disabled",
1082
+ borrowedIdleCapacity: false
1083
+ };
1084
+ }
1085
+ if (input.admission.dynamicCapacityUnits === null) {
1086
+ return {
1087
+ outcome: "admit",
1088
+ reason: "capacity_unknown",
1089
+ borrowedIdleCapacity: false
1090
+ };
1091
+ }
1092
+ const available = Math.max(0, input.admission.dynamicCapacityUnits - input.admission.inUseUnits);
1093
+ if (available === 0) {
1094
+ return {
1095
+ outcome: "pace",
1096
+ reason: "capacity_saturated",
1097
+ borrowedIdleCapacity: false
1098
+ };
1099
+ }
1100
+ if (policy.managerPriorityEnabled && input.request.priority === "standard" && input.admission.queuedManagerCount > 0 && available <= input.admission.queuedManagerCount) {
1101
+ if (input.request.waitAgeMs >= policy.managerStandardStarvationMs) {
1102
+ return {
1103
+ outcome: "admit",
1104
+ reason: "standard_starvation_bound",
1105
+ borrowedIdleCapacity: false
1106
+ };
1107
+ }
1108
+ return {
1109
+ outcome: "pace",
1110
+ reason: "manager_priority",
1111
+ borrowedIdleCapacity: false
1112
+ };
1113
+ }
1114
+ if (input.request.priority === "standard" && input.admission.queuedManagerCount === 0) {
1115
+ return {
1116
+ outcome: "admit",
1117
+ reason: "work_conserving_borrow",
1118
+ borrowedIdleCapacity: true
1119
+ };
1120
+ }
1121
+ return {
1122
+ outcome: "admit",
1123
+ reason: "capacity_available",
1124
+ borrowedIdleCapacity: false
1125
+ };
1126
+ }
1127
+ function scoreCandidate(candidate, input, policy, rejectedByIsolation, preferredOverlayMember = false) {
1128
+ const confidence = candidateConfidence(candidate, policy);
1129
+ const bindingUsed = bindingUsedPercent(candidate);
1130
+ const hardQuotaKnown = confidence === "high" || confidence === "medium";
1131
+ const rejectionReason = !candidate.allocatorEnabled ? "allocator_disabled" : candidate.status !== "active" ? "unavailable" : (candidate.cooldownRemainingMs ?? 0) > 0 ? "cooling" : hardQuotaKnown && bindingUsed !== null && bindingUsed >= policy.placementUsageCeilingPercent ? "quota_ceiling" : rejectedByIsolation ? "overlay_isolation" : null;
1132
+ const confidenceFactor = confidenceWeight(confidence);
1133
+ const quotaPressure = Math.round(
1134
+ ((bindingUsed ?? 50) * confidenceFactor + 50 * (1 - confidenceFactor)) * SCORE_SCALE
1135
+ );
1136
+ const leasePressure = candidate.activeLeaseCount * policy.activeLeaseScore;
1137
+ const observedBurnConfidence = confidenceWeight(candidate.observedBurn.confidence);
1138
+ const observedBurn = maximumWindowBurn(candidate.observedBurn);
1139
+ const observedBurnPressure = Math.round(
1140
+ observedBurn * policy.observedBurnScorePerPercentHour * observedBurnConfidence
1141
+ );
1142
+ const burnConfidence = confidenceWeight(candidate.inferredUnexplainedBurn.confidence);
1143
+ const inferredBurn = maximumWindowBurn(candidate.inferredUnexplainedBurn);
1144
+ const inferredBurnPressure = Math.round(
1145
+ inferredBurn * policy.inferredBurnScorePerPercentHour * burnConfidence
1146
+ );
1147
+ const runwayPressure = runwayRiskPressure(candidate, confidence, policy);
1148
+ const uncertaintyPressure = quotaUncertaintyScore(confidence, policy);
1149
+ const cacheState = effectiveCodexFleetCacheStateV1(candidate.cache, policy);
1150
+ const cacheAffinityBenefit = candidate.key === input.request.currentCandidateKey ? cacheAffinityBenefitFor(cacheState, policy) : 0;
1151
+ const overlayPreferenceBenefit = preferredOverlayMember ? policy.overlayPreferenceScore : 0;
1152
+ return {
1153
+ candidateKey: candidate.key,
1154
+ eligible: rejectionReason === null,
1155
+ rejectionReason,
1156
+ quotaPressure,
1157
+ leasePressure,
1158
+ observedBurnPressure,
1159
+ inferredBurnPressure,
1160
+ runwayPressure,
1161
+ uncertaintyPressure,
1162
+ cacheAffinityBenefit,
1163
+ cacheState,
1164
+ overlayPreferenceBenefit,
1165
+ total: quotaPressure + leasePressure + observedBurnPressure + inferredBurnPressure + runwayPressure + uncertaintyPressure - cacheAffinityBenefit - overlayPreferenceBenefit,
1166
+ confidence
1167
+ };
1168
+ }
1169
+ function maximumWindowBurn(burn) {
1170
+ return Math.max(burn.primaryPercentPerHour ?? 0, burn.secondaryPercentPerHour ?? 0);
1171
+ }
1172
+ function windowBurn(burn, window) {
1173
+ return window === "primary" ? burn.primaryPercentPerHour ?? 0 : burn.secondaryPercentPerHour ?? 0;
1174
+ }
1175
+ function runwayRiskPressure(candidate, quotaConfidence, policy) {
1176
+ if (quotaConfidence === "unknown") return 0;
1177
+ const windows = [
1178
+ ["primary", candidate.quota.primary],
1179
+ ["secondary", candidate.quota.secondary]
1180
+ ];
1181
+ let maximumPressure = 0;
1182
+ for (const [windowKey, window] of windows) {
1183
+ if (window.usedPercent === null || window.resetRemainingMs === null || window.resetRemainingMs === 0) {
1184
+ continue;
1185
+ }
1186
+ const observedConfidence = confidenceWeight(
1187
+ lowerConfidence(candidate.observedBurn.confidence, quotaConfidence)
1188
+ );
1189
+ const inferredConfidence = confidenceWeight(
1190
+ lowerConfidence(candidate.inferredUnexplainedBurn.confidence, quotaConfidence)
1191
+ );
1192
+ const confidenceBoundedBurn = windowBurn(candidate.observedBurn, windowKey) * observedConfidence + windowBurn(candidate.inferredUnexplainedBurn, windowKey) * inferredConfidence;
1193
+ if (confidenceBoundedBurn <= 0) continue;
1194
+ const exhaustionRunwayHours = Math.max(0, 100 - window.usedPercent) / confidenceBoundedBurn;
1195
+ const resetHorizonHours = window.resetRemainingMs / 60 / 6e4;
1196
+ const atRiskHours = Math.min(
1197
+ policy.runwayRiskCapHours,
1198
+ Math.max(0, resetHorizonHours - exhaustionRunwayHours)
1199
+ );
1200
+ maximumPressure = Math.max(
1201
+ maximumPressure,
1202
+ Math.round(atRiskHours * policy.runwayScorePerAtRiskHour)
1203
+ );
1204
+ }
1205
+ return maximumPressure;
1206
+ }
1207
+ function selectOverlayScope(input, policy, baseEligibleKeys) {
1208
+ if (!policy.overlaysEnabled || input.request.overlayMode === "none" || input.request.overlayKey === null) {
1209
+ return {
1210
+ rejectedByIsolation: /* @__PURE__ */ new Set(),
1211
+ preferredMembers: /* @__PURE__ */ new Set(),
1212
+ isolatedEmpty: false,
1213
+ strandedEligibleCount: 0
1214
+ };
1215
+ }
1216
+ const members = new Set(
1217
+ input.candidates.filter(
1218
+ (candidate) => baseEligibleKeys.has(candidate.key) && candidate.overlayKeys.includes(input.request.overlayKey)
1219
+ ).map((candidate) => candidate.key)
1220
+ );
1221
+ if (input.request.overlayMode === "prefer") {
1222
+ if (members.size === 0) {
1223
+ return {
1224
+ rejectedByIsolation: /* @__PURE__ */ new Set(),
1225
+ preferredMembers: members,
1226
+ isolatedEmpty: false,
1227
+ strandedEligibleCount: 0
1228
+ };
1229
+ }
1230
+ return {
1231
+ // Preference is a bounded score benefit, never a hard partition. Healthy
1232
+ // authorized outsiders remain eligible and borrowable.
1233
+ rejectedByIsolation: /* @__PURE__ */ new Set(),
1234
+ preferredMembers: members,
1235
+ isolatedEmpty: false,
1236
+ strandedEligibleCount: 0
1237
+ };
1238
+ }
1239
+ const outside = [...baseEligibleKeys].filter((candidateKey) => !members.has(candidateKey));
1240
+ return {
1241
+ rejectedByIsolation: new Set(outside),
1242
+ preferredMembers: members,
1243
+ isolatedEmpty: members.size === 0,
1244
+ strandedEligibleCount: outside.length
1245
+ };
1246
+ }
1247
+ function candidateConfidence(candidate, policy) {
1248
+ const age = candidate.quota.checkedAgeMs;
1249
+ if (age === null || age > policy.quotaStaleAfterMs) return "unknown";
1250
+ const windows = [candidate.quota.primary, candidate.quota.secondary];
1251
+ const completeWindowCount = windows.filter(
1252
+ (window) => window.usedPercent !== null && window.resetRemainingMs !== null
1253
+ ).length;
1254
+ const hasPartialWindow = windows.some(
1255
+ (window) => window.usedPercent === null !== (window.resetRemainingMs === null)
1256
+ );
1257
+ if (completeWindowCount === 0) return "unknown";
1258
+ const completenessCeiling = hasPartialWindow ? "low" : completeWindowCount === windows.length ? "high" : "medium";
1259
+ const completeConfidence = lowerConfidence(candidate.quota.confidence, completenessCeiling);
1260
+ if (age > policy.quotaFreshForMs) {
1261
+ return lowerConfidence(completeConfidence, "low");
1262
+ }
1263
+ return completeConfidence;
1264
+ }
1265
+ function effectiveCodexFleetCacheStateV1(cache, policy) {
1266
+ const { hitRatio, sampledTokens, checkedAgeMs, confidence, state, thresholdObservedForMs } = cache;
1267
+ if (hitRatio === null || sampledTokens === null || sampledTokens < policy.cacheMinimumSampledTokens || checkedAgeMs === null || checkedAgeMs > policy.cacheFreshForMs || confidenceWeight(confidence) < confidenceWeight("medium")) {
1268
+ return "unknown";
1269
+ }
1270
+ const observedForMs = thresholdObservedForMs ?? 0;
1271
+ if (state === "healthy") {
1272
+ return hitRatio < policy.cacheCollapseThreshold && observedForMs >= policy.cacheCollapseDwellMs ? "collapsed" : "healthy";
1273
+ }
1274
+ if (state === "collapsed") {
1275
+ return hitRatio >= policy.cacheCollapseRecoveryThreshold && observedForMs >= policy.cacheRecoveryDwellMs ? "healthy" : "collapsed";
1276
+ }
1277
+ if (hitRatio < policy.cacheCollapseThreshold && observedForMs >= policy.cacheCollapseDwellMs) {
1278
+ return "collapsed";
1279
+ }
1280
+ if (hitRatio >= policy.cacheCollapseRecoveryThreshold && observedForMs >= policy.cacheRecoveryDwellMs) {
1281
+ return "healthy";
1282
+ }
1283
+ return "unknown";
1284
+ }
1285
+ function cacheAffinityBenefitFor(state, policy) {
1286
+ if (state === "healthy") return policy.healthyCacheAffinityBenefit;
1287
+ if (state === "collapsed") return policy.collapsedCacheAffinityBenefit;
1288
+ return policy.unknownCacheAffinityBenefit;
1289
+ }
1290
+ function bindingUsedPercent(candidate) {
1291
+ const windows = [candidate.quota.primary, candidate.quota.secondary].filter((window) => window.usedPercent !== null && window.resetRemainingMs !== null).map((window) => window.resetRemainingMs === 0 ? 0 : window.usedPercent).filter((used) => used !== null);
1292
+ return windows.length > 0 ? Math.max(...windows) : null;
1293
+ }
1294
+ function quotaUncertaintyScore(confidence, policy) {
1295
+ if (confidence === "unknown") return policy.unknownQuotaScore;
1296
+ if (confidence === "low") return policy.lowQuotaConfidenceScore;
1297
+ if (confidence === "medium") return policy.mediumQuotaConfidenceScore;
1298
+ return 0;
1299
+ }
1300
+ function emptyDecision(reason, admission, confidence) {
1301
+ return {
1302
+ outcome: admission.outcome === "pace" ? "paced" : "none",
1303
+ selectedCandidateKey: null,
1304
+ reason,
1305
+ admission,
1306
+ borrowedOverlayCapacity: false,
1307
+ strandedEligibleCount: 0,
1308
+ confidence,
1309
+ scores: []
1310
+ };
1311
+ }
1312
+ function aggregateConfidence(scores) {
1313
+ if (scores.length === 0) return "unknown";
1314
+ return scores.reduce(
1315
+ (lowest, score) => confidenceWeight(score.confidence) < confidenceWeight(lowest) ? score.confidence : lowest,
1316
+ "high"
1317
+ );
1318
+ }
1319
+ function normalizeInput(input, maxCandidates) {
1320
+ const currentCandidateKey = normalizeOptionalKey(input.request.currentCandidateKey);
1321
+ const candidates = input.candidates.map(normalizeCandidate).sort((a, b) => compareCodexFleetCanonicalStringsV1(a.key, b.key));
1322
+ for (let index = 1; index < candidates.length; index += 1) {
1323
+ if (candidates[index - 1].key === candidates[index].key) {
1324
+ throw new Error(`Duplicate Codex fleet candidate key: ${candidates[index].key}`);
1325
+ }
1326
+ }
1327
+ let bounded = candidates.slice(0, maxCandidates);
1328
+ if (currentCandidateKey && candidates.some((candidate) => candidate.key === currentCandidateKey) && !bounded.some((candidate) => candidate.key === currentCandidateKey)) {
1329
+ bounded = [
1330
+ ...bounded.slice(0, Math.max(0, maxCandidates - 1)),
1331
+ candidates.find((candidate) => candidate.key === currentCandidateKey)
1332
+ ].sort((a, b) => compareCodexFleetCanonicalStringsV1(a.key, b.key));
1333
+ }
1334
+ return {
1335
+ input: {
1336
+ observedAtMs: normalizeInteger(input.observedAtMs, 0, Number.MAX_SAFE_INTEGER),
1337
+ request: {
1338
+ placement: input.request.placement === "fenced_in_flight" ? "fenced_in_flight" : "new",
1339
+ priority: input.request.priority === "manager" ? "manager" : "standard",
1340
+ currentCandidateKey,
1341
+ waitAgeMs: normalizeInteger(input.request.waitAgeMs, 0, MAX_DURATION_MS),
1342
+ overlayKey: normalizeOptionalKey(input.request.overlayKey),
1343
+ overlayMode: input.request.overlayMode === "isolate" ? "isolate" : input.request.overlayMode === "prefer" ? "prefer" : "none"
1344
+ },
1345
+ admission: {
1346
+ dynamicCapacityUnits: input.admission.dynamicCapacityUnits === null ? null : normalizeInteger(input.admission.dynamicCapacityUnits, 0, MAX_COUNT),
1347
+ inUseUnits: normalizeInteger(input.admission.inUseUnits, 0, MAX_COUNT),
1348
+ queuedManagerCount: normalizeInteger(input.admission.queuedManagerCount, 0, MAX_COUNT),
1349
+ emergencyFuseActive: input.admission.emergencyFuseActive === true
1350
+ },
1351
+ candidates: bounded
1352
+ },
1353
+ truncatedCandidateCount: candidates.length - bounded.length
1354
+ };
1355
+ }
1356
+ function normalizeCandidate(candidate) {
1357
+ return {
1358
+ key: normalizeKey(candidate.key),
1359
+ status: candidate.status === "active" || candidate.status === "needs_relogin" || candidate.status === "error" ? candidate.status : "unknown",
1360
+ allocatorEnabled: candidate.allocatorEnabled === true,
1361
+ cooldownRemainingMs: normalizeNullableInteger(
1362
+ candidate.cooldownRemainingMs,
1363
+ 0,
1364
+ MAX_DURATION_MS
1365
+ ),
1366
+ activeLeaseCount: normalizeInteger(candidate.activeLeaseCount, 0, MAX_COUNT),
1367
+ quota: {
1368
+ primary: normalizeQuotaWindow(candidate.quota.primary),
1369
+ secondary: normalizeQuotaWindow(candidate.quota.secondary),
1370
+ checkedAgeMs: normalizeNullableInteger(candidate.quota.checkedAgeMs, 0, MAX_DURATION_MS),
1371
+ confidence: normalizeConfidence(candidate.quota.confidence)
1372
+ },
1373
+ cache: {
1374
+ hitRatio: normalizeNullableNumber(candidate.cache.hitRatio, 0, 1, 4),
1375
+ sampledTokens: normalizeNullableInteger(candidate.cache.sampledTokens, 0, MAX_COUNT),
1376
+ checkedAgeMs: normalizeNullableInteger(candidate.cache.checkedAgeMs, 0, MAX_DURATION_MS),
1377
+ confidence: normalizeConfidence(candidate.cache.confidence),
1378
+ state: normalizeCacheState(candidate.cache.state),
1379
+ thresholdObservedForMs: normalizeNullableInteger(
1380
+ candidate.cache.thresholdObservedForMs,
1381
+ 0,
1382
+ MAX_DURATION_MS
1383
+ )
1384
+ },
1385
+ observedBurn: {
1386
+ primaryPercentPerHour: normalizeNullableNumber(
1387
+ candidate.observedBurn.primaryPercentPerHour,
1388
+ 0,
1389
+ 100,
1390
+ 3
1391
+ ),
1392
+ secondaryPercentPerHour: normalizeNullableNumber(
1393
+ candidate.observedBurn.secondaryPercentPerHour,
1394
+ 0,
1395
+ 100,
1396
+ 3
1397
+ ),
1398
+ confidence: normalizeConfidence(candidate.observedBurn.confidence)
1399
+ },
1400
+ inferredUnexplainedBurn: {
1401
+ primaryPercentPerHour: normalizeNullableNumber(
1402
+ candidate.inferredUnexplainedBurn.primaryPercentPerHour,
1403
+ 0,
1404
+ 100,
1405
+ 3
1406
+ ),
1407
+ secondaryPercentPerHour: normalizeNullableNumber(
1408
+ candidate.inferredUnexplainedBurn.secondaryPercentPerHour,
1409
+ 0,
1410
+ 100,
1411
+ 3
1412
+ ),
1413
+ confidence: normalizeConfidence(candidate.inferredUnexplainedBurn.confidence)
1414
+ },
1415
+ overlayKeys: [...new Set(candidate.overlayKeys.map(normalizeKey))].sort(compareCodexFleetCanonicalStringsV1).slice(0, CODEX_FLEET_POLICY_MAX_OVERLAYS_PER_CANDIDATE)
1416
+ };
1417
+ }
1418
+ function normalizeQuotaWindow(window) {
1419
+ return {
1420
+ usedPercent: normalizeNullableNumber(window.usedPercent, 0, 100, 3),
1421
+ resetRemainingMs: normalizeNullableInteger(window.resetRemainingMs, 0, MAX_DURATION_MS)
1422
+ };
1423
+ }
1424
+ function normalizePolicy(policy) {
1425
+ const quotaFreshForMs = normalizeInteger(policy.quotaFreshForMs, 1, MAX_DURATION_MS);
1426
+ const cacheCollapseThreshold = normalizeNumber(policy.cacheCollapseThreshold, 0, 1, 4);
1427
+ return {
1428
+ maxCandidates: normalizeInteger(policy.maxCandidates, 1, CODEX_FLEET_POLICY_MAX_CANDIDATES),
1429
+ quotaFreshForMs,
1430
+ quotaStaleAfterMs: normalizeInteger(policy.quotaStaleAfterMs, quotaFreshForMs, MAX_DURATION_MS),
1431
+ placementUsageCeilingPercent: normalizeNumber(policy.placementUsageCeilingPercent, 1, 100, 3),
1432
+ cacheFreshForMs: normalizeInteger(policy.cacheFreshForMs, 1, MAX_DURATION_MS),
1433
+ cacheCollapseThreshold,
1434
+ cacheCollapseRecoveryThreshold: normalizeNumber(
1435
+ policy.cacheCollapseRecoveryThreshold,
1436
+ cacheCollapseThreshold,
1437
+ 1,
1438
+ 4
1439
+ ),
1440
+ cacheMinimumSampledTokens: normalizeInteger(policy.cacheMinimumSampledTokens, 1, MAX_COUNT),
1441
+ cacheCollapseDwellMs: normalizeInteger(policy.cacheCollapseDwellMs, 1, MAX_DURATION_MS),
1442
+ cacheRecoveryDwellMs: normalizeInteger(policy.cacheRecoveryDwellMs, 1, MAX_DURATION_MS),
1443
+ activeLeaseScore: normalizeNumber(policy.activeLeaseScore, 0, MAX_COUNT, 3),
1444
+ unknownQuotaScore: normalizeNumber(policy.unknownQuotaScore, 0, MAX_COUNT, 3),
1445
+ lowQuotaConfidenceScore: normalizeNumber(policy.lowQuotaConfidenceScore, 0, MAX_COUNT, 3),
1446
+ mediumQuotaConfidenceScore: normalizeNumber(policy.mediumQuotaConfidenceScore, 0, MAX_COUNT, 3),
1447
+ inferredBurnScorePerPercentHour: normalizeNumber(
1448
+ policy.inferredBurnScorePerPercentHour,
1449
+ 0,
1450
+ MAX_COUNT,
1451
+ 3
1452
+ ),
1453
+ observedBurnScorePerPercentHour: normalizeNumber(
1454
+ policy.observedBurnScorePerPercentHour,
1455
+ 0,
1456
+ MAX_COUNT,
1457
+ 3
1458
+ ),
1459
+ runwayRiskCapHours: normalizeNumber(policy.runwayRiskCapHours, 0, 24 * 31, 3),
1460
+ runwayScorePerAtRiskHour: normalizeNumber(policy.runwayScorePerAtRiskHour, 0, MAX_COUNT, 3),
1461
+ healthyCacheAffinityBenefit: normalizeNumber(
1462
+ policy.healthyCacheAffinityBenefit,
1463
+ 0,
1464
+ MAX_COUNT,
1465
+ 3
1466
+ ),
1467
+ unknownCacheAffinityBenefit: normalizeNumber(
1468
+ policy.unknownCacheAffinityBenefit,
1469
+ 0,
1470
+ MAX_COUNT,
1471
+ 3
1472
+ ),
1473
+ collapsedCacheAffinityBenefit: normalizeNumber(
1474
+ policy.collapsedCacheAffinityBenefit,
1475
+ 0,
1476
+ MAX_COUNT,
1477
+ 3
1478
+ ),
1479
+ switchHysteresisScore: normalizeNumber(policy.switchHysteresisScore, 0, MAX_COUNT, 3),
1480
+ admissionPacingEnabled: policy.admissionPacingEnabled === true,
1481
+ managerPriorityEnabled: policy.managerPriorityEnabled === true,
1482
+ managerStandardStarvationMs: normalizeInteger(
1483
+ policy.managerStandardStarvationMs,
1484
+ 1,
1485
+ MAX_DURATION_MS
1486
+ ),
1487
+ emergencyFuseEnabled: policy.emergencyFuseEnabled === true,
1488
+ overlaysEnabled: policy.overlaysEnabled === true,
1489
+ overlayPreferenceScore: normalizeNumber(policy.overlayPreferenceScore, 0, MAX_COUNT, 3)
1490
+ };
1491
+ }
1492
+ function normalizeConfidence(value) {
1493
+ return value === "high" || value === "medium" || value === "low" ? value : "unknown";
1494
+ }
1495
+ function normalizeCacheState(value) {
1496
+ return value === "healthy" || value === "collapsed" ? value : "unknown";
1497
+ }
1498
+ function confidenceWeight(confidence) {
1499
+ if (confidence === "high") return 1;
1500
+ if (confidence === "medium") return 0.6;
1501
+ if (confidence === "low") return 0.25;
1502
+ return 0;
1503
+ }
1504
+ function lowerConfidence(value, ceiling) {
1505
+ return confidenceWeight(value) < confidenceWeight(ceiling) ? value : ceiling;
1506
+ }
1507
+ function normalizeKey(value) {
1508
+ if (!/^[a-zA-Z0-9._:-]{1,32}$/.test(value)) {
1509
+ throw new Error("Codex fleet candidate/overlay keys must be 1-32 opaque safe characters");
1510
+ }
1511
+ return value;
1512
+ }
1513
+ function normalizeOptionalKey(value) {
1514
+ return value === null ? null : normalizeKey(value);
1515
+ }
1516
+ function normalizeNullableNumber(value, min, max, decimals) {
1517
+ return value === null ? null : normalizeNumber(value, min, max, decimals);
1518
+ }
1519
+ function normalizeNumber(value, min, max, decimals) {
1520
+ const finite = Number.isFinite(value) ? value : min;
1521
+ const clamped = Math.min(max, Math.max(min, finite));
1522
+ const scale = 10 ** decimals;
1523
+ return Math.round(clamped * scale) / scale;
1524
+ }
1525
+ function normalizeNullableInteger(value, min, max) {
1526
+ return value === null ? null : normalizeInteger(value, min, max);
1527
+ }
1528
+ function normalizeInteger(value, min, max) {
1529
+ return Math.round(normalizeNumber(value, min, max, 0));
1530
+ }
1531
+ function readCodexFleetDecisionV1(value, candidateKeys) {
1532
+ const decision = strictRecord(value, [
1533
+ "outcome",
1534
+ "selectedCandidateKey",
1535
+ "reason",
1536
+ "admission",
1537
+ "borrowedOverlayCapacity",
1538
+ "strandedEligibleCount",
1539
+ "confidence",
1540
+ "scores"
1541
+ ]);
1542
+ const outcome = strictEnum(decision.outcome, ["selected", "paced", "none"]);
1543
+ const selectedCandidateKey = strictOptionalKey(decision.selectedCandidateKey);
1544
+ const reason = strictEnum(decision.reason, [
1545
+ "fenced_in_flight",
1546
+ "fenced_candidate_missing",
1547
+ "admission_paced",
1548
+ "no_eligible_candidate",
1549
+ "overlay_isolated_empty",
1550
+ "best_score",
1551
+ "affinity_best",
1552
+ "hysteresis_hold"
1553
+ ]);
1554
+ const admissionRecord = strictRecord(decision.admission, [
1555
+ "outcome",
1556
+ "reason",
1557
+ "borrowedIdleCapacity"
1558
+ ]);
1559
+ const admission = {
1560
+ outcome: strictEnum(admissionRecord.outcome, ["admit", "pace"]),
1561
+ reason: strictEnum(admissionRecord.reason, [
1562
+ "fenced_in_flight",
1563
+ "pacing_disabled",
1564
+ "capacity_unknown",
1565
+ "capacity_available",
1566
+ "work_conserving_borrow",
1567
+ "manager_priority",
1568
+ "standard_starvation_bound",
1569
+ "capacity_saturated",
1570
+ "emergency_fuse"
1571
+ ]),
1572
+ borrowedIdleCapacity: strictBoolean(admissionRecord.borrowedIdleCapacity)
1573
+ };
1574
+ if (!Array.isArray(decision.scores) || decision.scores.length > candidateKeys.size) {
1575
+ throw new Error("Codex fleet replay decision scores are not a bounded array");
1576
+ }
1577
+ const scores = decision.scores.map(readCodexFleetScoreV1);
1578
+ if (new Set(scores.map((score) => score.candidateKey)).size !== scores.length || scores.some((score) => !candidateKeys.has(score.candidateKey))) {
1579
+ throw new Error("Codex fleet replay decision has invalid candidate scores");
1580
+ }
1581
+ const borrowedOverlayCapacity = strictBoolean(decision.borrowedOverlayCapacity);
1582
+ const strandedEligibleCount = strictInteger(decision.strandedEligibleCount, 0, MAX_COUNT);
1583
+ const selectedReasons = [
1584
+ "fenced_in_flight",
1585
+ "best_score",
1586
+ "affinity_best",
1587
+ "hysteresis_hold"
1588
+ ];
1589
+ const noneReasons = [
1590
+ "fenced_candidate_missing",
1591
+ "no_eligible_candidate",
1592
+ "overlay_isolated_empty"
1593
+ ];
1594
+ const paceReasons = ["manager_priority", "capacity_saturated", "emergency_fuse"];
1595
+ const consistent = outcome === "selected" ? selectedCandidateKey !== null && admission.outcome === "admit" && selectedReasons.includes(reason) && scores.some((score) => score.candidateKey === selectedCandidateKey) : outcome === "paced" ? selectedCandidateKey === null && reason === "admission_paced" && admission.outcome === "pace" && paceReasons.includes(admission.reason) : selectedCandidateKey === null && admission.outcome === "admit" && noneReasons.includes(reason);
1596
+ if (!consistent || strandedEligibleCount > candidateKeys.size || admission.borrowedIdleCapacity !== (admission.reason === "work_conserving_borrow") || borrowedOverlayCapacity && (outcome !== "selected" || strandedEligibleCount !== 0)) {
1597
+ throw new Error("Codex fleet replay decision is internally inconsistent");
1598
+ }
1599
+ return {
1600
+ outcome,
1601
+ selectedCandidateKey,
1602
+ reason,
1603
+ admission,
1604
+ borrowedOverlayCapacity,
1605
+ strandedEligibleCount,
1606
+ confidence: strictConfidence(decision.confidence),
1607
+ scores
1608
+ };
1609
+ }
1610
+ function readCodexFleetScoreV1(value) {
1611
+ const score = strictRecord(value, [
1612
+ "candidateKey",
1613
+ "eligible",
1614
+ "rejectionReason",
1615
+ "quotaPressure",
1616
+ "leasePressure",
1617
+ "observedBurnPressure",
1618
+ "inferredBurnPressure",
1619
+ "runwayPressure",
1620
+ "uncertaintyPressure",
1621
+ "cacheAffinityBenefit",
1622
+ "cacheState",
1623
+ "overlayPreferenceBenefit",
1624
+ "total",
1625
+ "confidence"
1626
+ ]);
1627
+ const parsed = {
1628
+ candidateKey: normalizeKey(strictString(score.candidateKey)),
1629
+ eligible: strictBoolean(score.eligible),
1630
+ rejectionReason: score.rejectionReason === null ? null : strictEnum(score.rejectionReason, [
1631
+ "allocator_disabled",
1632
+ "unavailable",
1633
+ "cooling",
1634
+ "quota_ceiling",
1635
+ "overlay_isolation"
1636
+ ]),
1637
+ quotaPressure: strictFiniteNumber(score.quotaPressure, 0, Number.MAX_SAFE_INTEGER),
1638
+ leasePressure: strictFiniteNumber(score.leasePressure, 0, Number.MAX_SAFE_INTEGER),
1639
+ observedBurnPressure: strictFiniteNumber(
1640
+ score.observedBurnPressure,
1641
+ 0,
1642
+ Number.MAX_SAFE_INTEGER
1643
+ ),
1644
+ inferredBurnPressure: strictFiniteNumber(
1645
+ score.inferredBurnPressure,
1646
+ 0,
1647
+ Number.MAX_SAFE_INTEGER
1648
+ ),
1649
+ runwayPressure: strictFiniteNumber(score.runwayPressure, 0, Number.MAX_SAFE_INTEGER),
1650
+ uncertaintyPressure: strictFiniteNumber(score.uncertaintyPressure, 0, Number.MAX_SAFE_INTEGER),
1651
+ cacheAffinityBenefit: strictFiniteNumber(
1652
+ score.cacheAffinityBenefit,
1653
+ 0,
1654
+ Number.MAX_SAFE_INTEGER
1655
+ ),
1656
+ cacheState: strictEnum(score.cacheState, ["unknown", "healthy", "collapsed"]),
1657
+ overlayPreferenceBenefit: strictFiniteNumber(
1658
+ score.overlayPreferenceBenefit,
1659
+ 0,
1660
+ Number.MAX_SAFE_INTEGER
1661
+ ),
1662
+ total: strictFiniteNumber(score.total, -Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER),
1663
+ confidence: strictConfidence(score.confidence)
1664
+ };
1665
+ const expectedTotal = parsed.quotaPressure + parsed.leasePressure + parsed.observedBurnPressure + parsed.inferredBurnPressure + parsed.runwayPressure + parsed.uncertaintyPressure - parsed.cacheAffinityBenefit - parsed.overlayPreferenceBenefit;
1666
+ if (parsed.eligible !== (parsed.rejectionReason === null) || parsed.total !== expectedTotal) {
1667
+ throw new Error("Codex fleet replay score is internally inconsistent");
1668
+ }
1669
+ return parsed;
1670
+ }
1671
+ function strictRecord(value, expectedKeys) {
1672
+ if (value === null || typeof value !== "object" || Array.isArray(value) || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) {
1673
+ throw new Error("Codex fleet replay value must be a plain object");
1674
+ }
1675
+ const record = value;
1676
+ const actualKeys = Object.keys(record).sort(compareCodexFleetCanonicalStringsV1);
1677
+ const canonicalExpected = [...expectedKeys].sort(compareCodexFleetCanonicalStringsV1);
1678
+ if (canonicalJson(actualKeys) !== canonicalJson(canonicalExpected)) {
1679
+ throw new Error("Codex fleet replay object has missing or unknown fields");
1680
+ }
1681
+ return record;
1682
+ }
1683
+ function strictEnum(value, values) {
1684
+ if (typeof value !== "string" || !values.includes(value)) {
1685
+ throw new Error("Codex fleet replay enum value is invalid");
1686
+ }
1687
+ return value;
1688
+ }
1689
+ function strictConfidence(value) {
1690
+ return strictEnum(value, ["unknown", "low", "medium", "high"]);
1691
+ }
1692
+ function strictString(value) {
1693
+ if (typeof value !== "string") throw new Error("Codex fleet replay value must be a string");
1694
+ return value;
1695
+ }
1696
+ function strictOptionalKey(value) {
1697
+ return value === null ? null : normalizeKey(strictString(value));
1698
+ }
1699
+ function strictBoolean(value) {
1700
+ if (typeof value !== "boolean") throw new Error("Codex fleet replay value must be boolean");
1701
+ return value;
1702
+ }
1703
+ function strictFiniteNumber(value, min, max) {
1704
+ if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max) {
1705
+ throw new Error("Codex fleet replay numeric value is invalid");
1706
+ }
1707
+ return value;
1708
+ }
1709
+ function strictInteger(value, min, max) {
1710
+ const number = strictFiniteNumber(value, min, max);
1711
+ if (!Number.isInteger(number)) throw new Error("Codex fleet replay value must be an integer");
1712
+ return number;
1713
+ }
1714
+ function strictSha256(value) {
1715
+ if (typeof value !== "string" || !/^[a-f0-9]{64}$/.test(value)) {
1716
+ throw new Error("Codex fleet replay fingerprint must be lowercase SHA-256");
1717
+ }
1718
+ return value;
1719
+ }
1720
+ function fingerprint(value) {
1721
+ const serialized = canonicalJson(value);
1722
+ return bytesToHex(sha256(new TextEncoder().encode(serialized)));
1723
+ }
1724
+ function fingerprintReplayInput(input, truncatedCandidateCount) {
1725
+ return fingerprint({ input, truncatedCandidateCount });
1726
+ }
1727
+ function canonicalJson(value) {
1728
+ return JSON.stringify(sortJson(value));
1729
+ }
1730
+ function sortJson(value) {
1731
+ if (Array.isArray(value)) return value.map(sortJson);
1732
+ if (value && typeof value === "object") {
1733
+ return Object.fromEntries(
1734
+ Object.entries(value).sort(([left], [right]) => compareCodexFleetCanonicalStringsV1(left, right)).map(([key, child]) => [key, sortJson(child)])
1735
+ );
1736
+ }
1737
+ return value;
1738
+ }
1739
+
867
1740
  // src/index.ts
868
1741
  var SessionStatus = z2.enum([
869
1742
  "queued",
@@ -1226,6 +2099,8 @@ var ErrorCode = z2.enum([
1226
2099
  "conflict",
1227
2100
  "idempotency_conflict",
1228
2101
  "limit_exceeded",
2102
+ "nested_agent_depth_exceeded",
2103
+ "nested_agent_depth_override_forbidden",
1229
2104
  "provider_verification_failed",
1230
2105
  "upstream_unavailable",
1231
2106
  "internal_error"
@@ -1238,6 +2113,32 @@ var ErrorEnvelope = z2.object({
1238
2113
  details: z2.record(z2.string(), z2.unknown()).optional()
1239
2114
  })
1240
2115
  });
2116
+ var MAX_NESTED_AGENT_DEPTH = 2147483647;
2117
+ var NestedAgentDepthValue = z2.number().int().nonnegative().max(MAX_NESTED_AGENT_DEPTH);
2118
+ var NestedAgentDepthAttemptValue = z2.number().int().nonnegative().max(MAX_NESTED_AGENT_DEPTH + 1);
2119
+ var NestedAgentDepthPolicySource = z2.enum([
2120
+ "session",
2121
+ "workspace",
2122
+ "deployment",
2123
+ "default"
2124
+ ]);
2125
+ var SessionSpawnDenial = z2.object({
2126
+ id: z2.string().uuid(),
2127
+ accountId: z2.string().uuid(),
2128
+ workspaceId: z2.string().uuid(),
2129
+ parentSessionId: z2.string().uuid().nullable(),
2130
+ rootSessionId: z2.string().uuid().nullable(),
2131
+ currentDepth: NestedAgentDepthValue,
2132
+ attemptedDepth: NestedAgentDepthAttemptValue,
2133
+ effectiveMaxNestedAgentDepth: NestedAgentDepthValue,
2134
+ requestedMaxNestedAgentDepthOverride: NestedAgentDepthValue.nullable(),
2135
+ policySource: NestedAgentDepthPolicySource,
2136
+ policySessionId: z2.string().uuid().nullable(),
2137
+ subjectId: z2.string().nullable(),
2138
+ code: z2.enum(["nested_agent_depth_exceeded", "nested_agent_depth_override_forbidden"]),
2139
+ idempotencyKey: z2.string().nullable(),
2140
+ createdAt: z2.string()
2141
+ });
1241
2142
  var Permission = z2.enum([
1242
2143
  "account:read",
1243
2144
  "account:admin",
@@ -1599,7 +2500,10 @@ var WorkspaceTranscriptionPolicy = z2.object({
1599
2500
  });
1600
2501
  var WorkspaceSettingsSchema = z2.object({
1601
2502
  memoryEnabled: z2.boolean().optional(),
1602
- transcription: WorkspaceTranscriptionPolicy.optional()
2503
+ transcription: WorkspaceTranscriptionPolicy.optional(),
2504
+ // null clears the workspace override and falls back to the persisted
2505
+ // deployment policy. The database boundary validates the same range.
2506
+ maxNestedAgentDepth: NestedAgentDepthValue.nullable().optional()
1603
2507
  }).passthrough();
1604
2508
  function resolveWorkspaceMemoryEnabled(settings) {
1605
2509
  const parsed = WorkspaceSettingsSchema.safeParse(settings ?? {});
@@ -1607,7 +2511,8 @@ function resolveWorkspaceMemoryEnabled(settings) {
1607
2511
  }
1608
2512
  var UpdateWorkspaceSettingsRequest = z2.object({
1609
2513
  memoryEnabled: z2.boolean().optional(),
1610
- transcription: WorkspaceTranscriptionPolicy.optional()
2514
+ transcription: WorkspaceTranscriptionPolicy.optional(),
2515
+ maxNestedAgentDepth: NestedAgentDepthValue.nullable().optional()
1611
2516
  }).passthrough();
1612
2517
  var SetWorkspaceDefaultRigRequest = z2.object({
1613
2518
  rigId: z2.string().uuid().nullable()
@@ -2678,7 +3583,7 @@ function reasoningEffortForMetadata(metadata, fallback) {
2678
3583
  return value === "none" || value === "minimal" || value === "low" || value === "medium" || value === "high" || value === "xhigh" ? value : fallback;
2679
3584
  }
2680
3585
  function stableJson(value) {
2681
- return JSON.stringify(sortJson(value));
3586
+ return JSON.stringify(sortJson2(value));
2682
3587
  }
2683
3588
  function resourceIdentityKey(resource) {
2684
3589
  if (resource.kind === "file") {
@@ -2686,13 +3591,13 @@ function resourceIdentityKey(resource) {
2686
3591
  }
2687
3592
  return `repository:${resource.uri}`;
2688
3593
  }
2689
- function sortJson(value) {
3594
+ function sortJson2(value) {
2690
3595
  if (Array.isArray(value)) {
2691
- return value.map(sortJson);
3596
+ return value.map(sortJson2);
2692
3597
  }
2693
3598
  if (value && typeof value === "object") {
2694
3599
  return Object.fromEntries(
2695
- Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, nested]) => [key, sortJson(nested)])
3600
+ Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, nested]) => [key, sortJson2(nested)])
2696
3601
  );
2697
3602
  }
2698
3603
  return value;
@@ -2729,6 +3634,35 @@ var SessionGoalPausedReason = z2.enum([
2729
3634
  "max_auto_continuations",
2730
3635
  "limits"
2731
3636
  ]);
3637
+ var SessionGoalContinuationState = z2.enum([
3638
+ "inactive",
3639
+ "scheduled",
3640
+ "running",
3641
+ "blocked",
3642
+ "invariant_broken"
3643
+ ]);
3644
+ var SessionGoalContinuationReason = z2.enum([
3645
+ "goal_inactive",
3646
+ "wake_pending",
3647
+ "continuation_pending",
3648
+ "human_work_pending",
3649
+ "goal_turn_running",
3650
+ "human_turn_running",
3651
+ "workstream_paused",
3652
+ "approval_required",
3653
+ "provider_backpressure",
3654
+ "session_cancelled",
3655
+ "system_work_pending",
3656
+ "missing_obligation"
3657
+ ]);
3658
+ var SessionGoalContinuation = z2.object({
3659
+ state: SessionGoalContinuationState,
3660
+ reason: SessionGoalContinuationReason,
3661
+ wakeRevision: z2.number().int().nonnegative(),
3662
+ observedRevision: z2.number().int().nonnegative(),
3663
+ nextAttemptAt: z2.string().datetime({ offset: true }).nullable(),
3664
+ lastError: z2.string().nullable()
3665
+ });
2732
3666
  var SessionGoal = z2.object({
2733
3667
  id: z2.string().uuid(),
2734
3668
  accountId: z2.string().uuid(),
@@ -2746,6 +3680,9 @@ var SessionGoal = z2.object({
2746
3680
  noProgressStreak: z2.number().int().nonnegative(),
2747
3681
  maxAutoContinuations: z2.number().int().positive().nullable(),
2748
3682
  metadata: z2.record(z2.string(), z2.unknown()),
3683
+ // Optional for source compatibility with older clients; the API always
3684
+ // supplies this authoritative continuation projection.
3685
+ continuation: SessionGoalContinuation.optional(),
2749
3686
  createdAt: z2.string(),
2750
3687
  updatedAt: z2.string()
2751
3688
  });
@@ -3031,6 +3968,33 @@ var SaveComposerDraftRequest = ComposerDraft.pick({
3031
3968
  model: true,
3032
3969
  reasoningEffort: true
3033
3970
  }).extend({ expectedRevision: z2.number().int().nonnegative() });
3971
+ var NewSessionDraftOptions = z2.object({
3972
+ sandboxBackend: SandboxBackend.optional(),
3973
+ targetSandboxId: z2.string().uuid().optional(),
3974
+ workingDir: z2.string().min(1).optional(),
3975
+ variableSetId: z2.string().uuid().optional(),
3976
+ rigId: z2.string().uuid().optional(),
3977
+ goal: GoalSpec.optional(),
3978
+ firstPartyMcpPermissions: z2.array(Permission).optional()
3979
+ });
3980
+ var NewSessionDraft = z2.object({
3981
+ revision: z2.number().int().nonnegative(),
3982
+ text: z2.string(),
3983
+ resources: z2.array(ResourceRef),
3984
+ tools: z2.array(ToolRef),
3985
+ model: z2.string().min(1),
3986
+ reasoningEffort: ReasoningEffort,
3987
+ options: NewSessionDraftOptions,
3988
+ updatedAt: z2.string().nullable()
3989
+ });
3990
+ var SaveNewSessionDraftRequest = NewSessionDraft.pick({
3991
+ text: true,
3992
+ resources: true,
3993
+ tools: true,
3994
+ model: true,
3995
+ reasoningEffort: true,
3996
+ options: true
3997
+ }).extend({ expectedRevision: z2.number().int().nonnegative() });
3034
3998
  var WORKSPACE_CONTROL_REASON_MAX_BYTES = 8 * 1024;
3035
3999
  var WORKSPACE_CONTROL_ACTOR_MAX_BYTES = 1024;
3036
4000
  var WORKSPACE_CONTROL_EVENT_MAX_BYTES = 16 * 1024;
@@ -3435,7 +4399,10 @@ var ScheduledTaskAgentConfig = z2.object({
3435
4399
  model: z2.string().min(1).optional(),
3436
4400
  reasoningEffort: ReasoningEffort.optional(),
3437
4401
  sandboxBackend: SandboxBackend.optional(),
3438
- goal: GoalSpec.optional()
4402
+ goal: GoalSpec.optional(),
4403
+ // Durable task override. Scheduled dispatch is trusted to preserve this
4404
+ // snapshot even if the workspace/deployment policy narrows later.
4405
+ maxNestedAgentDepth: NestedAgentDepthValue.optional()
3439
4406
  });
3440
4407
  var ScheduledTask = z2.object({
3441
4408
  id: z2.string().uuid(),
@@ -4018,6 +4985,14 @@ var Session = z2.object({
4018
4985
  // direct API creates and scheduled-task runs. When set, this session's
4019
4986
  // terminal-for-now transitions wake the parent.
4020
4987
  parentSessionId: z2.string().uuid().nullable(),
4988
+ // Server-authored nested-agent lineage/policy. Root sessions are depth 0;
4989
+ // snapshots are immutable and govern only future descendant creation.
4990
+ rootSessionId: z2.string().uuid(),
4991
+ nestedAgentDepth: NestedAgentDepthValue,
4992
+ maxNestedAgentDepthOverride: NestedAgentDepthValue.nullable(),
4993
+ effectiveMaxNestedAgentDepth: NestedAgentDepthValue,
4994
+ nestedAgentDepthPolicySource: NestedAgentDepthPolicySource,
4995
+ nestedAgentDepthPolicySessionId: z2.string().uuid().nullable(),
4021
4996
  // Workspace-scoped CREATE idempotency key the session was created under (the
4022
4997
  // dedup target collapsing double-submit/retry races to one session); null
4023
4998
  // when the create carried no key.
@@ -4202,6 +5177,10 @@ var SessionEventType = z2.enum([
4202
5177
  // credential allocator per-turn selection audit. Payload is metadata only: credential row
4203
5178
  // id, bounded strategy/reason, and pool counts — never token material.
4204
5179
  "codex.credential.selected",
5180
+ // Adaptive fleet shadow decision record. Contains only bounded opaque candidate aliases,
5181
+ // normalized pressure/cache/confidence features, deterministic fingerprints,
5182
+ // the actual-vs-shadow comparison, and no credential/account identity.
5183
+ "codex.fleet.decision",
4205
5184
  // credential allocator durable zero-capacity wait lifecycle. Runtime/system events only;
4206
5185
  // no synthetic user message is created when capacity returns.
4207
5186
  "codex.capacity.waiting",
@@ -4577,7 +5556,7 @@ var TerminalPtyOutputDeltaPayload = z2.object({
4577
5556
  var TerminalPtyExitedPayload = z2.object({
4578
5557
  ptyId: z2.string().uuid(),
4579
5558
  exitCode: z2.number().int().nullable(),
4580
- reason: z2.enum(["exit", "killed", "owner_gone", "timeout"])
5559
+ reason: z2.enum(["exit", "killed", "owner_gone", "timeout", "lost"])
4581
5560
  });
4582
5561
  var FsNodeType = z2.enum(["file", "dir", "symlink", "other"]);
4583
5562
  var FsTreeNode = z2.lazy(
@@ -4930,7 +5909,8 @@ var TerminalExecRequest = z2.object({
4930
5909
  command: z2.string().min(1),
4931
5910
  cwd: z2.string().default(""),
4932
5911
  // workspace-relative
4933
- // Soft per-call wall-clock bound (the box yields output back when reached).
5912
+ // Hard wall-clock bound. A timeout response is returned only after the exact
5913
+ // provider process is physically absent and any retained admission settles.
4934
5914
  timeoutMs: z2.number().int().positive().max(12e4).default(3e4),
4935
5915
  // Stream the deltas onto A1 as the agent firehose (so other viewers see it),
4936
5916
  // in addition to returning the buffered result inline.
@@ -4939,10 +5919,10 @@ var TerminalExecRequest = z2.object({
4939
5919
  var TerminalExecResponse = z2.object({
4940
5920
  stdout: z2.string(),
4941
5921
  stderr: z2.string(),
4942
- exitCode: z2.number().int().nullable(),
4943
- // True when the process was still running when the call yielded (a long
4944
- // command); the remaining output drains onto A1 if emitStream was set.
4945
- running: z2.boolean(),
5922
+ exitCode: z2.number().int(),
5923
+ // Retained for wire compatibility; synchronous exec never exposes a live
5924
+ // provider process. Interactive work uses the PTY API.
5925
+ running: z2.literal(false),
4946
5926
  wallTimeSeconds: z2.number().nonnegative()
4947
5927
  });
4948
5928
  var PtyOpenRequest = z2.object({
@@ -5665,6 +6645,14 @@ var CreateSessionRequest = withVariableSetIdAlias({
5665
6645
  // creation of a brand-new session. Absent means no create-dedup (each call
5666
6646
  // is an independent create).
5667
6647
  idempotencyKey: z2.string().min(1).max(200).optional(),
6648
+ // The exact actor-private pre-session draft revision represented by this
6649
+ // create. The durable initializer consumes only this revision. A newer draft
6650
+ // written by a sibling tab survives, while every failed pre-initialization
6651
+ // create leaves the submitted draft intact.
6652
+ expectedNewSessionDraftRevision: z2.number().int().nonnegative().optional(),
6653
+ // A child may lower its inherited limit freely; an increase requires
6654
+ // workspace:admin and is checked again at the DB transaction boundary.
6655
+ maxNestedAgentDepth: NestedAgentDepthValue.optional(),
5668
6656
  // Permissions the session's first-party MCP token should carry. A top-level
5669
6657
  // omission uses the deployment's worker default; a child omission inherits
5670
6658
  // the creating session's effective grant. An explicit set is capped at
@@ -5969,6 +6957,9 @@ var SessionCapabilities = z2.object({
5969
6957
  liveness: z2.enum(["cold", "warming", "warm", "draining"]),
5970
6958
  // Echoed on viewer heartbeats (the split-brain fence).
5971
6959
  leaseEpoch: z2.number().int().nonnegative(),
6960
+ workspaceGeneration: z2.number().int().nonnegative().nullable().default(null),
6961
+ archiveGeneration: z2.number().int().nonnegative().nullable().default(null),
6962
+ archiveComplete: z2.boolean().default(false),
5972
6963
  viewerHeartbeatIntervalMs: z2.number().int().positive().default(3e4),
5973
6964
  FileSystem: z2.object({
5974
6965
  available: z2.boolean(),
@@ -6052,6 +7043,9 @@ var ViewerHolder = z2.object({
6052
7043
  liveness: z2.enum(["cold", "warming", "warm", "draining"]),
6053
7044
  // The epoch the viewer is fenced on; echoed back on heartbeats.
6054
7045
  leaseEpoch: z2.number().int().nonnegative(),
7046
+ workspaceGeneration: z2.number().int().nonnegative().nullable(),
7047
+ archiveGeneration: z2.number().int().nonnegative().nullable(),
7048
+ archiveComplete: z2.boolean(),
6055
7049
  viewerHeartbeatIntervalMs: z2.number().int().positive(),
6056
7050
  // The desktop pixel tunnel URL the viewer connects to directly; null until
6057
7051
  // a viewer grant is minted (gated until then).
@@ -6266,6 +7260,9 @@ var MachineView = z2.object({
6266
7260
  state: MachineState,
6267
7261
  active: z2.boolean(),
6268
7262
  isSessionGroup: z2.boolean(),
7263
+ workspaceGeneration: z2.number().int().nonnegative().nullable(),
7264
+ archiveGeneration: z2.number().int().nonnegative().nullable(),
7265
+ archiveComplete: z2.boolean(),
6269
7266
  os: z2.string(),
6270
7267
  arch: z2.string(),
6271
7268
  hasDisplay: z2.boolean(),
@@ -6300,7 +7297,10 @@ var SwapActiveSandboxResponse = z2.object({
6300
7297
  "offline_enrollment",
6301
7298
  "unsupported_backend_context",
6302
7299
  "transient_establishment",
6303
- "concurrent_swap"
7300
+ "concurrent_swap",
7301
+ "recovery_in_progress",
7302
+ "recovery_degraded",
7303
+ "recovery_unrecoverable"
6304
7304
  ]).optional()
6305
7305
  });
6306
7306
  var MachineMetricsSeriesResponse = z2.object({
@@ -6663,6 +7663,10 @@ export {
6663
7663
  CAPABILITY_DESCRIPTORS,
6664
7664
  CLEARED_RUN_STATE_BLOB,
6665
7665
  CLEARED_RUN_STATE_MARKER,
7666
+ CODEX_FLEET_POLICY_MAX_CANDIDATES,
7667
+ CODEX_FLEET_POLICY_MAX_OVERLAYS_PER_CANDIDATE,
7668
+ CODEX_FLEET_POLICY_SCHEMA_VERSION,
7669
+ CODEX_FLEET_POLICY_VERSION,
6666
7670
  CapabilityCatalogAuthKind,
6667
7671
  CapabilityCatalogItem,
6668
7672
  CapabilityCatalogResponse,
@@ -6714,6 +7718,7 @@ export {
6714
7718
  CreateWorkspaceEnvironmentRequest,
6715
7719
  CreateWorkspaceRequest,
6716
7720
  CredentialAuthNeededPayload,
7721
+ DEFAULT_CODEX_FLEET_POLICY_V1,
6717
7722
  DEFAULT_FIRST_PARTY_MCP_PERMISSIONS,
6718
7723
  DESKTOP_STREAM_PORT,
6719
7724
  DelegatedAccessTokenPayload,
@@ -6837,6 +7842,7 @@ export {
6837
7842
  ListConnectionsResponse,
6838
7843
  ListEnrollmentsResponse,
6839
7844
  ListWorkspaceMembersResponse,
7845
+ MAX_NESTED_AGENT_DEPTH,
6840
7846
  MachineKind,
6841
7847
  MachineMetricsSeriesResponse,
6842
7848
  MachineState,
@@ -6859,6 +7865,11 @@ export {
6859
7865
  ModelPricingScheduleV1,
6860
7866
  ModelPricingV1,
6861
7867
  MoveSessionQueueItemRequest,
7868
+ NestedAgentDepthAttemptValue,
7869
+ NestedAgentDepthPolicySource,
7870
+ NestedAgentDepthValue,
7871
+ NewSessionDraft,
7872
+ NewSessionDraftOptions,
6862
7873
  OAuthStartRequest,
6863
7874
  OAuthStartResponse,
6864
7875
  OPENGENI_API_CONTRACT_HEADER,
@@ -6931,6 +7942,7 @@ export {
6931
7942
  SandboxCommandOutputDeltaPayload,
6932
7943
  SandboxOs,
6933
7944
  SaveComposerDraftRequest,
7945
+ SaveNewSessionDraftRequest,
6934
7946
  ScheduledTask,
6935
7947
  ScheduledTaskAgentConfig,
6936
7948
  ScheduledTaskOverlapPolicy,
@@ -6965,6 +7977,9 @@ export {
6965
7977
  SessionEventSemanticClass,
6966
7978
  SessionEventType,
6967
7979
  SessionGoal,
7980
+ SessionGoalContinuation,
7981
+ SessionGoalContinuationReason,
7982
+ SessionGoalContinuationState,
6968
7983
  SessionGoalCreatedBy,
6969
7984
  SessionGoalPausedReason,
6970
7985
  SessionGoalStatus,
@@ -6978,6 +7993,7 @@ export {
6978
7993
  SessionMcpServerMetadata,
6979
7994
  SessionQueueMutationResponse,
6980
7995
  SessionQueueSnapshot,
7996
+ SessionSpawnDenial,
6981
7997
  SessionStatus,
6982
7998
  SessionStructuredCapabilities,
6983
7999
  SessionSystemUpdate,
@@ -7090,9 +8106,14 @@ export {
7090
8106
  boundSessionEvent,
7091
8107
  boundSessionEventPayload,
7092
8108
  boundWorkspaceControlEvent,
8109
+ canonicalCodexFleetReplayJsonV1,
7093
8110
  capabilityCatalogItemIsTrustedForExposure,
7094
8111
  compactSessionEventResult,
8112
+ compareCodexFleetCanonicalStringsV1,
8113
+ createCodexFleetReplayRecordV1,
7095
8114
  defaultRepositoryMountPath,
8115
+ effectiveCodexFleetCacheStateV1,
8116
+ evaluateCodexFleetDecisionV1,
7096
8117
  evaluateWorkspaceModelPolicy,
7097
8118
  gitCredentialBindingIdForRepository,
7098
8119
  gitCredentialProviderForRepository,
@@ -7104,8 +8125,10 @@ export {
7104
8125
  normalizeRepositorySubpath,
7105
8126
  normalizeResourceMountPath,
7106
8127
  prefixedMcpToolName,
8128
+ readCodexFleetReplayRecordV1,
7107
8129
  readTurnExecutionPolicyV1,
7108
8130
  reasoningEffortForMetadata,
8131
+ replayCodexFleetDecisionV1,
7109
8132
  resolveRetainedOutputRange,
7110
8133
  resolveSessionEventTypeFilters,
7111
8134
  resolveWorkspaceMemoryEnabled,