codex-copilot-dx 0.9.27 → 0.9.28
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/README.md +1 -1
- package/docs/ARCHITECTURE.md +11 -4
- package/docs/README.md +1 -0
- package/docs/REFERENCE.md +41 -0
- package/package.json +1 -1
- package/src/copilot-responses-compat.mjs +72 -43
- package/src/http-transport.mjs +1 -1
- package/src/local-compaction-recovery.mjs +246 -0
- package/src/responses-handler.mjs +10 -1
- package/src/responses-proxy.mjs +5 -3
- package/src/responses-request.mjs +1 -1
package/README.md
CHANGED
|
@@ -57,7 +57,7 @@ The dashboard does not poll in the background; refresh when needed.
|
|
|
57
57
|
CCDX does not claim it can verify the App's internal model cache externally.
|
|
58
58
|
- After a package upgrade, restart the running CCDX adapter. Choosing a model or
|
|
59
59
|
effort on a current adapter takes effect on its next Auto-review request.
|
|
60
|
-
- Request-body bytes, local-history bytes and the model's token window are
|
|
60
|
+
- `0.9.28` adds verified local plaintext recovery after connection-owned compaction rejection; see the reference for strict source and safety limits. Request-body bytes, local-history bytes and the model's token window are
|
|
61
61
|
different limits. Request-context figures are observed metadata, not exact
|
|
62
62
|
live session occupancy. Prompts and images are not retained by that panel.
|
|
63
63
|
- `ccdx cache --clean --history` also clears active response history and can
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -47,10 +47,17 @@ optional boundary. Core inference keeps its existing service port and lifecycle.
|
|
|
47
47
|
|
|
48
48
|
Connection-ownership replay rejection is a provider-owned retry policy. It
|
|
49
49
|
removes only unavailable reasoning once, preserving visible history and tools.
|
|
50
|
-
Opaque compaction cannot be assumed equivalent to remaining plaintext
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
50
|
+
Opaque compaction cannot be assumed equivalent to remaining plaintext. The
|
|
51
|
+
`0.9.28` injects a lazy, asynchronous local recovery capability
|
|
52
|
+
at the HTTP boundary, while preserving the synchronous provider-selector API.
|
|
53
|
+
`local-compaction-recovery.mjs` owns source lookup, readonly decoding and verified
|
|
54
|
+
reassembly; it is not a general transcript service or startup scanner. The
|
|
55
|
+
provider policy decides whether to retry. HTTP and pre-output SSE/JSON failures
|
|
56
|
+
share the single-use policy, byte admission and cancellation boundaries.
|
|
57
|
+
Without a complete verified local source, rejection still returns
|
|
58
|
+
`ccdx_history_rebuild_required`, without modifying stored history. Diagnostic
|
|
59
|
+
metadata cannot reconstruct unavailable encrypted memory. LAN/browser callers
|
|
60
|
+
and referenced/split histories do not gain filesystem recovery access.
|
|
54
61
|
|
|
55
62
|
## Configuration ownership
|
|
56
63
|
|
package/docs/README.md
CHANGED
|
@@ -17,6 +17,7 @@ These reports record a specific release and test environment. Their version,
|
|
|
17
17
|
test counts, timings, live-provider observations, and limitations remain
|
|
18
18
|
historical facts rather than current guarantees.
|
|
19
19
|
|
|
20
|
+
- [0.9.28: verified local plaintext recovery and validation boundaries](RELEASE_0.9.28.md)
|
|
20
21
|
- [0.9.27: Windows certificate setup without Git/OpenSSL](RELEASE_0.9.27.md)
|
|
21
22
|
- [0.9.26: Windows native predictions, safe ownership recovery and dashboard disclosures](RELEASE_0.9.26.md)
|
|
22
23
|
- [Windows prediction validation history](WINDOWS_PREDICTION_PREVIEW.md)
|
package/docs/REFERENCE.md
CHANGED
|
@@ -203,6 +203,47 @@ Responses-only models and compaction use Copilot's Responses transport directly.
|
|
|
203
203
|
|
|
204
204
|
The adapter handles response history, encrypted reasoning state, function/custom tools, images, compaction, cancellation, retries, and usage metadata within the compatibility boundaries below. Routing prefers endpoint metadata from Copilot's live or cached catalog; when metadata is unavailable, a small built-in set identifies known Responses-only GPT models.
|
|
205
205
|
|
|
206
|
+
### Local compaction recovery
|
|
207
|
+
|
|
208
|
+
`0.9.28` adds bounded local recovery; the affected user's real chat still needs
|
|
209
|
+
verification. After the exact decoded HTTP 400 `input item does not belong
|
|
210
|
+
to this connection` rejection, or its HTTP-200/pre-output Responses failure
|
|
211
|
+
equivalent, a request containing encrypted compaction can attempt one verified
|
|
212
|
+
plaintext rebuild. Healthy encrypted histories remain unchanged.
|
|
213
|
+
|
|
214
|
+
The reader is loaded only after this failure. It requires a loopback peer and
|
|
215
|
+
Host, no browser Origin, and LAN mode disabled. It binds a UUID from native
|
|
216
|
+
`thread-id` / `client_metadata.thread_id`, or an exact UUID session/cache key
|
|
217
|
+
when primary metadata is absent. Conflicting primary IDs are rejected. It reads
|
|
218
|
+
only UUID-matching rollout filenames under the service's configured
|
|
219
|
+
`CODEX_HOME/sessions` and `archived_sessions`; it does not search by conversation
|
|
220
|
+
title, similarity, arbitrary request paths or another machine's filesystem.
|
|
221
|
+
|
|
222
|
+
Supported source files are complete JSONL logs and their `.jsonl.zst` variants,
|
|
223
|
+
decoded with Node's built-in Zstandard support. Header identity, the exact
|
|
224
|
+
compaction ciphertext, retained message order and function/custom-tool pairs
|
|
225
|
+
must match. A history-base reference, fork reference, rollback/reset marker,
|
|
226
|
+
missing plaintext tool content, malformed data or multiple matching sources
|
|
227
|
+
stops recovery. Referenced/split histories are not assembled by this recovery;
|
|
228
|
+
the caller must have a complete standalone source prefix.
|
|
229
|
+
|
|
230
|
+
The request replaces the rejected compaction with recorded plaintext before it,
|
|
231
|
+
retains current instructions and post-compaction input, and removes unavailable
|
|
232
|
+
reasoning. It does not decrypt or claim to reproduce hidden encrypted reasoning.
|
|
233
|
+
Normal preparation, image limits and upstream model/context limits still apply.
|
|
234
|
+
The reader has a five-second deadline, a 4,096-entry directory lookup bound and
|
|
235
|
+
a 16-candidate bound. Decoded reads and the rebuilt body are bounded by the
|
|
236
|
+
running adapter's decoded-body limit; history admission reservations cover
|
|
237
|
+
recovery preparation. Requests cannot retry after visible output has begun.
|
|
238
|
+
|
|
239
|
+
Neither the original rollout nor client configuration is rewritten. Recovery
|
|
240
|
+
diagnostics contain type/count/status metadata, not transcript text, ciphertext
|
|
241
|
+
or file paths. If verification fails, `ccdx_history_rebuild_required` includes
|
|
242
|
+
`recovery.local_status`; "not modified" does not imply CCDX has backed up complete
|
|
243
|
+
plaintext. Cross-machine/LAN recovery is intentionally unavailable. A full
|
|
244
|
+
plaintext replay can still exceed the upstream context window; this recovery
|
|
245
|
+
does not silently truncate it or add chunked re-compaction.
|
|
246
|
+
|
|
206
247
|
### Fast and Standard modes
|
|
207
248
|
|
|
208
249
|
Codex can select Standard or Fast without changing CCDX configuration. When the client requests a model with `service_tier: "priority"`, CCDX uses its exact `-fast` model only when the live Copilot catalog advertises that variant as enabled, selectable, OpenAI-owned, and Responses-only. Standard mode continues to use the base model; CCDX does not invent Fast availability when the upstream catalog does not provide it. This retains the established `gpt-5.6-sol` / `gpt-5.6-sol-fast` mapping and applies the same exact-match rule to future models.
|
package/package.json
CHANGED
|
@@ -72,53 +72,82 @@ export function selectCopilotResponseRetry(
|
|
|
72
72
|
return null;
|
|
73
73
|
}
|
|
74
74
|
|
|
75
|
+
// Preserve the synchronous selector contract; disk recovery is an explicitly
|
|
76
|
+
// injected, asynchronous capability at the HTTP boundary, never a blanket retry.
|
|
77
|
+
export async function selectCopilotResponseRetryWithHistory(reqContext, statusCode, errorText, usedPolicies = new Set(), options = {}) {
|
|
78
|
+
try { return selectCopilotResponseRetry(reqContext, statusCode, errorText, usedPolicies); }
|
|
79
|
+
catch (error) {
|
|
80
|
+
if (error.code !== "ccdx_history_rebuild_required" || !options.restorePlaintextHistory) throw error;
|
|
81
|
+
let restored;
|
|
82
|
+
try { restored = await options.restorePlaintextHistory(reqContext, { reserveHistory: options.reserveHistory }); }
|
|
83
|
+
catch (failure) {
|
|
84
|
+
options.assertPrepareActive?.();
|
|
85
|
+
if (options.signal?.aborted) throw options.signal.reason || failure;
|
|
86
|
+
const reason = /^[a-z][a-z_]{1,60}$/.test(failure.code || "") ? failure.code : "local_history_unavailable";
|
|
87
|
+
error.jsonBody.error.recovery.local_status = reason;
|
|
88
|
+
throw error;
|
|
89
|
+
}
|
|
90
|
+
usedPolicies.add("encrypted-connection-rejected");
|
|
91
|
+
return { ...restored, policyId: "encrypted-connection-rejected", usedPolicies,
|
|
92
|
+
warning: "saved compaction rejected; retrying once with verified complete local plaintext history" };
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
75
96
|
export async function openCopilotResponse(reqContext, upstream = copilotResponses, options = {}) {
|
|
76
97
|
const usedPolicies = options.usedRetryPolicies || new Set();
|
|
77
98
|
let payloadPrepared = false;
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
99
|
+
let releaseRecovery;
|
|
100
|
+
try {
|
|
101
|
+
for (let attempt = 0; attempt <= RETRY_POLICIES.length; attempt += 1) {
|
|
102
|
+
let resp;
|
|
103
|
+
try {
|
|
104
|
+
options.assertPrepareActive?.();
|
|
105
|
+
resp = await upstream(reqContext.body, {
|
|
106
|
+
assertActive: options.assertPrepareActive,
|
|
107
|
+
signal: options.signal,
|
|
108
|
+
currentInputStart: reqContext.currentInputStart,
|
|
109
|
+
onUpstreamStart: options.onUpstreamStart,
|
|
110
|
+
payloadPrepared,
|
|
111
|
+
});
|
|
112
|
+
} finally { releaseRecovery?.();releaseRecovery = null; }
|
|
113
|
+
markUpstreamHeaders();
|
|
114
|
+
options.assertPrepareActive?.();
|
|
115
|
+
payloadPrepared = true;
|
|
116
|
+
if (resp.ok) {
|
|
117
|
+
reqContext = finalizeEncryptedHistoryRebase(reqContext);
|
|
118
|
+
return { resp, reqContext, usedRetryPolicies: usedPolicies };
|
|
119
|
+
}
|
|
94
120
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
121
|
+
const errorText = await readBoundedResponseText(resp, {
|
|
122
|
+
maxBytes: MAX_UPSTREAM_ERROR_BODY_BYTES,
|
|
123
|
+
label: "Copilot Responses error body",
|
|
124
|
+
});
|
|
125
|
+
options.assertPrepareActive?.();
|
|
126
|
+
let retry;
|
|
127
|
+
try { retry = await selectCopilotResponseRetryWithHistory(reqContext, resp.status, errorText, usedPolicies, options); }
|
|
128
|
+
catch (error) {
|
|
129
|
+
if (error.code === "ccdx_history_rebuild_required") {
|
|
130
|
+
const details = responseFailureDetails({ error: error.jsonBody.error }, "upstream.http_error", {
|
|
131
|
+
model: reqContext.body.model, headers: resp.headers, retrySkipped: error.code });
|
|
132
|
+
error.jsonBody.error.upstream_request_id = details.upstream_request_id;
|
|
133
|
+
options.responseFailures?.record?.({ ...details, recovery: error.jsonBody.error.recovery });
|
|
134
|
+
}
|
|
135
|
+
throw error;
|
|
108
136
|
}
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
137
|
+
releaseRecovery = retry?.releasePreparation;
|
|
138
|
+
if (retry?.policyId === "encrypted-connection-rejected") {
|
|
139
|
+
options.responseFailures?.record?.({ ...responseFailureDetails(JSON.parse(errorText), "upstream.http_error", {
|
|
140
|
+
model: reqContext.body.model, headers: resp.headers, retried: true, retryPolicy: retry.policyId }),
|
|
141
|
+
recovery: retry.recovery });
|
|
142
|
+
}
|
|
143
|
+
if (retry) {
|
|
144
|
+
reqContext = retry.reqContext;
|
|
145
|
+
if (retry.recovery?.source === "local_codex_rollout") payloadPrepared = false;
|
|
146
|
+
console.warn(status("warn", retry.warning));
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
return { resp, reqContext, errorText, usedRetryPolicies: usedPolicies };
|
|
120
150
|
}
|
|
121
|
-
|
|
122
|
-
}
|
|
123
|
-
throw httpError("Responses compatibility retry limit exceeded", 502);
|
|
151
|
+
throw httpError("Responses compatibility retry limit exceeded", 502);
|
|
152
|
+
} finally { releaseRecovery?.(); }
|
|
124
153
|
}
|
package/src/http-transport.mjs
CHANGED
|
@@ -19,7 +19,7 @@ const zstdDecompressAsync = zlib.zstdDecompress ? promisify(zlib.zstdDecompress)
|
|
|
19
19
|
|
|
20
20
|
const HTTP_RUNTIME_CONFIG = loadRuntimeConfig();
|
|
21
21
|
const MAX_BODY_BYTES = HTTP_RUNTIME_CONFIG.maxBodyBytes;
|
|
22
|
-
const MAX_DECODED_BODY_BYTES = decodedBodyLimitPreference().bytes;
|
|
22
|
+
export const MAX_DECODED_BODY_BYTES = decodedBodyLimitPreference().bytes;
|
|
23
23
|
|
|
24
24
|
export const MAX_UPSTREAM_ERROR_BODY_BYTES = 1024 * 1024;
|
|
25
25
|
export const MAX_UPSTREAM_MODEL_CATALOG_BYTES = 8 * 1024 * 1024;
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { createZstdDecompress } from "node:zlib";
|
|
6
|
+
import { codexPaths } from "./codex-paths.mjs";
|
|
7
|
+
import { isLoopbackAddress, isLoopbackHostHeader, isLanAllowed } from "./security.mjs";
|
|
8
|
+
import { decodedBodyLimitPreference } from "./user-settings.mjs";
|
|
9
|
+
import { isResponsesToolOutputItem, readResponsesToolOutputParts } from "./responses-content.mjs";
|
|
10
|
+
import { prepareResponsesRequest } from "./responses-request.mjs";
|
|
11
|
+
|
|
12
|
+
const UUID = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
|
|
13
|
+
const CALLS = new Map([["function_call", "function_call_output"], ["custom_tool_call", "custom_tool_call_output"]]);
|
|
14
|
+
|
|
15
|
+
function unavailable(code) {
|
|
16
|
+
return Object.assign(new Error("Verified local plaintext history is unavailable"), { code });
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function threadId(request, body) {
|
|
20
|
+
const metadata = body?.client_metadata;
|
|
21
|
+
const primary = [request.headers?.["thread-id"], request.headers?.["x-codex-thread-id"], metadata?.thread_id];
|
|
22
|
+
const values = primary.filter(value => value !== undefined);
|
|
23
|
+
if (!values.length) values.push(metadata?.session_id ?? request.headers?.["session-id"] ?? body?.prompt_cache_key);
|
|
24
|
+
if (values.some(value => typeof value !== "string" || !UUID.test(value))) throw unavailable("thread_binding_missing");
|
|
25
|
+
const ids = new Set(values.map(value => value.toLowerCase()));
|
|
26
|
+
if (ids.size !== 1) throw unavailable("thread_binding_conflict");
|
|
27
|
+
return [...ids][0];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function opaque(value) {
|
|
31
|
+
if (Array.isArray(value)) return value.some(opaque);
|
|
32
|
+
if (!value || typeof value !== "object") return false;
|
|
33
|
+
return Object.hasOwn(value, "encrypted_content") || value.type === "encrypted_content" || Object.values(value).some(opaque);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function plaintext(item) {
|
|
37
|
+
if (!item || typeof item !== "object" || typeof item.type !== "string") throw unavailable("unsupported_rollout_item");
|
|
38
|
+
if (["reasoning", "compaction"].includes(item.type)) return null;
|
|
39
|
+
const out = structuredClone(item);
|
|
40
|
+
for (const key of Object.keys(out)) if (key === "id" || key.startsWith("internal_")) delete out[key];
|
|
41
|
+
// This field is replay metadata, not a replacement for a visible item. Never
|
|
42
|
+
// omit opaque content parts or invent plaintext for an encrypted tool result.
|
|
43
|
+
if ((out.type === "message" && out.content?.length) || (isResponsesToolOutputItem(out) && out.output !== undefined)) {
|
|
44
|
+
delete out.encrypted_content;
|
|
45
|
+
}
|
|
46
|
+
if (opaque(out) || (isResponsesToolOutputItem(out) && opaque(readResponsesToolOutputParts(out)?.parts))) {
|
|
47
|
+
throw unavailable("plaintext_content_missing");
|
|
48
|
+
}
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function fingerprint(item) {
|
|
53
|
+
const normalized = { ...item };
|
|
54
|
+
delete normalized.id;delete normalized.status;
|
|
55
|
+
if (item.type === "message" && Array.isArray(item.content)) normalized.content = item.content.map(part => {
|
|
56
|
+
if (!["input_text", "output_text"].includes(part?.type)) return part;
|
|
57
|
+
const text = { ...part };delete text.annotations;return text;
|
|
58
|
+
});
|
|
59
|
+
return createHash("sha256").update(JSON.stringify(normalized, (_key, value) => {
|
|
60
|
+
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
61
|
+
return Object.fromEntries(Object.keys(value).sort().map(name => [name, value[name]]));
|
|
62
|
+
}
|
|
63
|
+
return value;
|
|
64
|
+
})).digest("hex");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function candidateFiles(directory, id, check) {
|
|
68
|
+
const found = [];
|
|
69
|
+
let entries = 0;
|
|
70
|
+
async function walk(parent, depth) {
|
|
71
|
+
check();
|
|
72
|
+
const stat = await fs.lstat(parent);
|
|
73
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw unavailable("unsafe_rollout_path");
|
|
74
|
+
const iterator = await fs.opendir(parent);
|
|
75
|
+
for await (const entry of iterator) {
|
|
76
|
+
check();
|
|
77
|
+
if (++entries > 4096) throw unavailable("rollout_lookup_limit");
|
|
78
|
+
const file = path.join(parent, entry.name);
|
|
79
|
+
if (entry.isDirectory() && depth < 3) await walk(file, depth + 1);
|
|
80
|
+
else if (entry.isFile() && /^rollout-.*\.jsonl(?:\.zst)?$/.test(entry.name) && entry.name.toLowerCase().includes(id)) {
|
|
81
|
+
if (found.length >= 16) throw unavailable("rollout_lookup_limit");
|
|
82
|
+
found.push(file);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
for (const name of ["sessions", "archived_sessions"]) {
|
|
87
|
+
try { await walk(path.join(directory, name), 0); }
|
|
88
|
+
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
89
|
+
}
|
|
90
|
+
return found;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function readPrefix(file, directory, id, ciphertext, budget, check, signal) {
|
|
94
|
+
const real = await fs.realpath(file);
|
|
95
|
+
if (!real.startsWith(directory + path.sep)) throw unavailable("unsafe_rollout_path");
|
|
96
|
+
const before = await fs.lstat(file);
|
|
97
|
+
if (!before.isFile() || before.isSymbolicLink()) throw unavailable("unsafe_rollout_path");
|
|
98
|
+
if (!before.size) throw unavailable("incomplete_rollout");
|
|
99
|
+
const handle = await fs.open(file, constants.O_RDONLY | (process.platform === "win32" ? 0 : constants.O_NOFOLLOW || 0));
|
|
100
|
+
let stream, raw;
|
|
101
|
+
try {
|
|
102
|
+
const stat = await handle.stat();
|
|
103
|
+
// Older Windows libuv reports the device number differently for lstat and
|
|
104
|
+
// fstat. The validated path, file ID and snapshot size remain mandatory.
|
|
105
|
+
if (!stat.isFile() || stat.ino !== before.ino || stat.size !== before.size
|
|
106
|
+
|| (process.platform !== "win32" && stat.dev !== before.dev)) throw unavailable("rollout_changed");
|
|
107
|
+
raw = handle.createReadStream({ autoClose: false, end: stat.size - 1, highWaterMark: 64 * 1024, signal });
|
|
108
|
+
stream = file.endsWith(".zst") ? raw.pipe(createZstdDecompress()) : raw;
|
|
109
|
+
if (stream !== raw) raw.on("error", error => stream.destroy(error));
|
|
110
|
+
const items = [];
|
|
111
|
+
let metadata = false, matched = false, parts = [], length = 0, bytesRead = 0;
|
|
112
|
+
const record = bytes => {
|
|
113
|
+
check();
|
|
114
|
+
const line = bytes.toString("utf8").replace(/^\uFEFF/, "").trim();
|
|
115
|
+
if (!line) return;
|
|
116
|
+
let row;
|
|
117
|
+
try { row = JSON.parse(line); } catch { throw unavailable("invalid_rollout"); }
|
|
118
|
+
const value = row.payload;
|
|
119
|
+
if (!metadata) {
|
|
120
|
+
if (row.type !== "session_meta" || value?.id?.toLowerCase() !== id) throw unavailable("rollout_identity_mismatch");
|
|
121
|
+
if (value.history_base || value.forked_from_id || (row.ordinal !== undefined && row.ordinal !== 0)
|
|
122
|
+
|| (value.history_mode && !["full", "paginated"].includes(value.history_mode))) throw unavailable("incomplete_rollout");
|
|
123
|
+
metadata = true;return;
|
|
124
|
+
}
|
|
125
|
+
if (row.type === "session_meta" || (row.type === "event_msg" && /rollback|rolled_back|rewind|history_reset|context_reset/.test(value?.type || ""))) {
|
|
126
|
+
throw unavailable("unsupported_history_change");
|
|
127
|
+
}
|
|
128
|
+
if (row.type === "compacted" || row.type === "response_item") {
|
|
129
|
+
const candidates = row.type === "compacted" ? value?.replacement_history : [value];
|
|
130
|
+
if (Array.isArray(candidates) && candidates.some(item => item?.type === "compaction" && item.encrypted_content === ciphertext)) {
|
|
131
|
+
matched = true;return;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (row.type === "response_item") {
|
|
135
|
+
const item = plaintext(value);
|
|
136
|
+
if (item) items.push(item);
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
for await (const chunk of stream) {
|
|
140
|
+
check();budget.remaining -= chunk.length;bytesRead += chunk.length;
|
|
141
|
+
if (budget.remaining < 0) throw unavailable("rollout_read_limit");
|
|
142
|
+
let start = 0;
|
|
143
|
+
while (start < chunk.length) {
|
|
144
|
+
const end = chunk.indexOf(10, start);
|
|
145
|
+
const part = chunk.subarray(start, end < 0 ? chunk.length : end);
|
|
146
|
+
parts.push(part);length += part.length;
|
|
147
|
+
if (end < 0) break;
|
|
148
|
+
record(Buffer.concat(parts, length));parts = [];length = 0;
|
|
149
|
+
if (matched) return { items, bytes: bytesRead };
|
|
150
|
+
start = end + 1;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
if (length) record(Buffer.concat(parts, length));
|
|
154
|
+
return matched ? { items, bytes: bytesRead } : null;
|
|
155
|
+
} finally {
|
|
156
|
+
stream?.destroy();raw?.destroy();await handle.close();
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function joinHistory(source, input, compactionIndex, check) {
|
|
161
|
+
if (!source.length || !source.some(item => item.type === "message" && item.role === "user")) throw unavailable("incomplete_rollout");
|
|
162
|
+
const signatures = source.map(fingerprint);
|
|
163
|
+
let cursor = 0;
|
|
164
|
+
const instructions = [];
|
|
165
|
+
for (const original of input.slice(0, compactionIndex)) {
|
|
166
|
+
check();
|
|
167
|
+
const item = plaintext(original);
|
|
168
|
+
if (!item) continue;
|
|
169
|
+
const match = signatures.indexOf(fingerprint(item), cursor);
|
|
170
|
+
if (match >= 0) cursor = match + 1;
|
|
171
|
+
else if (item.type === "message" && ["system", "developer"].includes(item.role)) instructions.push(item);
|
|
172
|
+
else throw unavailable("retained_prefix_mismatch");
|
|
173
|
+
}
|
|
174
|
+
const suffix = input.slice(compactionIndex + 1).map(plaintext).filter(Boolean);
|
|
175
|
+
const items = [...source, ...instructions, ...suffix];
|
|
176
|
+
const calls = new Map();
|
|
177
|
+
for (const item of items) {
|
|
178
|
+
check();
|
|
179
|
+
if (CALLS.has(item.type)) {
|
|
180
|
+
if (!item.call_id || calls.has(item.call_id)) throw unavailable("invalid_tool_pairs");
|
|
181
|
+
calls.set(item.call_id, { type: CALLS.get(item.type), completed: false });
|
|
182
|
+
} else if ([...CALLS.values()].includes(item.type)) {
|
|
183
|
+
const call = calls.get(item.call_id);
|
|
184
|
+
if (!call || call.type !== item.type || call.completed) throw unavailable("invalid_tool_pairs");
|
|
185
|
+
call.completed = true;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
if ([...calls.values()].some(call => !call.completed)) throw unavailable("invalid_tool_pairs");
|
|
189
|
+
return { items, currentInputStart: source.length + instructions.length };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Loaded only after a confirmed provider ownership rejection, never on startup
|
|
193
|
+
// or healthy requests. It cannot serve remote/browser callers or mutate logs.
|
|
194
|
+
export async function recoverLocalCompaction(reqContext, { request, env = process.env,
|
|
195
|
+
signal, assertActive, reserveHistory, maxBytes, timeoutMs = 5000 } = {}) {
|
|
196
|
+
const started = Date.now();
|
|
197
|
+
const check = () => {
|
|
198
|
+
assertActive?.();
|
|
199
|
+
if (signal?.aborted) throw signal.reason || new DOMException("Aborted", "AbortError");
|
|
200
|
+
if (Date.now() - started > timeoutMs) throw unavailable("rollout_read_timeout");
|
|
201
|
+
};
|
|
202
|
+
check();
|
|
203
|
+
if (isLanAllowed(env) || !isLoopbackAddress(request?.socket?.remoteAddress)
|
|
204
|
+
|| !isLoopbackHostHeader(request?.headers?.host) || request?.headers?.origin !== undefined) {
|
|
205
|
+
throw unavailable("local_request_required");
|
|
206
|
+
}
|
|
207
|
+
const id = threadId(request, reqContext.body);
|
|
208
|
+
const input = reqContext.body?.input;
|
|
209
|
+
const compactions = Array.isArray(input) ? input.filter(item => item?.type === "compaction" && item.encrypted_content) : [];
|
|
210
|
+
if (compactions.length !== 1) throw unavailable("multiple_compactions");
|
|
211
|
+
if (typeof compactions[0].encrypted_content !== "string") throw unavailable("invalid_compaction");
|
|
212
|
+
const limit = maxBytes ?? decodedBodyLimitPreference({ env }).bytes;
|
|
213
|
+
let release, transferred = false;
|
|
214
|
+
try {
|
|
215
|
+
release = await reserveHistory?.(limit, { signal });
|
|
216
|
+
check();
|
|
217
|
+
const directory = await fs.realpath(codexPaths({ env }).directory);
|
|
218
|
+
const files = await candidateFiles(directory, id, check);
|
|
219
|
+
const budget = { remaining: limit };
|
|
220
|
+
let source;
|
|
221
|
+
for (const file of files) {
|
|
222
|
+
check();
|
|
223
|
+
const candidate = await readPrefix(file, directory, id, compactions[0].encrypted_content, budget, check, signal);
|
|
224
|
+
if (!candidate) continue;
|
|
225
|
+
if (source) throw unavailable("ambiguous_rollout");
|
|
226
|
+
source = candidate;
|
|
227
|
+
}
|
|
228
|
+
if (!source) throw unavailable("matching_rollout_missing");
|
|
229
|
+
const restored = joinHistory(source.items, input, input.indexOf(compactions[0]), check);
|
|
230
|
+
const body = { ...reqContext.body, input: restored.items };
|
|
231
|
+
delete body.previous_response_id;
|
|
232
|
+
const bodyBytes = Buffer.byteLength(JSON.stringify(body));
|
|
233
|
+
if (bodyBytes > limit) throw unavailable("restored_payload_limit");
|
|
234
|
+
release?.resize?.(bodyBytes);
|
|
235
|
+
const currentItems = new Set(body.input.slice(restored.currentInputStart));
|
|
236
|
+
const prepared = prepareResponsesRequest(body, { mutate: true, copilotBoundary: false, assertActive: check });
|
|
237
|
+
const currentInputStart = prepared.body.input.findIndex(item => currentItems.has(item));
|
|
238
|
+
prepared.currentInputStart = currentInputStart < 0 ? prepared.body.input.length : currentInputStart;
|
|
239
|
+
prepared.surface = reqContext.surface;
|
|
240
|
+
prepared.routePlan = reqContext.routePlan;
|
|
241
|
+
transferred = true;
|
|
242
|
+
return { reqContext: prepared, releasePreparation: release, recovery: { source: "local_codex_rollout", restored_items: restored.items.length,
|
|
243
|
+
compaction_items_removed: 1, reasoning_items_removed: input.filter(item => item?.type === "reasoning").length,
|
|
244
|
+
source_bytes: source.bytes } };
|
|
245
|
+
} finally { if (!transferred) release?.(); }
|
|
246
|
+
}
|
|
@@ -3,6 +3,7 @@ import { applyCopilotResponsesRequestPolicies } from "./copilot-responses-policy
|
|
|
3
3
|
import {
|
|
4
4
|
createRequestAbort,
|
|
5
5
|
logRequestFailure,
|
|
6
|
+
MAX_DECODED_BODY_BYTES,
|
|
6
7
|
MAX_UPSTREAM_CHAT_SUCCESS_BODY_BYTES,
|
|
7
8
|
MAX_UPSTREAM_ERROR_BODY_BYTES,
|
|
8
9
|
readJsonBody,
|
|
@@ -189,7 +190,7 @@ export function createResponsesHandler(options) {
|
|
|
189
190
|
}
|
|
190
191
|
}
|
|
191
192
|
assertPrepareActive();
|
|
192
|
-
return { historySnapshot: retrySnapshot, release };
|
|
193
|
+
return { historySnapshot: retrySnapshot, reserveHistory: releaseRetryRequest.reserveResponseHistory, release };
|
|
193
194
|
} catch (error) {
|
|
194
195
|
release();
|
|
195
196
|
throw error;
|
|
@@ -308,6 +309,12 @@ export function createResponsesHandler(options) {
|
|
|
308
309
|
if (prepared.historyParentId === null) releaseHistorySnapshot();
|
|
309
310
|
applyCopilotResponsesRequestPolicies(prepared.body);
|
|
310
311
|
if (routePlan.protocol === "openai-responses") {
|
|
312
|
+
const restorePlaintextHistory = async (context, { reserveHistory } = {}) => {
|
|
313
|
+
assertPrepareActive();
|
|
314
|
+
const { recoverLocalCompaction } = await import("./local-compaction-recovery.mjs");
|
|
315
|
+
return recoverLocalCompaction(context, { request: req, env: openAIModelEnv,
|
|
316
|
+
signal: abort.signal, assertActive: assertPrepareActive, reserveHistory, maxBytes: MAX_DECODED_BODY_BYTES });
|
|
317
|
+
};
|
|
311
318
|
const result = await proxyCopilotResponses(prepared, req, res, responsesFn, {
|
|
312
319
|
acquireRetryPreparation,
|
|
313
320
|
assertPrepareActive,
|
|
@@ -317,6 +324,8 @@ export function createResponsesHandler(options) {
|
|
|
317
324
|
onStreamStart: startStream,
|
|
318
325
|
releaseRequest: releaseUpstreamPayload,
|
|
319
326
|
responseFailures,
|
|
327
|
+
restorePlaintextHistory,
|
|
328
|
+
reserveHistory: releaseRequest.reserveResponseHistory,
|
|
320
329
|
streamIdleTimeoutMs,
|
|
321
330
|
keepaliveIntervalMs,
|
|
322
331
|
});
|
package/src/responses-proxy.mjs
CHANGED
|
@@ -11,7 +11,7 @@ import { httpError } from "./http-errors.mjs";
|
|
|
11
11
|
import {
|
|
12
12
|
hasCopilotResponseRetryPolicy,
|
|
13
13
|
openCopilotResponse,
|
|
14
|
-
|
|
14
|
+
selectCopilotResponseRetryWithHistory,
|
|
15
15
|
} from "./copilot-responses-compat.mjs";
|
|
16
16
|
import {
|
|
17
17
|
dropMaterializedResponseHistory,
|
|
@@ -345,11 +345,13 @@ async function selectStreamFailureRetry(reqContext, failure, usedRetryPolicies,
|
|
|
345
345
|
assertActive: options.assertPrepareActive,
|
|
346
346
|
historySnapshot: preparation?.historySnapshot,
|
|
347
347
|
});
|
|
348
|
-
const retry =
|
|
348
|
+
const retry = await selectCopilotResponseRetryWithHistory(restored, 400, errorText, usedRetryPolicies, {
|
|
349
|
+
...options, reserveHistory: preparation?.reserveHistory || options.reserveHistory,
|
|
350
|
+
});
|
|
349
351
|
options.assertPrepareActive?.();
|
|
350
352
|
keepReservation = Boolean(retry);
|
|
351
353
|
return {
|
|
352
|
-
retry: retry ? { ...retry, releasePreparation: preparation?.release } : null,
|
|
354
|
+
retry: retry ? { ...retry, releasePreparation: () => { retry.releasePreparation?.();preparation?.release(); } } : null,
|
|
353
355
|
retrySkipped: null,
|
|
354
356
|
};
|
|
355
357
|
} catch (error) {
|
|
@@ -200,7 +200,7 @@ export function sanitizeConnectionOwnedReasoningRequest(reqContext) {
|
|
|
200
200
|
const compactions = input.filter(item => item?.type === "compaction" && item.encrypted_content);
|
|
201
201
|
const reasoning = input.filter(item => item?.type === "reasoning" && item.encrypted_content);
|
|
202
202
|
if (compactions.length) {
|
|
203
|
-
const message = "
|
|
203
|
+
const message = "The request contains encrypted compaction and upstream rejected saved state. Verified local recovery was unavailable; restore the full plaintext conversation history before retrying. CCDX has not modified the original history.";
|
|
204
204
|
throw Object.assign(new Error(message), { statusCode: 400, code: "ccdx_history_rebuild_required",
|
|
205
205
|
jsonBody: { error: { type: "invalid_request_error", code: "ccdx_history_rebuild_required", message,
|
|
206
206
|
recoverable: true, recovery: { action: "restore_plaintext_history", compaction_items: compactions.length, reasoning_items: reasoning.length } } } });
|