codex-copilot-dx 1.3.17 → 1.3.19
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 +16 -0
- package/docs/REFERENCE.md +18 -3
- package/package.json +1 -1
- package/src/atomic-file.mjs +42 -0
- package/src/bounded-file.mjs +16 -0
- package/src/claude-gateway.mjs +21 -6
- package/src/clients/codex-models.mjs +17 -6
- package/src/codex-app-control.mjs +67 -0
- package/src/codex-image-host.mjs +124 -31
- package/src/codex-launch-control.mjs +132 -0
- package/src/connection-runtime.mjs +5 -4
- package/src/conversation-source-guard.mjs +32 -28
- package/src/dashboard/console.js +2 -2
- package/src/dashboard/features.js +55 -10
- package/src/dashboard/index.html +2 -0
- package/src/dashboard/language.js +28 -0
- package/src/dashboard/status.js +5 -1
- package/src/http-transport.mjs +1 -1
- package/src/image-control.mjs +11 -24
- package/src/image-host-state.mjs +3 -1
- package/src/lock.mjs +6 -6
- package/src/messages-history-transfer.mjs +34 -27
- package/src/native-images.mjs +19 -6
- package/src/providers/api-token-count.mjs +12 -2
- package/src/providers/api.mjs +15 -7
- package/src/providers/m365-conversation-accounts.mjs +29 -16
- package/src/providers/m365.mjs +2 -2
- package/src/response-failures.mjs +8 -3
- package/src/responses-byte-budget.mjs +2 -1
- package/src/responses-handler.mjs +4 -2
- package/src/safe-upstream-error.mjs +79 -0
- package/src/service-control.mjs +18 -5
|
@@ -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
|
@@ -6,6 +6,7 @@ import { readAccessSettings } from "./access-settings.mjs";
|
|
|
6
6
|
import { servicePreferences } from "./user-settings.mjs";
|
|
7
7
|
import { observeRequestedModel, currentRequestContext } from "./request-context.mjs";
|
|
8
8
|
import { recordResponsesUsage } from "./usage-store.mjs";
|
|
9
|
+
import { readSafeUpstreamReason } from "./safe-upstream-error.mjs";
|
|
9
10
|
|
|
10
11
|
export const NATIVE_IMAGE_MODEL = DEFAULT_IMAGE_MODEL;
|
|
11
12
|
export const IMAGE_MAX_BYTES = 32 * 1024 * 1024;
|
|
@@ -57,11 +58,11 @@ export function createNativeImagesHandler({ client, acquireRequest, privacy, env
|
|
|
57
58
|
models = () => [], selection = () => readAccessSettings({ env, home }).clients.codex.image_model,
|
|
58
59
|
requestBodyTimeoutMs = 120000, timeoutMs = 180000, enabled = () => servicePreferences({ env, home }).image_enabled,
|
|
59
60
|
allowed = () => nativeImageAccess({ env, home }) } = {}) {
|
|
60
|
-
let active = 0;
|
|
61
|
+
let active = 0, processing = 0;
|
|
61
62
|
const metrics = { total: 0, succeeded: 0, failed: 0, busy: 0, cancelled: 0 };
|
|
62
63
|
const handler = async (req, res, operation) => {
|
|
63
64
|
const abort = createRequestAbort(req, res);
|
|
64
|
-
let release = () => {}, admitted = false;
|
|
65
|
+
let release = () => {}, admitted = false, processingSlot = false;
|
|
65
66
|
metrics.total++;
|
|
66
67
|
try {
|
|
67
68
|
if (!isLoopbackAddress(req.socket?.remoteAddress) || req.headers.host !== undefined && !isLoopbackHostHeader(req.headers.host)
|
|
@@ -69,8 +70,8 @@ export function createNativeImagesHandler({ client, acquireRequest, privacy, env
|
|
|
69
70
|
if (String(req.headers["content-type"] || "").split(";", 1)[0].trim().toLowerCase() !== "application/json") throw httpError("Images require application/json", 415);
|
|
70
71
|
if (!allowed()) throw httpError("GitHub Copilot access is disabled for Codex", 403);
|
|
71
72
|
if (!enabled()) throw httpError("Image requests are paused", 503);
|
|
72
|
-
if (
|
|
73
|
-
active++;admitted = true;
|
|
73
|
+
if (processing >= 2) { metrics.busy++;throw httpError("Two image requests are already active", 503); }
|
|
74
|
+
active++;processing++;admitted = true;processingSlot = true;
|
|
74
75
|
abort.setTimeout(requestBodyTimeoutMs, "request_body_timeout");
|
|
75
76
|
release = await acquireRequest(req, { signal: abort.signal });
|
|
76
77
|
const parsed = await readJsonBody(req, { admission: release, signal: abort.signal, maxBodyBytes: BODY_MAX_BYTES, maxDecodedBodyBytes: BODY_MAX_BYTES });
|
|
@@ -87,7 +88,19 @@ export function createNativeImagesHandler({ client, acquireRequest, privacy, env
|
|
|
87
88
|
const forward = input => client.images(operation, { ...body, prompt: input.input }, { signal: abort.signal });
|
|
88
89
|
const call = privacy?.wrap ? privacy.wrap(forward, { res, protocol: "responses", client: "codex" }) : forward;
|
|
89
90
|
const response = await call({ input: body.prompt }, { signal: abort.signal });
|
|
90
|
-
if (!response.ok) {
|
|
91
|
+
if (!response.ok) {
|
|
92
|
+
metrics.failed++;
|
|
93
|
+
// The upstream request has finished. Do not hold image concurrency or
|
|
94
|
+
// body admission while an optional error reason is read.
|
|
95
|
+
release();release = () => {};processing--;processingSlot = false;
|
|
96
|
+
const reason = await readSafeUpstreamReason(response, { signal: abort.signal });
|
|
97
|
+
abort.signal.throwIfAborted();
|
|
98
|
+
const code = `ccdx_images_http_${response.status}`, headers = new Headers(response.headers);
|
|
99
|
+
headers.set("Content-Type", "application/json");
|
|
100
|
+
sendUpstreamError(res, { status: response.status, headers }, JSON.stringify({ error: { type: "upstream_error", code,
|
|
101
|
+
message: reason?.message || code, ...(reason ? { upstream_code: reason.code } : {}) } }));
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
91
104
|
const text = await readBoundedResponseText(response, { maxBytes: RESPONSE_MAX_BYTES, signal: abort.signal, label: "Copilot image response" });
|
|
92
105
|
let result;
|
|
93
106
|
try { result = JSON.parse(text); } catch { throw httpError("Copilot returned invalid image JSON", 502); }
|
|
@@ -104,7 +117,7 @@ export function createNativeImagesHandler({ client, acquireRequest, privacy, env
|
|
|
104
117
|
if (abort.reason === "client_closed" || abort.reason === "client_aborted") metrics.cancelled++;
|
|
105
118
|
logRequestFailure("images", error, abort);
|
|
106
119
|
sendJsonError(res, error, error.statusCode || 502);
|
|
107
|
-
} finally { release();if (admitted) active--;abort.cleanup(); }
|
|
120
|
+
} finally { release();if (admitted) active--;if (processingSlot) processing--;abort.cleanup(); }
|
|
108
121
|
};
|
|
109
122
|
handler.stats = () => ({ ...metrics, active, native: true, model: imageModelSelection(models(), selection()).selected_model });
|
|
110
123
|
return handler;
|
|
@@ -19,7 +19,8 @@ export function createApiTokenCounter({ request, now = Date.now }) {
|
|
|
19
19
|
const serialized = JSON.stringify(body), size = Buffer.byteLength(serialized), hash = size <= 1024 * 1024 ? createHash("sha256").update(scope).update(serialized).digest("hex") : null;
|
|
20
20
|
const identity = hash || {};
|
|
21
21
|
async function run(probe) {
|
|
22
|
-
const key = probe ? "probe:" + scope : "body:" + hash, waiter = { start: options.onUpstreamStart, observe: options.onCountObservation,
|
|
22
|
+
const key = probe ? "probe:" + scope : "body:" + hash, waiter = { start: options.onUpstreamStart, observe: options.onCountObservation,
|
|
23
|
+
errorHeaders: options.onUpstreamErrorHeaders, signal: options.signal, identity };
|
|
23
24
|
let flight = flights.get(key);
|
|
24
25
|
if (flight && [...flight.waiters].every(item => item.signal?.aborted)) { flights.delete(key);bytes -= flight.bytes;flight = null; }
|
|
25
26
|
const joinable = (probe || hash !== null) && (Boolean(flight) || flights.size < 16 && (probe || bytes + size <= 4 * 1024 * 1024));
|
|
@@ -33,11 +34,20 @@ export function createApiTokenCounter({ request, now = Date.now }) {
|
|
|
33
34
|
item.observe?.(item.identity === flight.identity ? { upstream: true, shared: flight.shared } : { waited: true });
|
|
34
35
|
};
|
|
35
36
|
if (flight.started) start(waiter);
|
|
37
|
+
if (flight.errorStatus && (flight.errorStatus === 404 || waiter.identity === flight.identity)) {
|
|
38
|
+
try { waiter.errorHeaders?.(flight.errorStatus); } catch {}
|
|
39
|
+
}
|
|
36
40
|
const task = async signal => {
|
|
37
41
|
try {
|
|
38
42
|
if (signal?.aborted) throw signal.reason;
|
|
39
43
|
const response = await request(body, { ...options, bodyText: serialized, signal, observeUpstream: false,
|
|
40
|
-
onUpstreamStart() { flight.started = true;for (const item of flight.waiters) if (!item.signal?.aborted) start(item); }
|
|
44
|
+
onUpstreamStart() { flight.started = true;for (const item of flight.waiters) if (!item.signal?.aborted) start(item); },
|
|
45
|
+
onUpstreamErrorHeaders(status) {
|
|
46
|
+
flight.errorStatus = status;
|
|
47
|
+
for (const item of flight.waiters) if (!item.signal?.aborted && (status === 404 || item.identity === flight.identity)) {
|
|
48
|
+
try { item.errorHeaders?.(status); } catch {}
|
|
49
|
+
}
|
|
50
|
+
} });
|
|
41
51
|
if (signal?.aborted) { await response.body?.cancel();throw signal.reason; }
|
|
42
52
|
if (response.status === 404) {
|
|
43
53
|
await response.body?.cancel();observe(scope, 404);const result = missed();
|
package/src/providers/api.mjs
CHANGED
|
@@ -5,11 +5,12 @@ 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";
|
|
12
12
|
import { transportErrorDetails } from "../operation-error.mjs";
|
|
13
|
+
import { readSafeUpstreamReason } from "../safe-upstream-error.mjs";
|
|
13
14
|
import { resolveModelCapabilities, deploymentRevision, constrainModelRequest } from "../model-capabilities.mjs";
|
|
14
15
|
import { apiModelMetadata } from "./api-model-metadata.mjs";
|
|
15
16
|
import { markRequestObservation, markUpstreamStarted } from "../stream-performance.mjs";
|
|
@@ -85,11 +86,13 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
85
86
|
const result = await transport.fetch(url, { method: body ? "POST" : "GET", headers, body: serialized, signal: options.signal });
|
|
86
87
|
if (result.status >= 300 && result.status < 400) { await result.body?.cancel();throw accessError("ccdx_api_redirect_refused", 502); }
|
|
87
88
|
if (!result.ok) {
|
|
88
|
-
|
|
89
|
+
try { options.onUpstreamErrorHeaders?.(result.status); } catch { /* Optional admission release cannot hide the upstream response. */ }
|
|
90
|
+
const reason = await readSafeUpstreamReason(result, { signal: options.signal });const code = `ccdx_api_http_${result.status}`;
|
|
89
91
|
const safeHeaders = { "Content-Type": "application/json" }, retry = result.headers.get("retry-after");
|
|
90
92
|
if (/^\d{1,8}$/.test(retry || "")) safeHeaders["Retry-After"] = retry;
|
|
91
93
|
else if (retry && Number.isFinite(Date.parse(retry))) safeHeaders["Retry-After"] = new Date(retry).toUTCString();
|
|
92
|
-
return new Response(JSON.stringify({ type: "error", error: { type: "api_error", code, message:
|
|
94
|
+
return new Response(JSON.stringify({ type: "error", error: { type: "api_error", code, message: reason?.message || code,
|
|
95
|
+
...(reason ? { upstream_code: reason.code } : {}) } }), { status: result.status, headers: safeHeaders });
|
|
93
96
|
}
|
|
94
97
|
return result;
|
|
95
98
|
} catch (error) {
|
|
@@ -160,10 +163,15 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
160
163
|
applyRequestPolicies() {},
|
|
161
164
|
compatibility: { hasRetry: () => false, selectRetry: async () => null,
|
|
162
165
|
async openResponse(context, upstream, options) {
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
if (!
|
|
166
|
+
let headersObserved = false;
|
|
167
|
+
const resp = await upstream(context.body, { assertActive: options.assertPrepareActive, signal: options.signal, currentInputStart: context.currentInputStart, onUpstreamStart: options.onUpstreamStart,
|
|
168
|
+
onUpstreamErrorHeaders(status) { headersObserved = true;markUpstreamHeaders(status);options.releaseRequest?.(context); } });
|
|
169
|
+
if (!headersObserved) markUpstreamHeaders(resp.status);
|
|
170
|
+
// request() already discarded the vendor body and projected a safe error.
|
|
171
|
+
if (!resp.ok) {
|
|
172
|
+
const errorText = await readBoundedResponseText(resp, { maxBytes: MAX_UPSTREAM_ERROR_BODY_BYTES, signal: options.signal, label: "API error response" });
|
|
173
|
+
return { resp, reqContext: context, errorText, usedRetryPolicies: new Set() };
|
|
174
|
+
}
|
|
167
175
|
return { resp, reqContext: context, errorText: undefined, usedRetryPolicies: new Set() };
|
|
168
176
|
} },
|
|
169
177
|
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.");
|
|
@@ -2,6 +2,7 @@ import { boundedDiagnosticText, redactDiagnosticText } from "./diagnostic-text.m
|
|
|
2
2
|
import { currentRequestContext } from "./request-context.mjs";
|
|
3
3
|
import { isProviderId } from "./provider-metadata.mjs";
|
|
4
4
|
import { transportErrorDetails } from "./operation-error.mjs";
|
|
5
|
+
import { safeUpstreamReason } from "./safe-upstream-error.mjs";
|
|
5
6
|
|
|
6
7
|
const DEFAULT_RECENT_FAILURES = 10;
|
|
7
8
|
|
|
@@ -104,7 +105,7 @@ export function createResponseFailureDiagnostics({
|
|
|
104
105
|
};
|
|
105
106
|
}
|
|
106
107
|
|
|
107
|
-
export function upstreamErrorEvidence(text, { includeMessage = false } = {}) {
|
|
108
|
+
export function upstreamErrorEvidence(text, { includeMessage = false, status = null } = {}) {
|
|
108
109
|
const errorBody = !String(text || "").trim() ? "empty" : "unstructured";
|
|
109
110
|
let error;
|
|
110
111
|
try { const parsed = JSON.parse(text); error = parsed?.error; } catch {}
|
|
@@ -115,7 +116,10 @@ export function upstreamErrorEvidence(text, { includeMessage = false } = {}) {
|
|
|
115
116
|
const param = typeof error.param === "string" && error.param.length <= 160
|
|
116
117
|
&& /^(?:model|input|tools|tool_choice|reasoning|text|temperature|top_p|max_output_tokens|service_tier|store|stream|include|previous_response_id|parallel_tool_calls)(?:\.[a-z_][a-z\d_]*|\[\d+\])*$/i.test(error.param)
|
|
117
118
|
? error.param : undefined;
|
|
119
|
+
const upstreamCode = (safeUpstreamReason(error.upstream_code, status) || safeUpstreamReason(error.code, status)
|
|
120
|
+
|| safeUpstreamReason(error.type, status))?.code;
|
|
118
121
|
return { error_body: "structured", code: technical(error.code), error_type: technical(error.type),
|
|
122
|
+
...(upstreamCode ? { upstream_code: upstreamCode } : {}),
|
|
119
123
|
parameter: param, ...(includeMessage && typeof error.message === "string" ? { diagnostic_message: safeFailureMessage(error.message) } : {}) };
|
|
120
124
|
}
|
|
121
125
|
|
|
@@ -179,7 +183,7 @@ export function isDiscoveryRequest(method, pathname) {
|
|
|
179
183
|
}
|
|
180
184
|
|
|
181
185
|
export function buildHttpFailureDetails({ statusCode, route, requestId, model, code, origin, headers, model_error,
|
|
182
|
-
error_body, error_type, parameter, diagnostic_message, method, target, request_options, upstream_attempts, attempt_timings, requested_model, provider,
|
|
186
|
+
error_body, error_type, upstream_code, parameter, diagnostic_message, method, target, request_options, upstream_attempts, attempt_timings, requested_model, provider,
|
|
183
187
|
application, reason, capability_cached, shared_upstream, transport }) {
|
|
184
188
|
if (!reason && code === "ccdx_client_source_disabled" && upstream_attempts === 0 && origin !== "upstream_http") {
|
|
185
189
|
reason = code;origin = "client_validation";
|
|
@@ -204,7 +208,8 @@ export function buildHttpFailureDetails({ statusCode, route, requestId, model, c
|
|
|
204
208
|
message: model_error ? "The model source reported an error; the original HTTP response was preserved." : message } }, model_error ? "model.error" : "http.error", { headers, provider });
|
|
205
209
|
return { ...details, request_id: requestId, http_status: statusCode, route,
|
|
206
210
|
origin: origin || (route === "not_found" ? "route" : "unclassified"), local_message: true,
|
|
207
|
-
...(error_body ? { error_body } : {}), ...(error_type ? { error_type } : {}),
|
|
211
|
+
...(error_body ? { error_body } : {}), ...(error_type ? { error_type } : {}),
|
|
212
|
+
...(safeUpstreamReason(upstream_code, statusCode) ? { upstream_code } : {}), ...(parameter ? { parameter } : {}),
|
|
208
213
|
...(diagnostic_message ? { diagnostic_message } : {}),
|
|
209
214
|
...(method ? { method } : {}), ...(target ? { target } : {}),
|
|
210
215
|
...(request_options ? { request_options } : {}),
|
|
@@ -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";
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// Only fixed, documented-shaped codes leave this module; vendor messages and
|
|
2
|
+
// request data are never returned or logged.
|
|
3
|
+
const reasons = new Map([
|
|
4
|
+
["credit_balance_exhausted", { statuses: [429], message: "The source account has no remaining credits." }],
|
|
5
|
+
["insufficient_quota", { statuses: [429], message: "The source account has insufficient quota." }],
|
|
6
|
+
["quota_exceeded", { statuses: [429], message: "The source account has exceeded its quota." }],
|
|
7
|
+
["rate_limit_exceeded", { statuses: [429], message: "The source request rate limit was reached." }],
|
|
8
|
+
["rate_limit_error", { statuses: [429], message: "The source request rate limit was reached." }],
|
|
9
|
+
["context_length_exceeded", { statuses: [400, 413, 422], message: "The source reports that the context is too long." }],
|
|
10
|
+
["context_window_exceeded", { statuses: [400, 413, 422], message: "The source reports that the context is too long." }],
|
|
11
|
+
["content_policy_violation", { statuses: [400, 403, 422], message: "The source rejected the request under its content policy." }],
|
|
12
|
+
]);
|
|
13
|
+
const MAX_ACTIVE_READS = 4;
|
|
14
|
+
let activeReads = 0;
|
|
15
|
+
|
|
16
|
+
function cancelBody(body) {
|
|
17
|
+
try { void Promise.resolve(body?.cancel()).catch(() => {}); } catch {}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function safeUpstreamReason(code, status) {
|
|
21
|
+
const reason = typeof code === "string" ? reasons.get(code) : null;
|
|
22
|
+
return reason?.statuses.includes(status) ? { code, message: reason.message } : null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function readChunk(reader, signal) {
|
|
26
|
+
if (signal.aborted) return Promise.reject(signal.reason);
|
|
27
|
+
return new Promise((resolve, reject) => {
|
|
28
|
+
let settled = false;
|
|
29
|
+
const finish = (fn, value) => { if (settled) return;settled = true;signal.removeEventListener("abort", onAbort);fn(value); };
|
|
30
|
+
const onAbort = () => finish(reject, signal.reason);
|
|
31
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
32
|
+
reader.read().then(value => finish(resolve, value), error => finish(reject, error));
|
|
33
|
+
if (signal.aborted) onAbort();
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Failure responses only. A stalled body or a stalled cancellation cannot delay
|
|
38
|
+
// the caller beyond the budget. The original request's cancellation wins.
|
|
39
|
+
export async function readSafeUpstreamReason(response, { signal, timeoutMs = 200, maxBytes = 64 * 1024 } = {}) {
|
|
40
|
+
if (signal?.aborted) {
|
|
41
|
+
cancelBody(response?.body);
|
|
42
|
+
signal.throwIfAborted();
|
|
43
|
+
}
|
|
44
|
+
if (!response?.body) return null;
|
|
45
|
+
if (activeReads >= MAX_ACTIVE_READS) { cancelBody(response.body);return null; }
|
|
46
|
+
activeReads++;
|
|
47
|
+
const deadline = performance.now() + timeoutMs;
|
|
48
|
+
const controller = new AbortController(), timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
49
|
+
const readSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
|
|
50
|
+
let reader, finished = false;
|
|
51
|
+
try {
|
|
52
|
+
const length = Number(response.headers?.get?.("content-length"));
|
|
53
|
+
if (Number.isFinite(length) && length > maxBytes) return null;
|
|
54
|
+
reader = response.body.getReader();const chunks = [];let bytes = 0;
|
|
55
|
+
while (true) {
|
|
56
|
+
if (performance.now() >= deadline) controller.abort();
|
|
57
|
+
const { done, value } = await readChunk(reader, readSignal);
|
|
58
|
+
if (done) { finished = true;break; }
|
|
59
|
+
if (Number.isFinite(value?.byteLength) && bytes + value.byteLength > maxBytes) return null;
|
|
60
|
+
const chunk = Buffer.from(value);bytes += chunk.length;
|
|
61
|
+
if (bytes > maxBytes) return null;
|
|
62
|
+
chunks.push(chunk);
|
|
63
|
+
}
|
|
64
|
+
let value;try { value = JSON.parse(Buffer.concat(chunks, bytes).toString("utf8")); } catch { return null; }
|
|
65
|
+
const error = value?.error;
|
|
66
|
+
if (!error || typeof error !== "object" || Array.isArray(error)) return null;
|
|
67
|
+
return safeUpstreamReason(error.code, response.status) || safeUpstreamReason(error.type, response.status);
|
|
68
|
+
} catch (error) {
|
|
69
|
+
if (signal?.aborted) signal.throwIfAborted();
|
|
70
|
+
return null;
|
|
71
|
+
} finally {
|
|
72
|
+
clearTimeout(timer);
|
|
73
|
+
if (!finished) {
|
|
74
|
+
try { void Promise.resolve(reader ? reader.cancel() : response.body.cancel()).catch(() => {}); } catch {}
|
|
75
|
+
}
|
|
76
|
+
try { reader?.releaseLock(); } catch {}
|
|
77
|
+
activeReads--;
|
|
78
|
+
}
|
|
79
|
+
}
|
package/src/service-control.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createImageHostState } from "./image-host-state.mjs";
|
|
2
2
|
import { controlImage } from "./image-control.mjs";
|
|
3
|
+
import { controlCodexLaunch } from "./codex-launch-control.mjs";
|
|
3
4
|
import { serviceSettingsSnapshot, servicePreferences, writeServicePreference,
|
|
4
5
|
writeTerminalAnimationTheme, writeTerminalColorTheme, responseHistoryLimitPreference, writeResponseHistoryLimitMib,
|
|
5
6
|
nightlyUpdatePreference, writeNightlyUpdatePreference, decodedBodyLimitPreference, writeDecodedBodyLimitMib } from "./user-settings.mjs";
|
|
@@ -12,7 +13,7 @@ import { imageSetupSummary, configureImageSetup } from "./image-setup.mjs";
|
|
|
12
13
|
|
|
13
14
|
export function createServiceControl({ env = process.env, home, providerRuntime, clientIntegration, terminal,
|
|
14
15
|
nightlyStatus = () => null, nightlyChanged = () => {},
|
|
15
|
-
manualUpdate, predictionControl = controlPrediction, imageControl = configureImageSetup, imageHostControl = controlImage,
|
|
16
|
+
manualUpdate, predictionControl = controlPrediction, imageControl = configureImageSetup, imageHostControl = controlImage, codexLaunchControl = controlCodexLaunch,
|
|
16
17
|
adapterPort = 2026, adapterHost = "127.0.0.1",
|
|
17
18
|
readImages = () => imageSetupSummary({ env, home }).configured, readPrediction = () => readPredictionSettings({ env, home }) } = {}) {
|
|
18
19
|
const options = { env, home };
|
|
@@ -46,17 +47,20 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
46
47
|
if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("Invalid setting action");
|
|
47
48
|
const allowed = { preference: ["action", "key", "value"], nightly_update: ["action", "enabled"], animation: ["action", "theme"], color_theme: ["action", "theme"],
|
|
48
49
|
history_limit: ["action", "mib"], history_clean: ["action"], prediction_fix: ["action"],
|
|
49
|
-
prediction: ["action", "operation"], image: ["action", "operation", "model", "evidence"],
|
|
50
|
+
prediction: ["action", "operation"], image: ["action", "operation", "model", "evidence", "confirmed"],
|
|
51
|
+
codex_app: ["action", "operation", "intent", "confirmed"],
|
|
50
52
|
update: ["action", "confirmed"], decoded_limit: ["action", "mib"],
|
|
51
53
|
preferences: ["action", "values", "revision"], reset_preferences: ["action", "revision", "backup_id", "scope"], restore_preferences: ["action", "revision", "backup_id", "scope"],
|
|
52
54
|
provider: ["action", "operation", "provider", "model", "auto_review_model", "auto_review_effort", "account_id"] }[input.action];
|
|
53
55
|
if (!allowed || Object.keys(input).some(key => !allowed.includes(key))) throw new Error("Unknown setting action or field");
|
|
54
56
|
lastOperation = null;
|
|
55
|
-
if (input.action === "
|
|
57
|
+
if (input.action === "codex_app") {
|
|
58
|
+
lastOperation = { feature: "codex_app", result: await codexLaunchControl(input.operation, { ...options, host: adapterHost, port: adapterPort,
|
|
59
|
+
integration: clientIntegration, state: imageHostState, intent: input.intent, confirmed: input.confirmed, models: providerRuntime?.imageModels?.().models || [] }) };
|
|
60
|
+
} else if (input.action === "prediction") {
|
|
56
61
|
lastOperation = { feature: "prediction", result: await predictionControl(input.operation, { ...options, integration: clientIntegration }) };
|
|
57
62
|
} else if (input.action === "image") {
|
|
58
|
-
if (input.operation
|
|
59
|
-
else if (["check", "repair", "open"].includes(input.operation)) lastOperation = { feature: "image", result: await imageHostControl(input.operation, { ...options, host: adapterHost, port: adapterPort, integration: clientIntegration, state: imageHostState, models: providerRuntime?.imageModels?.().models || [] }) };
|
|
63
|
+
if (["check", "repair", "open", "focus", "restart"].includes(input.operation)) lastOperation = { feature: "image", result: await imageHostControl(input.operation, { ...options, host: adapterHost, port: adapterPort, integration: clientIntegration, state: imageHostState, confirmed: input.confirmed, models: providerRuntime?.imageModels?.().models || [] }) };
|
|
60
64
|
else if (["pause", "resume"].includes(input.operation)) writeServicePreference("image_enabled", input.operation === "resume", options);
|
|
61
65
|
else lastOperation = { feature: "image", result: await imageControl(input, { ...options, providerRuntime, adapterPort, adapterHost }) };
|
|
62
66
|
} else if (input.action === "update") {
|
|
@@ -108,6 +112,15 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
108
112
|
return snapshot();
|
|
109
113
|
}
|
|
110
114
|
return { snapshot, busy: () => pending > 0, action(input) {
|
|
115
|
+
// Image-host evidence must not wait behind a user-initiated App restart:
|
|
116
|
+
// the host sends it with a short deadline as the new App starts.
|
|
117
|
+
if (input?.action === "image" && input.operation === "report") {
|
|
118
|
+
try {
|
|
119
|
+
if (Object.keys(input).some(key => !["action", "operation", "evidence"].includes(key))) throw new Error("Unknown setting action or field");
|
|
120
|
+
imageHostState.report(input.evidence);terminal?.image?.(imageHostState.snapshot());
|
|
121
|
+
return Promise.resolve(snapshot());
|
|
122
|
+
} catch (error) { return Promise.reject(error); }
|
|
123
|
+
}
|
|
111
124
|
const counted = input?.action !== "update";if (counted) pending++;
|
|
112
125
|
const operation = serial.then(() => apply(input)).finally(() => { if (counted) pending--; });serial = operation.catch(() => {});return operation;
|
|
113
126
|
} };
|