codex-copilot-dx 1.2.21 → 1.2.23

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 (47) hide show
  1. package/README.md +7 -7
  2. package/bin/cli.mjs +77 -14
  3. package/docs/ARCHITECTURE.md +94 -3
  4. package/docs/REFERENCE.md +142 -6
  5. package/package.json +2 -1
  6. package/src/account-tools.mjs +1 -1
  7. package/src/adapter.mjs +23 -6
  8. package/src/api-catalog-refresh.mjs +6 -2
  9. package/src/api-secrets.mjs +28 -9
  10. package/src/auth.mjs +2 -0
  11. package/src/bounded-result-cache.mjs +12 -0
  12. package/src/claude-gateway.mjs +19 -3
  13. package/src/cli-status.mjs +2 -2
  14. package/src/client-gateway-keys.mjs +7 -3
  15. package/src/client-integration.mjs +3 -0
  16. package/src/connection-runtime.mjs +25 -6
  17. package/src/conversation-source-guard.mjs +3 -1
  18. package/src/dashboard/console.js +12 -2
  19. package/src/dashboard/flow.js +62 -33
  20. package/src/dashboard/index.html +8 -0
  21. package/src/dashboard/language.js +47 -0
  22. package/src/dashboard/status.js +29 -8
  23. package/src/dashboard/ui.css +18 -2
  24. package/src/dashboard/ui.js +4 -4
  25. package/src/dashboard/view-boundary.js +41 -0
  26. package/src/dashboard-tools.mjs +1 -0
  27. package/src/dashboard.mjs +26 -5
  28. package/src/image-mcp.mjs +3 -0
  29. package/src/image-references.mjs +9 -0
  30. package/src/local-tools.mjs +1 -1
  31. package/src/m365-settings.mjs +5 -0
  32. package/src/nightly-update.mjs +107 -0
  33. package/src/optional-routes.mjs +19 -5
  34. package/src/provider-runtime.mjs +3 -2
  35. package/src/providers/api-token-count.mjs +61 -0
  36. package/src/providers/api.mjs +17 -7
  37. package/src/release-install.mjs +24 -12
  38. package/src/request-context.mjs +8 -0
  39. package/src/response-failures.mjs +25 -5
  40. package/src/response-history.mjs +50 -0
  41. package/src/responses-handler.mjs +3 -0
  42. package/src/service-control.mjs +9 -3
  43. package/src/service-supervisor.mjs +168 -0
  44. package/src/service-worker.mjs +87 -0
  45. package/src/stream-performance.mjs +3 -1
  46. package/src/terminal-console.mjs +1 -0
  47. package/src/user-settings.mjs +15 -0
@@ -1,11 +1,13 @@
1
1
  import { serviceSettingsSnapshot, servicePreferences, writeServicePreference,
2
- writeTerminalAnimationTheme, writeTerminalColorTheme, responseHistoryLimitPreference, writeResponseHistoryLimitMib } from "./user-settings.mjs";
2
+ writeTerminalAnimationTheme, writeTerminalColorTheme, responseHistoryLimitPreference, writeResponseHistoryLimitMib,
3
+ nightlyUpdatePreference, writeNightlyUpdatePreference } from "./user-settings.mjs";
3
4
  import { readImageProviderConfig } from "./image-provider-config.mjs";
4
5
  import { readPredictionSettings } from "./native-prediction-profile.mjs";
5
6
  import { cacheRuntimeSnapshot, cleanRuntimeCaches, setHistoryCacheLimit } from "./cache-control.mjs";
6
7
  import { isTerminalAnimationTheme } from "./terminal-animation.mjs";
7
8
 
8
9
  export function createServiceControl({ env = process.env, home, providerRuntime, clientIntegration, terminal,
10
+ nightlyStatus = () => null, nightlyChanged = () => {},
9
11
  readImages = () => readImageProviderConfig({ env, home }), readPrediction = () => readPredictionSettings({ env, home }) } = {}) {
10
12
  const options = { env, home };
11
13
  let serial = Promise.resolve();
@@ -14,7 +16,9 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
14
16
  let imageConfigured = false, predictionConfigured = false;
15
17
  try { imageConfigured = Boolean(readImages()); } catch {}
16
18
  try { predictionConfigured = readPrediction().enabled === true; } catch {}
19
+ const enabled = nightlyUpdatePreference(options), nightly = nightlyStatus();
17
20
  return { source: "service_settings", saved, theme, color_theme,
21
+ nightly_update: { enabled, ...nightly, effect: enabled && !nightly ? "next_start" : "immediate" },
18
22
  effective: {
19
23
  terminal_animation_enabled: { value: terminal?.enabled === true && saved.terminal_animation_enabled && !/^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || ""),
20
24
  state: terminal?.enabled === true ? "immediate" : "terminal_unavailable", locked: /^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || "") },
@@ -27,11 +31,13 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
27
31
  }
28
32
  async function apply(input) {
29
33
  if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("Invalid setting action");
30
- const allowed = { preference: ["action", "key", "value"], animation: ["action", "theme"], color_theme: ["action", "theme"],
34
+ const allowed = { preference: ["action", "key", "value"], nightly_update: ["action", "enabled"], animation: ["action", "theme"], color_theme: ["action", "theme"],
31
35
  history_limit: ["action", "mib"], history_clean: ["action"], prediction_fix: ["action"],
32
36
  provider: ["action", "operation", "provider", "model", "auto_review_model", "auto_review_effort", "account_id"] }[input.action];
33
37
  if (!allowed || Object.keys(input).some(key => !allowed.includes(key))) throw new Error("Unknown setting action or field");
34
- if (input.action === "preference") {
38
+ if (input.action === "nightly_update") {
39
+ writeNightlyUpdatePreference(input.enabled, options);nightlyChanged(input.enabled);
40
+ } else if (input.action === "preference") {
35
41
  writeServicePreference(input.key, input.value, options);
36
42
  if (input.key === "prediction_enabled") clientIntegration?.setPredictionActive(input.value);
37
43
  terminal?.apply?.({ ...servicePreferences(options) });
@@ -0,0 +1,168 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fork } from 'node:child_process';
4
+ import { nightlyUpdatePreference, userSettingsPath } from './user-settings.mjs';
5
+ import { atomicWriteFileIfChangedSync } from './atomic-file.mjs';
6
+ import { createNpmReleaseFetch } from './release-install.mjs';
7
+ import { installedUpdateEnvironment, retainCurrentRuntime, lookupNightlyRelease, eligiblePatch, nightlyWindow, nightlyDay, NIGHTLY_IDLE_MS, prepareNightlyRelease, verifyNightlyRuntime, readNightlyState } from './nightly-update.mjs';
8
+
9
+ export function launchServiceWorker(target, { args = [], env = process.env, state, preserve = false, warm = false, sources = [], onPreference = () => {}, forkImpl = fork } = {}) {
10
+ const child = forkImpl(path.join(target,'bin/cli.mjs'),preserve ? [...args.filter(value=>value!=='--no-browser'),'--no-browser'] : args, {
11
+ env:{...env,CCDX_SUPERVISED_SERVICE:'1',...(preserve?{CCDX_AUTO_LAUNCH:'0'}:{})},stdio:['inherit','inherit','inherit','ipc'],serialization:'advanced',windowsHide:true,
12
+ });
13
+ let sequence=0,settled=false;const pending=new Map();
14
+ let readyResolve,readyReject;const ready=new Promise((resolve,reject)=>{readyResolve=resolve;readyReject=reject;});
15
+ const timer=setTimeout(()=>readyReject(new Error('startup_timeout')),90000);
16
+ let exitedResolve;const exited=new Promise(resolve=>{exitedResolve=resolve;});
17
+ const fail=error=>{if(!settled){settled=true;clearTimeout(timer);readyReject(error);}for(const entry of pending.values())entry.reject(error);pending.clear();};
18
+ child.on('error',()=>{fail(new Error('worker_failed'));if(!child.pid)exitedResolve({code:1,signal:null});});
19
+ child.on('exit',(code,signal)=>{fail(new Error('worker_exited'));exitedResolve({code,signal});});
20
+ child.on('message',message=>{
21
+ if(message?.type==='ccdx:boot'){child.send({type:'ccdx:init',protocol:1,preserve,warm,sources,state});state=undefined;}
22
+ else if(message?.type==='ccdx:ready'){settled=true;clearTimeout(timer);readyResolve(message.value);}
23
+ else if(message?.type==='ccdx:preference')onPreference(message.enabled===true);
24
+ else if(message?.type==='ccdx:reply'){
25
+ 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
+ }
27
+ });
28
+ function call(action, value) {
29
+ let timer;const id=++sequence;
30
+ return Promise.race([new Promise((resolve,reject)=>{
31
+ if(!child.connected){reject(new Error('worker_disconnected'));return;}
32
+ pending.set(id,{resolve,reject});child.send({type:'ccdx:call',id,action,value},error=>{if(error){pending.delete(id);reject(new Error('worker_disconnected'));}});
33
+ }),new Promise((_,reject)=>{timer=setTimeout(()=>{pending.delete(id);reject(new Error('worker_timeout'));},20000);})]).finally(()=>clearTimeout(timer));
34
+ }
35
+ return { child,ready,exited,call,
36
+ status(value){if(child.connected)child.send({type:'ccdx:update-status',value},()=>{});},
37
+ notice(code){if(child.connected)child.send({type:'ccdx:notice',code},()=>{});},
38
+ async stop(){if(!child.pid||child.exitCode!==null||child.signalCode)return;child.send?.({type:'ccdx:stop'},()=>{});let timer,forced;
39
+ try{await Promise.race([exited,new Promise((resolve,reject)=>{timer=setTimeout(()=>{child.kill('SIGKILL');exited.then(resolve);forced=setTimeout(()=>reject(new Error('worker_stop_timeout')),5000);},15000);})]);}finally{clearTimeout(timer);clearTimeout(forced);}
40
+ },
41
+ };
42
+ }
43
+
44
+ // Runtime-independent transaction, exercised with real child processes by CI.
45
+ export async function switchServiceVersion({ worker, current, candidate, baseline, launch, stopped = () => false, cancelled = stopped, onPhase = () => {}, signal }) {
46
+ let transaction,next,transfer;
47
+ const abort = () => { void next?.stop().catch(() => {}); };
48
+ signal?.addEventListener('abort',abort,{once:true});
49
+ const matches = value => value?.fingerprint === baseline.fingerprint && Array.isArray(value.business) && value.business.length === baseline.business.length
50
+ && baseline.business.every(before => {
51
+ const after = value.business.find(client => client.id === before.id);
52
+ if (!after || ['enabled','source','default_model'].some(key => before[key] !== after[key]) || JSON.stringify(before.scopes) !== JSON.stringify(after.scopes)
53
+ || !before.default_unavailable && after.default_unavailable || !Array.isArray(after.models)) return false;
54
+ const models = new Set(after.models.map(model => JSON.stringify(model)));
55
+ return (before.models || []).every(model => models.has(JSON.stringify(model)));
56
+ });
57
+ const healthy = (value, promoted = false) => Object.entries(baseline.health || {}).every(([key, needed]) => !needed || key === 'prediction' && !promoted || value.health?.[key] === true);
58
+ try {
59
+ if(cancelled())throw new Error('update_cancelled');
60
+ const before=await worker.call('inspect');
61
+ if(before.busy||before.fingerprint!==baseline.fingerprint||JSON.stringify(before.business)!==JSON.stringify(baseline.business))throw new Error('service_changed');
62
+ const sources=[...new Set(baseline.business.flatMap(client=>client.models?.map(model=>model[0])||[]))];
63
+ next=launch(candidate.target,{preserve:true,warm:true,sources});
64
+ const ready=await next.ready;
65
+ if(ready.version!==candidate.version||!matches(ready))throw new Error('candidate_state_changed');
66
+ if(!healthy(ready))throw new Error('candidate_unavailable');
67
+ if(cancelled())throw new Error('update_cancelled');
68
+ transaction=await candidate.install();
69
+ if(cancelled())throw new Error('update_cancelled');
70
+ onPhase('switching');transfer=await worker.call('quiesce');
71
+ if(transfer.fingerprint!==baseline.fingerprint||JSON.stringify(transfer.business)!==JSON.stringify(baseline.business)||transfer.activity.total!==baseline.activity.total)throw new Error('service_changed');
72
+ if(cancelled())throw new Error('update_cancelled');
73
+ await next.call('import',transfer.state);
74
+ await worker.call('release');
75
+ if(cancelled())throw new Error('update_cancelled');
76
+ const promoted=await next.call('promote');
77
+ if(!matches(promoted)||!healthy(promoted,true))throw new Error('candidate_state_changed');
78
+ if(cancelled())throw new Error('update_cancelled');
79
+ await next.call('commit');transaction.commit();transaction=null;
80
+ let retired;
81
+ try { await worker.stop();current.cleanup(); } catch { retired = { worker, current };next.notice?.('old_runtime_cleanup_pending'); }
82
+ transfer=null;return {worker:next,current:candidate,version:candidate.version,retired};
83
+ }catch(error){
84
+ await next?.stop();
85
+ let failure=error;
86
+ try{transaction?.rollback();}catch{failure=new Error('installation_restore_failed');}
87
+ if(!stopped()){
88
+ await worker.call('resume').catch(()=>{});
89
+ }
90
+ candidate.cleanup();failure.restoredWorker=worker;throw failure;
91
+ } finally { signal?.removeEventListener('abort',abort); }
92
+ }
93
+
94
+ export function createNightlyScheduler({enabled,inspect,currentVersion,lookup,prepare,apply,status=()=>{},onFailure=()=>{},now=()=>new Date(),state={attempted_day:null,paused_version:null},persist=()=>{}}) {
95
+ let attemptedDay=state.attempted_day,flight=null,controller,lastBusyAt=now().getTime(),lastTickAt=lastBusyAt,lastCount=null,pausedVersion=state.paused_version;
96
+ const save=()=>persist({attempted_day:attemptedDay,paused_version:pausedVersion});
97
+ const publish=(phase,extra={})=>status({phase,...extra});
98
+ async function tick(){
99
+ if(flight||!enabled())return;
100
+ flight=(async()=>{
101
+ const sample=await inspect(),date=now(),time=date.getTime();
102
+ if(time-lastTickAt>120000||time<lastTickAt)lastBusyAt=time;
103
+ lastTickAt=time;
104
+ const count=sample.activity.total;
105
+ if(sample.busy||sample.activity.active>0||lastCount!==count){lastBusyAt=time;lastCount=count;}
106
+ if(!nightlyWindow(date)||attemptedDay===nightlyDay(date)||time-lastBusyAt<NIGHTLY_IDLE_MS){publish('watching');return;}
107
+ attemptedDay=nightlyDay(date);controller=new AbortController();save();
108
+ try{
109
+ publish('checking');const release=await lookup({signal:controller.signal});
110
+ if(!enabled()||controller.signal.aborted)return;
111
+ if(!eligiblePatch(currentVersion(),release,time)||release.version===pausedVersion){publish('watching');return;}
112
+ publish('preparing',{version:release.version});const candidate=await prepare(release,{signal:controller.signal});
113
+ const latest=await inspect();
114
+ if(!enabled()||controller.signal.aborted||!nightlyWindow(now())||latest.busy||latest.activity.active||latest.activity.total!==count){candidate.cleanup();publish('deferred');return;}
115
+ try{await apply(candidate,sample,{signal:controller.signal});publish('updated',{version:release.version});}
116
+ catch(error){if(!controller.signal.aborted&&!['service_busy','state_too_large','service_changed','update_cancelled','candidate_unavailable'].includes(error.message)){pausedVersion=release.version;save();}throw error;}
117
+ }catch(error){
118
+ const known=['service_busy','state_too_large','service_changed','update_cancelled','candidate_state_changed','candidate_unavailable','installation_changed','installation_restore_failed','startup_timeout','worker_exited','worker_failed','worker_timeout'];
119
+ onFailure(known.includes(error.message)?error.message:'update_failed');
120
+ publish(controller.signal.aborted?'cancelled':['service_busy','state_too_large','service_changed','update_cancelled','candidate_unavailable'].includes(error.message)?'deferred':'paused');
121
+ }
122
+ finally{controller=null;}
123
+ })().catch(()=>publish('unavailable')).finally(()=>{controller=null;flight=null;});
124
+ return flight;
125
+ }
126
+ return {tick,cancel(){controller?.abort();},wait:()=>flight,async close(){controller?.abort();await flight;},get busy(){return Boolean(flight);}};
127
+ }
128
+
129
+ export async function runServiceSupervisor({args=process.argv.slice(2),env=process.env,environment=installedUpdateEnvironment({env}),
130
+ now=()=>new Date(),launch=launchServiceWorker,prepare=prepareNightlyRelease,lookup,processObj=process,log=message=>console.log(message),
131
+ retain=retainCurrentRuntime,verify=verifyNightlyRuntime,timers={setInterval,clearInterval}}={}) {
132
+ 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(()=>{});};
136
+ processObj.once('SIGINT',stop);processObj.once('SIGTERM',stop);
137
+ try{
138
+ await verify(current.target,version,{brokerRequired:fs.existsSync(path.join(current.target,'node_modules/@azure/msal-node-runtime'))});
139
+ if(stopping)return 0;
140
+ worker=start(current.target);const boot=await worker.ready;
141
+ if(boot.reused){await worker.exited;return 0;}
142
+ const stateFile=path.join(path.dirname(userSettingsPath({env})),'nightly-update-state.json');let state;
143
+ try{state=readNightlyState(stateFile);}catch{state=null;worker.status({phase:'unavailable'});worker.notice('update_records_unreadable');}
144
+ let fetchImpl;
145
+ scheduler=createNightlyScheduler({enabled:()=>!stopping&&retired.size===0&&state!==null&&nightlyUpdatePreference({env}),now,currentVersion:()=>version,state:state||undefined,
146
+ persist:value=>atomicWriteFileIfChangedSync(stateFile,JSON.stringify(value)+'\n',{mode:0o600}),
147
+ inspect:()=>worker.call('inspect'),status:value=>worker.status(value),
148
+ onFailure:code=>worker.notice(code),
149
+ lookup:lookup|| (async options=>{fetchImpl||=createNpmReleaseFetch(environment.npmCli,{env});return lookupNightlyRelease(fetchImpl,options);}),
150
+ 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
+ },
161
+ });
162
+ timer=timers.setInterval(()=>scheduler.tick(),60000);timer.unref?.();
163
+ // 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;}
165
+ const deliberate=stopping;stop();await scheduler.close();await worker.stop();return deliberate?0:1;
166
+ }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();}
168
+ }
@@ -0,0 +1,87 @@
1
+ import path from 'node:path';
2
+ import { createHash } from 'node:crypto';
3
+ import { serialize } from 'node:v8';
4
+ import { codexPaths } from './codex-paths.mjs';
5
+ import { claudeClientPaths } from './claude-client-config.mjs';
6
+ import { accessSettingsPath } from './access-settings.mjs';
7
+ import { userSettingsPath } from './user-settings.mjs';
8
+ import { readBoundedFileSync } from './bounded-file.mjs';
9
+ import { authProfilePaths, readAuthProfileCredentials } from './auth-profile.mjs';
10
+ import { m365Paths } from './m365-settings.mjs';
11
+
12
+ export const HANDOFF_MAX_BYTES = 64 * 1024 * 1024;
13
+ export function clientStateFingerprint(options = {}) {
14
+ const codex = codexPaths(options), connections = accessSettingsPath(options);
15
+ const github = authProfilePaths('codex', options);
16
+ const files = [codex.config, path.join(codex.directory, 'auth.json'), connections, userSettingsPath(options),
17
+ github.tokenPath, m365Paths(options).settings, m365Paths(options).gateway,
18
+ path.join(path.dirname(connections), 'client-gateway-keys.json'), path.join(path.dirname(connections), 'codex-gateway-owner.json'), ...Object.values(claudeClientPaths(options))];
19
+ const hash = createHash('sha256');
20
+ const credentials = readAuthProfileCredentials('codex', options);
21
+ hash.update(JSON.stringify([credentials.valid, credentials.identity?.id ?? null, credentials.identity?.login ?? null]));
22
+ for (const file of files) {
23
+ hash.update(file);try { hash.update(readBoundedFileSync(file, { maxBytes: 8 * 1024 * 1024 })); }
24
+ catch (error) { if (error.code !== 'ENOENT') throw error;hash.update('missing'); }
25
+ }
26
+ return hash.digest('hex');
27
+ }
28
+ export function serviceBusinessState(runtime) {
29
+ const graph = runtime.connections();
30
+ return graph.clients.map(client => ({ id: client.id, enabled: client.enabled, source: client.source, default_model: client.default_model ?? client.model ?? null,
31
+ scopes: runtime.privateScopes?.(client.id) || [],
32
+ models: client.model_plan?.models.map(model => [model.source, model.public_id]).sort((a,b) => JSON.stringify(a).localeCompare(JSON.stringify(b))) || [],
33
+ default_unavailable: client.model_plan?.default_unavailable === true }));
34
+ }
35
+
36
+ export async function createServiceWorker({ processObj = process } = {}) {
37
+ let preserving = false, draining = false, warming = false, handlers, stopRequested = false, updateStatus = { phase: 'watching' };
38
+ const boot = await new Promise((resolve, reject) => {
39
+ const timer = setTimeout(() => { processObj.off('message', receive);reject(new Error('Supervisor initialization timed out')); }, 15000);
40
+ function receive(message) {
41
+ if (message?.type !== 'ccdx:init' || message.protocol !== 1) return;
42
+ clearTimeout(timer);processObj.off('message', receive);resolve(message);
43
+ }
44
+ processObj.on('message', receive);processObj.send({ type: 'ccdx:boot', protocol: 1 });
45
+ });
46
+ preserving = boot.preserve === true;
47
+ warming = boot.warm === true;
48
+ draining = preserving;
49
+ const stop = () => { stopRequested = true;void handlers?.stop(); };
50
+ processObj.once('disconnect', stop);
51
+ processObj.on('message', async message => {
52
+ if (message?.type === 'ccdx:stop') { stop();return; }
53
+ if (!message || !handlers) return;
54
+ if (message.type === 'ccdx:notice' && /^[a-z_]{1,64}$/.test(message.code || '')) { handlers.notice?.(message.code);return; }
55
+ if (message.type === 'ccdx:update-status') { updateStatus = message.value;return; }
56
+ if (message.type !== 'ccdx:call' || !Number.isSafeInteger(message.id)) return;
57
+ try {
58
+ let value;
59
+ if (message.action === 'inspect') value = handlers.inspect();
60
+ else if (message.action === 'commit') { value = handlers.inspect();await handlers.activate?.();preserving = false;draining = false; }
61
+ else if (message.action === 'resume') { await handlers.resume?.();draining = false;value = handlers.inspect(); }
62
+ else if (message.action === 'release') { if (!draining) throw new Error('service_busy');await handlers.release();value = handlers.inspect(); }
63
+ else if (message.action === 'import') { if (!warming) throw new Error('service_busy');await handlers.importState(message.value);value = handlers.inspect(); }
64
+ else if (message.action === 'promote') { if (!warming) throw new Error('service_busy');await handlers.promote();warming = false;value = handlers.inspect(); }
65
+ else if (message.action === 'quiesce') {
66
+ if (handlers.inspect().busy) throw new Error('service_busy');
67
+ draining = true;
68
+ const state = await handlers.exportState();
69
+ if (state.history.bytes + state.optional.bytes + (state.providers?.bytes || 0) > HANDOFF_MAX_BYTES || serialize(state).byteLength > HANDOFF_MAX_BYTES) { draining = false;throw new Error('state_too_large'); }
70
+ value = { ...handlers.inspect(), state };
71
+ } else throw new Error('unknown_action');
72
+ processObj.send({ type: 'ccdx:reply', id: message.id, value });
73
+ } catch (error) {
74
+ const code = ['service_busy', 'state_too_large', 'unknown_action'].includes(error.message) ? error.message : 'handoff_unavailable';
75
+ processObj.send({ type: 'ccdx:reply', id: message.id, error: code });
76
+ }
77
+ });
78
+ return {
79
+ get preserving() { return preserving; }, get draining() { return draining; }, get warming() { return warming; },
80
+ get needsGithub() { return warming && Array.isArray(boot.sources) && boot.sources.includes('github'); },
81
+ takeState() { const state = boot.state;boot.state = undefined;return state; },
82
+ status: () => updateStatus,
83
+ preferenceChanged(enabled) { if (processObj.connected !== false) processObj.send({ type: 'ccdx:preference', enabled }, () => {}); },
84
+ reused() { processObj.send({ type: 'ccdx:ready', protocol: 1, value: { reused: true } }); },
85
+ async ready(value) { handlers = value;if (stopRequested) { await handlers.stop();return; }processObj.send({ type: 'ccdx:ready', protocol: 1, value: handlers.inspect() }); },
86
+ };
87
+ }
@@ -458,6 +458,8 @@ export async function measureRequestStageAsync(stage, operation) {
458
458
  }
459
459
 
460
460
  export function markUpstreamStarted(streaming = true) {
461
+ const context = currentRequestContext();
462
+ if (context) context.upstreamAttempts = (context.upstreamAttempts || 0) + 1;
461
463
  tracker()?.upstreamStarted(streaming);
462
464
  }
463
465
 
@@ -489,7 +491,7 @@ export function markResponseModel(model, { requestedModel, configuredModel = fal
489
491
  const context = currentRequestContext();
490
492
  if (context) {
491
493
  context.model = model;
492
- if (requestedModel !== undefined) context.requestedModel = modelLabel(requestedModel);
494
+ if (requestedModel !== undefined && context.requestedModel === undefined) context.requestedModel = modelLabel(requestedModel);
493
495
  }
494
496
  tracker()?.setModel?.(model, { configured: configuredModel });
495
497
  }
@@ -132,6 +132,7 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
132
132
  return {
133
133
  get enabled() { return supported() && fits && !verbose; },
134
134
  start() { if (running) return;running = true;tick(); },
135
+ pause() { running = false;if (timer) timers.clearTimeout(timer);timer = null;if (lines) output.write("\n");lines = 0;previous = [];dirty = true; },
135
136
  beginRequest() { active++;dirty = true;let done = false;return () => { if (!done) { done = true;active = Math.max(0, active - 1);dirty = true; } }; },
136
137
  log(method, args) {
137
138
  const message = redactDiagnosticText(format(...args));
@@ -51,6 +51,10 @@ export function readUserSettings({ env = process.env, home = os.homedir(), stric
51
51
  delete parsed[key];
52
52
  }
53
53
  }
54
+ if (Object.hasOwn(parsed, "nightly_updates") && typeof parsed.nightly_updates !== "boolean") {
55
+ if (strict) throw invalidSettings(filePath, "nightly_updates must be a boolean");
56
+ delete parsed.nightly_updates;
57
+ }
54
58
  if (Object.hasOwn(parsed, "terminal_color_theme") && !isColorTheme(parsed.terminal_color_theme)) {
55
59
  if (strict) throw invalidSettings(filePath, "terminal_color_theme must be green, klein or pink");
56
60
  delete parsed.terminal_color_theme;
@@ -123,6 +127,17 @@ export function servicePreferences(options = {}) {
123
127
  const settings = readUserSettings({ ...options, strict: true });
124
128
  return serviceFlags(settings);
125
129
  }
130
+ export function nightlyUpdatePreference(options = {}) {
131
+ return readUserSettings({ ...options, strict: true }).nightly_updates === true;
132
+ }
133
+ export function writeNightlyUpdatePreference(enabled, options = {}) {
134
+ if (typeof enabled !== "boolean") throw new Error("Nightly updates require a boolean");
135
+ return withFileLockSync(`${userSettingsPath(options)}.lock`, () => {
136
+ const settings = readUserSettings({ ...options, strict: true });
137
+ atomicWriteFileIfChangedSync(userSettingsPath(options), `${JSON.stringify({ ...settings, nightly_updates: enabled }, null, 2)}\n`, { mode: 0o600 });
138
+ return enabled;
139
+ });
140
+ }
126
141
  const serviceFlags = settings => Object.fromEntries(SERVICE_FLAGS.map(key => [key, settings[key] !== false]));
127
142
 
128
143
  // One strict read gives each status update a coherent view; no stale cache.