codex-copilot-dx 1.3.7 → 1.3.9

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.
Files changed (46) hide show
  1. package/README.md +7 -16
  2. package/bin/cli.mjs +55 -31
  3. package/docs/ARCHITECTURE.md +25 -1
  4. package/docs/REFERENCE.md +45 -10
  5. package/package.json +3 -3
  6. package/src/claude-gateway.mjs +21 -18
  7. package/src/cli-command-spec.mjs +3 -2
  8. package/src/cli-image.mjs +2 -80
  9. package/src/cli-options.mjs +1 -1
  10. package/src/client-integration.mjs +11 -4
  11. package/src/connection-runtime.mjs +1 -0
  12. package/src/dashboard/connections.js +5 -1
  13. package/src/dashboard/console.js +12 -6
  14. package/src/dashboard/features.js +73 -0
  15. package/src/dashboard/index.html +15 -14
  16. package/src/dashboard/language.js +60 -16
  17. package/src/dashboard/tools.js +4 -1
  18. package/src/dashboard/ui.js +1 -1
  19. package/src/dashboard/usage.js +2 -2
  20. package/src/dashboard-api.mjs +7 -2
  21. package/src/dashboard-tools.mjs +2 -1
  22. package/src/dashboard.mjs +1 -0
  23. package/src/doctor-compat.mjs +19 -13
  24. package/src/doctor.mjs +1 -1
  25. package/src/image-setup.mjs +110 -0
  26. package/src/local-privacy.mjs +15 -11
  27. package/src/local-tools.mjs +8 -2
  28. package/src/messages-history-transfer.mjs +12 -2
  29. package/src/messages-system-policy.mjs +20 -0
  30. package/src/model-capabilities.mjs +2 -2
  31. package/src/native-prediction-profile.mjs +5 -2
  32. package/src/native-prediction.mjs +18 -2
  33. package/src/optional-routes.mjs +1 -1
  34. package/src/prediction-control.mjs +64 -0
  35. package/src/prediction-operations.mjs +68 -0
  36. package/src/prediction-preference.mjs +75 -0
  37. package/src/privacy-model.mjs +35 -21
  38. package/src/privacy-transform.mjs +35 -4
  39. package/src/providers/m365.mjs +5 -2
  40. package/src/service-control.mjs +33 -7
  41. package/src/service-supervisor.mjs +39 -18
  42. package/src/service-worker.mjs +13 -1
  43. package/src/terminal-console.mjs +2 -2
  44. package/src/usage-analytics.mjs +6 -1
  45. package/src/usage-store.mjs +21 -8
  46. package/src/usage.mjs +18 -5
@@ -1,4 +1,4 @@
1
- import { createHmac } from "node:crypto";
1
+ import { createHash, createHmac } from "node:crypto";
2
2
  import { StringDecoder } from "node:string_decoder";
3
3
  import { privacyFailure } from "./privacy-model.mjs";
4
4
 
@@ -23,7 +23,7 @@ function leaves(value, add, inArguments = false) {
23
23
  }
24
24
  function requestTexts(body, protocol) {
25
25
  const items = [], nested = [];
26
- const add = (parent, key, text) => { if (text && !text.startsWith("data:")) items.push({ parent, key, text, secret: /^(?:password|passwd|api_key|apikey|access_token|refresh_token|client_secret|secret_key|auth_token|db_password|credential|token)$/i.test(String(key)) }); };
26
+ const add = (parent, key, text) => { if (text && !text.startsWith("data:")) items.push({ parent, key, text, secret: /^(?:password|passwd|api_key|apikey|access_token|refresh_token|client_secret|secret_key|auth_token|db_password|credential|secret|token)$/i.test(String(key)) }); };
27
27
  const text = (parent, key) => { if (typeof parent?.[key] === "string") add(parent, key, parent[key]);else if (Array.isArray(parent?.[key])) for (const block of parent[key]) if (["text", "input_text", "output_text"].includes(block?.type)) add(block, "text", block.text); };
28
28
  const args = (parent, key) => {
29
29
  if (typeof parent[key] === "string") {
@@ -69,18 +69,49 @@ function ruleSpans(text, personal) {
69
69
  }
70
70
  return spans;
71
71
  }
72
- export async function maskPrivacyRequest(body, { protocol, client = "api", personal = false, secret, find, signal }) {
72
+ export function createPrivacyRuleCache({ maxBytes = 1024 * 1024, maxEntries = 2048 } = {}) {
73
+ const entries = new Map();let bytes = 0, hits = 0, scans = 0;
74
+ return {
75
+ find(text, personal) {
76
+ if (text.length < 256) { scans++;return ruleSpans(text, personal); }
77
+ const key = `${personal ? 1 : 0}:` + createHash("sha256").update(text).digest("hex");
78
+ if (entries.has(key)) {
79
+ const entry = entries.get(key);entries.delete(key);entries.set(key, entry);hits++;
80
+ return entry.spans.map(span => ({ ...span }));
81
+ }
82
+ scans++;const spans = ruleSpans(text, personal), cost = Buffer.byteLength(JSON.stringify(spans)) + 128;
83
+ if (cost <= maxBytes) {
84
+ entries.set(key, { spans: spans.map(span => ({ ...span })), cost });bytes += cost;
85
+ while (entries.size > maxEntries || bytes > maxBytes) { const oldest = entries.keys().next().value;bytes -= entries.get(oldest).cost;entries.delete(oldest); }
86
+ }
87
+ return spans;
88
+ },
89
+ clear() { entries.clear();bytes = 0; },
90
+ stats: () => ({ entries: entries.size, bytes, hits, scans, max_bytes: maxBytes }),
91
+ };
92
+ }
93
+ function modelSpanFits(text, start, end, label) {
94
+ const value = text.slice(start, end);
95
+ if (label === "common_secret" && /^\d+$/.test(value)) {
96
+ return /(?:\b(?:api_key|apikey|access_token|refresh_token|client_secret|secret_key|auth_token|db_password|password|passwd|passcode|secret|token|pin)|密钥|密码|令牌|口令)["'`]?[\s:=:]*(?:(?:is|was|是|为|為)\s*)?["'`]?$/i.test(text.slice(Math.max(0, start - 96), start));
97
+ }
98
+ if (label === "private_person" && /^[A-Za-z_$][\w$]*$/.test(value)
99
+ && /\b(?:function|class|const|let|var)\s+$/.test(text.slice(Math.max(0, start - 32), start))) return false;
100
+ return true;
101
+ }
102
+ export async function maskPrivacyRequest(body, { protocol, client = "api", personal = false, secret, find, signal, rules = ruleSpans }) {
73
103
  const copy = structuredClone(body), { items, nested } = requestTexts(copy, protocol), texts = items.map(item => item.text);
74
104
  if (items.length > 8192 || texts.reduce((n, text) => n + Buffer.byteLength(text), 0) > 8 * 1024 * 1024) throw privacyFailure("request_too_large");
75
105
  const found = texts.length ? await find(texts, { signal }) : [], values = new Map(), kinds = {}, total = { count: 0, bytes: 0 };
76
106
  if (!Array.isArray(found) || found.length !== texts.length) throw privacyFailure("engine_invalid");
77
107
  for (let i = 0; i < items.length; i++) {
78
- const item = items[i], bytes = Buffer.from(item.text), spans = ruleSpans(item.text, personal);
108
+ const item = items[i], bytes = Buffer.from(item.text), spans = rules(item.text, personal);
79
109
  if (item.secret) spans.push({ start: 0, end: item.text.length, kind: "secret" });
80
110
  for (const span of found[i] || []) {
81
111
  if (!Number.isInteger(span.start) || !Number.isInteger(span.end) || span.start < 0 || span.end <= span.start || span.end > bytes.length || !Number.isFinite(span.score)) throw privacyFailure("engine_invalid");
82
112
  if (span.score < 0.8 || span.label !== "common_secret" && !(personal && personalKinds.has(span.label))) continue;
83
113
  const start = bytes.subarray(0, span.start).toString("utf8").length, end = bytes.subarray(0, span.end).toString("utf8").length;
114
+ if (!modelSpanFits(item.text, start, end, span.label)) continue;
84
115
  spans.push({ start, end, kind: span.label === "common_secret" ? "secret" : span.label });
85
116
  }
86
117
  spans.sort((a, b) => a.start - b.start || b.end - a.end);
@@ -126,7 +126,7 @@ export function createM365Provider({ home, env = process.env, account: accountOv
126
126
  const serialized = body ? options.bodyText ?? JSON.stringify(body) : undefined;
127
127
  if (serialized !== undefined) requestHeaders["Content-Length"] = String(Buffer.byteLength(serialized));
128
128
  options.onUpstreamStart?.();
129
- if (body) { markUpstreamStarted(body.stream === true);if (!options.countTokens) markRequestObservation({ max_output_tokens_sent: endpoint.includes("messages") ? body.max_tokens : body.max_output_tokens }); }
129
+ if (body) { if (options.observeUpstream !== false) markUpstreamStarted(body.stream === true);if (!options.countTokens) markRequestObservation({ max_output_tokens_sent: endpoint.includes("messages") ? body.max_tokens : body.max_output_tokens }); }
130
130
  try {
131
131
  const send = fetchImpl || await transport(options.signal);
132
132
  const response = await send(`${M365_API_BASE}${endpoint}`, { method: body ? "POST" : "GET", headers: requestHeaders,
@@ -233,12 +233,15 @@ export function createM365Provider({ home, env = process.env, account: accountOv
233
233
  const adjusted = limitM365CacheTtl(body);
234
234
  if (adjusted.changed && !cacheTtlAdjustments) log("info", "Microsoft 365 supports 5m prompt caching; 1h cache retention is capped to 5m. Content and breakpoints are unchanged.");
235
235
  cacheTtlAdjustments += adjusted.changed;
236
- return request(options.countTokens ? "/v1/messages/count_tokens" : "/v1/messages", model.id === adjusted.body.model ? adjusted.body : { ...adjusted.body, model: model.id }, options);
236
+ const requestBody = model.id === adjusted.body.model ? adjusted.body : { ...adjusted.body, model: model.id };
237
+ return request(options.countTokens ? "/v1/messages/count_tokens" : "/v1/messages", requestBody, requestBody === body ? options : { ...options, bodyText: undefined });
237
238
  },
238
239
  runtimeStatus: () => ({ ...auth.snapshot(), account_bound: Boolean(account), upstream_host: new URL(M365_API_BASE).hostname,
239
240
  model_endpoint_cache_entries: catalog?.data.length || 0, model_list_flights: flight ? 1 : 0 }),
240
241
  };
241
242
  return {
243
+ messagesSystemMode: "native",
244
+ coordinateMessagesCounts: true,
242
245
  id: "m365", client, registry, auth, refresh, profileId: profile,
243
246
  models: family => m365Models(catalog, family),
244
247
  catalog: () => catalog?.data || [],
@@ -1,17 +1,22 @@
1
1
  import { serviceSettingsSnapshot, servicePreferences, writeServicePreference,
2
2
  writeTerminalAnimationTheme, writeTerminalColorTheme, responseHistoryLimitPreference, writeResponseHistoryLimitMib,
3
- nightlyUpdatePreference, writeNightlyUpdatePreference } from "./user-settings.mjs";
3
+ nightlyUpdatePreference, writeNightlyUpdatePreference, decodedBodyLimitPreference, writeDecodedBodyLimitMib } from "./user-settings.mjs";
4
4
  import { readImageProviderConfig } from "./image-provider-config.mjs";
5
5
  import { readPredictionSettings } from "./native-prediction-profile.mjs";
6
6
  import { cacheRuntimeSnapshot, cleanRuntimeCaches, setHistoryCacheLimit } from "./cache-control.mjs";
7
7
  import { isTerminalAnimationTheme } from "./terminal-animation.mjs";
8
8
  import { settingsPreferencesSnapshot, writeSettingsPreferences } from "./settings-preferences.mjs";
9
+ import { predictionControlSnapshot, controlPrediction } from "./prediction-control.mjs";
10
+ import { imageSetupSummary, configureImageSetup } from "./image-setup.mjs";
9
11
 
10
12
  export function createServiceControl({ env = process.env, home, providerRuntime, clientIntegration, terminal,
11
13
  nightlyStatus = () => null, nightlyChanged = () => {},
14
+ manualUpdate, predictionControl = controlPrediction, imageControl = configureImageSetup,
15
+ adapterPort = 2026, adapterHost = "127.0.0.1",
12
16
  readImages = () => readImageProviderConfig({ env, home }), readPrediction = () => readPredictionSettings({ env, home }) } = {}) {
13
17
  const options = { env, home };
14
- let serial = Promise.resolve();
18
+ let serial = Promise.resolve(), lastOperation = null, pending = 0;
19
+ const featureSnapshot = read => { try { return read(options); } catch { return { status: "unavailable" }; } };
15
20
  function snapshot() {
16
21
  const { saved, theme, color_theme, historyLimit } = serviceSettingsSnapshot(options), prediction = clientIntegration?.snapshot().prediction;
17
22
  let imageConfigured = false, predictionConfigured = false;
@@ -19,6 +24,8 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
19
24
  try { predictionConfigured = readPrediction().enabled === true; } catch {}
20
25
  const enabled = nightlyUpdatePreference(options), nightly = nightlyStatus();
21
26
  return { source: "service_settings", saved, theme, color_theme, preferences: settingsPreferencesSnapshot(options), local_privacy: providerRuntime?.privacy?.snapshot(),
27
+ features: { prediction: { ...featureSnapshot(predictionControlSnapshot), bridge: prediction?.bridge || "stopped", active: prediction?.active === true }, image: featureSnapshot(imageSetupSummary) },
28
+ decoded_body: decodedBodyLimitPreference(options), manual_update: { available: typeof manualUpdate === "function" }, last_operation: lastOperation,
22
29
  nightly_update: { enabled, ...nightly, effect: enabled && !nightly ? "next_start" : "immediate" },
23
30
  effective: {
24
31
  terminal_animation_enabled: { value: terminal?.enabled === true && saved.terminal_animation_enabled && !/^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || ""),
@@ -34,10 +41,26 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
34
41
  if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("Invalid setting action");
35
42
  const allowed = { preference: ["action", "key", "value"], nightly_update: ["action", "enabled"], animation: ["action", "theme"], color_theme: ["action", "theme"],
36
43
  history_limit: ["action", "mib"], history_clean: ["action"], prediction_fix: ["action"],
44
+ prediction: ["action", "operation"], image: ["action", "operation", "endpoint", "key", "model"],
45
+ update: ["action", "confirmed"], decoded_limit: ["action", "mib"],
37
46
  preferences: ["action", "values", "revision"], reset_preferences: ["action", "revision", "backup_id", "scope"], restore_preferences: ["action", "revision", "backup_id", "scope"],
38
47
  provider: ["action", "operation", "provider", "model", "auto_review_model", "auto_review_effort", "account_id"] }[input.action];
39
48
  if (!allowed || Object.keys(input).some(key => !allowed.includes(key))) throw new Error("Unknown setting action or field");
40
- if (["preferences", "reset_preferences", "restore_preferences"].includes(input.action)) {
49
+ lastOperation = null;
50
+ if (input.action === "prediction") {
51
+ lastOperation = { feature: "prediction", result: await predictionControl(input.operation, { ...options, integration: clientIntegration }) };
52
+ } else if (input.action === "image") {
53
+ for (const [key, limit] of [["endpoint", 2048], ["key", 8192], ["model", 200]]) if (input[key] !== undefined && (typeof input[key] !== "string" || input[key].length > limit)) throw new Error("Invalid image setup input");
54
+ if (["pause", "resume"].includes(input.operation)) writeServicePreference("image_enabled", input.operation === "resume", options);
55
+ else lastOperation = { feature: "image", result: await imageControl(input, { ...options, adapterPort, adapterHost }) };
56
+ } else if (input.action === "update") {
57
+ if (input.confirmed !== true) throw new Error("Confirm installation and the idle service switch");
58
+ if (!manualUpdate) throw new Error("This launch cannot update itself; use the installer or start CCDX from its installed command");
59
+ lastOperation = { feature: "update", result: await manualUpdate() };
60
+ } else if (input.action === "decoded_limit") {
61
+ if (decodedBodyLimitPreference(options).source === "environment") throw new Error("Request limit is controlled by the launch environment");
62
+ writeDecodedBodyLimitMib(input.mib, options);
63
+ } else if (["preferences", "reset_preferences", "restore_preferences"].includes(input.action)) {
41
64
  const before = nightlyUpdatePreference(options);
42
65
  writeSettingsPreferences(input, options);
43
66
  if (input.action !== "preferences" || Object.keys(input.values || {}).some(key => key.startsWith("privacy_"))) providerRuntime?.privacy?.settingsChanged();
@@ -47,8 +70,8 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
47
70
  } else if (input.action === "nightly_update") {
48
71
  writeNightlyUpdatePreference(input.enabled, options);nightlyChanged(input.enabled);
49
72
  } else if (input.action === "preference") {
50
- writeServicePreference(input.key, input.value, options);
51
- if (input.key === "prediction_enabled") clientIntegration?.setPredictionActive(input.value);
73
+ if (input.key === "prediction_enabled") await predictionControl(input.value ? "enable" : "disable", { ...options, integration: clientIntegration });
74
+ else writeServicePreference(input.key, input.value, options);
52
75
  terminal?.apply?.({ ...servicePreferences(options) });
53
76
  } else if (input.action === "color_theme") {
54
77
  writeTerminalColorTheme(input.theme, options);terminal?.apply?.({ color_theme: input.theme });
@@ -57,7 +80,7 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
57
80
  writeTerminalAnimationTheme(input.theme, options);terminal?.apply?.({ theme: input.theme });
58
81
  } else if (input.action === "prediction_fix") {
59
82
  if (!clientIntegration) throw new Error("Prediction integration is unavailable");
60
- await clientIntegration.fix();
83
+ await predictionControl("repair", { ...options, integration: clientIntegration });
61
84
  } else if (input.action === "history_limit") {
62
85
  if (responseHistoryLimitPreference(options).source === "environment") throw new Error("History limit is controlled by CCDX_RESPONSE_HISTORY_MAX_BYTES");
63
86
  if (!Number.isSafeInteger(input.mib)) throw new Error("History limit must be an integer MiB value");
@@ -74,5 +97,8 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
74
97
  }
75
98
  return snapshot();
76
99
  }
77
- return { snapshot, action(input) { const operation = serial.then(() => apply(input));serial = operation.catch(() => {});return operation; } };
100
+ return { snapshot, busy: () => pending > 0, action(input) {
101
+ const counted = input?.action !== "update";if (counted) pending++;
102
+ const operation = serial.then(() => apply(input)).finally(() => { if (counted) pending--; });serial = operation.catch(() => {});return operation;
103
+ } };
78
104
  }
@@ -4,9 +4,10 @@ import { fork } from 'node:child_process';
4
4
  import { nightlyUpdatePreference, userSettingsPath } from './user-settings.mjs';
5
5
  import { atomicWriteFileIfChangedSync } from './atomic-file.mjs';
6
6
  import { createNpmReleaseFetch } from './release-install.mjs';
7
+ import { isVersionGreater } from './version.mjs';
7
8
  import { installedUpdateEnvironment, retainCurrentRuntime, lookupNightlyRelease, eligiblePatch, nightlyWindow, nightlyDay, NIGHTLY_IDLE_MS, prepareNightlyRelease, verifyNightlyRuntime, readNightlyState } from './nightly-update.mjs';
8
9
 
9
- export function launchServiceWorker(target, { args = [], env = process.env, state, preserve = false, warm = false, sources = [], onPreference = () => {}, forkImpl = fork } = {}) {
10
+ export function launchServiceWorker(target, { args = [], env = process.env, state, preserve = false, warm = false, sources = [], onPreference = () => {}, onManualUpdate = () => {}, forkImpl = fork } = {}) {
10
11
  const child = forkImpl(path.join(target,'bin/cli.mjs'),preserve ? [...args.filter(value=>value!=='--no-browser'),'--no-browser'] : args, {
11
12
  env:{...env,CCDX_SUPERVISED_SERVICE:'1',...(preserve?{CCDX_AUTO_LAUNCH:'0'}:{})},stdio:['inherit','inherit','inherit','ipc'],serialization:'advanced',windowsHide:true,
12
13
  });
@@ -21,6 +22,7 @@ export function launchServiceWorker(target, { args = [], env = process.env, stat
21
22
  if(message?.type==='ccdx:boot'){child.send({type:'ccdx:init',protocol:1,preserve,warm,sources,state});state=undefined;}
22
23
  else if(message?.type==='ccdx:ready'){settled=true;clearTimeout(timer);readyResolve(message.value);}
23
24
  else if(message?.type==='ccdx:preference')onPreference(message.enabled===true);
25
+ else if(message?.type==='ccdx:manual-update')onManualUpdate();
24
26
  else if(message?.type==='ccdx:reply'){
25
27
  const entry=pending.get(message.id);if(!entry)return;pending.delete(message.id);message.error?entry.reject(new Error(message.error)):entry.resolve(message.value);
26
28
  }
@@ -130,9 +132,9 @@ export async function runServiceSupervisor({args=process.argv.slice(2),env=proce
130
132
  now=()=>new Date(),launch=launchServiceWorker,prepare=prepareNightlyRelease,lookup,processObj=process,log=message=>console.log(message),
131
133
  retain=retainCurrentRuntime,verify=verifyNightlyRuntime,timers={setInterval,clearInterval}}={}) {
132
134
  let current=retain(environment),version=JSON.parse(fs.readFileSync(path.join(current.target,'package.json'))).version;
133
- let stopping=false,worker,pendingWorker,timer,scheduler;const retired=new Set();
134
- const start=(target,options={})=>pendingWorker=launch(target,{args,env,...options,onPreference:enabled=>{if(!enabled)scheduler?.cancel();}});
135
- const stop=()=>{if(stopping)return;stopping=true;timers.clearInterval(timer);scheduler?.cancel();void worker?.stop().catch(()=>{});if(pendingWorker!==worker)void pendingWorker?.stop().catch(()=>{});for(const item of retired)void item.worker.stop().catch(()=>{});};
135
+ let stopping=false,worker,pendingWorker,timer,scheduler,manualFlight=null,manualController=null,requestManualUpdate;const retired=new Set();
136
+ const start=(target,options={})=>pendingWorker=launch(target,{args,env,...options,onPreference:enabled=>{if(!enabled)scheduler?.cancel();},onManualUpdate:()=>{void requestManualUpdate?.();}});
137
+ const stop=()=>{if(stopping)return;stopping=true;timers.clearInterval(timer);scheduler?.cancel();manualController?.abort();void worker?.stop().catch(()=>{});if(pendingWorker!==worker)void pendingWorker?.stop().catch(()=>{});for(const item of retired)void item.worker.stop().catch(()=>{});};
136
138
  processObj.once('SIGINT',stop);processObj.once('SIGTERM',stop);
137
139
  try{
138
140
  await verify(current.target,version,{brokerRequired:fs.existsSync(path.join(current.target,'node_modules/@azure/msal-node-runtime'))});
@@ -142,27 +144,46 @@ export async function runServiceSupervisor({args=process.argv.slice(2),env=proce
142
144
  const stateFile=path.join(path.dirname(userSettingsPath({env})),'nightly-update-state.json');let state;
143
145
  try{state=readNightlyState(stateFile);}catch{state=null;worker.status({phase:'unavailable'});worker.notice('update_records_unreadable');}
144
146
  let fetchImpl;
145
- scheduler=createNightlyScheduler({enabled:()=>!stopping&&retired.size===0&&state!==null&&nightlyUpdatePreference({env}),now,currentVersion:()=>version,state:state||undefined,
147
+ const readRelease=lookup|| (async options=>{fetchImpl||=createNpmReleaseFetch(environment.npmCli,{env});return lookupNightlyRelease(fetchImpl,options);});
148
+ async function installCandidate(candidate,baseline,options,manual=false) {
149
+ try {
150
+ if(JSON.parse(fs.readFileSync(path.join(environment.target,'package.json'))).version!==version){candidate.cleanup();throw new Error('installation_changed');}
151
+ const result=await switchServiceVersion({worker,current,candidate,baseline,launch:start,stopped:()=>stopping,
152
+ cancelled:()=>stopping||!manual&&(!nightlyUpdatePreference({env})||!nightlyWindow(now())),onPhase:phase=>worker.status({phase,version:candidate.version}),signal:options.signal});
153
+ worker=result.worker;current=result.current;version=result.version;
154
+ if(result.retired)retired.add(result.retired);
155
+ }catch(error){if(error.restoredWorker)worker=error.restoredWorker;throw error;}
156
+ }
157
+ async function manualUpdate() {
158
+ if(stopping||manualFlight)return;
159
+ scheduler?.cancel();
160
+ manualController=new AbortController();
161
+ manualFlight=(async()=>{
162
+ await scheduler?.wait();worker.status({phase:'checking',manual:true});
163
+ const baseline=await worker.call('inspect');
164
+ if(baseline.busy||baseline.activity.active)throw new Error('service_busy');
165
+ const release=await readRelease({currentVersion:version,signal:manualController.signal});
166
+ if(!release||!isVersionGreater(release.version,version)){worker.status({phase:'current',manual:true});return;}
167
+ worker.status({phase:'preparing',version:release.version,manual:true});
168
+ const candidate=await prepare(release,{environment,env,fetchImpl,signal:manualController.signal});
169
+ try {await installCandidate(candidate,baseline,{signal:manualController.signal},true);worker.status({phase:'updated',version,manual:true});}
170
+ catch(error){candidate.cleanup();throw error;}
171
+ })().catch(error=>{worker.status({phase:error.message==='service_busy'?'deferred':'failed',manual:true});worker.notice('manual_update_failed');}).finally(()=>{manualFlight=null;manualController=null;});
172
+ await manualFlight;
173
+ }
174
+ requestManualUpdate=manualUpdate;
175
+ scheduler=createNightlyScheduler({enabled:()=>!stopping&&!manualFlight&&retired.size===0&&state!==null&&nightlyUpdatePreference({env}),now,currentVersion:()=>version,state:state||undefined,
146
176
  persist:value=>atomicWriteFileIfChangedSync(stateFile,JSON.stringify(value)+'\n',{mode:0o600}),
147
177
  inspect:()=>worker.call('inspect'),status:value=>worker.status(value),
148
178
  onFailure:code=>worker.notice(code),
149
- lookup:lookup|| (async options=>{fetchImpl||=createNpmReleaseFetch(environment.npmCli,{env});return lookupNightlyRelease(fetchImpl,options);}),
179
+ lookup:readRelease,
150
180
  prepare:(release,options)=>prepare(release,{environment,env,...options,fetchImpl}),
151
- apply:async(candidate,baseline,options)=>{
152
- try{
153
- const globalVersion=JSON.parse(fs.readFileSync(path.join(environment.target,'package.json'))).version;
154
- if(globalVersion!==version){candidate.cleanup();throw new Error('installation_changed');}
155
- const result=await switchServiceVersion({worker,current,candidate,baseline,launch:start,stopped:()=>stopping,
156
- cancelled:()=>stopping||!nightlyUpdatePreference({env})||!nightlyWindow(now()),onPhase:phase=>worker.status({phase,version:candidate.version}),signal:options.signal});
157
- worker=result.worker;current=result.current;version=result.version;
158
- if(result.retired)retired.add(result.retired);
159
- }catch(error){if(error.restoredWorker)worker=error.restoredWorker;throw error;}
160
- },
181
+ apply:installCandidate,
161
182
  });
162
183
  timer=timers.setInterval(()=>scheduler.tick(),60000);timer.unref?.();
163
184
  // An unexpected worker exit is reported once. A deliberate Ctrl+C never restarts it.
164
- while(!stopping){const observed=worker;await observed.exited;if(scheduler.busy){await scheduler.wait();if(worker!==observed)continue;}break;}
185
+ while(!stopping){const observed=worker;await observed.exited;if(manualFlight)await manualFlight;if(scheduler.busy)await scheduler.wait();if(worker!==observed)continue;break;}
165
186
  const deliberate=stopping;stop();await scheduler.close();await worker.stop();return deliberate?0:1;
166
187
  }catch(error){if(!worker&&!stopping)throw error;if(!stopping)log('[WARN] Nightly supervisor could not continue; run ccdx again.');const deliberate=stopping;stop();return deliberate?0:1;}
167
- finally{timers.clearInterval(timer);processObj.off('SIGINT',stop);processObj.off('SIGTERM',stop);if(stopping)await worker?.stop();for(const item of retired){try{await item.worker.stop();item.current.cleanup();}catch{}}current.cleanup();}
188
+ finally{timers.clearInterval(timer);processObj.off('SIGINT',stop);processObj.off('SIGTERM',stop);if(stopping)await worker?.stop();if(manualFlight)await manualFlight;for(const item of retired){try{await item.worker.stop();item.current.cleanup();}catch{}}current.cleanup();}
168
189
  }
@@ -8,13 +8,15 @@ import { userSettingsPath } from './user-settings.mjs';
8
8
  import { readBoundedFileSync } from './bounded-file.mjs';
9
9
  import { authProfilePaths, readAuthProfileCredentials } from './auth-profile.mjs';
10
10
  import { m365Paths } from './m365-settings.mjs';
11
+ import { imageProviderConfigPath } from './image-provider-config.mjs';
12
+ import { readPredictionSettings } from './native-prediction-profile.mjs';
11
13
 
12
14
  export const HANDOFF_MAX_BYTES = 64 * 1024 * 1024;
13
15
  export function clientStateFingerprint(options = {}) {
14
16
  const codex = codexPaths(options), connections = accessSettingsPath(options);
15
17
  const github = authProfilePaths('codex', options);
16
18
  const files = [codex.config, path.join(codex.directory, 'auth.json'), connections, userSettingsPath(options),
17
- github.tokenPath, m365Paths(options).settings, m365Paths(options).gateway,
19
+ github.tokenPath, imageProviderConfigPath(options), m365Paths(options).settings, m365Paths(options).gateway,
18
20
  path.join(path.dirname(connections), 'client-gateway-keys.json'), path.join(path.dirname(connections), 'codex-gateway-owner.json'), ...Object.values(claudeClientPaths(options))];
19
21
  const hash = createHash('sha256');
20
22
  const credentials = readAuthProfileCredentials('codex', options);
@@ -23,6 +25,11 @@ export function clientStateFingerprint(options = {}) {
23
25
  hash.update(file);try { hash.update(readBoundedFileSync(file, { maxBytes: 8 * 1024 * 1024 })); }
24
26
  catch (error) { if (error.code !== 'ENOENT') throw error;hash.update('missing'); }
25
27
  }
28
+ const prediction = readPredictionSettings(options);
29
+ // Port allocation and App stat bookkeeping can change when the new listener
30
+ // starts. User intent and trust ownership must stay stable across handoff.
31
+ hash.update(JSON.stringify([prediction.enabled, prediction.store ?? null, prediction.certificateHash ?? null,
32
+ prediction.credentialsDirectory ?? null, prediction.app?.app ?? null, prediction.app?.profile ?? null]));
26
33
  return hash.digest('hex');
27
34
  }
28
35
  export function serviceBusinessState(runtime) {
@@ -81,6 +88,11 @@ export async function createServiceWorker({ processObj = process } = {}) {
81
88
  takeState() { const state = boot.state;boot.state = undefined;return state; },
82
89
  status: () => updateStatus,
83
90
  preferenceChanged(enabled) { if (processObj.connected !== false) processObj.send({ type: 'ccdx:preference', enabled }, () => {}); },
91
+ requestUpdate() {
92
+ if (warming || draining || processObj.connected === false) throw new Error('Service update is unavailable during a version switch');
93
+ processObj.send({ type: 'ccdx:manual-update' });
94
+ return { status: 'queued' };
95
+ },
84
96
  reused() { processObj.send({ type: 'ccdx:ready', protocol: 1, value: { reused: true } }); },
85
97
  async ready(value) { handlers = value;if (stopRequested) { await handlers.stop();return; }processObj.send({ type: 'ccdx:ready', protocol: 1, value: handlers.inspect() }); },
86
98
  };
@@ -55,13 +55,13 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
55
55
  const rate = usage.cache_hit_rate;
56
56
  const cacheHit = Number.isFinite(rate) && rate >= 0 && rate <= 1 ? `${usage.cache_hit_rate_partial ? "~" : ""}${(rate * 100).toFixed(1)}%` : "—";
57
57
  const usageRows = [[left < 23 ? "Records" : "Usage records", usage.records ?? null], ["Input", usage.input_tokens ?? null], [left < 23 ? "Reused" : "Reused input", usage.cached_input_tokens ?? null],
58
- ["Output", usage.output_tokens ?? null], [left < 23 ? "Partial" : "Partial records", usage.partial_records ?? null], ["Cache hit", cacheHit]];
58
+ [left < 23 ? "Written" : "Cache write", usage.cache_write_input_tokens ?? null], ["Output", usage.output_tokens ?? null], [left < 23 ? "Partial" : "Partial records", usage.partial_records ?? null], ["Cache hit", cacheHit]];
59
59
  const requestRows = [["Total", requests], ["Active", inferenceActive], ["Completed", sum("completed")], ["Incomplete", sum("incomplete")], ["Failed", sum("failed")], ["Cancelled", sum("cancelled")]];
60
60
  if (sum("unknown")) { usageRows.push(["", ""]);requestRows.push(["Unknown", sum("unknown")]); }
61
61
  const title = compactTitle ? [`┌─ Usage ${"─".repeat(left - 8)}┬─ Requests ${"─".repeat(right - 11)}┐`]
62
62
  : [rule("┌", "┬", "┐"), row(cell("Usage / this run", undefined, left), cell(right < 23 ? "Requests" : "Model requests", undefined, right)), rule("├", "┼", "┤")];
63
63
  return [...title,
64
- ...usageRows.map(([label, value], index) => row(cell(label, value === undefined ? (label ? null : undefined) : value, left), cell(...requestRows[index], right))), rule("└", "┴", "┘")];
64
+ ...usageRows.map(([label, value], index) => row(cell(label, value === undefined ? (label ? null : undefined) : value, left), cell(...(requestRows[index] || ["", undefined]), right))), rule("└", "┴", "┘")];
65
65
  }
66
66
  function render() {
67
67
  if (!running || !supported() || verbose) { frameDelay = 1000;return; }
@@ -3,7 +3,7 @@ import { cacheReadTokens, usageCacheHitRate, usageProvider } from "./usage-store
3
3
  const DAY_MS = 86400000;
4
4
  const DAYS = 365;
5
5
  const MAX_MODELS = 100;
6
- const TOKEN_FIELDS = ["input_tokens", "output_tokens", "total_tokens", "cached_input_tokens", "cache_read_input_tokens", "cache_hit_unknown_requests", "cache_hit_invalid_requests"];
6
+ const TOKEN_FIELDS = ["input_tokens", "output_tokens", "total_tokens", "cached_input_tokens", "cache_read_input_tokens", "cache_write_input_tokens", "cache_hit_unknown_requests", "cache_hit_invalid_requests", "cache_hit_known_requests", "cache_hit_input_tokens", "cache_hit_read_tokens"];
7
7
 
8
8
  export function createUsageAnalytics({ timeZone = "UTC", now = Date.now(), qualifyProviders = false } = {}) {
9
9
  const formatter = new Intl.DateTimeFormat("sv-SE", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" });
@@ -33,7 +33,12 @@ export function createUsageAnalytics({ timeZone = "UTC", now = Date.now(), quali
33
33
  output_tokens: values.output_tokens || 0,
34
34
  total_tokens: values.total_tokens ?? (values.input_tokens || 0) + (values.output_tokens || 0),
35
35
  cache_read_tokens: cacheReadTokens(values) ?? null,
36
+ cache_write_input_tokens: values.cache_write_input_tokens ?? null,
36
37
  cache_hit_rate: usageCacheHitRate(values),
38
+ cache_hit_known_requests: values.cache_hit_known_requests || 0,
39
+ cache_hit_unknown_requests: values.cache_hit_unknown_requests || 0,
40
+ cache_hit_input_tokens: values.cache_hit_input_tokens ?? null,
41
+ cache_hit_read_tokens: values.cache_hit_read_tokens ?? null,
37
42
  cache_hit_rate_partial: values.cache_hit_unknown_requests > 0,
38
43
  tokens_partial: values.tokens_partial === true || values.cache_hit_invalid_requests > 0,
39
44
  };
@@ -203,17 +203,16 @@ function scheduleUsageWriteDrain() {
203
203
  export function recordUsage(record) {
204
204
  if (!record) return Promise.resolve();
205
205
  const usage = record.usage || {};
206
- const { cached, unknown, invalid } = usageCacheEvidence(usage);
206
+ const { cached } = usageCacheEvidence(usage);
207
207
  const provider = usageProvider(record), label = runtimeUsageByProvider.has(provider) || runtimeUsageByProvider.size < 18 ? provider : "other";
208
208
  if (!runtimeUsageByProvider.has(label)) runtimeUsageByProvider.set(label, { records: 0, input_tokens: 0, cached_input_tokens: 0, output_tokens: 0, partial_records: 0 });
209
209
  for (const totals of [runtimeUsage, runtimeUsageByProvider.get(label)]) {
210
210
  totals.records++;
211
- for (const [target, value] of [["input_tokens", usage.input_tokens], ["cached_input_tokens", cached], ["output_tokens", usage.output_tokens]]) {
212
- if (Number.isFinite(value) && value >= 0) totals[target] += value;
211
+ for (const [target, value] of [["input_tokens", usage.input_tokens], ["cached_input_tokens", cached], ["cache_write_input_tokens", usage.cache_write_input_tokens], ["output_tokens", usage.output_tokens]]) {
212
+ if (Number.isFinite(value) && value >= 0) totals[target] = (totals[target] || 0) + value;
213
213
  }
214
214
  if (!Number.isFinite(usage.input_tokens) || !Number.isFinite(usage.output_tokens) || cached === undefined) totals.partial_records++;
215
- if (unknown) totals.cache_hit_unknown_requests = (totals.cache_hit_unknown_requests || 0) + 1;
216
- if (invalid) totals.cache_hit_invalid_requests = (totals.cache_hit_invalid_requests || 0) + 1;
215
+ addCacheEvidence(totals, usage);
217
216
  }
218
217
  if (process.env.CCDX_DISABLE_USAGE === "1") return Promise.resolve();
219
218
  const filePath = usageLogPath();
@@ -341,15 +340,13 @@ export function summarizeUsage(records, { provider = "" } = {}) {
341
340
  const modelTotals = summary.byModel[model];
342
341
  modelTotals.requests += 1;
343
342
  addUsageTotals(modelTotals, record.usage);
344
- const { unknown, invalid } = usageCacheEvidence(record.usage || {});
345
343
  const qualified = `${source} / ${model}`;
346
344
  if (!Object.hasOwn(summary.bySourceModel, qualified)) summary.bySourceModel[qualified] = { requests: 0 };
347
345
  const sourceTotals = summary.bySourceModel[qualified];
348
346
  sourceTotals.requests++;
349
347
  addUsageTotals(sourceTotals, record.usage);
350
348
  for (const target of [summary.totals, modelTotals, sourceTotals]) {
351
- if (unknown) target.cache_hit_unknown_requests = (target.cache_hit_unknown_requests || 0) + 1;
352
- if (invalid) target.cache_hit_invalid_requests = (target.cache_hit_invalid_requests || 0) + 1;
349
+ addCacheEvidence(target, record.usage || {});
353
350
  }
354
351
  }
355
352
  return summary;
@@ -436,6 +433,11 @@ export function cacheReadTokens(usage = {}) {
436
433
  }
437
434
 
438
435
  export function usageCacheHitRate(usage = {}) {
436
+ if (usage.cache_hit_known_requests !== undefined || usage.cache_hit_unknown_requests !== undefined) {
437
+ const input = usage.cache_hit_input_tokens, cached = usage.cache_hit_read_tokens;
438
+ return usage.cache_hit_known_requests > 0 && Number.isFinite(input) && input > 0
439
+ && Number.isFinite(cached) && cached >= 0 && cached <= input ? cached / input : null;
440
+ }
439
441
  const input = usage.input_tokens;
440
442
  const cached = cacheReadTokens(usage);
441
443
  if (usage.cache_hit_invalid_requests > 0 || !Number.isFinite(input) || input <= 0
@@ -443,6 +445,17 @@ export function usageCacheHitRate(usage = {}) {
443
445
  return cached / input;
444
446
  }
445
447
 
448
+ function addCacheEvidence(target, usage) {
449
+ const { cached, unknown, invalid } = usageCacheEvidence(usage);
450
+ if (unknown) target.cache_hit_unknown_requests = (target.cache_hit_unknown_requests || 0) + 1;
451
+ else {
452
+ target.cache_hit_known_requests = (target.cache_hit_known_requests || 0) + 1;
453
+ target.cache_hit_input_tokens = (target.cache_hit_input_tokens || 0) + usage.input_tokens;
454
+ target.cache_hit_read_tokens = (target.cache_hit_read_tokens || 0) + cached;
455
+ }
456
+ if (invalid) target.cache_hit_invalid_requests = (target.cache_hit_invalid_requests || 0) + 1;
457
+ }
458
+
446
459
  function usageCacheEvidence(usage) {
447
460
  const input = usage.input_tokens, cached = cacheReadTokens(usage);
448
461
  const unknown = !Number.isFinite(input) || input < 0 || !Number.isFinite(cached) || cached < 0 || cached > input;
package/src/usage.mjs CHANGED
@@ -28,6 +28,8 @@ function fmt(n) {
28
28
  return Number.isFinite(n) ? n.toLocaleString("en-US") : "0";
29
29
  }
30
30
 
31
+ const writeTokens = n => Number.isFinite(n) ? fmt(n) : "—";
32
+
31
33
  function tableNumber(n) {
32
34
  return Number.isFinite(n) ? n.toLocaleString("en-US") : undefined;
33
35
  }
@@ -53,13 +55,13 @@ function formatPlainUsageSummary(summary, filePath, { sanitize = false } = {}) {
53
55
  }
54
56
  lines.push(
55
57
  `Records: ${fmt(summary.requests)}`,
56
- `Tokens: input=${fmt(summary.totals.input_tokens)} cache_read=${fmt(cacheReadTokens(summary.totals))} output=${fmt(summary.totals.output_tokens)} total=${fmt(summary.totals.total_tokens)}`,
57
- `Cache hit: ${cacheHitPercent(summary.totals)} (cached/input tokens)`,
58
+ `Tokens: input=${fmt(summary.totals.input_tokens)} cache_read=${fmt(cacheReadTokens(summary.totals))} cache_write=${writeTokens(summary.totals.cache_write_input_tokens)} output=${fmt(summary.totals.output_tokens)} total=${fmt(summary.totals.total_tokens)}`,
59
+ `Cache hit: ${cacheHitPercent(summary.totals)} (cached/input tokens; valid paired records only)`,
58
60
  "",
59
61
  "By model:",
60
62
  );
61
63
  for (const [model, row] of Object.entries(usageModelGroups(summary))) {
62
- lines.push(` ${terminalCell(model)}: records=${fmt(row.requests)} input=${fmt(row.input_tokens)} cache_read=${fmt(cacheReadTokens(row))} output=${fmt(row.output_tokens)} total=${fmt(row.total_tokens)} cache_hit=${cacheHitPercent(row)}`);
64
+ lines.push(` ${terminalCell(model)}: records=${fmt(row.requests)} input=${fmt(row.input_tokens)} cache_read=${fmt(cacheReadTokens(row))} cache_write=${writeTokens(row.cache_write_input_tokens)} output=${fmt(row.output_tokens)} total=${fmt(row.total_tokens)} cache_hit=${cacheHitPercent(row)}`);
63
65
  }
64
66
  return (sanitize ? lines.map((line) => terminalCell(line, { fallback: "" })) : lines).join("\n");
65
67
  }
@@ -77,6 +79,7 @@ function usageTableRow(model, usage) {
77
79
  records: tableNumber(usage.requests),
78
80
  input: tableNumber(usage.input_tokens),
79
81
  cacheRead: tableNumber(cacheReadTokens(usage)),
82
+ cacheWrite: tableNumber(usage.cache_write_input_tokens),
80
83
  output: tableNumber(usage.output_tokens),
81
84
  total: tableNumber(usage.total_tokens),
82
85
  cacheHit: cacheHitPercent(usage),
@@ -84,7 +87,7 @@ function usageTableRow(model, usage) {
84
87
  }
85
88
 
86
89
  function usageDetailLine(model, usage) {
87
- return `${terminalCell(model)}: input=${fmt(usage.input_tokens)} cache_read=${fmt(cacheReadTokens(usage))} output=${fmt(usage.output_tokens)} cache_hit=${cacheHitPercent(usage)}`;
90
+ return `${terminalCell(model)}: input=${fmt(usage.input_tokens)} cache_read=${fmt(cacheReadTokens(usage))} cache_write=${writeTokens(usage.cache_write_input_tokens)} output=${fmt(usage.output_tokens)} cache_hit=${cacheHitPercent(usage)}`;
88
91
  }
89
92
 
90
93
  function formatTableUsageSummary(summary, filePath, output) {
@@ -95,10 +98,11 @@ function formatTableUsageSummary(summary, filePath, output) {
95
98
  { key: "records", label: "RECORDS", align: "right" },
96
99
  { key: "input", label: "INPUT", align: "right" },
97
100
  { key: "cacheRead", label: "CACHE READ", align: "right" },
101
+ { key: "cacheWrite", label: "CACHE WRITE", align: "right" },
98
102
  { key: "output", label: "OUTPUT", align: "right" },
99
103
  { key: "total", label: "TOTAL", align: "right" },
100
104
  ];
101
- const compactColumns = [columns[0], columns[1], columns[5]];
105
+ const compactColumns = [columns[0], columns[1], columns[6]];
102
106
  const modelUsage = Object.entries(usageModelGroups(summary))
103
107
  .map(([model, row]) => ({ model, row }))
104
108
  .sort(compareModelUsage);
@@ -111,6 +115,11 @@ function formatTableUsageSummary(summary, filePath, output) {
111
115
  width: cliOutputWidth(output),
112
116
  gap: 1,
113
117
  });
118
+ const writeOmitted = table.compact || table.overflow;
119
+ if (writeOmitted) {
120
+ columns.splice(columns.findIndex(column => column.key === "cacheWrite"), 1);
121
+ table = formatResponsiveCliTable({ columns: [...columns, { key: "cacheHit", label: "HIT %", align: "right" }], compactColumns: columns, rows, width: cliOutputWidth(output), gap: 1 });
122
+ }
114
123
  const rateFits = !table.compact;
115
124
  if (table.overflow) {
116
125
  table = formatResponsiveCliTable({ columns, compactColumns, rows, width: cliOutputWidth(output), gap: 1 });
@@ -118,6 +127,10 @@ function formatTableUsageSummary(summary, filePath, output) {
118
127
  table.compact = false;
119
128
  }
120
129
  const lines = [`Usage log: ${safePath}`, ...providerSummaryLines(summary), "", table.output];
130
+ if (writeOmitted && !table.compact && Number.isFinite(totalUsage.cache_write_input_tokens)) {
131
+ lines.push("", "Cache writes:", `TOTAL: ${writeTokens(totalUsage.cache_write_input_tokens)}`,
132
+ ...modelUsage.filter(({ row }) => Number.isFinite(row.cache_write_input_tokens)).map(({ model, row }) => `${terminalCell(model)}: ${writeTokens(row.cache_write_input_tokens)}`));
133
+ }
121
134
  if (table.compact) {
122
135
  lines.push(
123
136
  "",