@opengeni/contracts 0.18.0 → 0.19.4
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.d.ts +970 -67
- package/dist/index.js +1378 -16
- package/dist/index.js.map +1 -1
- package/package.json +2 -1
- package/src/codex-fleet-policy.ts +1405 -0
- package/src/index.ts +302 -6
- package/src/secret-redaction.ts +364 -0
package/dist/index.js
CHANGED
|
@@ -864,6 +864,1134 @@ 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
|
+
|
|
1740
|
+
// src/secret-redaction.ts
|
|
1741
|
+
var MIN_REDACTABLE_VALUE_LENGTH = 6;
|
|
1742
|
+
var REDACTED = "[redacted]";
|
|
1743
|
+
var MAX_REDACTION_DEPTH = 64;
|
|
1744
|
+
var CYCLE_MARKER = "[OpenGeni omitted cyclic value during secret redaction]";
|
|
1745
|
+
var DEPTH_MARKER = "[OpenGeni omitted value beyond secret-redaction depth]";
|
|
1746
|
+
var SENSITIVE_FIELD_NAMES = /* @__PURE__ */ new Set([
|
|
1747
|
+
"authorization",
|
|
1748
|
+
"proxyauthorization",
|
|
1749
|
+
"cookie",
|
|
1750
|
+
"setcookie",
|
|
1751
|
+
"accesstoken",
|
|
1752
|
+
"refreshtoken",
|
|
1753
|
+
"idtoken",
|
|
1754
|
+
"apikey",
|
|
1755
|
+
"secret",
|
|
1756
|
+
"clientsecret",
|
|
1757
|
+
"password",
|
|
1758
|
+
"passwd",
|
|
1759
|
+
"privatekey",
|
|
1760
|
+
"credential",
|
|
1761
|
+
"credentials",
|
|
1762
|
+
"credentialencrypted",
|
|
1763
|
+
"encryptedcredential",
|
|
1764
|
+
"headersencrypted",
|
|
1765
|
+
"encryptedpkceverifier",
|
|
1766
|
+
"codeverifier",
|
|
1767
|
+
"signingkey"
|
|
1768
|
+
]);
|
|
1769
|
+
var CREDENTIAL_HEADER_PATTERNS = [
|
|
1770
|
+
/^(?:proxy-)?authorization$/i,
|
|
1771
|
+
/^(?:set-)?cookie$/i,
|
|
1772
|
+
/^(?:x[-_])?api[-_]?key$/i,
|
|
1773
|
+
/^(?:x[-_])?(?:access|refresh|id)[-_]?token$/i,
|
|
1774
|
+
/^(?:x[-_])?(?:auth|session)[-_]?(?:token|key|secret)$/i,
|
|
1775
|
+
/^(?:x[-_])?(?:client|app|consumer)[-_]?secret$/i,
|
|
1776
|
+
/^x-opengeni-access-key$/i
|
|
1777
|
+
];
|
|
1778
|
+
var SECRET_KEY_SOURCE = "(?:proxy[-_ ]?authorization|authorization|set[-_ ]?cookie|cookie|access[-_ ]?token|refresh[-_ ]?token|id[-_ ]?token|api[-_ ]?key|client[-_ ]?secret|secret|password|passwd|private[-_ ]?key|credential(?:s|[-_ ]?encrypted)?|encrypted[-_ ]?credential|encrypted[-_ ]?pkce[-_ ]?verifier|code[-_ ]?verifier|signing[-_ ]?key)";
|
|
1779
|
+
var UNQUOTED_SECRET_KEY_SOURCE = "(?:access[-_ ]?token|refresh[-_ ]?token|id[-_ ]?token|api[-_ ]?key|client[-_ ]?secret|secret|password|passwd|private[-_ ]?key|credential(?:s|[-_ ]?encrypted)?|encrypted[-_ ]?credential|encrypted[-_ ]?pkce[-_ ]?verifier|code[-_ ]?verifier|signing[-_ ]?key)";
|
|
1780
|
+
var AUTHORIZATION_HEADER_PATTERN = /(\b(?:proxy-)?authorization[^\S\r\n]*:[^\S\r\n]*)([^\r\n'"`]+)/gi;
|
|
1781
|
+
var COOKIE_HEADER_PATTERN = /(\b(?:set-cookie|cookie)\s*:\s*)([^\r\n'"`]+)/gi;
|
|
1782
|
+
var API_KEY_HEADER_PATTERN = /(\b(?:x[-_])?api[-_]?key[^\S\r\n]*:[^\S\r\n]*)([^\r\n'"`]+)/gi;
|
|
1783
|
+
var CURL_USER_PATTERN = /((?:^|\s)(?:-u|--user)(?:=|\s+))(?:("[^"]*")|('[^']*')|([^\s]+))/gm;
|
|
1784
|
+
var URL_USERINFO_PATTERN = /(https?:\/\/)[^\s/@]+@/gi;
|
|
1785
|
+
var SIGNED_QUERY_PATTERN = new RegExp(
|
|
1786
|
+
`([?&](?:sig|signature|x-amz-signature|x-amz-credential|x-amz-security-token|x-goog-signature|x-goog-credential|access_token|refresh_token|token)=)([^&#\\s'"<>]+)`,
|
|
1787
|
+
"gi"
|
|
1788
|
+
);
|
|
1789
|
+
var QUOTED_SECRET_ASSIGNMENT_PATTERN = new RegExp(
|
|
1790
|
+
`((?:["']${SECRET_KEY_SOURCE}["']|\\b${SECRET_KEY_SOURCE})\\s*[:=]\\s*)(["'])(.*?)\\2`,
|
|
1791
|
+
"gi"
|
|
1792
|
+
);
|
|
1793
|
+
var UNQUOTED_SECRET_ASSIGNMENT_PATTERN = new RegExp(
|
|
1794
|
+
`((?:\\b${UNQUOTED_SECRET_KEY_SOURCE})\\s*[:=]\\s*)([^\\s,;}&]+)`,
|
|
1795
|
+
"gi"
|
|
1796
|
+
);
|
|
1797
|
+
var SECRET_ENV_ASSIGNMENT_PATTERN = /((?:^|[\s;])(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|CREDENTIAL|AUTHORIZATION|COOKIE)[A-Za-z0-9_]*\s*=\s*)(?:("[^"]*")|('[^']*')|([^\s;]+))/gim;
|
|
1798
|
+
var PROVIDER_TOKEN_PATTERNS = [
|
|
1799
|
+
/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,
|
|
1800
|
+
/\bgh[pousr]_[A-Za-z0-9]{20,}\b/g,
|
|
1801
|
+
/\bglpat-[A-Za-z0-9_-]{20,}\b/g,
|
|
1802
|
+
/\bsk-[A-Za-z0-9_-]{20,}\b/g,
|
|
1803
|
+
/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g,
|
|
1804
|
+
/\bAIza[0-9A-Za-z_-]{30,}\b/g,
|
|
1805
|
+
/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g,
|
|
1806
|
+
/\bogd_[A-Za-z0-9._~-]{10,}\b/g,
|
|
1807
|
+
/\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g
|
|
1808
|
+
];
|
|
1809
|
+
function isSensitiveFieldName(name) {
|
|
1810
|
+
return SENSITIVE_FIELD_NAMES.has(normalizeFieldName(name));
|
|
1811
|
+
}
|
|
1812
|
+
function isCredentialHeaderName(name) {
|
|
1813
|
+
return CREDENTIAL_HEADER_PATTERNS.some((pattern) => pattern.test(name));
|
|
1814
|
+
}
|
|
1815
|
+
function redactSensitiveKey(key, knownSecrets = []) {
|
|
1816
|
+
return replacePreparedSecrets(key, prepareSecrets(knownSecrets));
|
|
1817
|
+
}
|
|
1818
|
+
function redactSensitiveText(text, knownSecrets = []) {
|
|
1819
|
+
let redacted = replacePreparedSecrets(text, prepareSecrets(knownSecrets));
|
|
1820
|
+
redacted = redacted.replace(
|
|
1821
|
+
AUTHORIZATION_HEADER_PATTERN,
|
|
1822
|
+
(match, prefix, rawValue) => {
|
|
1823
|
+
const value = rawValue.trimEnd();
|
|
1824
|
+
const trailingWhitespace = rawValue.slice(value.length);
|
|
1825
|
+
const schemeMatch = value.match(/^([A-Za-z][A-Za-z0-9_-]*)(\s+)(.+)$/);
|
|
1826
|
+
if (schemeMatch) {
|
|
1827
|
+
const scheme = schemeMatch[1];
|
|
1828
|
+
const whitespace = schemeMatch[2];
|
|
1829
|
+
const credential = schemeMatch[3];
|
|
1830
|
+
if (scheme && whitespace && credential) {
|
|
1831
|
+
return isRedactionMarker(credential.trim()) ? match : `${prefix}${scheme}${whitespace}${REDACTED}${trailingWhitespace}`;
|
|
1832
|
+
}
|
|
1833
|
+
}
|
|
1834
|
+
return isRedactionMarker(value) ? match : `${prefix}${REDACTED}${trailingWhitespace}`;
|
|
1835
|
+
}
|
|
1836
|
+
);
|
|
1837
|
+
redacted = redacted.replace(COOKIE_HEADER_PATTERN, `$1${REDACTED}`);
|
|
1838
|
+
redacted = redacted.replace(API_KEY_HEADER_PATTERN, `$1${REDACTED}`);
|
|
1839
|
+
redacted = redacted.replace(CURL_USER_PATTERN, (_match, prefix) => {
|
|
1840
|
+
return `${prefix}${REDACTED}`;
|
|
1841
|
+
});
|
|
1842
|
+
redacted = redacted.replace(URL_USERINFO_PATTERN, `$1${REDACTED}@`);
|
|
1843
|
+
redacted = redacted.replace(SIGNED_QUERY_PATTERN, `$1${REDACTED}`);
|
|
1844
|
+
redacted = redacted.replace(
|
|
1845
|
+
QUOTED_SECRET_ASSIGNMENT_PATTERN,
|
|
1846
|
+
(match, prefix, quote, value) => isRedactionMarker(value) ? match : `${prefix}${quote}${REDACTED}${quote}`
|
|
1847
|
+
);
|
|
1848
|
+
redacted = redacted.replace(
|
|
1849
|
+
UNQUOTED_SECRET_ASSIGNMENT_PATTERN,
|
|
1850
|
+
(match, prefix, value) => isRedactionMarker(value) ? match : `${prefix}${REDACTED}`
|
|
1851
|
+
);
|
|
1852
|
+
redacted = redacted.replace(
|
|
1853
|
+
SECRET_ENV_ASSIGNMENT_PATTERN,
|
|
1854
|
+
(match, prefix, doubleQuoted, singleQuoted, bare) => {
|
|
1855
|
+
const value = doubleQuoted ?? singleQuoted ?? bare ?? "";
|
|
1856
|
+
return isRedactionMarker(stripMatchingQuotes(value)) ? match : `${prefix}${REDACTED}`;
|
|
1857
|
+
}
|
|
1858
|
+
);
|
|
1859
|
+
for (const pattern of PROVIDER_TOKEN_PATTERNS) {
|
|
1860
|
+
redacted = redacted.replace(pattern, REDACTED);
|
|
1861
|
+
}
|
|
1862
|
+
return redacted;
|
|
1863
|
+
}
|
|
1864
|
+
function redactSensitiveData(value, knownSecrets = []) {
|
|
1865
|
+
return redactSensitiveDataDeep(value, knownSecrets, /* @__PURE__ */ new WeakSet(), 0);
|
|
1866
|
+
}
|
|
1867
|
+
function createSecretRedactor(knownSecrets) {
|
|
1868
|
+
const prepared = prepareSecrets(knownSecrets).map(({ marker, value }) => ({
|
|
1869
|
+
name: marker.slice("[redacted:".length, -1),
|
|
1870
|
+
value
|
|
1871
|
+
}));
|
|
1872
|
+
return (value) => redactSensitiveData(value, prepared);
|
|
1873
|
+
}
|
|
1874
|
+
function redactSerializedJson(serialized, knownSecrets = []) {
|
|
1875
|
+
try {
|
|
1876
|
+
return JSON.stringify(redactSensitiveData(JSON.parse(serialized), knownSecrets));
|
|
1877
|
+
} catch {
|
|
1878
|
+
return redactSensitiveText(serialized, knownSecrets);
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1881
|
+
function identityRedactor(value) {
|
|
1882
|
+
return value;
|
|
1883
|
+
}
|
|
1884
|
+
function redactSensitiveDataDeep(value, knownSecrets, seen, depth) {
|
|
1885
|
+
if (typeof value === "string") {
|
|
1886
|
+
return redactSensitiveText(value, knownSecrets);
|
|
1887
|
+
}
|
|
1888
|
+
if (!value || typeof value !== "object" || value instanceof Date) {
|
|
1889
|
+
return value;
|
|
1890
|
+
}
|
|
1891
|
+
if (depth >= MAX_REDACTION_DEPTH) {
|
|
1892
|
+
return DEPTH_MARKER;
|
|
1893
|
+
}
|
|
1894
|
+
if (seen.has(value)) {
|
|
1895
|
+
return CYCLE_MARKER;
|
|
1896
|
+
}
|
|
1897
|
+
seen.add(value);
|
|
1898
|
+
try {
|
|
1899
|
+
if (Array.isArray(value)) {
|
|
1900
|
+
return value.map((item) => redactSensitiveDataDeep(item, knownSecrets, seen, depth + 1));
|
|
1901
|
+
}
|
|
1902
|
+
if (!isPlainObject(value)) {
|
|
1903
|
+
return value;
|
|
1904
|
+
}
|
|
1905
|
+
const usedKeys = /* @__PURE__ */ new Set();
|
|
1906
|
+
return Object.fromEntries(
|
|
1907
|
+
Object.entries(value).map(([key, child]) => {
|
|
1908
|
+
const safeKey = nextUniqueKey(redactSensitiveKey(key, knownSecrets), usedKeys);
|
|
1909
|
+
if (isSensitiveFieldName(key)) {
|
|
1910
|
+
return [safeKey, REDACTED];
|
|
1911
|
+
}
|
|
1912
|
+
if (normalizeFieldName(key) === "headers") {
|
|
1913
|
+
return [safeKey, redactHeaderMap(child, knownSecrets, seen, depth + 1)];
|
|
1914
|
+
}
|
|
1915
|
+
return [safeKey, redactSensitiveDataDeep(child, knownSecrets, seen, depth + 1)];
|
|
1916
|
+
})
|
|
1917
|
+
);
|
|
1918
|
+
} finally {
|
|
1919
|
+
seen.delete(value);
|
|
1920
|
+
}
|
|
1921
|
+
}
|
|
1922
|
+
function redactHeaderMap(value, knownSecrets, seen, depth) {
|
|
1923
|
+
if (!isPlainObject(value)) {
|
|
1924
|
+
return redactSensitiveDataDeep(value, knownSecrets, seen, depth);
|
|
1925
|
+
}
|
|
1926
|
+
if (depth >= MAX_REDACTION_DEPTH) return DEPTH_MARKER;
|
|
1927
|
+
if (seen.has(value)) return CYCLE_MARKER;
|
|
1928
|
+
seen.add(value);
|
|
1929
|
+
try {
|
|
1930
|
+
const usedKeys = /* @__PURE__ */ new Set();
|
|
1931
|
+
return Object.fromEntries(
|
|
1932
|
+
Object.entries(value).map(([key, child]) => {
|
|
1933
|
+
const safeKey = nextUniqueKey(redactSensitiveKey(key, knownSecrets), usedKeys);
|
|
1934
|
+
return [
|
|
1935
|
+
safeKey,
|
|
1936
|
+
isCredentialHeaderName(key) ? REDACTED : redactSensitiveDataDeep(child, knownSecrets, seen, depth + 1)
|
|
1937
|
+
];
|
|
1938
|
+
})
|
|
1939
|
+
);
|
|
1940
|
+
} finally {
|
|
1941
|
+
seen.delete(value);
|
|
1942
|
+
}
|
|
1943
|
+
}
|
|
1944
|
+
function prepareSecrets(knownSecrets) {
|
|
1945
|
+
const unique = /* @__PURE__ */ new Map();
|
|
1946
|
+
for (const secret of knownSecrets) {
|
|
1947
|
+
if (secret.value.length < MIN_REDACTABLE_VALUE_LENGTH || unique.has(secret.value)) {
|
|
1948
|
+
continue;
|
|
1949
|
+
}
|
|
1950
|
+
unique.set(secret.value, `[redacted:${safeSecretName(secret.name)}]`);
|
|
1951
|
+
}
|
|
1952
|
+
return [...unique].map(([value, marker]) => ({ marker, value })).sort((a, b) => b.value.length - a.value.length || a.marker.localeCompare(b.marker));
|
|
1953
|
+
}
|
|
1954
|
+
function replacePreparedSecrets(text, prepared) {
|
|
1955
|
+
let redacted = text;
|
|
1956
|
+
for (const secret of prepared) {
|
|
1957
|
+
if (redacted.includes(secret.value)) {
|
|
1958
|
+
redacted = redacted.split(secret.value).join(secret.marker);
|
|
1959
|
+
}
|
|
1960
|
+
}
|
|
1961
|
+
return redacted;
|
|
1962
|
+
}
|
|
1963
|
+
function nextUniqueKey(base, usedKeys) {
|
|
1964
|
+
let candidate = base;
|
|
1965
|
+
let suffix = 2;
|
|
1966
|
+
while (usedKeys.has(candidate)) {
|
|
1967
|
+
candidate = `${base}#${suffix}`;
|
|
1968
|
+
suffix += 1;
|
|
1969
|
+
}
|
|
1970
|
+
usedKeys.add(candidate);
|
|
1971
|
+
return candidate;
|
|
1972
|
+
}
|
|
1973
|
+
function safeSecretName(name) {
|
|
1974
|
+
const safe = name.toUpperCase().replace(/[^A-Z0-9_]+/g, "_").replace(/^_+|_+$/g, "");
|
|
1975
|
+
return safe.slice(0, 64) || "KNOWN_SECRET";
|
|
1976
|
+
}
|
|
1977
|
+
function normalizeFieldName(name) {
|
|
1978
|
+
return name.toLowerCase().replace(/[-_\s]/g, "");
|
|
1979
|
+
}
|
|
1980
|
+
function isPlainObject(value) {
|
|
1981
|
+
if (!value || typeof value !== "object") return false;
|
|
1982
|
+
const prototype = Object.getPrototypeOf(value);
|
|
1983
|
+
return prototype === Object.prototype || prototype === null;
|
|
1984
|
+
}
|
|
1985
|
+
function isRedactionMarker(value) {
|
|
1986
|
+
return /^\[redacted(?::[A-Z0-9_]{1,64})?\]$/.test(value);
|
|
1987
|
+
}
|
|
1988
|
+
function stripMatchingQuotes(value) {
|
|
1989
|
+
if (value.length >= 2 && (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'"))) {
|
|
1990
|
+
return value.slice(1, -1);
|
|
1991
|
+
}
|
|
1992
|
+
return value;
|
|
1993
|
+
}
|
|
1994
|
+
|
|
867
1995
|
// src/index.ts
|
|
868
1996
|
var SessionStatus = z2.enum([
|
|
869
1997
|
"queued",
|
|
@@ -1226,18 +2354,48 @@ var ErrorCode = z2.enum([
|
|
|
1226
2354
|
"conflict",
|
|
1227
2355
|
"idempotency_conflict",
|
|
1228
2356
|
"limit_exceeded",
|
|
2357
|
+
"nested_agent_depth_exceeded",
|
|
2358
|
+
"nested_agent_depth_override_forbidden",
|
|
1229
2359
|
"provider_verification_failed",
|
|
1230
2360
|
"upstream_unavailable",
|
|
1231
2361
|
"internal_error"
|
|
1232
2362
|
]);
|
|
1233
2363
|
var ErrorEnvelope = z2.object({
|
|
1234
2364
|
error: z2.object({
|
|
2365
|
+
status: z2.number().int().min(400).max(599),
|
|
1235
2366
|
code: ErrorCode,
|
|
1236
2367
|
message: z2.string(),
|
|
2368
|
+
retryable: z2.boolean(),
|
|
1237
2369
|
requestId: z2.string().optional(),
|
|
1238
2370
|
details: z2.record(z2.string(), z2.unknown()).optional()
|
|
1239
2371
|
})
|
|
1240
2372
|
});
|
|
2373
|
+
var MAX_NESTED_AGENT_DEPTH = 2147483647;
|
|
2374
|
+
var NestedAgentDepthValue = z2.number().int().nonnegative().max(MAX_NESTED_AGENT_DEPTH);
|
|
2375
|
+
var NestedAgentDepthAttemptValue = z2.number().int().nonnegative().max(MAX_NESTED_AGENT_DEPTH + 1);
|
|
2376
|
+
var NestedAgentDepthPolicySource = z2.enum([
|
|
2377
|
+
"session",
|
|
2378
|
+
"workspace",
|
|
2379
|
+
"deployment",
|
|
2380
|
+
"default"
|
|
2381
|
+
]);
|
|
2382
|
+
var SessionSpawnDenial = z2.object({
|
|
2383
|
+
id: z2.string().uuid(),
|
|
2384
|
+
accountId: z2.string().uuid(),
|
|
2385
|
+
workspaceId: z2.string().uuid(),
|
|
2386
|
+
parentSessionId: z2.string().uuid().nullable(),
|
|
2387
|
+
rootSessionId: z2.string().uuid().nullable(),
|
|
2388
|
+
currentDepth: NestedAgentDepthValue,
|
|
2389
|
+
attemptedDepth: NestedAgentDepthAttemptValue,
|
|
2390
|
+
effectiveMaxNestedAgentDepth: NestedAgentDepthValue,
|
|
2391
|
+
requestedMaxNestedAgentDepthOverride: NestedAgentDepthValue.nullable(),
|
|
2392
|
+
policySource: NestedAgentDepthPolicySource,
|
|
2393
|
+
policySessionId: z2.string().uuid().nullable(),
|
|
2394
|
+
subjectId: z2.string().nullable(),
|
|
2395
|
+
code: z2.enum(["nested_agent_depth_exceeded", "nested_agent_depth_override_forbidden"]),
|
|
2396
|
+
idempotencyKey: z2.string().nullable(),
|
|
2397
|
+
createdAt: z2.string()
|
|
2398
|
+
});
|
|
1241
2399
|
var Permission = z2.enum([
|
|
1242
2400
|
"account:read",
|
|
1243
2401
|
"account:admin",
|
|
@@ -1599,7 +2757,10 @@ var WorkspaceTranscriptionPolicy = z2.object({
|
|
|
1599
2757
|
});
|
|
1600
2758
|
var WorkspaceSettingsSchema = z2.object({
|
|
1601
2759
|
memoryEnabled: z2.boolean().optional(),
|
|
1602
|
-
transcription: WorkspaceTranscriptionPolicy.optional()
|
|
2760
|
+
transcription: WorkspaceTranscriptionPolicy.optional(),
|
|
2761
|
+
// null clears the workspace override and falls back to the persisted
|
|
2762
|
+
// deployment policy. The database boundary validates the same range.
|
|
2763
|
+
maxNestedAgentDepth: NestedAgentDepthValue.nullable().optional()
|
|
1603
2764
|
}).passthrough();
|
|
1604
2765
|
function resolveWorkspaceMemoryEnabled(settings) {
|
|
1605
2766
|
const parsed = WorkspaceSettingsSchema.safeParse(settings ?? {});
|
|
@@ -1607,7 +2768,8 @@ function resolveWorkspaceMemoryEnabled(settings) {
|
|
|
1607
2768
|
}
|
|
1608
2769
|
var UpdateWorkspaceSettingsRequest = z2.object({
|
|
1609
2770
|
memoryEnabled: z2.boolean().optional(),
|
|
1610
|
-
transcription: WorkspaceTranscriptionPolicy.optional()
|
|
2771
|
+
transcription: WorkspaceTranscriptionPolicy.optional(),
|
|
2772
|
+
maxNestedAgentDepth: NestedAgentDepthValue.nullable().optional()
|
|
1611
2773
|
}).passthrough();
|
|
1612
2774
|
var SetWorkspaceDefaultRigRequest = z2.object({
|
|
1613
2775
|
rigId: z2.string().uuid().nullable()
|
|
@@ -2319,6 +3481,22 @@ var KnowledgeSourceKind = z2.enum([
|
|
|
2319
3481
|
"other"
|
|
2320
3482
|
]);
|
|
2321
3483
|
var DocumentSearchMode = z2.enum(["hybrid", "vector", "keyword"]);
|
|
3484
|
+
var DocumentVisibility = z2.enum(["workspace", "private"]);
|
|
3485
|
+
var DocumentCurationStatus = z2.enum([
|
|
3486
|
+
"none",
|
|
3487
|
+
"pending",
|
|
3488
|
+
"suggested",
|
|
3489
|
+
"auto_filed",
|
|
3490
|
+
"failed"
|
|
3491
|
+
]);
|
|
3492
|
+
var DocumentCuration = z2.object({
|
|
3493
|
+
suggestedBaseId: z2.string().uuid().nullable(),
|
|
3494
|
+
suggestedBaseName: z2.string().nullable(),
|
|
3495
|
+
confidence: z2.number().min(0).max(1),
|
|
3496
|
+
reason: z2.string().nullable(),
|
|
3497
|
+
originalTitle: z2.string().nullable(),
|
|
3498
|
+
model: z2.string().nullable()
|
|
3499
|
+
});
|
|
2322
3500
|
var DocumentBase = z2.object({
|
|
2323
3501
|
id: z2.string().uuid(),
|
|
2324
3502
|
workspaceId: z2.string().uuid(),
|
|
@@ -2346,6 +3524,13 @@ var Document = z2.object({
|
|
|
2346
3524
|
sourceUpdatedAt: z2.string().nullable(),
|
|
2347
3525
|
sourceVersion: z2.string().nullable(),
|
|
2348
3526
|
aclTags: z2.array(z2.string()),
|
|
3527
|
+
visibility: DocumentVisibility,
|
|
3528
|
+
createdBy: z2.string().nullable(),
|
|
3529
|
+
agentAccess: z2.boolean(),
|
|
3530
|
+
summary: z2.string().nullable(),
|
|
3531
|
+
topics: z2.array(z2.string()),
|
|
3532
|
+
curationStatus: DocumentCurationStatus,
|
|
3533
|
+
curation: DocumentCuration.nullable(),
|
|
2349
3534
|
createdAt: z2.string(),
|
|
2350
3535
|
updatedAt: z2.string()
|
|
2351
3536
|
});
|
|
@@ -2388,7 +3573,22 @@ var AddDocumentRequest = z2.object({
|
|
|
2388
3573
|
sourceCreatedAt: z2.string().datetime({ offset: true }).optional(),
|
|
2389
3574
|
sourceUpdatedAt: z2.string().datetime({ offset: true }).optional(),
|
|
2390
3575
|
sourceVersion: z2.string().min(1).optional(),
|
|
2391
|
-
aclTags: z2.array(z2.string().min(1)).optional()
|
|
3576
|
+
aclTags: z2.array(z2.string().min(1)).optional(),
|
|
3577
|
+
visibility: DocumentVisibility.optional(),
|
|
3578
|
+
agentAccess: z2.boolean().optional()
|
|
3579
|
+
});
|
|
3580
|
+
var CreateKnowledgeDropRequest = z2.object({
|
|
3581
|
+
text: z2.string().min(1).max(2e6).optional(),
|
|
3582
|
+
fileId: z2.string().uuid().optional(),
|
|
3583
|
+
filename: z2.string().min(1).optional(),
|
|
3584
|
+
title: z2.string().min(1).optional(),
|
|
3585
|
+
visibility: DocumentVisibility.optional(),
|
|
3586
|
+
agentAccess: z2.boolean().optional()
|
|
3587
|
+
}).refine((value) => value.text === void 0 !== (value.fileId === void 0), {
|
|
3588
|
+
message: "provide exactly one of text or fileId"
|
|
3589
|
+
});
|
|
3590
|
+
var MoveDocumentRequest = z2.object({
|
|
3591
|
+
targetBaseId: z2.string().uuid().optional()
|
|
2392
3592
|
});
|
|
2393
3593
|
var DocumentSearchRequest = z2.object({
|
|
2394
3594
|
query: z2.string().min(1),
|
|
@@ -2678,7 +3878,7 @@ function reasoningEffortForMetadata(metadata, fallback) {
|
|
|
2678
3878
|
return value === "none" || value === "minimal" || value === "low" || value === "medium" || value === "high" || value === "xhigh" ? value : fallback;
|
|
2679
3879
|
}
|
|
2680
3880
|
function stableJson(value) {
|
|
2681
|
-
return JSON.stringify(
|
|
3881
|
+
return JSON.stringify(sortJson2(value));
|
|
2682
3882
|
}
|
|
2683
3883
|
function resourceIdentityKey(resource) {
|
|
2684
3884
|
if (resource.kind === "file") {
|
|
@@ -2686,13 +3886,13 @@ function resourceIdentityKey(resource) {
|
|
|
2686
3886
|
}
|
|
2687
3887
|
return `repository:${resource.uri}`;
|
|
2688
3888
|
}
|
|
2689
|
-
function
|
|
3889
|
+
function sortJson2(value) {
|
|
2690
3890
|
if (Array.isArray(value)) {
|
|
2691
|
-
return value.map(
|
|
3891
|
+
return value.map(sortJson2);
|
|
2692
3892
|
}
|
|
2693
3893
|
if (value && typeof value === "object") {
|
|
2694
3894
|
return Object.fromEntries(
|
|
2695
|
-
Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, nested]) => [key,
|
|
3895
|
+
Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, nested]) => [key, sortJson2(nested)])
|
|
2696
3896
|
);
|
|
2697
3897
|
}
|
|
2698
3898
|
return value;
|
|
@@ -2729,6 +3929,35 @@ var SessionGoalPausedReason = z2.enum([
|
|
|
2729
3929
|
"max_auto_continuations",
|
|
2730
3930
|
"limits"
|
|
2731
3931
|
]);
|
|
3932
|
+
var SessionGoalContinuationState = z2.enum([
|
|
3933
|
+
"inactive",
|
|
3934
|
+
"scheduled",
|
|
3935
|
+
"running",
|
|
3936
|
+
"blocked",
|
|
3937
|
+
"invariant_broken"
|
|
3938
|
+
]);
|
|
3939
|
+
var SessionGoalContinuationReason = z2.enum([
|
|
3940
|
+
"goal_inactive",
|
|
3941
|
+
"wake_pending",
|
|
3942
|
+
"continuation_pending",
|
|
3943
|
+
"human_work_pending",
|
|
3944
|
+
"goal_turn_running",
|
|
3945
|
+
"human_turn_running",
|
|
3946
|
+
"workstream_paused",
|
|
3947
|
+
"approval_required",
|
|
3948
|
+
"provider_backpressure",
|
|
3949
|
+
"session_cancelled",
|
|
3950
|
+
"system_work_pending",
|
|
3951
|
+
"missing_obligation"
|
|
3952
|
+
]);
|
|
3953
|
+
var SessionGoalContinuation = z2.object({
|
|
3954
|
+
state: SessionGoalContinuationState,
|
|
3955
|
+
reason: SessionGoalContinuationReason,
|
|
3956
|
+
wakeRevision: z2.number().int().nonnegative(),
|
|
3957
|
+
observedRevision: z2.number().int().nonnegative(),
|
|
3958
|
+
nextAttemptAt: z2.string().datetime({ offset: true }).nullable(),
|
|
3959
|
+
lastError: z2.string().nullable()
|
|
3960
|
+
});
|
|
2732
3961
|
var SessionGoal = z2.object({
|
|
2733
3962
|
id: z2.string().uuid(),
|
|
2734
3963
|
accountId: z2.string().uuid(),
|
|
@@ -2746,6 +3975,9 @@ var SessionGoal = z2.object({
|
|
|
2746
3975
|
noProgressStreak: z2.number().int().nonnegative(),
|
|
2747
3976
|
maxAutoContinuations: z2.number().int().positive().nullable(),
|
|
2748
3977
|
metadata: z2.record(z2.string(), z2.unknown()),
|
|
3978
|
+
// Optional for source compatibility with older clients; the API always
|
|
3979
|
+
// supplies this authoritative continuation projection.
|
|
3980
|
+
continuation: SessionGoalContinuation.optional(),
|
|
2749
3981
|
createdAt: z2.string(),
|
|
2750
3982
|
updatedAt: z2.string()
|
|
2751
3983
|
});
|
|
@@ -2761,6 +3993,17 @@ var UpdateSessionGoalRequest = z2.object({
|
|
|
2761
3993
|
var UpdateSessionRequest = z2.object({
|
|
2762
3994
|
title: z2.string().min(1).max(200)
|
|
2763
3995
|
});
|
|
3996
|
+
var UpdateSessionToolPolicyRequest = z2.union([
|
|
3997
|
+
z2.object({
|
|
3998
|
+
mode: z2.literal("workspace_default"),
|
|
3999
|
+
expectedVersion: z2.number().int().positive()
|
|
4000
|
+
}).strict(),
|
|
4001
|
+
z2.object({
|
|
4002
|
+
mode: z2.literal("explicit").optional(),
|
|
4003
|
+
tools: z2.array(ToolRef).max(64),
|
|
4004
|
+
expectedVersion: z2.number().int().positive()
|
|
4005
|
+
}).strict()
|
|
4006
|
+
]);
|
|
2764
4007
|
var UpdateSessionPinRequest = z2.object({
|
|
2765
4008
|
pinned: z2.boolean(),
|
|
2766
4009
|
expectedVersion: z2.number().int().nonnegative().optional()
|
|
@@ -2834,6 +4077,7 @@ var SessionAuthorizationOperation = z2.enum([
|
|
|
2834
4077
|
"session.human_input.write",
|
|
2835
4078
|
"session.title.write",
|
|
2836
4079
|
"session.mcp.approval_policy.write",
|
|
4080
|
+
"session.tool_policy.write",
|
|
2837
4081
|
"session.goal.read",
|
|
2838
4082
|
"session.goal.write",
|
|
2839
4083
|
"session.child.create"
|
|
@@ -3031,6 +4275,36 @@ var SaveComposerDraftRequest = ComposerDraft.pick({
|
|
|
3031
4275
|
model: true,
|
|
3032
4276
|
reasoningEffort: true
|
|
3033
4277
|
}).extend({ expectedRevision: z2.number().int().nonnegative() });
|
|
4278
|
+
var NewSessionDraftOptions = z2.object({
|
|
4279
|
+
sandboxBackend: SandboxBackend.optional(),
|
|
4280
|
+
targetSandboxId: z2.string().uuid().optional(),
|
|
4281
|
+
workingDir: z2.string().min(1).optional(),
|
|
4282
|
+
variableSetId: z2.string().uuid().optional(),
|
|
4283
|
+
rigId: z2.string().uuid().optional(),
|
|
4284
|
+
goal: GoalSpec.optional(),
|
|
4285
|
+
firstPartyMcpPermissions: z2.array(Permission).optional()
|
|
4286
|
+
});
|
|
4287
|
+
var NewSessionDraft = z2.object({
|
|
4288
|
+
revision: z2.number().int().nonnegative(),
|
|
4289
|
+
text: z2.string(),
|
|
4290
|
+
resources: z2.array(ResourceRef),
|
|
4291
|
+
tools: z2.array(ToolRef),
|
|
4292
|
+
/** False means the workspace-default MCP policy is still inherited. */
|
|
4293
|
+
toolsProvided: z2.boolean().default(false),
|
|
4294
|
+
model: z2.string().min(1),
|
|
4295
|
+
reasoningEffort: ReasoningEffort,
|
|
4296
|
+
options: NewSessionDraftOptions,
|
|
4297
|
+
updatedAt: z2.string().nullable()
|
|
4298
|
+
});
|
|
4299
|
+
var SaveNewSessionDraftRequest = NewSessionDraft.pick({
|
|
4300
|
+
text: true,
|
|
4301
|
+
resources: true,
|
|
4302
|
+
tools: true,
|
|
4303
|
+
toolsProvided: true,
|
|
4304
|
+
model: true,
|
|
4305
|
+
reasoningEffort: true,
|
|
4306
|
+
options: true
|
|
4307
|
+
}).extend({ expectedRevision: z2.number().int().nonnegative() });
|
|
3034
4308
|
var WORKSPACE_CONTROL_REASON_MAX_BYTES = 8 * 1024;
|
|
3035
4309
|
var WORKSPACE_CONTROL_ACTOR_MAX_BYTES = 1024;
|
|
3036
4310
|
var WORKSPACE_CONTROL_EVENT_MAX_BYTES = 16 * 1024;
|
|
@@ -3435,7 +4709,10 @@ var ScheduledTaskAgentConfig = z2.object({
|
|
|
3435
4709
|
model: z2.string().min(1).optional(),
|
|
3436
4710
|
reasoningEffort: ReasoningEffort.optional(),
|
|
3437
4711
|
sandboxBackend: SandboxBackend.optional(),
|
|
3438
|
-
goal: GoalSpec.optional()
|
|
4712
|
+
goal: GoalSpec.optional(),
|
|
4713
|
+
// Durable task override. Scheduled dispatch is trusted to preserve this
|
|
4714
|
+
// snapshot even if the workspace/deployment policy narrows later.
|
|
4715
|
+
maxNestedAgentDepth: NestedAgentDepthValue.optional()
|
|
3439
4716
|
});
|
|
3440
4717
|
var ScheduledTask = z2.object({
|
|
3441
4718
|
id: z2.string().uuid(),
|
|
@@ -3974,6 +5251,10 @@ var Session = z2.object({
|
|
|
3974
5251
|
// Origin of the persisted tool allow-list. Optional for rolling client
|
|
3975
5252
|
// compatibility; current servers emit it and legacy rows map to `legacy`.
|
|
3976
5253
|
toolPolicy: SessionToolPolicy.optional(),
|
|
5254
|
+
// Optimistic-concurrency fence for durable policy mutations. Optional for
|
|
5255
|
+
// older clients/fixtures; current servers always emit the authoritative
|
|
5256
|
+
// value.
|
|
5257
|
+
toolPolicyVersion: z2.number().int().positive().optional(),
|
|
3977
5258
|
// Secret-safe current resolution, computed at an API/read or execution
|
|
3978
5259
|
// boundary from IDs only. Optional because internal DB readers need not load
|
|
3979
5260
|
// the workspace runtime registry.
|
|
@@ -4018,6 +5299,14 @@ var Session = z2.object({
|
|
|
4018
5299
|
// direct API creates and scheduled-task runs. When set, this session's
|
|
4019
5300
|
// terminal-for-now transitions wake the parent.
|
|
4020
5301
|
parentSessionId: z2.string().uuid().nullable(),
|
|
5302
|
+
// Server-authored nested-agent lineage/policy. Root sessions are depth 0;
|
|
5303
|
+
// snapshots are immutable and govern only future descendant creation.
|
|
5304
|
+
rootSessionId: z2.string().uuid(),
|
|
5305
|
+
nestedAgentDepth: NestedAgentDepthValue,
|
|
5306
|
+
maxNestedAgentDepthOverride: NestedAgentDepthValue.nullable(),
|
|
5307
|
+
effectiveMaxNestedAgentDepth: NestedAgentDepthValue,
|
|
5308
|
+
nestedAgentDepthPolicySource: NestedAgentDepthPolicySource,
|
|
5309
|
+
nestedAgentDepthPolicySessionId: z2.string().uuid().nullable(),
|
|
4021
5310
|
// Workspace-scoped CREATE idempotency key the session was created under (the
|
|
4022
5311
|
// dedup target collapsing double-submit/retry races to one session); null
|
|
4023
5312
|
// when the create carried no key.
|
|
@@ -4195,6 +5484,7 @@ var SessionEventType = z2.enum([
|
|
|
4195
5484
|
// PTY session ended (exitCode/reason)
|
|
4196
5485
|
"session.title_set",
|
|
4197
5486
|
"session.mcp.approval_policy.updated",
|
|
5487
|
+
"session.tool_policy.updated",
|
|
4198
5488
|
// Multi-account Codex (P1): the account a session's turn runs on changed
|
|
4199
5489
|
// (manual switch in P1; failover/rotation in P3 reuse the same event). Drives
|
|
4200
5490
|
// the in-session "Running on:" indicator's live flip.
|
|
@@ -4202,6 +5492,10 @@ var SessionEventType = z2.enum([
|
|
|
4202
5492
|
// credential allocator per-turn selection audit. Payload is metadata only: credential row
|
|
4203
5493
|
// id, bounded strategy/reason, and pool counts — never token material.
|
|
4204
5494
|
"codex.credential.selected",
|
|
5495
|
+
// Adaptive fleet shadow decision record. Contains only bounded opaque candidate aliases,
|
|
5496
|
+
// normalized pressure/cache/confidence features, deterministic fingerprints,
|
|
5497
|
+
// the actual-vs-shadow comparison, and no credential/account identity.
|
|
5498
|
+
"codex.fleet.decision",
|
|
4205
5499
|
// credential allocator durable zero-capacity wait lifecycle. Runtime/system events only;
|
|
4206
5500
|
// no synthetic user message is created when capacity returns.
|
|
4207
5501
|
"codex.capacity.waiting",
|
|
@@ -4331,7 +5625,8 @@ var SESSION_EVENT_SEMANTIC_CLASS_TYPES = {
|
|
|
4331
5625
|
"workspace.inference.resumed",
|
|
4332
5626
|
"session.queue.changed",
|
|
4333
5627
|
"session.queue.prompt.cancelled",
|
|
4334
|
-
"session.mcp.approval_policy.updated"
|
|
5628
|
+
"session.mcp.approval_policy.updated",
|
|
5629
|
+
"session.tool_policy.updated"
|
|
4335
5630
|
],
|
|
4336
5631
|
terminal: [
|
|
4337
5632
|
"turn.completed",
|
|
@@ -4577,7 +5872,7 @@ var TerminalPtyOutputDeltaPayload = z2.object({
|
|
|
4577
5872
|
var TerminalPtyExitedPayload = z2.object({
|
|
4578
5873
|
ptyId: z2.string().uuid(),
|
|
4579
5874
|
exitCode: z2.number().int().nullable(),
|
|
4580
|
-
reason: z2.enum(["exit", "killed", "owner_gone", "timeout"])
|
|
5875
|
+
reason: z2.enum(["exit", "killed", "owner_gone", "timeout", "lost"])
|
|
4581
5876
|
});
|
|
4582
5877
|
var FsNodeType = z2.enum(["file", "dir", "symlink", "other"]);
|
|
4583
5878
|
var FsTreeNode = z2.lazy(
|
|
@@ -4930,7 +6225,8 @@ var TerminalExecRequest = z2.object({
|
|
|
4930
6225
|
command: z2.string().min(1),
|
|
4931
6226
|
cwd: z2.string().default(""),
|
|
4932
6227
|
// workspace-relative
|
|
4933
|
-
//
|
|
6228
|
+
// Hard wall-clock bound. A timeout response is returned only after the exact
|
|
6229
|
+
// provider process is physically absent and any retained admission settles.
|
|
4934
6230
|
timeoutMs: z2.number().int().positive().max(12e4).default(3e4),
|
|
4935
6231
|
// Stream the deltas onto A1 as the agent firehose (so other viewers see it),
|
|
4936
6232
|
// in addition to returning the buffered result inline.
|
|
@@ -4939,10 +6235,10 @@ var TerminalExecRequest = z2.object({
|
|
|
4939
6235
|
var TerminalExecResponse = z2.object({
|
|
4940
6236
|
stdout: z2.string(),
|
|
4941
6237
|
stderr: z2.string(),
|
|
4942
|
-
exitCode: z2.number().int()
|
|
4943
|
-
//
|
|
4944
|
-
//
|
|
4945
|
-
running: z2.
|
|
6238
|
+
exitCode: z2.number().int(),
|
|
6239
|
+
// Retained for wire compatibility; synchronous exec never exposes a live
|
|
6240
|
+
// provider process. Interactive work uses the PTY API.
|
|
6241
|
+
running: z2.literal(false),
|
|
4946
6242
|
wallTimeSeconds: z2.number().nonnegative()
|
|
4947
6243
|
});
|
|
4948
6244
|
var PtyOpenRequest = z2.object({
|
|
@@ -5665,6 +6961,14 @@ var CreateSessionRequest = withVariableSetIdAlias({
|
|
|
5665
6961
|
// creation of a brand-new session. Absent means no create-dedup (each call
|
|
5666
6962
|
// is an independent create).
|
|
5667
6963
|
idempotencyKey: z2.string().min(1).max(200).optional(),
|
|
6964
|
+
// The exact actor-private pre-session draft revision represented by this
|
|
6965
|
+
// create. The durable initializer consumes only this revision. A newer draft
|
|
6966
|
+
// written by a sibling tab survives, while every failed pre-initialization
|
|
6967
|
+
// create leaves the submitted draft intact.
|
|
6968
|
+
expectedNewSessionDraftRevision: z2.number().int().nonnegative().optional(),
|
|
6969
|
+
// A child may lower its inherited limit freely; an increase requires
|
|
6970
|
+
// workspace:admin and is checked again at the DB transaction boundary.
|
|
6971
|
+
maxNestedAgentDepth: NestedAgentDepthValue.optional(),
|
|
5668
6972
|
// Permissions the session's first-party MCP token should carry. A top-level
|
|
5669
6973
|
// omission uses the deployment's worker default; a child omission inherits
|
|
5670
6974
|
// the creating session's effective grant. An explicit set is capped at
|
|
@@ -5904,10 +7208,14 @@ var GitHubRepository = z2.object({
|
|
|
5904
7208
|
accountType: z2.string().nullable()
|
|
5905
7209
|
});
|
|
5906
7210
|
var GitHubRepositoryScope = z2.enum(["all", "selected"]);
|
|
7211
|
+
var GitHubBindingStatus = z2.enum(["disabled", "unbound", "bound"]);
|
|
7212
|
+
var GitHubInstallationLifecycle = z2.enum(["active", "suspended", "deleted", "unverified"]);
|
|
5907
7213
|
var GitHubInstallationBinding = z2.object({
|
|
5908
7214
|
installationId: z2.number().int().positive(),
|
|
7215
|
+
githubAccountId: z2.number().int().positive().nullable(),
|
|
5909
7216
|
accountLogin: z2.string().nullable(),
|
|
5910
7217
|
accountType: z2.string().nullable(),
|
|
7218
|
+
lifecycle: GitHubInstallationLifecycle,
|
|
5911
7219
|
repositoryScope: GitHubRepositoryScope,
|
|
5912
7220
|
repositoryCount: z2.number().int().nonnegative(),
|
|
5913
7221
|
createdAt: z2.string(),
|
|
@@ -5915,6 +7223,7 @@ var GitHubInstallationBinding = z2.object({
|
|
|
5915
7223
|
});
|
|
5916
7224
|
var GitHubAppInfo = z2.object({
|
|
5917
7225
|
configured: z2.boolean(),
|
|
7226
|
+
status: GitHubBindingStatus,
|
|
5918
7227
|
appId: z2.string().nullable(),
|
|
5919
7228
|
clientId: z2.string().nullable(),
|
|
5920
7229
|
appSlug: z2.string().nullable(),
|
|
@@ -5969,6 +7278,9 @@ var SessionCapabilities = z2.object({
|
|
|
5969
7278
|
liveness: z2.enum(["cold", "warming", "warm", "draining"]),
|
|
5970
7279
|
// Echoed on viewer heartbeats (the split-brain fence).
|
|
5971
7280
|
leaseEpoch: z2.number().int().nonnegative(),
|
|
7281
|
+
workspaceGeneration: z2.number().int().nonnegative().nullable().default(null),
|
|
7282
|
+
archiveGeneration: z2.number().int().nonnegative().nullable().default(null),
|
|
7283
|
+
archiveComplete: z2.boolean().default(false),
|
|
5972
7284
|
viewerHeartbeatIntervalMs: z2.number().int().positive().default(3e4),
|
|
5973
7285
|
FileSystem: z2.object({
|
|
5974
7286
|
available: z2.boolean(),
|
|
@@ -6052,6 +7364,9 @@ var ViewerHolder = z2.object({
|
|
|
6052
7364
|
liveness: z2.enum(["cold", "warming", "warm", "draining"]),
|
|
6053
7365
|
// The epoch the viewer is fenced on; echoed back on heartbeats.
|
|
6054
7366
|
leaseEpoch: z2.number().int().nonnegative(),
|
|
7367
|
+
workspaceGeneration: z2.number().int().nonnegative().nullable(),
|
|
7368
|
+
archiveGeneration: z2.number().int().nonnegative().nullable(),
|
|
7369
|
+
archiveComplete: z2.boolean(),
|
|
6055
7370
|
viewerHeartbeatIntervalMs: z2.number().int().positive(),
|
|
6056
7371
|
// The desktop pixel tunnel URL the viewer connects to directly; null until
|
|
6057
7372
|
// a viewer grant is minted (gated until then).
|
|
@@ -6266,6 +7581,9 @@ var MachineView = z2.object({
|
|
|
6266
7581
|
state: MachineState,
|
|
6267
7582
|
active: z2.boolean(),
|
|
6268
7583
|
isSessionGroup: z2.boolean(),
|
|
7584
|
+
workspaceGeneration: z2.number().int().nonnegative().nullable(),
|
|
7585
|
+
archiveGeneration: z2.number().int().nonnegative().nullable(),
|
|
7586
|
+
archiveComplete: z2.boolean(),
|
|
6269
7587
|
os: z2.string(),
|
|
6270
7588
|
arch: z2.string(),
|
|
6271
7589
|
hasDisplay: z2.boolean(),
|
|
@@ -6300,7 +7618,10 @@ var SwapActiveSandboxResponse = z2.object({
|
|
|
6300
7618
|
"offline_enrollment",
|
|
6301
7619
|
"unsupported_backend_context",
|
|
6302
7620
|
"transient_establishment",
|
|
6303
|
-
"concurrent_swap"
|
|
7621
|
+
"concurrent_swap",
|
|
7622
|
+
"recovery_in_progress",
|
|
7623
|
+
"recovery_degraded",
|
|
7624
|
+
"recovery_unrecoverable"
|
|
6304
7625
|
]).optional()
|
|
6305
7626
|
});
|
|
6306
7627
|
var MachineMetricsSeriesResponse = z2.object({
|
|
@@ -6568,6 +7889,7 @@ var WorkspaceModelCatalogResponse = /* @__PURE__ */ defineModelContractSchema(
|
|
|
6568
7889
|
);
|
|
6569
7890
|
var OPENGENI_API_CONTRACT_REVISION = "2026-07-turn-instructions-v1";
|
|
6570
7891
|
var OPENGENI_API_CONTRACT_HEADER = "x-opengeni-api-contract";
|
|
7892
|
+
var OPENGENI_CORRELATION_HEADER = "x-opengeni-correlation-id";
|
|
6571
7893
|
var ClientConfig = /* @__PURE__ */ defineModelContractSchema(
|
|
6572
7894
|
() => z2.object({
|
|
6573
7895
|
deploymentRevision: z2.string(),
|
|
@@ -6663,6 +7985,10 @@ export {
|
|
|
6663
7985
|
CAPABILITY_DESCRIPTORS,
|
|
6664
7986
|
CLEARED_RUN_STATE_BLOB,
|
|
6665
7987
|
CLEARED_RUN_STATE_MARKER,
|
|
7988
|
+
CODEX_FLEET_POLICY_MAX_CANDIDATES,
|
|
7989
|
+
CODEX_FLEET_POLICY_MAX_OVERLAYS_PER_CANDIDATE,
|
|
7990
|
+
CODEX_FLEET_POLICY_SCHEMA_VERSION,
|
|
7991
|
+
CODEX_FLEET_POLICY_VERSION,
|
|
6666
7992
|
CapabilityCatalogAuthKind,
|
|
6667
7993
|
CapabilityCatalogItem,
|
|
6668
7994
|
CapabilityCatalogResponse,
|
|
@@ -6703,6 +8029,7 @@ export {
|
|
|
6703
8029
|
CreateDocumentBaseRequest,
|
|
6704
8030
|
CreateFileUploadRequest,
|
|
6705
8031
|
CreateFileUploadResponse,
|
|
8032
|
+
CreateKnowledgeDropRequest,
|
|
6706
8033
|
CreateKnowledgeMemoryRequest,
|
|
6707
8034
|
CreateRigRequest,
|
|
6708
8035
|
CreateScheduledTaskRequest,
|
|
@@ -6714,6 +8041,7 @@ export {
|
|
|
6714
8041
|
CreateWorkspaceEnvironmentRequest,
|
|
6715
8042
|
CreateWorkspaceRequest,
|
|
6716
8043
|
CredentialAuthNeededPayload,
|
|
8044
|
+
DEFAULT_CODEX_FLEET_POLICY_V1,
|
|
6717
8045
|
DEFAULT_FIRST_PARTY_MCP_PERMISSIONS,
|
|
6718
8046
|
DESKTOP_STREAM_PORT,
|
|
6719
8047
|
DelegatedAccessTokenPayload,
|
|
@@ -6733,10 +8061,13 @@ export {
|
|
|
6733
8061
|
DiscoverMcpCapabilitiesResponse,
|
|
6734
8062
|
Document,
|
|
6735
8063
|
DocumentBase,
|
|
8064
|
+
DocumentCuration,
|
|
8065
|
+
DocumentCurationStatus,
|
|
6736
8066
|
DocumentSearchMode,
|
|
6737
8067
|
DocumentSearchRequest,
|
|
6738
8068
|
DocumentSearchResult,
|
|
6739
8069
|
DocumentStatus,
|
|
8070
|
+
DocumentVisibility,
|
|
6740
8071
|
EditSessionQueueItemRequest,
|
|
6741
8072
|
EffectiveControlBlocker,
|
|
6742
8073
|
EffectiveControlResumeOption,
|
|
@@ -6796,7 +8127,9 @@ export {
|
|
|
6796
8127
|
GitFileStatusCode,
|
|
6797
8128
|
GitHubAppInfo,
|
|
6798
8129
|
GitHubAppManifestCreate,
|
|
8130
|
+
GitHubBindingStatus,
|
|
6799
8131
|
GitHubInstallationBinding,
|
|
8132
|
+
GitHubInstallationLifecycle,
|
|
6800
8133
|
GitHubRepositoriesResponse,
|
|
6801
8134
|
GitHubRepository,
|
|
6802
8135
|
GitHubRepositoryScope,
|
|
@@ -6837,6 +8170,7 @@ export {
|
|
|
6837
8170
|
ListConnectionsResponse,
|
|
6838
8171
|
ListEnrollmentsResponse,
|
|
6839
8172
|
ListWorkspaceMembersResponse,
|
|
8173
|
+
MAX_NESTED_AGENT_DEPTH,
|
|
6840
8174
|
MachineKind,
|
|
6841
8175
|
MachineMetricsSeriesResponse,
|
|
6842
8176
|
MachineState,
|
|
@@ -6858,11 +8192,18 @@ export {
|
|
|
6858
8192
|
ModelCredentialSourceV1,
|
|
6859
8193
|
ModelPricingScheduleV1,
|
|
6860
8194
|
ModelPricingV1,
|
|
8195
|
+
MoveDocumentRequest,
|
|
6861
8196
|
MoveSessionQueueItemRequest,
|
|
8197
|
+
NestedAgentDepthAttemptValue,
|
|
8198
|
+
NestedAgentDepthPolicySource,
|
|
8199
|
+
NestedAgentDepthValue,
|
|
8200
|
+
NewSessionDraft,
|
|
8201
|
+
NewSessionDraftOptions,
|
|
6862
8202
|
OAuthStartRequest,
|
|
6863
8203
|
OAuthStartResponse,
|
|
6864
8204
|
OPENGENI_API_CONTRACT_HEADER,
|
|
6865
8205
|
OPENGENI_API_CONTRACT_REVISION,
|
|
8206
|
+
OPENGENI_CORRELATION_HEADER,
|
|
6866
8207
|
OPENGENI_HOST_EXPORT_SCHEMA_REVISION,
|
|
6867
8208
|
PackInstallation,
|
|
6868
8209
|
PackInstallationStatus,
|
|
@@ -6931,6 +8272,7 @@ export {
|
|
|
6931
8272
|
SandboxCommandOutputDeltaPayload,
|
|
6932
8273
|
SandboxOs,
|
|
6933
8274
|
SaveComposerDraftRequest,
|
|
8275
|
+
SaveNewSessionDraftRequest,
|
|
6934
8276
|
ScheduledTask,
|
|
6935
8277
|
ScheduledTaskAgentConfig,
|
|
6936
8278
|
ScheduledTaskOverlapPolicy,
|
|
@@ -6965,6 +8307,9 @@ export {
|
|
|
6965
8307
|
SessionEventSemanticClass,
|
|
6966
8308
|
SessionEventType,
|
|
6967
8309
|
SessionGoal,
|
|
8310
|
+
SessionGoalContinuation,
|
|
8311
|
+
SessionGoalContinuationReason,
|
|
8312
|
+
SessionGoalContinuationState,
|
|
6968
8313
|
SessionGoalCreatedBy,
|
|
6969
8314
|
SessionGoalPausedReason,
|
|
6970
8315
|
SessionGoalStatus,
|
|
@@ -6978,6 +8323,7 @@ export {
|
|
|
6978
8323
|
SessionMcpServerMetadata,
|
|
6979
8324
|
SessionQueueMutationResponse,
|
|
6980
8325
|
SessionQueueSnapshot,
|
|
8326
|
+
SessionSpawnDenial,
|
|
6981
8327
|
SessionStatus,
|
|
6982
8328
|
SessionStructuredCapabilities,
|
|
6983
8329
|
SessionSystemUpdate,
|
|
@@ -7039,6 +8385,7 @@ export {
|
|
|
7039
8385
|
UpdateSessionMcpApprovalPolicyResponse,
|
|
7040
8386
|
UpdateSessionPinRequest,
|
|
7041
8387
|
UpdateSessionRequest,
|
|
8388
|
+
UpdateSessionToolPolicyRequest,
|
|
7042
8389
|
UpdateVariableSetRequest,
|
|
7043
8390
|
UpdateWorkspaceEnvironmentRequest,
|
|
7044
8391
|
UpdateWorkspaceMemberRequest,
|
|
@@ -7090,13 +8437,22 @@ export {
|
|
|
7090
8437
|
boundSessionEvent,
|
|
7091
8438
|
boundSessionEventPayload,
|
|
7092
8439
|
boundWorkspaceControlEvent,
|
|
8440
|
+
canonicalCodexFleetReplayJsonV1,
|
|
7093
8441
|
capabilityCatalogItemIsTrustedForExposure,
|
|
7094
8442
|
compactSessionEventResult,
|
|
8443
|
+
compareCodexFleetCanonicalStringsV1,
|
|
8444
|
+
createCodexFleetReplayRecordV1,
|
|
8445
|
+
createSecretRedactor,
|
|
7095
8446
|
defaultRepositoryMountPath,
|
|
8447
|
+
effectiveCodexFleetCacheStateV1,
|
|
8448
|
+
evaluateCodexFleetDecisionV1,
|
|
7096
8449
|
evaluateWorkspaceModelPolicy,
|
|
7097
8450
|
gitCredentialBindingIdForRepository,
|
|
7098
8451
|
gitCredentialProviderForRepository,
|
|
8452
|
+
identityRedactor,
|
|
7099
8453
|
isClearedRunStateBlob,
|
|
8454
|
+
isCredentialHeaderName,
|
|
8455
|
+
isSensitiveFieldName,
|
|
7100
8456
|
measureSessionEventJson,
|
|
7101
8457
|
mergeResourceRefs,
|
|
7102
8458
|
mergeToolRefs,
|
|
@@ -7104,8 +8460,14 @@ export {
|
|
|
7104
8460
|
normalizeRepositorySubpath,
|
|
7105
8461
|
normalizeResourceMountPath,
|
|
7106
8462
|
prefixedMcpToolName,
|
|
8463
|
+
readCodexFleetReplayRecordV1,
|
|
7107
8464
|
readTurnExecutionPolicyV1,
|
|
7108
8465
|
reasoningEffortForMetadata,
|
|
8466
|
+
redactSensitiveData,
|
|
8467
|
+
redactSensitiveKey,
|
|
8468
|
+
redactSensitiveText,
|
|
8469
|
+
redactSerializedJson,
|
|
8470
|
+
replayCodexFleetDecisionV1,
|
|
7109
8471
|
resolveRetainedOutputRange,
|
|
7110
8472
|
resolveSessionEventTypeFilters,
|
|
7111
8473
|
resolveWorkspaceMemoryEnabled,
|