codex-copilot-dx 1.3.17 → 1.3.18
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/docs/ARCHITECTURE.md +8 -0
- package/docs/REFERENCE.md +8 -0
- package/package.json +1 -1
- package/src/atomic-file.mjs +42 -0
- package/src/bounded-file.mjs +16 -0
- package/src/claude-gateway.mjs +17 -4
- package/src/codex-image-host.mjs +124 -31
- package/src/connection-runtime.mjs +4 -3
- package/src/conversation-source-guard.mjs +32 -28
- package/src/lock.mjs +6 -6
- package/src/messages-history-transfer.mjs +34 -27
- package/src/native-images.mjs +9 -1
- package/src/providers/api.mjs +6 -3
- package/src/providers/m365-conversation-accounts.mjs +29 -16
- package/src/providers/m365.mjs +2 -2
- package/src/responses-byte-budget.mjs +2 -1
- package/src/responses-handler.mjs +4 -2
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -1116,3 +1116,11 @@ Usage presentation maps configured api_ identifiers to current provider labels a
|
|
|
1116
1116
|
`image-control.mjs` owns explicit check/repair/open operations for WebUI and terminal commands, reusing client configuration, host preparation and the existing prediction-aware launcher. Repair cannot kill an App or start another service. `image-host-state.mjs` retains bounded, process-local host evidence; the stdio bridge reports initialization and successful new-thread registration through the protected same-origin settings channel without blocking model traffic. Reporter work is bounded and aborted when the original CLI exits. Runtime evidence never contains prompts, images, paths or raw chat identifiers and cannot establish registration in unobserved chats. Manual loopback checks echo a nonce and explicitly identify their Node-only scope.
|
|
1117
1117
|
|
|
1118
1118
|
The existing salted session observation is projected into request metadata. Active requests can reference the previous retained request from the same anonymous session, application and provider; this does not change request routing, history or tool caches. Chat endpoint recognition accepts both `/chat/completions` and `/v1/chat/completions`. Bare JSON error lines in a Messages event stream terminate with an explicit protocol diagnostic rather than waiting for message_stop; normal SSE frames retain their bytes.
|
|
1119
|
+
|
|
1120
|
+
## Boundary reliability (1.3.18)
|
|
1121
|
+
|
|
1122
|
+
Native image failures cancel the vendor response and project safe JSON; API Responses compatibility consumes the existing sanitized error once and retains its metadata. Image history collection records whether the current container appended references instead of rescanning previous containers.
|
|
1123
|
+
|
|
1124
|
+
The stdio host uses a paused-source line pump only while a destination is blocked or a frame requires asynchronous work. Passthrough stays synchronous. Both directions serialize destination writes; output batching is bounded by the destination high-water mark plus one complete frame. Child close, input cancellation and stdout drain are coordinated before removing listeners. Host-tool registration, image return items, account/approval traffic and App launch ownership are unchanged.
|
|
1125
|
+
|
|
1126
|
+
`bounded-file.mjs` and `atomic-file.mjs` provide asynchronous bounded reads and durable single/paired writes for request-path state. Other synchronous configuration callers retain their APIs. Conversation admission and company-account guards use abortable asynchronous lock waiting with their prior timeout/stale policy. Messages transfer plans reserve in-process ownership while committing; primary and marker writes retain rollback behavior. JSON/SSE delivery awaits the applicable commit, and settled source checks keep a synchronous cached path. No new cache, file format or provider-selection policy is introduced.
|
package/docs/REFERENCE.md
CHANGED
|
@@ -578,6 +578,12 @@ unknown candidate-visibility value. A successful recovery only means the bridge
|
|
|
578
578
|
was recreated on the original address, not that gray text appeared.
|
|
579
579
|
|
|
580
580
|
|
|
581
|
+
## Error delivery and conversation commits
|
|
582
|
+
|
|
583
|
+
Image upstream HTTP errors return safe JSON with a `ccdx_images_http_<status>` code, the original status and allowlisted response metadata. Vendor error bodies are cancelled rather than forwarded. Custom API Responses reuse the provider's already-sanitized JSON and validated Retry-After in both streaming and non-streaming requests; these changes do not introduce retries.
|
|
584
|
+
|
|
585
|
+
Conversation-source admission and Messages checkpoint commits wait asynchronously for the existing cross-process locks. Cancellation ends lock waits. Checkpoint writes retain the primary/marker ordering and rollback behavior; the gateway awaits a successful commit before forwarding corresponding usable JSON or SSE output. Cached source checks keep their synchronous fast path. CLI configuration writers retain their existing synchronous behavior.
|
|
586
|
+
|
|
581
587
|
## Native image generation
|
|
582
588
|
|
|
583
589
|
The native image host uses the current CCDX address for separate Images API requests. CCDX serves `POST /v1/images/generations` and `POST /v1/images/edits`, reuses the existing GitHub Copilot authentication, and maps the native client’s `gpt-image-2` request to the selected available GHC image model. GPT Image 2.5 Flare is the default when advertised. The `X-CCDX-Image-Model` response header identifies the actual model. Image usage counts toward the GitHub account’s image credits; organization model policies still apply. The image model does not replace the selected conversation model.
|
|
@@ -586,6 +592,8 @@ On macOS with Codex 0.166 or later, CCDX launches the unchanged Codex CLI throug
|
|
|
586
592
|
|
|
587
593
|
The Web UI image panel and terminal `check`, `repair`, and `open` controls share the service's image controller. `check` verifies the Node loopback response with a fresh nonce and checks the launcher and runtime evidence; it does not prove the Codex App's proxy route. `repair` prepares owned launch files and client configuration without opening or closing the App. `open` preserves the established prediction route and opens Codex only when it is closed. A running App produces `needs_app_relaunch`; finish tasks and quit it yourself, then use `open` and a new chat. Disabled image settings and custom launch routes are preserved.
|
|
588
594
|
|
|
595
|
+
The stdio host pauses each input source when its destination is blocked or an asynchronous frame operation is pending. Ordinary frames retain their synchronous path and original wire text; output batching follows the destination high-water mark. Shutdown waits for child close and queued stdout delivery, including a final frame without a newline. No arbitrary new protocol-frame byte limit is imposed.
|
|
596
|
+
|
|
589
597
|
The runtime separately reports host initialization, accepted new-chat registration and image-call outcomes. Reports contain only host PID, anonymous host/chat identifiers, event type and time, remain in bounded process memory, and are not an automatic image-generation probe. Registration evidence applies to observed chats, not every existing conversation. Dead host processes are unconfirmed. The TUI exposes the repair command; terminal image status includes the same host state. Request details show anonymous session correlation and the previous retained request's outcome when supplied session metadata allows it; missing identity stays unassigned.
|
|
590
598
|
|
|
591
599
|
The adapter uses `CODEX_CLI_PATH` only for the App launch requested by CCDX. It does not modify App binaries, ChatGPT authentication files, credential storage mode or account-plan declarations. All other app-server traffic, including Apps and approval requests, passes through to the original CLI. Existing custom CLI routes and unowned launcher files are preserved. A running App retains its existing launch environment. If its image tool is missing, fully quit the App, start Codex through CCDX, and use a new chat. CCDX does not forcibly restart the App. Native built-in image tool availability still depends on the installed client and thread. A successful direct API request alone does not establish visible App behavior.
|
package/package.json
CHANGED
package/src/atomic-file.mjs
CHANGED
|
@@ -135,3 +135,45 @@ export function atomicWriteFileIfChangedSync(filePath, data, options = {}) {
|
|
|
135
135
|
atomicWriteFileSync(filePath, data, options);
|
|
136
136
|
return true;
|
|
137
137
|
}
|
|
138
|
+
|
|
139
|
+
export async function atomicWriteFile(filePath, data, { mode = 0o600, preserveMode = true } = {}) {
|
|
140
|
+
const io = fs.promises, directory = path.dirname(filePath);
|
|
141
|
+
let finalMode = mode;
|
|
142
|
+
if (preserveMode) { try { finalMode = (await io.stat(filePath)).mode & 0o777; } catch (error) { if (error.code !== "ENOENT") throw error; } }
|
|
143
|
+
await io.mkdir(directory, { recursive: true, mode: 0o700 });
|
|
144
|
+
const tempPath = path.join(directory, `.${path.basename(filePath)}.${process.pid}.${randomUUID()}.tmp`);
|
|
145
|
+
let file;
|
|
146
|
+
try {
|
|
147
|
+
file = await io.open(tempPath, "wx", finalMode);await file.writeFile(data);await file.sync();await file.close();file = null;
|
|
148
|
+
await io.rename(tempPath, filePath);await io.chmod(filePath, finalMode);
|
|
149
|
+
if (process.platform !== "win32") {
|
|
150
|
+
let dir;
|
|
151
|
+
try { dir = await io.open(directory, "r");await dir.sync(); }
|
|
152
|
+
catch (error) { if (!["EINVAL", "ENOTSUP", "EBADF"].includes(error.code)) throw error; }
|
|
153
|
+
finally { await dir?.close(); }
|
|
154
|
+
}
|
|
155
|
+
} finally {
|
|
156
|
+
await file?.close();
|
|
157
|
+
try { await io.unlink(tempPath); } catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export async function atomicWriteFilePair(primaryPath, primaryData, secondaryPath, secondaryData, { mode = 0o600, writeFile = atomicWriteFile, unlinkFile = file => fs.promises.unlink(file) } = {}) {
|
|
162
|
+
const snapshot = async file => {
|
|
163
|
+
try { return { data: await fs.promises.readFile(file), mode: (await fs.promises.stat(file)).mode & 0o777 }; }
|
|
164
|
+
catch (error) { if (error.code === "ENOENT") return null;throw error; }
|
|
165
|
+
};
|
|
166
|
+
const remove = async file => { try { await unlinkFile(file); } catch (error) { if (error.code !== "ENOENT") throw error; } };
|
|
167
|
+
const write = (file, data, mode) => writeFile(file, data, { mode, preserveMode: false });
|
|
168
|
+
const before = [await snapshot(primaryPath), await snapshot(secondaryPath)];
|
|
169
|
+
try {
|
|
170
|
+
await write(primaryPath, primaryData, mode);
|
|
171
|
+
if (secondaryData === null) await remove(secondaryPath);else await write(secondaryPath, secondaryData, mode);
|
|
172
|
+
} catch (error) {
|
|
173
|
+
for (const [file, saved] of [[primaryPath, before[0]], [secondaryPath, before[1]]]) {
|
|
174
|
+
try { if (saved) await write(file, saved.data, saved.mode);else await remove(file); }
|
|
175
|
+
catch (cause) { error.rollbackError ||= cause; }
|
|
176
|
+
}
|
|
177
|
+
throw error;
|
|
178
|
+
}
|
|
179
|
+
}
|
package/src/bounded-file.mjs
CHANGED
|
@@ -26,3 +26,19 @@ export function readBoundedFileSync(filePath, { maxBytes = MAX_SETTINGS_FILE_BYT
|
|
|
26
26
|
return encoding ? value.toString(encoding) : value;
|
|
27
27
|
} finally { fs.closeSync(fd); }
|
|
28
28
|
}
|
|
29
|
+
|
|
30
|
+
export async function readBoundedFile(filePath, { maxBytes = MAX_SETTINGS_FILE_BYTES, encoding } = {}) {
|
|
31
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) throw new RangeError("Invalid local file byte limit");
|
|
32
|
+
const file = await fs.promises.open(filePath, fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK || 0));
|
|
33
|
+
try {
|
|
34
|
+
const stat = await file.stat();
|
|
35
|
+
if (!stat.isFile() || stat.size > maxBytes) throw Object.assign(new Error("Local configuration file exceeds its read limit or is not a regular file"), { code: "ccdx_local_file_limit" });
|
|
36
|
+
const buffer = Buffer.alloc(stat.size + 1);let size = 0;
|
|
37
|
+
while (size < buffer.length) {
|
|
38
|
+
const { bytesRead } = await file.read(buffer, size, buffer.length - size, size);
|
|
39
|
+
if (!bytesRead) break;size += bytesRead;
|
|
40
|
+
}
|
|
41
|
+
if (size > stat.size) throw Object.assign(new Error("Local configuration file grew during reading; retry after the write finishes"), { code: "ccdx_local_file_changed" });
|
|
42
|
+
const value = buffer.subarray(0, size);return encoding ? value.toString(encoding) : value;
|
|
43
|
+
} finally { await file.close(); }
|
|
44
|
+
}
|
package/src/claude-gateway.mjs
CHANGED
|
@@ -175,7 +175,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
175
175
|
observeMessagesWindow(selectedProvider, configuredModel || model, selectedCapability, selectedModel);
|
|
176
176
|
}
|
|
177
177
|
tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });
|
|
178
|
-
conversation = validateConversation?.(body, req.headers, selectedProvider);
|
|
178
|
+
conversation = await validateConversation?.(body, req.headers, selectedProvider, abort.signal);
|
|
179
179
|
if (!countTokens) observeContextSession(body, req.headers, selectedProvider, "messages");
|
|
180
180
|
terminalOrigin = "transport";
|
|
181
181
|
const call = privacy?.wrap(selectedProvider.client.messages, { res, protocol: "messages", client: privacyClient }) || selectedProvider.client.messages;
|
|
@@ -220,7 +220,8 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
220
220
|
if (!upstream.ok) context.onHttpError?.({ ...upstreamErrorEvidence(raw),
|
|
221
221
|
origin: context.countObservation?.cached ? "capability_cache" : "upstream_http", headers: upstream.headers });
|
|
222
222
|
if (!countTokens && upstream.ok && value?.type === "message" && Array.isArray(value.content)) {
|
|
223
|
-
if (value.content.some(hasMessageState)) conversation?.commit?.({ tool: value.content.some(block => block?.type === "tool_use") });
|
|
223
|
+
if (value.content.some(hasMessageState)) await conversation?.commit?.({ tool: value.content.some(block => block?.type === "tool_use") });
|
|
224
|
+
abort.signal.throwIfAborted();
|
|
224
225
|
model = value.model || model;responseId = value.id;usage = value.usage;stopReason = value.stop_reason;
|
|
225
226
|
sawStop = typeof stopReason === "string";outcome = stopReason === "max_tokens" ? "incomplete" : sawStop ? "completed" : "failed";
|
|
226
227
|
} else if (countTokens && upstream.ok && !modelFailure) outcome = "completed";
|
|
@@ -230,6 +231,14 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
230
231
|
if (!/^text\/event-stream(?:\s*;|$)/i.test(upstream.headers.get("content-type") || "")) throw new Error("Expected a Claude event stream");
|
|
231
232
|
abort.setTimeout(config.streamIdleTimeoutMs, "stream_idle_timeout");
|
|
232
233
|
res.writeHead(upstream.status, { ...headers, "Cache-Control": "no-cache" });
|
|
234
|
+
let commitState = null, conversationCommitted = false;
|
|
235
|
+
const commitOutput = async () => {
|
|
236
|
+
if (commitState && !conversationCommitted && conversation?.commit) {
|
|
237
|
+
conversationCommitted = await conversation.commit(commitState) === true;
|
|
238
|
+
abort.signal.throwIfAborted();
|
|
239
|
+
}
|
|
240
|
+
commitState = null;
|
|
241
|
+
};
|
|
233
242
|
const observer = createMessagesObserver(event => {
|
|
234
243
|
if (event.type === "error") {
|
|
235
244
|
failedEvent = true;outcome = "failed";
|
|
@@ -238,7 +247,9 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
238
247
|
}
|
|
239
248
|
if (sawStop || failedEvent) return;
|
|
240
249
|
if (event.type === "content_block_start" && hasMessageState(event.content_block)
|
|
241
|
-
|| event.type === "content_block_delta" && (isMessagesOutputDelta(event.delta) || event.delta?.type === "signature_delta" && event.delta.signature))
|
|
250
|
+
|| event.type === "content_block_delta" && (isMessagesOutputDelta(event.delta) || event.delta?.type === "signature_delta" && event.delta.signature)) {
|
|
251
|
+
if (!conversationCommitted) commitState = { tool: commitState?.tool === true || event.content_block?.type === "tool_use" };
|
|
252
|
+
}
|
|
242
253
|
if (event.type === "message_start") { responseId = event.message?.id;model = event.message?.model || model;usage = event.message?.usage || {}; }
|
|
243
254
|
if (event.type === "content_block_delta" && isMessagesOutputDelta(event.delta)) tracker?.firstOutput();
|
|
244
255
|
if (event.type === "message_delta") {
|
|
@@ -253,12 +264,14 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
253
264
|
const { value, done } = await reader.read();if (done) break;
|
|
254
265
|
tracker?.upstreamActivity();abort.setTimeout(config.streamIdleTimeoutMs, "stream_idle_timeout");
|
|
255
266
|
const frames = observer.write(value);
|
|
267
|
+
await commitOutput();
|
|
256
268
|
let writable = true;
|
|
257
269
|
for (const chunk of frames) if (!await writeOrDrain(res, chunk, { signal: abort.signal })) { writable = false;break; }
|
|
258
270
|
if (!writable) break;
|
|
259
271
|
if (sawStop || failedEvent) break;
|
|
260
272
|
}
|
|
261
|
-
|
|
273
|
+
const tail = observer.finish();await commitOutput();
|
|
274
|
+
for (const chunk of tail) if (!await writeOrDrain(res, chunk, { signal: abort.signal })) break;
|
|
262
275
|
if (!sawStop && !failedEvent) throw new Error("Claude stream ended before message_stop");
|
|
263
276
|
if (!res.writableEnded) res.end();
|
|
264
277
|
} finally { await reader.cancel().catch(() => {});reader.releaseLock(); }
|
package/src/codex-image-host.mjs
CHANGED
|
@@ -140,15 +140,18 @@ export function createImageHostBridge({ baseUrl, codexHome, sendToCodex, fetchIm
|
|
|
140
140
|
}
|
|
141
141
|
|
|
142
142
|
return {
|
|
143
|
-
|
|
143
|
+
client(message) {
|
|
144
144
|
if (message.method === "initialize") {
|
|
145
145
|
experimental = message.params?.capabilities?.experimentalApi === true;
|
|
146
146
|
requests.set(JSON.stringify(message.id), { method: "initialize" });
|
|
147
147
|
}
|
|
148
148
|
if (["thread/start", "thread/resume", "thread/fork"].includes(message.method)) {
|
|
149
|
-
const
|
|
150
|
-
|
|
151
|
-
|
|
149
|
+
const remember = registered => {
|
|
150
|
+
requests.set(JSON.stringify(message.id), { method: message.method, params: message.params || {}, registered });
|
|
151
|
+
return registered ? { ...message, params: addImageHostTool(message.params || {}) } : message;
|
|
152
|
+
};
|
|
153
|
+
if (message.method === "thread/start" && experimental) return Promise.resolve(enabled()).then(remember);
|
|
154
|
+
return remember(false);
|
|
152
155
|
}
|
|
153
156
|
if (message.method === "turn/start") {
|
|
154
157
|
const context = threads.get(message.params?.threadId);
|
|
@@ -173,8 +176,8 @@ export function createImageHostBridge({ baseUrl, codexHome, sendToCodex, fetchIm
|
|
|
173
176
|
const controller = new AbortController(), key = JSON.stringify(message.id);
|
|
174
177
|
active.set(key, { controller, threadId: message.params.threadId });
|
|
175
178
|
void runImage(message.params, AbortSignal.any([controller.signal, AbortSignal.timeout(180000)]))
|
|
176
|
-
.then(result => { observe("generated", message.params.threadId);sendToCodex({ id: message.id, result }); })
|
|
177
|
-
.catch(error => { observe("failed", message.params.threadId);sendToCodex({ id: message.id, result: { success: false, contentItems: [{ type: "inputText", text: error.message }] } }); })
|
|
179
|
+
.then(async result => { observe("generated", message.params.threadId);await sendToCodex({ id: message.id, result }); })
|
|
180
|
+
.catch(async error => { observe("failed", message.params.threadId);try { await sendToCodex({ id: message.id, result: { success: false, contentItems: [{ type: "inputText", text: error.message }] } }); } catch {} })
|
|
178
181
|
.finally(() => active.delete(key));
|
|
179
182
|
return true;
|
|
180
183
|
},
|
|
@@ -182,15 +185,77 @@ export function createImageHostBridge({ baseUrl, codexHome, sendToCodex, fetchIm
|
|
|
182
185
|
};
|
|
183
186
|
}
|
|
184
187
|
|
|
185
|
-
function
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
188
|
+
function waitStream(stream, event, signal) {
|
|
189
|
+
return new Promise((resolve, reject) => {
|
|
190
|
+
const cleanup = () => {
|
|
191
|
+
stream.off(event, ready);stream.off("end", ended);stream.off("close", ended);stream.off("error", failed);
|
|
192
|
+
signal?.removeEventListener("abort", ended);
|
|
193
|
+
};
|
|
194
|
+
const ready = () => { cleanup();resolve(true); }, ended = () => { cleanup();resolve(false); }, failed = error => { cleanup();reject(error); };
|
|
195
|
+
stream.once(event, ready);stream.once("end", ended);stream.once("close", ended);stream.once("error", failed);
|
|
196
|
+
signal?.addEventListener("abort", ended, { once: true });
|
|
197
|
+
if (signal?.aborted || stream.destroyed) ended();
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function pumpLines(stream, accept, signal, flush = () => {}) {
|
|
202
|
+
const decoder = new StringDecoder("utf8");let buffer = "", ended = false, pending = false, stopped = false;
|
|
203
|
+
let resolve, reject;
|
|
204
|
+
const done = new Promise((ok, fail) => { resolve = ok;reject = fail; });
|
|
205
|
+
const stop = error => {
|
|
206
|
+
if (stopped) return;stopped = true;
|
|
207
|
+
stream.off("data", data);stream.off("end", end);stream.off("close", end);stream.off("error", stop);
|
|
208
|
+
signal.removeEventListener("abort", abort);stream.pause();
|
|
209
|
+
if (error) reject(error);else resolve();
|
|
210
|
+
};
|
|
211
|
+
const abort = () => stop();
|
|
212
|
+
const wait = operation => {
|
|
213
|
+
pending = true;stream.pause();
|
|
214
|
+
operation.then(() => { pending = false;consume(); }, stop);
|
|
215
|
+
};
|
|
216
|
+
const consume = () => {
|
|
217
|
+
if (stopped || pending) return;
|
|
218
|
+
try {
|
|
219
|
+
let boundary;
|
|
220
|
+
while ((boundary = buffer.indexOf("\n")) >= 0) {
|
|
221
|
+
const wire = buffer.slice(0, boundary + 1);buffer = buffer.slice(boundary + 1);
|
|
222
|
+
const operation = accept(wire.slice(0, -1), wire);
|
|
223
|
+
if (operation?.then) { wait(operation);return; }
|
|
224
|
+
}
|
|
225
|
+
if (ended && buffer) {
|
|
226
|
+
const wire = buffer;buffer = "";const operation = accept(wire, wire);
|
|
227
|
+
if (operation?.then) { wait(operation);return; }
|
|
228
|
+
}
|
|
229
|
+
const operation = flush();
|
|
230
|
+
if (operation?.then) { wait(operation);return; }
|
|
231
|
+
if (ended) stop();else stream.resume();
|
|
232
|
+
} catch (error) { stop(error); }
|
|
233
|
+
};
|
|
234
|
+
const data = chunk => { buffer += decoder.write(chunk);consume(); };
|
|
235
|
+
const end = () => { if (!ended) { ended = true;buffer += decoder.end();consume(); } };
|
|
236
|
+
stream.on("data", data);stream.once("end", end);stream.once("close", end);stream.once("error", stop);
|
|
237
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
238
|
+
if (signal.aborted) abort();else if (stream.readableEnded || stream.destroyed) end();
|
|
239
|
+
return done;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function hostWriter(stream, signal) {
|
|
243
|
+
let pending = null;
|
|
244
|
+
const direct = chunk => {
|
|
245
|
+
if (signal.aborted || stream.destroyed || stream.writableEnded) throw new Error("Image host destination closed");
|
|
246
|
+
if (!stream.write(chunk)) return waitStream(stream, "drain", signal).then(ready => { if (!ready) throw new Error("Image host destination closed"); });
|
|
247
|
+
};
|
|
248
|
+
return {
|
|
249
|
+
get pending() { return pending; },
|
|
250
|
+
write(chunk) {
|
|
251
|
+
const next = pending ? pending.then(() => direct(chunk)) : direct(chunk);
|
|
252
|
+
if (next) {
|
|
253
|
+
pending = next;
|
|
254
|
+
next.then(() => { if (pending === next) pending = null; }, () => {});
|
|
255
|
+
}
|
|
256
|
+
return next;
|
|
257
|
+
},
|
|
190
258
|
};
|
|
191
|
-
const end = () => { buffer += decoder.end();if (buffer) accept(buffer); };
|
|
192
|
-
stream.on("data", data);stream.on("end", end);
|
|
193
|
-
return () => { stream.removeListener("data", data);stream.removeListener("end", end); };
|
|
194
259
|
}
|
|
195
260
|
|
|
196
261
|
export async function runCodexImageHost({ codex, argv, baseUrl, env = process.env, input = process.stdin, output = process.stdout, error = process.stderr, spawnImpl = spawn } = {}) {
|
|
@@ -200,9 +265,13 @@ export async function runCodexImageHost({ codex, argv, baseUrl, env = process.en
|
|
|
200
265
|
&& (rest.indexOf("--listen") < 0 || rest[rest.indexOf("--listen") + 1] === "stdio://");
|
|
201
266
|
const childEnv = { ...env, CODEX_APP_RUNTIME_CLI_PATH: codex };delete childEnv.CODEX_CLI_PATH;
|
|
202
267
|
const child = spawnImpl(codex, args, { env: childEnv, stdio: ["pipe", "pipe", "pipe"] });
|
|
203
|
-
child
|
|
204
|
-
|
|
205
|
-
|
|
268
|
+
const completed = once(child, "close");completed.catch(() => {});
|
|
269
|
+
const inputAbort = new AbortController(), outputAbort = new AbortController(), reportingAbort = new AbortController();
|
|
270
|
+
let bridge, failure;
|
|
271
|
+
const fail = cause => { if (failure) return;failure = cause;inputAbort.abort();outputAbort.abort();bridge?.close();child.kill("SIGTERM"); };
|
|
272
|
+
const inputClosed = () => inputAbort.abort();
|
|
273
|
+
child.stdin.on("error", inputClosed);child.stdin.on("close", inputClosed);input.on("error", fail);child.stdout.on("error", fail);output.on("error", fail);
|
|
274
|
+
child.stderr.pipe(error, { end: false });
|
|
206
275
|
const hostId = randomUUID();let reporting = Promise.resolve(), pendingReports = 0;
|
|
207
276
|
const report = evidence => {
|
|
208
277
|
if (pendingReports >= 16) return;
|
|
@@ -215,24 +284,48 @@ export async function runCodexImageHost({ codex, argv, baseUrl, env = process.en
|
|
|
215
284
|
await response.body?.cancel();
|
|
216
285
|
}).catch(() => {}).finally(() => { pendingReports--; });
|
|
217
286
|
};
|
|
218
|
-
const
|
|
287
|
+
const destination = hostWriter(child.stdin, inputAbort.signal), client = hostWriter(output, outputAbort.signal);
|
|
288
|
+
const write = message => destination.write(JSON.stringify(message) + "\n");
|
|
289
|
+
let inputPump = Promise.resolve(), outputPump = Promise.resolve();
|
|
219
290
|
if (!stdio) { input.pipe(child.stdin);child.stdout.pipe(output, { end: false }); }
|
|
220
291
|
else {
|
|
221
292
|
bridge = createImageHostBridge({ baseUrl, codexHome: path.resolve(env.CODEX_HOME || path.join(env.HOME || process.env.HOME, ".codex")), sendToCodex: write, onEvent: report });
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
}))
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
293
|
+
inputPump = pumpLines(input, (raw, wire) => {
|
|
294
|
+
let message;try { message = JSON.parse(raw); } catch { return destination.write(wire); }
|
|
295
|
+
const forward = next => next === message ? destination.write(wire) : write(next);
|
|
296
|
+
const invalid = failure => client.write(JSON.stringify({ id: message.id, error: { code: -32602, message: failure.message } }) + "\n");
|
|
297
|
+
let next;try { next = bridge.client(message); } catch (failure) { return invalid(failure); }
|
|
298
|
+
return next?.then ? next.then(forward, invalid) : forward(next);
|
|
299
|
+
}, inputAbort.signal).then(() => {
|
|
300
|
+
if (!inputAbort.signal.aborted) { bridge.close();child.stdin.end(); }
|
|
301
|
+
}).catch(cause => { if (!inputAbort.signal.aborted) fail(cause); });
|
|
302
|
+
let buffered = "", bytes = 0;
|
|
303
|
+
const flush = () => {
|
|
304
|
+
if (!buffered) return;
|
|
305
|
+
const wire = buffered;buffered = "";bytes = 0;return client.write(wire);
|
|
306
|
+
};
|
|
307
|
+
const accept = (value, wire) => {
|
|
308
|
+
if (!value || !bridge.codex(value)) { buffered += wire;bytes += Buffer.byteLength(wire); }
|
|
309
|
+
if (bytes >= (output.writableHighWaterMark || 1)) return flush();
|
|
310
|
+
};
|
|
311
|
+
outputPump = pumpLines(child.stdout, (raw, wire) => {
|
|
312
|
+
let value;try { value = JSON.parse(raw); } catch {}
|
|
313
|
+
if (value?.method === "item/tool/call" && value.params?.namespace === IMAGE_HOST_NAMESPACE && destination.pending) return destination.pending.then(() => accept(value, wire));
|
|
314
|
+
return accept(value, wire);
|
|
315
|
+
}, outputAbort.signal, flush).catch(fail);
|
|
232
316
|
}
|
|
233
|
-
const stop = signal => { bridge?.close();child.kill(signal); };
|
|
317
|
+
const stop = signal => { bridge?.close();inputAbort.abort();outputAbort.abort();child.kill(signal); };
|
|
234
318
|
const interrupt = () => stop("SIGINT"), terminate = () => stop("SIGTERM");
|
|
235
319
|
process.once("SIGINT", interrupt);process.once("SIGTERM", terminate);
|
|
236
|
-
try {
|
|
237
|
-
|
|
320
|
+
try {
|
|
321
|
+
const [code, signal] = await completed;
|
|
322
|
+
bridge?.close();inputAbort.abort();await inputPump;await outputPump;
|
|
323
|
+
if (failure) throw failure;
|
|
324
|
+
return code ?? (signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 1);
|
|
325
|
+
} finally {
|
|
326
|
+
bridge?.close();inputAbort.abort();outputAbort.abort();reportingAbort.abort();
|
|
327
|
+
input.unpipe(child.stdin);input.pause();
|
|
328
|
+
child.stdin.off("error", inputClosed);child.stdin.off("close", inputClosed);input.off("error", fail);child.stdout.off("error", fail);output.off("error", fail);
|
|
329
|
+
process.removeListener("SIGINT", interrupt);process.removeListener("SIGTERM", terminate);
|
|
330
|
+
}
|
|
238
331
|
}
|
|
@@ -658,7 +658,7 @@ export function createConnectionRuntime({
|
|
|
658
658
|
if (!source) throw accessError("ccdx_api_not_ready", 503);
|
|
659
659
|
return source;
|
|
660
660
|
}
|
|
661
|
-
function validateConversation(body, headers, source, client = "codex") {
|
|
661
|
+
function validateConversation(body, headers, source, signal, client = "codex") {
|
|
662
662
|
if (!body || typeof body !== "object" || Array.isArray(body)) return;
|
|
663
663
|
if (
|
|
664
664
|
managed &&
|
|
@@ -683,7 +683,8 @@ export function createConnectionRuntime({
|
|
|
683
683
|
body,
|
|
684
684
|
headers,
|
|
685
685
|
identities()[client],
|
|
686
|
-
transfer
|
|
686
|
+
transfer,
|
|
687
|
+
signal
|
|
687
688
|
);
|
|
688
689
|
}
|
|
689
690
|
}
|
|
@@ -1509,7 +1510,7 @@ export function createConnectionRuntime({
|
|
|
1509
1510
|
finish,
|
|
1510
1511
|
};
|
|
1511
1512
|
},
|
|
1512
|
-
validateConversation: (body, headers, source) => validateConversation(body, headers, source, id),
|
|
1513
|
+
validateConversation: (body, headers, source, signal) => validateConversation(body, headers, source, signal, id),
|
|
1513
1514
|
onRequest() {
|
|
1514
1515
|
lastClients[id] = new Date().toISOString();
|
|
1515
1516
|
},
|
|
@@ -1,15 +1,16 @@
|
|
|
1
|
-
import fs from "node:fs";
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { createHmac } from "node:crypto";
|
|
4
4
|
import { accessSettingsPath, accessError } from "./access-settings.mjs";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
5
|
+
import { readBoundedFile } from "./bounded-file.mjs";
|
|
6
|
+
import { atomicWriteFile } from "./atomic-file.mjs";
|
|
7
|
+
import { withFileLock } from "./lock.mjs";
|
|
8
8
|
|
|
9
9
|
// Correlation only: retain hashes, never prompts, session IDs or credentials.
|
|
10
10
|
export function createConversationSourceGuard(options = {}) {
|
|
11
11
|
const file = path.join(path.dirname(accessSettingsPath(options)), "conversation-sources.json");let cache;
|
|
12
|
-
return (client, profile, body, headers = {}, salt, transfer) => {
|
|
12
|
+
return (client, profile, body, headers = {}, salt, transfer, signal) => {
|
|
13
|
+
signal?.throwIfAborted();
|
|
13
14
|
const hash = value => createHmac("sha256", salt).update(value).digest("hex");
|
|
14
15
|
const items = Array.isArray(body.messages) ? body.messages : Array.isArray(body.input) ? body.input : [];
|
|
15
16
|
const hasHistory = Boolean(body.previous_response_id) || items.filter(item => item?.role === "user").length > 1
|
|
@@ -25,30 +26,33 @@ export function createConversationSourceGuard(options = {}) {
|
|
|
25
26
|
const agent = headers["x-claude-code-agent-id"];
|
|
26
27
|
const child = identified && ["claude_app", "claude_code"].includes(client) && typeof agent === "string" && /^[\w-]{1,128}$/.test(agent) ? `\0agent\0${agent}` : "";
|
|
27
28
|
const key = hash(client + "\0" + input + child), owner = hash(profile);
|
|
28
|
-
const prepare = previousOwner => transfer?.prepare({ key, owner, previousOwner, profile, body,
|
|
29
|
+
const prepare = previousOwner => transfer?.prepare({ key, owner, previousOwner, profile, body, signal,
|
|
29
30
|
knownOwners: transfer.profiles?.map(hash) || [] });
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
prepared
|
|
33
|
-
if (
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
try { return withFileLockSync(`${file}.lock`, () => {
|
|
39
|
-
let owners = {};
|
|
40
|
-
try { owners = JSON.parse(readBoundedFileSync(file, { encoding: "utf8", maxBytes: 256 * 1024 })); } catch (error) { if (error.code !== "ENOENT") throw accessError("ccdx_conversation_state_invalid", 409); }
|
|
41
|
-
if (!owners || typeof owners !== "object" || Array.isArray(owners) || Object.keys(owners).length > 1024
|
|
42
|
-
|| Object.entries(owners).some(([key, owner]) => !/^[a-f0-9]{64}$/.test(key) || !/^[a-f0-9]{64}$/.test(owner))) throw accessError("ccdx_conversation_state_invalid", 409);
|
|
43
|
-
prepared = prepare(owners[key]);
|
|
44
|
-
if (prepared?.handled) { cache = owners;return prepared; }
|
|
45
|
-
if (owners[key] && owners[key] !== owner && (identified || hasHistory)) throw accessError("ccdx_conversation_source_changed", 409);
|
|
46
|
-
if (owners[key] !== owner) {
|
|
47
|
-
owners[key] = owner;while (Object.keys(owners).length > 1024) delete owners[Object.keys(owners)[0]];
|
|
48
|
-
atomicWriteFileSync(file, JSON.stringify(owners) + "\n", { mode: 0o600 });
|
|
31
|
+
if (!transfer && cache?.[key] === owner) return;
|
|
32
|
+
return (async () => {
|
|
33
|
+
let prepared;
|
|
34
|
+
if (cache?.[key]) {
|
|
35
|
+
prepared = await prepare(cache[key]);
|
|
36
|
+
if (prepared?.handled || cache[key] === owner) return prepared;
|
|
37
|
+
prepared?.release();
|
|
38
|
+
if (identified || hasHistory) throw accessError("ccdx_conversation_source_changed", 409);
|
|
49
39
|
}
|
|
50
|
-
|
|
51
|
-
return
|
|
52
|
-
|
|
40
|
+
await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
41
|
+
try { return await withFileLock(`${file}.lock`, async () => {
|
|
42
|
+
let owners = {};
|
|
43
|
+
try { owners = JSON.parse(await readBoundedFile(file, { encoding: "utf8", maxBytes: 256 * 1024 })); } catch (error) { if (error.code !== "ENOENT") throw accessError("ccdx_conversation_state_invalid", 409); }
|
|
44
|
+
if (!owners || typeof owners !== "object" || Array.isArray(owners) || Object.keys(owners).length > 1024
|
|
45
|
+
|| Object.entries(owners).some(([key, owner]) => !/^[a-f0-9]{64}$/.test(key) || !/^[a-f0-9]{64}$/.test(owner))) throw accessError("ccdx_conversation_state_invalid", 409);
|
|
46
|
+
prepared = await prepare(owners[key]);
|
|
47
|
+
if (prepared?.handled) { cache = owners;return prepared; }
|
|
48
|
+
if (owners[key] && owners[key] !== owner && (identified || hasHistory)) throw accessError("ccdx_conversation_source_changed", 409);
|
|
49
|
+
if (owners[key] !== owner) {
|
|
50
|
+
owners[key] = owner;while (Object.keys(owners).length > 1024) delete owners[Object.keys(owners)[0]];
|
|
51
|
+
await atomicWriteFile(file, JSON.stringify(owners) + "\n", { mode: 0o600 });
|
|
52
|
+
}
|
|
53
|
+
cache = owners;
|
|
54
|
+
return prepared;
|
|
55
|
+
}, { timeoutMs: 1000, staleMs: 60_000, pollMs: 10, signal }); } catch (error) { prepared?.release();throw error; }
|
|
56
|
+
})();
|
|
53
57
|
};
|
|
54
58
|
}
|
package/src/lock.mjs
CHANGED
|
@@ -1,10 +1,7 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { randomUUID } from "node:crypto";
|
|
4
|
-
|
|
5
|
-
function sleep(ms) {
|
|
6
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
7
|
-
}
|
|
4
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
8
5
|
|
|
9
6
|
// Synchronous configuration writers share the same cross-process lock format.
|
|
10
7
|
// Readers never take the lock. A live lock is never stolen on timeout.
|
|
@@ -269,6 +266,7 @@ export async function withFileLock(lockPath, fn, {
|
|
|
269
266
|
now = Date.now,
|
|
270
267
|
fsImpl = fs,
|
|
271
268
|
processAlive = processIsAlive,
|
|
269
|
+
signal,
|
|
272
270
|
} = {}) {
|
|
273
271
|
fs.mkdirSync(path.dirname(lockPath), { recursive: true });
|
|
274
272
|
const started = now();
|
|
@@ -277,12 +275,13 @@ export async function withFileLock(lockPath, fn, {
|
|
|
277
275
|
const guardPath = reclaimGuardPath(lockPath);
|
|
278
276
|
|
|
279
277
|
while (fd === null) {
|
|
278
|
+
signal?.throwIfAborted();
|
|
280
279
|
const beforeAcquire = now();
|
|
281
280
|
if (lockPathExists(guardPath, fsImpl)) {
|
|
282
281
|
maybeRemoveAbandonedGuard(guardPath, staleMs, beforeAcquire, fsImpl, processAlive);
|
|
283
282
|
if (lockPathExists(guardPath, fsImpl)) {
|
|
284
283
|
if (beforeAcquire - started >= timeoutMs) throw new Error(`Timed out waiting for lock: ${lockPath}`);
|
|
285
|
-
await
|
|
284
|
+
await delay(Math.min(pollMs, Math.max(1, timeoutMs - (beforeAcquire - started))), undefined, { signal });
|
|
286
285
|
continue;
|
|
287
286
|
}
|
|
288
287
|
}
|
|
@@ -306,11 +305,12 @@ export async function withFileLock(lockPath, fn, {
|
|
|
306
305
|
if (nowMs - started >= timeoutMs) {
|
|
307
306
|
throw new Error(`Timed out waiting for lock: ${lockPath}`);
|
|
308
307
|
}
|
|
309
|
-
await
|
|
308
|
+
await delay(Math.min(pollMs, Math.max(1, timeoutMs - (nowMs - started))), undefined, { signal });
|
|
310
309
|
}
|
|
311
310
|
}
|
|
312
311
|
|
|
313
312
|
try {
|
|
313
|
+
signal?.throwIfAborted();
|
|
314
314
|
return await fn();
|
|
315
315
|
} finally {
|
|
316
316
|
try {
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import fs from "node:fs";
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { createHash } from "node:crypto";
|
|
4
4
|
import { accessSettingsPath } from "./access-settings.mjs";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
5
|
+
import { readBoundedFile } from "./bounded-file.mjs";
|
|
6
|
+
import { atomicWriteFilePair } from "./atomic-file.mjs";
|
|
7
|
+
import { withFileLock } from "./lock.mjs";
|
|
8
8
|
|
|
9
9
|
const grants = new WeakMap(), HASH = /^[a-f0-9]{64}$/, LIMIT = 1024;
|
|
10
10
|
const digest = value => createHash("sha256").update(JSON.stringify(value, (key, entry) => key === "cache_control" ? undefined : entry)).digest("hex");
|
|
@@ -141,29 +141,29 @@ function project(body, count) {
|
|
|
141
141
|
// fingerprints; it neither changes routing nor stores conversation contents.
|
|
142
142
|
export function createMessagesHistoryTransfer(options = {}) {
|
|
143
143
|
const file = messagesTransferPath(options), canonicalFile = path.join(path.dirname(file), "conversation-prefixes.json"), active = new Map();let records;
|
|
144
|
-
function readFile(target, canonical = false) {
|
|
145
|
-
try { return checkedRecords(JSON.parse(
|
|
144
|
+
async function readFile(target, canonical = false) {
|
|
145
|
+
try { return checkedRecords(JSON.parse(await readBoundedFile(target, { encoding: "utf8", maxBytes: 512 * 1024 })), canonical); }
|
|
146
146
|
catch (error) { if (error.code === "ENOENT") return {};invalidState(); }
|
|
147
147
|
}
|
|
148
|
-
function read() {
|
|
149
|
-
const raw = readFile(file), canonical = readFile(canonicalFile, true);
|
|
148
|
+
async function read() {
|
|
149
|
+
const raw = await readFile(file), canonical = await readFile(canonicalFile, true);
|
|
150
150
|
return Object.fromEntries(Object.entries(raw).map(([key, record]) => [key, { ...record,
|
|
151
151
|
...(canonical[key]?.owner === record.owner && canonical[key].raw_count === record.count && canonical[key].raw_prefix === record.prefix ? { canonical: canonical[key] } : {}) }]));
|
|
152
152
|
}
|
|
153
|
-
function save(key, record) {
|
|
154
|
-
fs.
|
|
155
|
-
|
|
156
|
-
const next = read();delete next[key];next[key] = { ...record.raw, canonical: record.canonical };
|
|
153
|
+
async function save(key, record, signal) {
|
|
154
|
+
await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
155
|
+
await withFileLock(`${file}.lock`, async () => {
|
|
156
|
+
const next = await read();delete next[key];next[key] = { ...record.raw, canonical: record.canonical };
|
|
157
157
|
while (Object.keys(next).length > LIMIT) delete next[Object.keys(next)[0]];
|
|
158
158
|
const raw = Object.fromEntries(Object.entries(next).map(([key, { canonical, ...value }]) => [key, value]));
|
|
159
159
|
const canonical = Object.fromEntries(Object.entries(next).filter(([, value]) => value.canonical).map(([key, value]) => [key, value.canonical]));
|
|
160
160
|
checkedRecords({ version: 1, records: raw });checkedRecords({ version: 1, records: canonical }, true);
|
|
161
|
-
|
|
162
|
-
});
|
|
161
|
+
await atomicWriteFilePair(file, JSON.stringify({ version: 1, records: raw }) + "\n", canonicalFile, JSON.stringify({ version: 1, records: canonical }) + "\n");records = next;
|
|
162
|
+
}, { timeoutMs: 1000, staleMs: 60_000, pollMs: 10, signal });
|
|
163
163
|
}
|
|
164
|
-
return { prepare({ key, owner, previousOwner, profile, body, countTokens = false, knownOwners = [] }) {
|
|
164
|
+
return { async prepare({ key, owner, previousOwner, profile, body, countTokens = false, knownOwners = [], signal }) {
|
|
165
165
|
if (!Array.isArray(body?.messages) || body.input !== undefined) return null;
|
|
166
|
-
records
|
|
166
|
+
if (!records) records = await read();const entry = records[key], changed = entry ? entry.owner !== owner : Boolean(previousOwner && previousOwner !== owner);
|
|
167
167
|
const initial = knownOwners.includes(entry?.owner || previousOwner);
|
|
168
168
|
const hasHistory = history(body), noncommitting = countTokens || Boolean(changed || entry) && !hasHistory;
|
|
169
169
|
const items = changed || entry ? canonicalItems(body.messages) : null;
|
|
@@ -175,17 +175,19 @@ export function createMessagesHistoryTransfer(options = {}) {
|
|
|
175
175
|
}
|
|
176
176
|
const grant = { profile, noncommitting: true, initial, active: true };grants.set(body, grant);
|
|
177
177
|
const nextCheckpoint = countTokens ? null : checkpoint(owner, body.messages);
|
|
178
|
-
let toolLease, committed = false;
|
|
179
|
-
return { handled: true, commit(state) {
|
|
178
|
+
let toolLease, committed = false, released = false, committing;
|
|
179
|
+
return { handled: true, async commit(state) {
|
|
180
180
|
// A no-history model probe must not pin the conversation. An actual
|
|
181
181
|
// tool call must: its following results continue this very same turn.
|
|
182
|
-
if (
|
|
182
|
+
if (committing) return committing;
|
|
183
|
+
if (countTokens || !state?.tool || committed || released) return committed;
|
|
183
184
|
const lease = active.get(key);
|
|
184
185
|
if (lease && lease.owner !== owner) fail("ccdx_history_transfer_busy", "Wait for the current response to finish before switching sources.");
|
|
185
|
-
save(key, nextCheckpoint);committed = true;
|
|
186
186
|
toolLease = lease || { owner, count: 0 };toolLease.count++;active.set(key, toolLease);
|
|
187
|
+
committing = save(key, nextCheckpoint, signal).then(() => { committed = true;return true; });
|
|
188
|
+
return committing;
|
|
187
189
|
}, release() {
|
|
188
|
-
grant.active = false;if (toolLease && --toolLease.count === 0) active.delete(key);toolLease = null;
|
|
190
|
+
released = true;grant.active = false;if (toolLease && --toolLease.count === 0) active.delete(key);toolLease = null;
|
|
189
191
|
} };
|
|
190
192
|
}
|
|
191
193
|
const lease = active.get(key);
|
|
@@ -205,12 +207,17 @@ export function createMessagesHistoryTransfer(options = {}) {
|
|
|
205
207
|
removed = project(body, count);grant = { profile, noncommitting: false, initial, active: true };grants.set(body, grant);
|
|
206
208
|
}
|
|
207
209
|
const current = lease || { owner, count: 0 };current.count++;active.set(key, current);
|
|
208
|
-
let released = false, committed = false;
|
|
209
|
-
return { handled: Boolean(changed || entry), commit() {
|
|
210
|
-
if (
|
|
211
|
-
if (
|
|
212
|
-
|
|
213
|
-
|
|
210
|
+
let released = false, committed = false, committing;
|
|
211
|
+
return { handled: Boolean(changed || entry), async commit() {
|
|
212
|
+
if (committing) return committing;
|
|
213
|
+
if (committed || released) return committed;
|
|
214
|
+
committing = (async () => {
|
|
215
|
+
if (candidate) await save(key, candidate, signal);
|
|
216
|
+
committed = true;
|
|
217
|
+
if (candidate && changed) options.onTransfer?.({ removed_thinking: removed });
|
|
218
|
+
return true;
|
|
219
|
+
})();
|
|
220
|
+
return committing;
|
|
214
221
|
}, release() {
|
|
215
222
|
if (released) return;released = true;if (grant) grant.active = false;
|
|
216
223
|
if (--current.count === 0) active.delete(key);
|
package/src/native-images.mjs
CHANGED
|
@@ -87,7 +87,15 @@ export function createNativeImagesHandler({ client, acquireRequest, privacy, env
|
|
|
87
87
|
const forward = input => client.images(operation, { ...body, prompt: input.input }, { signal: abort.signal });
|
|
88
88
|
const call = privacy?.wrap ? privacy.wrap(forward, { res, protocol: "responses", client: "codex" }) : forward;
|
|
89
89
|
const response = await call({ input: body.prompt }, { signal: abort.signal });
|
|
90
|
-
if (!response.ok) {
|
|
90
|
+
if (!response.ok) {
|
|
91
|
+
metrics.failed++;
|
|
92
|
+
await response.body?.cancel().catch(() => {});
|
|
93
|
+
abort.signal.throwIfAborted();
|
|
94
|
+
const code = `ccdx_images_http_${response.status}`, headers = new Headers(response.headers);
|
|
95
|
+
headers.set("Content-Type", "application/json");
|
|
96
|
+
sendUpstreamError(res, { status: response.status, headers }, JSON.stringify({ error: { type: "upstream_error", code, message: code } }));
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
91
99
|
const text = await readBoundedResponseText(response, { maxBytes: RESPONSE_MAX_BYTES, signal: abort.signal, label: "Copilot image response" });
|
|
92
100
|
let result;
|
|
93
101
|
try { result = JSON.parse(text); } catch { throw httpError("Copilot returned invalid image JSON", 502); }
|
package/src/providers/api.mjs
CHANGED
|
@@ -5,7 +5,7 @@ import { publicModelCatalog } from "../provider-metadata.mjs";
|
|
|
5
5
|
import { resolveClaudeModel } from "../claude-models.mjs";
|
|
6
6
|
import { prepareResponsesPayload } from "../image-optimization.mjs";
|
|
7
7
|
import { enforceResponsesPayloadByteBudget } from "../responses-byte-budget.mjs";
|
|
8
|
-
import { MAX_UPSTREAM_MODEL_CATALOG_BYTES, readBoundedResponseText } from "../http-transport.mjs";
|
|
8
|
+
import { MAX_UPSTREAM_MODEL_CATALOG_BYTES, MAX_UPSTREAM_ERROR_BODY_BYTES, readBoundedResponseText } from "../http-transport.mjs";
|
|
9
9
|
import { markUpstreamHeaders } from "../stream-performance.mjs";
|
|
10
10
|
import { createApiNetwork } from "./api-network.mjs";
|
|
11
11
|
import { checkedApiKey } from "../api-secrets.mjs";
|
|
@@ -162,8 +162,11 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
162
162
|
async openResponse(context, upstream, options) {
|
|
163
163
|
const resp = await upstream(context.body, { assertActive: options.assertPrepareActive, signal: options.signal, currentInputStart: context.currentInputStart, onUpstreamStart: options.onUpstreamStart });
|
|
164
164
|
markUpstreamHeaders(resp.status);
|
|
165
|
-
//
|
|
166
|
-
if (!resp.ok) {
|
|
165
|
+
// request() already discarded the vendor body and projected a safe error.
|
|
166
|
+
if (!resp.ok) {
|
|
167
|
+
const errorText = await readBoundedResponseText(resp, { maxBytes: MAX_UPSTREAM_ERROR_BODY_BYTES, signal: options.signal, label: "API error response" });
|
|
168
|
+
return { resp, reqContext: context, errorText, usedRetryPolicies: new Set() };
|
|
169
|
+
}
|
|
167
170
|
return { resp, reqContext: context, errorText: undefined, usedRetryPolicies: new Set() };
|
|
168
171
|
} },
|
|
169
172
|
close() { closed = true;lifetime.abort();network?.close();for (const previous of retiring) previous.close();retiring.clear(); },
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
-
import { m365Paths,
|
|
3
|
-
import {
|
|
4
|
-
import fs from "node:fs";
|
|
2
|
+
import { m365Paths, m365AccountKey } from "../m365-settings.mjs";
|
|
3
|
+
import { withFileLock } from "../lock.mjs";
|
|
4
|
+
import fs from "node:fs/promises";
|
|
5
|
+
import { readBoundedFile } from "../bounded-file.mjs";
|
|
6
|
+
import { atomicWriteFile } from "../atomic-file.mjs";
|
|
5
7
|
import { messagesHistoryTransferGrant } from "../messages-history-transfer.mjs";
|
|
6
8
|
|
|
7
9
|
const changed = () => Object.assign(new Error("This conversation belongs to another company account. Start a new conversation."),
|
|
@@ -12,6 +14,7 @@ export function createM365ConversationGuard({ home } = {}) {
|
|
|
12
14
|
const { directory, conversations: file } = m365Paths({ home });
|
|
13
15
|
let cached;
|
|
14
16
|
return (account, body, headers = {}, options = {}) => {
|
|
17
|
+
options.signal?.throwIfAborted();
|
|
15
18
|
const items = Array.isArray(body.messages) ? body.messages : Array.isArray(body.input) ? body.input : [];
|
|
16
19
|
let session = headers["session_id"] || headers["session-id"] || headers["x-conversation-id"] || headers["x-claude-code-session-id"];
|
|
17
20
|
if (!session && typeof body.metadata?.user_id === "string") {
|
|
@@ -30,18 +33,28 @@ export function createM365ConversationGuard({ home } = {}) {
|
|
|
30
33
|
if (noncommitting && !hasHistory) return;
|
|
31
34
|
if (cached?.[key] === owner) return;
|
|
32
35
|
if (cached?.[key] && cached[key] !== owner) throw changed();
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
36
|
+
return (async () => {
|
|
37
|
+
await fs.mkdir(directory, { recursive: true, mode: 0o700 });
|
|
38
|
+
await withFileLock(`${file}.lock`, async () => {
|
|
39
|
+
let saved;
|
|
40
|
+
try {
|
|
41
|
+
if (!(await fs.lstat(file)).isFile()) throw Error("Expected a regular file");
|
|
42
|
+
saved = JSON.parse(await readBoundedFile(file, { encoding: "utf8", maxBytes: 4 * 1024 * 1024 }));
|
|
43
|
+
if (!saved || typeof saved !== "object" || Array.isArray(saved)) throw Error("Expected an object");
|
|
44
|
+
} catch (error) {
|
|
45
|
+
if (error.code === "ENOENT") saved = { owners: {} };
|
|
46
|
+
else throw Object.assign(new Error("M365 local configuration could not be read; existing files were preserved"), { code: "m365_config_invalid" });
|
|
47
|
+
}
|
|
48
|
+
if (!saved.owners || typeof saved.owners !== "object" || Array.isArray(saved.owners)
|
|
49
|
+
|| Object.keys(saved.owners).length > 1024 || Object.entries(saved.owners).some(([id, value]) => !/^[a-f0-9]{64}$/.test(id) || !/^[a-f0-9]{64}$/.test(value))) throw changed();
|
|
50
|
+
const owners = saved.owners;
|
|
51
|
+
if (owners[key] && owners[key] !== owner || !owners[key] && account.history_isolation && hasHistory && !(authorized && grant.initial)) throw changed();
|
|
52
|
+
if (noncommitting) return;
|
|
53
|
+
if (owners[key]) { cached = owners;return; }
|
|
54
|
+
owners[key] = owner;
|
|
55
|
+
while (Object.keys(owners).length > 1024) delete owners[Object.keys(owners)[0]];
|
|
56
|
+
await atomicWriteFile(file, `${JSON.stringify({ owners }, null, 2)}\n`, { mode: 0o600, preserveMode: false });cached = owners;
|
|
57
|
+
}, { timeoutMs: 1000, staleMs: 60_000, pollMs: 10, signal: options.signal });
|
|
58
|
+
})();
|
|
46
59
|
};
|
|
47
60
|
}
|
package/src/providers/m365.mjs
CHANGED
|
@@ -207,7 +207,7 @@ export function createM365Provider({ home, env = process.env, account: accountOv
|
|
|
207
207
|
cacheModelEndpoints() {},
|
|
208
208
|
async responses(body, options = {}) {
|
|
209
209
|
const model = selectedModel(body.model, "gpt");
|
|
210
|
-
if (account) guardConversation(account, body, currentRequestContext()?.clientHeaders || options.headers);
|
|
210
|
+
if (account) { const admission = guardConversation(account, body, currentRequestContext()?.clientHeaders || options.headers, { signal: options.signal });if (admission?.then) await admission; }
|
|
211
211
|
const prepared = await prepareResponsesPayload(body, { ...options.payloadOptions, assertActive: options.assertActive,
|
|
212
212
|
currentInputStart: options.currentInputStart || 0, signal: options.signal,
|
|
213
213
|
profiles: options.payloadPrepared ? [] : options.payloadOptions?.profiles,
|
|
@@ -225,7 +225,7 @@ export function createM365Provider({ home, env = process.env, account: accountOv
|
|
|
225
225
|
async messages(body, options = {}) {
|
|
226
226
|
if (catalog && now() - catalogAt >= SOFT_TTL_MS && !flight) void refresh().catch(() => {});
|
|
227
227
|
const model = selectedModel(body.model, "claude");
|
|
228
|
-
if (account) guardConversation(account, body, options.headers, { profile: profile(), countTokens: options.countTokens === true });
|
|
228
|
+
if (account) { const admission = guardConversation(account, body, options.headers, { profile: profile(), countTokens: options.countTokens === true, signal: options.signal });if (admission?.then) await admission; }
|
|
229
229
|
const efforts = modelReasoningEfforts(model);
|
|
230
230
|
if (body.output_config?.effort !== undefined && efforts && !efforts.includes(body.output_config.effort)) {
|
|
231
231
|
throw protocolError("m365_effort_unavailable", "The selected effort is not advertised by this model. Refresh its model list and select an available effort.");
|
|
@@ -45,6 +45,7 @@ function collectResponseImages(inputItems, currentInputStart, assertActive) {
|
|
|
45
45
|
originalOutput: options.originalOutput,
|
|
46
46
|
usesAnthropicParts: false,
|
|
47
47
|
};
|
|
48
|
+
const before = refs.length;
|
|
48
49
|
for (let partIndex = 0; partIndex < parts.length; partIndex += 1) {
|
|
49
50
|
if ((partIndex & 63) === 0) assertActive?.();
|
|
50
51
|
const identity = inlineImageIdentity(parts[partIndex]);
|
|
@@ -57,7 +58,7 @@ function collectResponseImages(inputItems, currentInputStart, assertActive) {
|
|
|
57
58
|
identity,
|
|
58
59
|
});
|
|
59
60
|
}
|
|
60
|
-
if (refs.
|
|
61
|
+
if (refs.length > before) records.push(record);
|
|
61
62
|
};
|
|
62
63
|
|
|
63
64
|
const historyBoundary = Math.min(Math.max(0, currentInputStart), inputItems.length);
|
|
@@ -218,7 +218,8 @@ export function createResponsesHandler(options) {
|
|
|
218
218
|
autoReviewModelResolver = () => options.providerPreference?.(provider.id);
|
|
219
219
|
if (provider.id !== "github") openAIModelEnv = { ...openAIModelEnv, CCDX_AUTO_REVIEW_MODEL: "" };
|
|
220
220
|
}
|
|
221
|
-
options.validateConversation?.(parsed, req.headers, provider);
|
|
221
|
+
const validation = options.validateConversation?.(parsed, req.headers, provider, abort.signal);
|
|
222
|
+
if (validation?.then) await validation;
|
|
222
223
|
observeContextSession(parsed, req.headers, provider);
|
|
223
224
|
activeDeadline = now() + upstreamTimeoutMs;
|
|
224
225
|
activeTimeoutReason = "responses_prepare_timeout";
|
|
@@ -509,7 +510,8 @@ export function createResponsesCompactHandler(options) {
|
|
|
509
510
|
autoReviewModelResolver = () => options.providerPreference?.(provider.id);
|
|
510
511
|
if (provider.id !== "github") openAIModelEnv = { ...openAIModelEnv, CCDX_AUTO_REVIEW_MODEL: "" };
|
|
511
512
|
}
|
|
512
|
-
options.validateConversation?.(parsed, req.headers, provider);
|
|
513
|
+
const validation = options.validateConversation?.(parsed, req.headers, provider, abort.signal);
|
|
514
|
+
if (validation?.then) await validation;
|
|
513
515
|
observeContextSession(parsed, req.headers, provider);
|
|
514
516
|
activeDeadline = now() + upstreamTimeoutMs;
|
|
515
517
|
activeTimeoutReason = "responses_prepare_timeout";
|