codex-copilot-dx 0.9.34 → 0.9.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/bin/cli.mjs +3 -1
- package/docs/ARCHITECTURE.md +12 -0
- package/docs/REFERENCE.md +34 -0
- package/package.json +1 -1
- package/src/adapter.mjs +7 -0
- package/src/dashboard/index.html +1 -1
- package/src/dashboard/ui.css +1 -1
- package/src/local-compaction-recovery.mjs +56 -12
- package/src/package-update.mjs +20 -1
- package/src/profile-model-runtime.mjs +1 -1
- package/src/responses-bridge.mjs +22 -7
- package/src/responses-chat-payload.mjs +6 -5
- package/src/responses-handler.mjs +2 -0
- package/src/status.mjs +2 -1
- package/src/stream-performance.mjs +6 -0
package/README.md
CHANGED
|
@@ -82,11 +82,11 @@ Auto refresh runs every 30 minutes while visible and can be switched off. Hidden
|
|
|
82
82
|
use public HTTPS URLs; well-known NAT64 mappings follow IPv4 address rules.
|
|
83
83
|
- Keep the adapter on loopback. LAN mode is only for trusted networks; do not
|
|
84
84
|
expose it to the public internet. The dashboard is not an authentication wall
|
|
85
|
-
for the API. Diagnostic errors may contain sensitive upstream text.
|
|
85
|
+
for the API. Inference rejects browser Origin headers; native clients remain supported. Diagnostic errors may contain sensitive upstream text.
|
|
86
86
|
|
|
87
87
|
Startup checks GitHub's latest-release web redirect, not npm or the anonymous REST quota, and suggests `ccdx update github`.
|
|
88
88
|
Updates install the exact stable tag; dependencies still use npm's configured registry. Lookup errors identify HTTP refusal, timeout, network failure or invalid redirects.
|
|
89
|
-
Updates warn about mismatched npm targets without changing PATH/prefix. Full `ccdx doctor` reports this target and readonly credential permissions; it never changes ACLs.
|
|
89
|
+
Updates warn about mismatched npm targets without changing PATH/prefix and verify the installed target version (exact tag for GitHub). Restart the adapter separately. Full `ccdx doctor` reports this target and readonly credential permissions; it never changes ACLs.
|
|
90
90
|
Recent errors separate HTTP and model failures. HTTP metadata retains status, source and IDs, not error bodies or prompts; original errors still reach Codex unchanged.
|
|
91
91
|
|
|
92
92
|
The dashboard and CLI separate prediction preference, bridge state and observed config traffic; candidate visibility stays unknown.
|
package/bin/cli.mjs
CHANGED
|
@@ -372,13 +372,14 @@ try {
|
|
|
372
372
|
await ensureAuth({ log: startupLogger("Auth") });
|
|
373
373
|
|
|
374
374
|
const profileRuntime = createProfileRuntime({ codexClient: defaultCopilotClient });
|
|
375
|
+
let startupComplete = false;
|
|
375
376
|
const profileModels = createProfileModelRuntime({
|
|
376
377
|
codexClient: profileRuntime.codexClient,
|
|
377
378
|
codexCredentialFingerprint: profileRuntime.codexCredentialFingerprint,
|
|
378
379
|
timeoutMs: MODEL_REFRESH_TIMEOUT_MS,
|
|
379
380
|
commandName: CLI_NAME,
|
|
380
381
|
autoReviewModelResolver: () => autoReviewModelPreference().model,
|
|
381
|
-
log: (kind, message) => console.log(startupCheck(kind, "Models", message)),
|
|
382
|
+
log: (kind, message) => console.log(startupComplete ? status(kind, message) : startupCheck(kind, "Models", message)),
|
|
382
383
|
});
|
|
383
384
|
|
|
384
385
|
// Refresh the VS Code version in the background; fallback is non-blocking.
|
|
@@ -435,6 +436,7 @@ try {
|
|
|
435
436
|
modelRefreshTimer.unref?.();
|
|
436
437
|
}
|
|
437
438
|
|
|
439
|
+
startupComplete = true;
|
|
438
440
|
console.log(startupReady({ baseUrl: adapterBaseUrl(ADAPTER_HOST, ADAPTER_PORT), commandName: CLI_NAME }));
|
|
439
441
|
|
|
440
442
|
const shutdown = async (signal) => {
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -17,6 +17,8 @@ The CLI composes the service. Client integration owns its `configure`, `start`,
|
|
|
17
17
|
`snapshot` and `close` operations. It does not forward inference requests or
|
|
18
18
|
render the dashboard. The adapter exposes integration snapshots and keeps
|
|
19
19
|
management/MCP routes separate from the Responses path.
|
|
20
|
+
The HTTP dispatch boundary rejects browser Origin-bearing inference requests
|
|
21
|
+
before body admission, credential use or provider dispatch; native LAN opt-in is unchanged.
|
|
20
22
|
|
|
21
23
|
Package installation is an explicit management operation in `package-update.mjs`,
|
|
22
24
|
not part of inference or optional client integration. Windows uses the system
|
|
@@ -29,6 +31,9 @@ global target. A different target warns, but never changes PATH or prefix. Its
|
|
|
29
31
|
bounded npm probe is limited to explicit update and full doctor commands.
|
|
30
32
|
Its stdout/stderr are captured separately; npm configuration warnings do not
|
|
31
33
|
leak into doctor output. The real installer's inherited streams are unchanged.
|
|
34
|
+
After installation, the updater verifies bounded package metadata at that same
|
|
35
|
+
selected target, with exact-version verification for GitHub. It never equates
|
|
36
|
+
installation with replacement of an already-running service.
|
|
32
37
|
|
|
33
38
|
Authentication keeps its public facade in `auth.mjs`. Device-code polling and
|
|
34
39
|
cancellation live in `auth-device-flow.mjs`; local discovery and transactional
|
|
@@ -95,6 +100,10 @@ Without a complete verified local source, rejection still returns
|
|
|
95
100
|
`ccdx_history_rebuild_required`, without modifying stored history. Diagnostic
|
|
96
101
|
metadata cannot reconstruct unavailable encrypted memory. LAN/browser callers
|
|
97
102
|
and referenced/split histories do not gain filesystem recovery access.
|
|
103
|
+
The recovery module reuses the existing abort-aware singleflight for equivalent
|
|
104
|
+
source reads, not prepared requests or reservation handles. Caller validation and
|
|
105
|
+
admission remain independent. Only bounded snapshot-bound failure codes survive
|
|
106
|
+
settlement for two seconds; no successful plaintext cache or transcript index exists.
|
|
98
107
|
|
|
99
108
|
## Dashboard reads
|
|
100
109
|
|
|
@@ -146,6 +155,9 @@ dashboard merges recent HTTP, model and request-timeline failures for display.
|
|
|
146
155
|
Tests cover module dependency direction, default-off behavior, concurrent writers,
|
|
147
156
|
proxy handshakes, TLS validation, streaming, history isolation and release lookup.
|
|
148
157
|
Performance measurements distinguish request preparation from model latency.
|
|
158
|
+
Actual loopback HTTP tests gate first-delta delivery before provider completion
|
|
159
|
+
and cancellation propagation for both native Responses and Chat translation.
|
|
160
|
+
Empty-stream diagnostics are additive scalar metadata, not a new retry policy.
|
|
149
161
|
Release reports describe a specific environment, not an SLA or a guarantee of
|
|
150
162
|
compatibility with every future client or corporate network policy.
|
|
151
163
|
CI runs Node 22.15 and 24 on Linux, Windows and macOS. The owned temporary-prefix
|
package/docs/REFERENCE.md
CHANGED
|
@@ -262,6 +262,13 @@ One in-process adapter listens on `127.0.0.1:2026` by default and exposes:
|
|
|
262
262
|
|
|
263
263
|
Responses-only models and compaction use Copilot's Responses transport directly. For requests routed through Chat Completions, CCDX converts the supported text, image, and function-tool subset and rejects incompatible message content rather than turning it into JSON text. Chat `length` and `content_filter` finish reasons become incomplete Responses in both streaming and non-streaming modes. Both streaming SSE and non-streaming responses are supported.
|
|
264
264
|
|
|
265
|
+
Chat conversion maps an explicitly supplied `reasoning.effort` to `reasoning_effort`.
|
|
266
|
+
Known effort values are checked against the existing model catalog when it advertises
|
|
267
|
+
an effort array; without that metadata, upstream validation remains authoritative.
|
|
268
|
+
No extra model lookup is made. Malformed function tools, forced undeclared functions,
|
|
269
|
+
unsupported tool-choice strings and unknown text formats receive a local compatibility
|
|
270
|
+
error instead of being dropped. Native Responses request fields are not changed by this check.
|
|
271
|
+
|
|
265
272
|
The adapter handles response history, encrypted reasoning state, function/custom tools, images, compaction, cancellation, retries, and usage metadata within the compatibility boundaries below. Routing prefers endpoint metadata from Copilot's live or cached catalog; when metadata is unavailable, a small built-in set identifies known Responses-only GPT models.
|
|
266
273
|
|
|
267
274
|
### Local compaction recovery
|
|
@@ -297,6 +304,15 @@ a 16-candidate bound. Decoded reads and the rebuilt body are bounded by the
|
|
|
297
304
|
running adapter's decoded-body limit; history admission reservations cover
|
|
298
305
|
recovery preparation. Requests cannot retry after visible output has begun.
|
|
299
306
|
|
|
307
|
+
Overlapping equivalent recovery readers share in-flight source discovery/decoding,
|
|
308
|
+
with independent cancellation and independent restored requests. Every caller retains
|
|
309
|
+
its admission reservation; exclusive admission can serialize reads instead of sharing.
|
|
310
|
+
Successful plaintext is not retained after the flight settles. Up to 32 failure-code
|
|
311
|
+
records last two seconds, keyed by the exact source file identity/size/timestamps,
|
|
312
|
+
thread, compaction digest and byte limit. Directory discovery still runs; missing
|
|
313
|
+
sources, cancellation, deadlines and unstable snapshots are not cached. Source changes
|
|
314
|
+
invalidate reuse. No transcript index, watcher or healthy-request scan is added.
|
|
315
|
+
|
|
300
316
|
Neither the original rollout nor client configuration is rewritten. Recovery
|
|
301
317
|
diagnostics contain type/count/status metadata, not transcript text, ciphertext
|
|
302
318
|
or file paths. If verification fails, `ccdx_history_rebuild_required` includes
|
|
@@ -411,6 +427,9 @@ Credentials found are not labeled online-authorized, cached model lists are not
|
|
|
411
427
|
labeled fresh upstream data, and image configuration is not a provider test.
|
|
412
428
|
Ready reports core readiness independently of optional prediction/image warnings.
|
|
413
429
|
Model refresh logs show counts; `ccdx models` retains the complete live list.
|
|
430
|
+
After Ready, background refresh uses the same two-column status/message layout as
|
|
431
|
+
other runtime logs. Status messages remove terminal controls and collapse newlines;
|
|
432
|
+
the static banner and multiline interactive prompts retain their own presentation.
|
|
414
433
|
VS Code compatibility-version details remain available in debug logging. Startup
|
|
415
434
|
does not wait for optional update/compression work or add online doctor/model probes.
|
|
416
435
|
|
|
@@ -574,6 +593,14 @@ Installer errors and nonzero exits fail the update without a success message or
|
|
|
574
593
|
automatic retry. Missing Git, blocked dependency downloads or npm cache-only
|
|
575
594
|
settings remain npm/environment errors, not fixed by changing the launcher.
|
|
576
595
|
|
|
596
|
+
After a zero installer exit, CCDX reads bounded metadata from npm's selected global
|
|
597
|
+
target and verifies the package name and stable version. GitHub requires the exact
|
|
598
|
+
selected release version. A missing/mismatched target fails verification without
|
|
599
|
+
retrying installation; if the global target could not be discovered, the command
|
|
600
|
+
explicitly reports that the installed version is unverified rather than announcing
|
|
601
|
+
an update. This check neither changes PATH/prefix/registry nor restarts a running
|
|
602
|
+
adapter, and it does not verify package-file integrity or npm's current latest tag.
|
|
603
|
+
|
|
577
604
|
Normal startup checks the official GitHub `releases/latest` web endpoint once in
|
|
578
605
|
the background, without accessing the npm registry or REST API. The anonymous
|
|
579
606
|
check requires no PAT or Copilot credentials, has a two-second deadline, validates
|
|
@@ -697,6 +724,12 @@ curl -s http://127.0.0.1:2026/_ccdx/status | jq
|
|
|
697
724
|
|
|
698
725
|
The status endpoint is restricted to the socket's real loopback address even when LAN binding is explicitly enabled. It reports fixed-size HTTP request counters separately from bounded `completed` / `incomplete` / `failed` / `cancelled` response outcomes by model and origin, plus bounded incomplete-reason counts, TTFT/TPOT histograms, admission pressure, memory use, response-history size/tree concentration/lookup misses, image queue/cache and adaptive-history state, model-cache counts, token expiry state, and the ten most recent upstream `response.failed` diagnostics retained by the running process. HTTP errors without a model terminal remain "without terminal" and retain their known origin; they are not counted as model failures. History eviction markers are not failed-request counts; `ccdx status` warns near the cache limit without deleting or compressing history. Failure diagnostics include the event type, model, error code/message, response/request IDs when supplied upstream, and retry outcome. Common credential forms, long opaque encrypted values, and explicitly labelled input/prompt/tool-content echoes are redacted. They are cleared when the adapter restarts. No request/response bodies, credential fields, or account profiles are copied into status. Arbitrary upstream prose cannot be guaranteed free of sensitive content; review diagnostics before sharing them.
|
|
699
726
|
|
|
727
|
+
`stream_performance.by_route.*.empty_stream_completions` counts completed streams
|
|
728
|
+
with no observed output and an explicit zero output-token count. The recent request's
|
|
729
|
+
`empty_stream_completion` flag records the same condition. Missing usage is not zero;
|
|
730
|
+
non-streaming replies and observed tool/refusal output are excluded. This diagnostic
|
|
731
|
+
does not change completion status, trigger a retry or reject legitimate empty replies.
|
|
732
|
+
|
|
700
733
|
`image_mcp` has its own HTTP route counter. After the image handler has been used, `image_generation` separately reports active, succeeded, failed, busy, cancelled, and chat-file delivery-failure counts, including tool errors returned with HTTP 200. A delivery failure can accompany a successful generation; it never causes another generation. Before handler initialization this field is `null`, meaning not observed, not necessarily disabled. Status never initializes that handler, reads its provider credential, installs guidance, or probes the provider. Input-image optimization metrics remain separate. `logging` reports pending records/bytes, queue caps, overflow drops, and write failures for usage and enabled debug-file logging.
|
|
701
734
|
|
|
702
735
|
`stream_performance.by_route` also reports `request_ttft_ms`, measured from adapter entry to the first observed output delta, including local preparation. The existing `ttft_ms` continues to start at upstream dispatch. Neither timestamp means the client has drained or displayed the output. `preparation_ms` contains bounded histograms for admission (including history reservations), body reading/decompression/JSON parsing, history materialization/compact preparation, image optimization, and request serialization. Each sample measures one operation, including failed operations; retries can add samples. These are diagnostic intervals rather than a complete breakdown of request time: body reading includes internal decoded-body admission waits; authentication, routing, and other preparation are not individually timed. Non-streaming requests contribute preparation samples without inventing a first-token measurement.
|
|
@@ -745,6 +778,7 @@ Recovery first tries compatible local credentials and starts Device Flow only wh
|
|
|
745
778
|
|
|
746
779
|
- CCDX binds to loopback by default. Non-loopback hosts are rejected unless `CCDX_ALLOW_LAN=1` is set explicitly.
|
|
747
780
|
- Enabling LAN binding exposes a Copilot-backed API to other reachable machines. Provide your own host firewall and network isolation; do not expose the listener to an untrusted network.
|
|
781
|
+
- Inference POSTs reject any browser `Origin` header before reading the body or contacting upstream, including simple `text/plain` requests. Native Codex/Node requests without Origin and deliberately enabled native LAN clients keep their existing access. This is not authentication or protection against untrusted local native programs.
|
|
748
782
|
- The GitHub OAuth credential is stored locally at `~/.local/share/copilot-api/github_token`. Short-lived Copilot service tokens remain in process memory and are refreshed as needed.
|
|
749
783
|
- The optional image API credential is stored separately with mode `0600` only after `ccdx enable-image`; it is never placed in Codex configuration or diagnostic output.
|
|
750
784
|
- Runtime status and usage records retain metadata rather than request/response content. Diagnostic logging records status and error messages; it is not a general redaction layer for arbitrary error text. See Debug logging before sharing logs.
|
package/package.json
CHANGED
package/src/adapter.mjs
CHANGED
|
@@ -204,6 +204,13 @@ export function createAdapterHandler(options = {}) {
|
|
|
204
204
|
upstreamTimeoutMs,
|
|
205
205
|
});
|
|
206
206
|
const dispatch = async (req, res, pathname) => {
|
|
207
|
+
if (req.method === "POST" && ["/v1/responses", "/v1/responses/compact"].includes(pathname)
|
|
208
|
+
&& Object.hasOwn(req.headers || {}, "origin")) {
|
|
209
|
+
const error = httpError("Browser origins are not allowed for inference", 403);
|
|
210
|
+
error.jsonBody = { error: { message: error.message, type: "invalid_request_error", code: "ccdx_browser_origin_forbidden" } };
|
|
211
|
+
sendJsonError(res, error, 403);
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
207
214
|
if (DASHBOARD_API_PATHS.has(pathname)) {
|
|
208
215
|
const { handleDashboardApi } = await import("./dashboard-api.mjs");
|
|
209
216
|
return handleDashboardApi(req, res, pathname, options.dashboardOptions);
|
package/src/dashboard/index.html
CHANGED
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
|
|
24
24
|
<main>
|
|
25
25
|
<section class="intro">
|
|
26
|
-
<h1><
|
|
26
|
+
<h1><svg class="status-icon" viewBox="0 0 64 64" aria-hidden="true" focusable="false"><g fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round"><ellipse cx="32" cy="32" rx="26" ry="10"/><ellipse cx="32" cy="32" rx="26" ry="10" transform="rotate(60 32 32)"/><ellipse cx="32" cy="32" rx="26" ry="10" transform="rotate(120 32 32)"/></g><circle cx="32" cy="32" r="4.5" fill="currentColor"/></svg> ccdx status</h1>
|
|
27
27
|
<div class="snapshot-meta"><p id="auth-account" role="status" data-i18n data-i18n-title title="Saved GitHub Copilot account / local credentials only; not an online entitlement check.">GitHub / READING</p><p id="updated" data-i18n>Reading status…</p></div>
|
|
28
28
|
</section>
|
|
29
29
|
|
package/src/dashboard/ui.css
CHANGED
|
@@ -24,7 +24,7 @@ button:disabled { opacity: .55; cursor: wait; }
|
|
|
24
24
|
:root[data-theme="light"] .icon-moon { display: block; }
|
|
25
25
|
.intro { display: flex; justify-content: space-between; align-items: baseline; gap: 20px; padding: 38px 0 25px; }
|
|
26
26
|
h1 { margin: 0; font-size: clamp(20px, 3vw, 27px); font-weight: 650; letter-spacing: -.035em; }
|
|
27
|
-
|
|
27
|
+
.status-icon { display: inline-block; width: 1em; height: 1em; vertical-align: -.125em; color: var(--accent); }
|
|
28
28
|
.intro p { margin: 0; color: var(--subtle); font-size: 11px; }
|
|
29
29
|
.snapshot-meta { display: flex; flex-wrap: wrap; justify-content: flex-end; align-items: baseline; gap: 8px 18px; min-width: 0; }
|
|
30
30
|
.intro .snapshot-meta p { margin: 0; overflow-wrap: anywhere; }
|
|
@@ -8,9 +8,14 @@ import { isLoopbackAddress, isLoopbackHostHeader, isLanAllowed } from "./securit
|
|
|
8
8
|
import { decodedBodyLimitPreference } from "./user-settings.mjs";
|
|
9
9
|
import { isResponsesToolOutputItem, readResponsesToolOutputParts } from "./responses-content.mjs";
|
|
10
10
|
import { prepareResponsesRequest } from "./responses-request.mjs";
|
|
11
|
+
import { createAbortAwareSingleflight } from "./bounded-result-cache.mjs";
|
|
11
12
|
|
|
12
13
|
const UUID = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
|
|
13
14
|
const CALLS = new Map([["function_call", "function_call_output"], ["custom_tool_call", "custom_tool_call_output"]]);
|
|
15
|
+
const sourceFlights = createAbortAwareSingleflight();
|
|
16
|
+
const sourceFailures = new Map();
|
|
17
|
+
const REUSABLE_FAILURES = new Set(["invalid_rollout", "incomplete_rollout", "rollout_identity_mismatch",
|
|
18
|
+
"plaintext_content_missing", "unsupported_rollout_item", "unsupported_history_change", "matching_rollout_missing", "ambiguous_rollout"]);
|
|
14
19
|
|
|
15
20
|
function unavailable(code) {
|
|
16
21
|
return Object.assign(new Error("Verified local plaintext history is unavailable"), { code });
|
|
@@ -189,6 +194,52 @@ function joinHistory(source, input, compactionIndex, check) {
|
|
|
189
194
|
return { items, currentInputStart: source.length + instructions.length };
|
|
190
195
|
}
|
|
191
196
|
|
|
197
|
+
async function sourceVersion(files) {
|
|
198
|
+
return JSON.stringify(await Promise.all(files.map(async file => {
|
|
199
|
+
const stat = await fs.lstat(file);
|
|
200
|
+
if (!stat.isFile() || stat.isSymbolicLink()) throw unavailable("unsafe_rollout_path");
|
|
201
|
+
return [file, stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs];
|
|
202
|
+
})));
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async function loadSource(directory, id, ciphertext, limit, timeoutMs, signal) {
|
|
206
|
+
const started = Date.now();
|
|
207
|
+
const check = () => {
|
|
208
|
+
if (signal.aborted) throw signal.reason;
|
|
209
|
+
if (Date.now() - started > timeoutMs) throw unavailable("rollout_read_timeout");
|
|
210
|
+
};
|
|
211
|
+
const files = await candidateFiles(directory, id, check);
|
|
212
|
+
const version = await sourceVersion(files);
|
|
213
|
+
// Cache only failure codes for exact file snapshots, never plaintext or a
|
|
214
|
+
// missing directory. Discovery still runs so added pages are not hidden.
|
|
215
|
+
const key = createHash("sha256").update(JSON.stringify([directory, id, ciphertext, limit, version])).digest("hex");
|
|
216
|
+
const cached = sourceFailures.get(key);
|
|
217
|
+
if (cached && cached.until > Date.now()) throw unavailable(cached.code);
|
|
218
|
+
sourceFailures.delete(key);
|
|
219
|
+
try {
|
|
220
|
+
let source;
|
|
221
|
+
const budget = { remaining: limit };
|
|
222
|
+
for (const file of files) {
|
|
223
|
+
check();
|
|
224
|
+
const candidate = await readPrefix(file, directory, id, ciphertext, budget, check, signal);
|
|
225
|
+
if (!candidate) continue;
|
|
226
|
+
if (source) throw unavailable("ambiguous_rollout");
|
|
227
|
+
source = candidate;
|
|
228
|
+
}
|
|
229
|
+
if (!source) throw unavailable("matching_rollout_missing");
|
|
230
|
+
if (await sourceVersion(files) !== version) throw unavailable("rollout_changed");
|
|
231
|
+
return source;
|
|
232
|
+
} catch (error) {
|
|
233
|
+
if (files.length && !signal.aborted && REUSABLE_FAILURES.has(error.code)
|
|
234
|
+
&& await sourceVersion(files) === version) {
|
|
235
|
+
for (const [old, value] of sourceFailures) if (value.until <= Date.now()) sourceFailures.delete(old);
|
|
236
|
+
while (sourceFailures.size >= 32) sourceFailures.delete(sourceFailures.keys().next().value);
|
|
237
|
+
sourceFailures.set(key, { code: error.code, until: Date.now() + 2000 });
|
|
238
|
+
}
|
|
239
|
+
throw error;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
192
243
|
// Loaded only after a confirmed provider ownership rejection, never on startup
|
|
193
244
|
// or healthy requests. It cannot serve remote/browser callers or mutate logs.
|
|
194
245
|
export async function recoverLocalCompaction(reqContext, { request, env = process.env,
|
|
@@ -215,18 +266,11 @@ export async function recoverLocalCompaction(reqContext, { request, env = proces
|
|
|
215
266
|
release = await reserveHistory?.(limit, { signal });
|
|
216
267
|
check();
|
|
217
268
|
const directory = await fs.realpath(codexPaths({ env }).directory);
|
|
218
|
-
const
|
|
219
|
-
const
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
const candidate = await readPrefix(file, directory, id, compactions[0].encrypted_content, budget, check, signal);
|
|
224
|
-
if (!candidate) continue;
|
|
225
|
-
if (source) throw unavailable("ambiguous_rollout");
|
|
226
|
-
source = candidate;
|
|
227
|
-
}
|
|
228
|
-
if (!source) throw unavailable("matching_rollout_missing");
|
|
229
|
-
const restored = joinHistory(source.items, input, input.indexOf(compactions[0]), check);
|
|
269
|
+
const ciphertext = compactions[0].encrypted_content;
|
|
270
|
+
const key = createHash("sha256").update(JSON.stringify([directory, id, ciphertext, limit, timeoutMs])).digest("hex");
|
|
271
|
+
const source = await sourceFlights.run(key, sharedSignal => loadSource(directory, id, ciphertext, limit, timeoutMs, sharedSignal), { signal });
|
|
272
|
+
check();
|
|
273
|
+
const restored = joinHistory(structuredClone(source.items), input, input.indexOf(compactions[0]), check);
|
|
230
274
|
const body = { ...reqContext.body, input: restored.items };
|
|
231
275
|
delete body.previous_response_id;
|
|
232
276
|
const bodyBytes = Buffer.byteLength(JSON.stringify(body));
|
package/src/package-update.mjs
CHANGED
|
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
|
|
|
5
5
|
import { createInterface } from "node:readline/promises";
|
|
6
6
|
import { lookupLatestRelease, githubReleaseVersion } from "./version.mjs";
|
|
7
7
|
import { terminalCell } from "./terminal-text.mjs";
|
|
8
|
+
import { readBoundedFileSync } from "./bounded-file.mjs";
|
|
8
9
|
|
|
9
10
|
const PACKAGE_NAME = "codex-copilot-dx";
|
|
10
11
|
const UPDATE_SPECS = {
|
|
@@ -84,6 +85,17 @@ function waitForExit(child) {
|
|
|
84
85
|
});
|
|
85
86
|
}
|
|
86
87
|
|
|
88
|
+
export function verifyInstalledPackage(target, { expectedVersion } = {}) {
|
|
89
|
+
if (!target) return null;
|
|
90
|
+
let pkg;
|
|
91
|
+
try { pkg = JSON.parse(readBoundedFileSync(path.join(target, "package.json"), { encoding: "utf8" })); } catch {}
|
|
92
|
+
if (pkg?.name !== PACKAGE_NAME || !githubReleaseVersion(pkg.version)
|
|
93
|
+
|| (expectedVersion && pkg.version !== expectedVersion)) {
|
|
94
|
+
throw new Error("npm finished, but the target package version could not be verified. Check ccdx doctor; installation was not retried.");
|
|
95
|
+
}
|
|
96
|
+
return pkg.version;
|
|
97
|
+
}
|
|
98
|
+
|
|
87
99
|
export async function runPackageUpdateCommand({
|
|
88
100
|
commandName = "ccdx",
|
|
89
101
|
env = process.env,
|
|
@@ -95,6 +107,7 @@ export async function runPackageUpdateCommand({
|
|
|
95
107
|
spawnImpl = spawn,
|
|
96
108
|
fetchImpl = fetch,
|
|
97
109
|
inspectEnvironmentFn = inspectPackageUpdateEnvironment,
|
|
110
|
+
verifyInstalledFn = verifyInstalledPackage,
|
|
98
111
|
} = {}) {
|
|
99
112
|
let selectedSource = normalizeUpdateSource(source);
|
|
100
113
|
if (source && !selectedSource) throw new Error(`Update source must be npm or github: ${source}`);
|
|
@@ -151,6 +164,12 @@ export async function runPackageUpdateCommand({
|
|
|
151
164
|
...launch.options,
|
|
152
165
|
});
|
|
153
166
|
await waitForExit(child);
|
|
154
|
-
|
|
167
|
+
const installedVersion = verifyInstalledFn(environment?.target, { expectedVersion: release?.version });
|
|
168
|
+
if (installedVersion) {
|
|
169
|
+
output.write(`Updated ${PACKAGE_NAME}: installed v${terminalCell(installedVersion)} at ${terminalCell(environment.target)}.\n`);
|
|
170
|
+
} else {
|
|
171
|
+
output.write("Installer finished; the global target was unavailable, so the installed version was not verified. Run ccdx doctor.\n");
|
|
172
|
+
}
|
|
173
|
+
output.write("Restart the running adapter to use the installed version; an existing service is not replaced automatically.\n");
|
|
155
174
|
return { cancelled: false, source: selectedSource };
|
|
156
175
|
}
|
|
@@ -122,7 +122,7 @@ export function createProfileModelRuntime({
|
|
|
122
122
|
}
|
|
123
123
|
const gptModelIds = gptModelIdsFromCopilotModels(models);
|
|
124
124
|
if (gptModelIds.length) {
|
|
125
|
-
emit("ok", `
|
|
125
|
+
emit("ok", `Model catalog refreshed: ${gptModelIds.length} GPT models`);
|
|
126
126
|
} else {
|
|
127
127
|
emit("warn", "Copilot models response contained no GPT models");
|
|
128
128
|
}
|
package/src/responses-bridge.mjs
CHANGED
|
@@ -69,7 +69,7 @@ function chatCompatibilityError(kind, itemType) {
|
|
|
69
69
|
return error;
|
|
70
70
|
}
|
|
71
71
|
|
|
72
|
-
export function responsesToChat(body) {
|
|
72
|
+
export function responsesToChat(body, { reasoningEfforts } = {}) {
|
|
73
73
|
const messages = [];
|
|
74
74
|
if (body.instructions) messages.push({ role: "system", content: body.instructions });
|
|
75
75
|
|
|
@@ -165,11 +165,16 @@ export function responsesToChat(body) {
|
|
|
165
165
|
const maxTok = body.max_output_tokens ?? body.max_tokens ?? body.max_completion_tokens;
|
|
166
166
|
if (maxTok !== undefined) chatReq.max_completion_tokens = maxTok;
|
|
167
167
|
|
|
168
|
+
if (body.tools !== undefined && !Array.isArray(body.tools)) throw chatCompatibilityError("tools", typeof body.tools);
|
|
168
169
|
if (body.tools?.length) {
|
|
169
|
-
|
|
170
|
-
|
|
170
|
+
if (body.tools.some(tool => tool?.type !== "function")) {
|
|
171
|
+
throw chatCompatibilityError("tool", body.tools.find(tool => tool?.type !== "function")?.type);
|
|
172
|
+
}
|
|
171
173
|
chatReq.tools = body.tools
|
|
172
174
|
.map((tool) => {
|
|
175
|
+
if (typeof (tool.function?.name ?? tool.name) !== "string" || !(tool.function?.name ?? tool.name).trim()) {
|
|
176
|
+
throw chatCompatibilityError("function tool", "missing_name");
|
|
177
|
+
}
|
|
173
178
|
if (tool.function?.name) return cloneJson(tool);
|
|
174
179
|
const fn = {
|
|
175
180
|
name: tool.name,
|
|
@@ -179,21 +184,29 @@ export function responsesToChat(body) {
|
|
|
179
184
|
};
|
|
180
185
|
for (const key of Object.keys(fn)) if (fn[key] === undefined) delete fn[key];
|
|
181
186
|
return { type: "function", function: fn };
|
|
182
|
-
})
|
|
183
|
-
.filter(Boolean)
|
|
184
|
-
.filter((t) => t.function?.name);
|
|
185
|
-
if (!chatReq.tools.length) delete chatReq.tools;
|
|
187
|
+
});
|
|
186
188
|
}
|
|
187
189
|
if (body.tool_choice !== undefined) {
|
|
188
190
|
if (typeof body.tool_choice === "string") {
|
|
191
|
+
if (!["auto", "none", "required"].includes(body.tool_choice)) throw chatCompatibilityError("tool choice", body.tool_choice);
|
|
189
192
|
chatReq.tool_choice = body.tool_choice;
|
|
190
193
|
} else if (body.tool_choice?.type === "function" && body.tool_choice.name) {
|
|
194
|
+
if (!chatReq.tools?.some(tool => tool.function.name === body.tool_choice.name)) {
|
|
195
|
+
throw chatCompatibilityError("tool choice", "undeclared_function");
|
|
196
|
+
}
|
|
191
197
|
chatReq.tool_choice = { type: "function", function: { name: body.tool_choice.name } };
|
|
192
198
|
} else {
|
|
193
199
|
throw chatCompatibilityError("tool choice", body.tool_choice?.type);
|
|
194
200
|
}
|
|
195
201
|
}
|
|
196
202
|
if (body.parallel_tool_calls !== undefined) chatReq.parallel_tool_calls = body.parallel_tool_calls;
|
|
203
|
+
if (body.reasoning?.effort !== undefined) {
|
|
204
|
+
if (!["none", "minimal", "low", "medium", "high", "xhigh", "max"].includes(body.reasoning.effort)
|
|
205
|
+
|| (Array.isArray(reasoningEfforts) && !reasoningEfforts.includes(body.reasoning.effort))) {
|
|
206
|
+
throw chatCompatibilityError("reasoning effort", String(body.reasoning.effort));
|
|
207
|
+
}
|
|
208
|
+
chatReq.reasoning_effort = body.reasoning.effort;
|
|
209
|
+
}
|
|
197
210
|
const textFormat = body.text?.format;
|
|
198
211
|
if (textFormat?.type === "json_schema") {
|
|
199
212
|
chatReq.response_format = {
|
|
@@ -207,6 +220,8 @@ export function responsesToChat(body) {
|
|
|
207
220
|
};
|
|
208
221
|
} else if (textFormat?.type === "json_object") {
|
|
209
222
|
chatReq.response_format = { type: "json_object" };
|
|
223
|
+
} else if (textFormat !== undefined && textFormat?.type !== "text") {
|
|
224
|
+
throw chatCompatibilityError("text format", textFormat?.type);
|
|
210
225
|
}
|
|
211
226
|
return chatReq;
|
|
212
227
|
}
|
|
@@ -32,8 +32,8 @@ function jsonPayload(value, assertActive) {
|
|
|
32
32
|
});
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
-
function chatRequest(responsesBody, stream) {
|
|
36
|
-
const chatReq = responsesToChat(responsesBody);
|
|
35
|
+
function chatRequest(responsesBody, stream, reasoningEfforts) {
|
|
36
|
+
const chatReq = responsesToChat(responsesBody, { reasoningEfforts });
|
|
37
37
|
chatReq.stream = Boolean(stream);
|
|
38
38
|
delete chatReq.max_tokens;
|
|
39
39
|
return stream ? withChatStreamUsage(chatReq) : chatReq;
|
|
@@ -81,12 +81,13 @@ function checkedChatPayload(chatReq, payload, limit, stage, adapted, assertActiv
|
|
|
81
81
|
export async function prepareResponsesChatPayload(reqContext, {
|
|
82
82
|
assertActive,
|
|
83
83
|
payloadOptions = {},
|
|
84
|
+
reasoningEfforts,
|
|
84
85
|
signal,
|
|
85
86
|
stream = false,
|
|
86
87
|
} = {}) {
|
|
87
88
|
assertActive?.();
|
|
88
89
|
const limit = configuredBodyLimit(payloadOptions);
|
|
89
|
-
let finalChatReq = chatRequest(reqContext.body, stream);
|
|
90
|
+
let finalChatReq = chatRequest(reqContext.body, stream, reasoningEfforts);
|
|
90
91
|
assertActive?.();
|
|
91
92
|
let finalChat = jsonPayload(finalChatReq, assertActive);
|
|
92
93
|
const hasInlineImage = bodyHasInlineImage(reqContext.body, assertActive);
|
|
@@ -108,7 +109,7 @@ export async function prepareResponsesChatPayload(reqContext, {
|
|
|
108
109
|
responsesPayload = { bodyText: prepared.bodyText, bodyBytes: prepared.bodyBytes };
|
|
109
110
|
adapted = prepared.adapted;
|
|
110
111
|
stage = prepared.stage;
|
|
111
|
-
finalChatReq = chatRequest(reqContext.body, stream);
|
|
112
|
+
finalChatReq = chatRequest(reqContext.body, stream, reasoningEfforts);
|
|
112
113
|
assertActive?.();
|
|
113
114
|
finalChat = jsonPayload(finalChatReq, assertActive);
|
|
114
115
|
}
|
|
@@ -132,7 +133,7 @@ export async function prepareResponsesChatPayload(reqContext, {
|
|
|
132
133
|
initialBodyBytes: responsesPayload.bodyBytes,
|
|
133
134
|
});
|
|
134
135
|
if (!trimmed.adapted) break;
|
|
135
|
-
const candidateChatReq = chatRequest(reqContext.body, stream);
|
|
136
|
+
const candidateChatReq = chatRequest(reqContext.body, stream, reasoningEfforts);
|
|
136
137
|
assertActive?.();
|
|
137
138
|
const candidateChat = jsonPayload(candidateChatReq, assertActive);
|
|
138
139
|
if (candidateChat.bodyBytes >= finalChat.bodyBytes) {
|
|
@@ -335,6 +335,8 @@ export function createResponsesHandler(options) {
|
|
|
335
335
|
let { chatReq, bodyText } = await prepareResponsesChatPayload(prepared, {
|
|
336
336
|
assertActive: assertPrepareActive,
|
|
337
337
|
payloadOptions: responsesPayloadOptions,
|
|
338
|
+
reasoningEfforts: (Array.isArray(modelRegistry?.models) ? modelRegistry.models : modelRegistry?.models?.data)
|
|
339
|
+
?.find(model => model?.id === upstreamModel)?.capabilities?.supports?.reasoning_effort,
|
|
338
340
|
signal: abort.signal,
|
|
339
341
|
stream: streaming,
|
|
340
342
|
});
|
package/src/status.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { currentRequestContext } from "./request-context.mjs";
|
|
2
|
+
import { terminalCell } from "./terminal-text.mjs";
|
|
2
3
|
|
|
3
4
|
const LABELS = {
|
|
4
5
|
info: "[INFO]",
|
|
@@ -13,5 +14,5 @@ export function status(kind, message) {
|
|
|
13
14
|
const requestContext = currentRequestContext();
|
|
14
15
|
const requestId = requestContext?.showRequestId ? requestContext.requestId : "";
|
|
15
16
|
const context = requestId ? ` request_id=${requestId}` : "";
|
|
16
|
-
return `${(LABELS[kind] || LABELS.info).padEnd(8)}${context ? `${context.trimStart()} ` : ""}${message}`;
|
|
17
|
+
return `${(LABELS[kind] || LABELS.info).padEnd(8)}${context ? `${terminalCell(context.trimStart())} ` : ""}${terminalCell(message, { fallback: "" })}`;
|
|
17
18
|
}
|
|
@@ -139,6 +139,7 @@ function createRoutePerformance() {
|
|
|
139
139
|
success_with_output: 0,
|
|
140
140
|
errors_with_output: 0,
|
|
141
141
|
zero_output_errors: 0,
|
|
142
|
+
empty_stream_completions: 0,
|
|
142
143
|
neutral: 0,
|
|
143
144
|
terminalTotals: emptyOutcomes(),
|
|
144
145
|
incompleteReasons: Object.create(null),
|
|
@@ -152,6 +153,7 @@ function routeSnapshot(route) {
|
|
|
152
153
|
success_with_output: route.success_with_output,
|
|
153
154
|
errors_with_output: route.errors_with_output,
|
|
154
155
|
zero_output_errors: route.zero_output_errors,
|
|
156
|
+
empty_stream_completions: route.empty_stream_completions,
|
|
155
157
|
neutral: route.neutral,
|
|
156
158
|
terminal_outcomes: {
|
|
157
159
|
totals: { ...route.terminalTotals },
|
|
@@ -274,6 +276,9 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
274
276
|
finished = true;
|
|
275
277
|
failed ||= finishFailed;
|
|
276
278
|
const outcome = terminalOutcome || (aborted ? "cancelled" : "unknown");
|
|
279
|
+
const emptyStreamCompletion = outcome === "completed" && upstreamStartedAt !== null
|
|
280
|
+
&& firstOutputAt === null && outputTokens === 0;
|
|
281
|
+
if (emptyStreamCompletion) route.empty_stream_completions += 1;
|
|
277
282
|
const origin = terminalOrigin || errorOrigin || (aborted ? "client_disconnect" : "unclassified");
|
|
278
283
|
route.terminalTotals[outcome] += 1;
|
|
279
284
|
if (incompleteReason) route.incompleteReasons[incompleteReason] = (route.incompleteReasons[incompleteReason] || 0) + 1;
|
|
@@ -288,6 +293,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
288
293
|
recentRequests.push({
|
|
289
294
|
request_id: typeof requestId === "string" && /^[a-zA-Z0-9_-]{1,80}$/.test(requestId) ? requestId : null,
|
|
290
295
|
at, route: routeName, model, outcome, origin, phase,
|
|
296
|
+
empty_stream_completion: emptyStreamCompletion,
|
|
291
297
|
failed: failed || aborted || (terminalOutcome !== null && terminalOutcome !== "completed"),
|
|
292
298
|
http_status: Number.isInteger(statusCode) && statusCode >= 100 && statusCode <= 599 ? statusCode : null,
|
|
293
299
|
upstream_attempts: attempts,
|