codex-copilot-dx 1.4.13 → 1.4.14

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.
@@ -55,6 +55,8 @@ Antigravity keeps a bounded local conversation route table with keyed session ha
55
55
 
56
56
  For managed GitHub Codex model plans, Auto Review resolves an explicit startup override within the authorized deployments before consulting saved or observed session routing. The saved effort is associated with its selected review route. A different override uses the app's requested effort, or Low when omitted and supported.
57
57
 
58
+ Antigravity stages the model binding separately from the source authorization guard. It commits a binding only after protocol completion, using request order to prevent a later-arriving response from an older request replacing a confirmed choice. The binding store retains only the account and conversation hashes, model alias and order. Lightweight runtime status reads its counters directly before composing provider, catalog and diagnostic details. The terminal's app management commands share the existing formatting, confirmation and management API contracts through their own command module.
59
+
58
60
  ## Composition and lifecycle
59
61
 
60
62
  ### Application control and shared source admission
package/docs/REFERENCE.md CHANGED
@@ -76,8 +76,7 @@ Choose **Follow conversation model** to use an observed model from the same Code
76
76
  The **Antigravity** page and `ccdx app antigravity status|models|enable|disable|open`
77
77
  manage the original macOS Gemini App. Enable requires acceptance of this data
78
78
  scope: Antigravity main answers follow the selected Google or Copilot model;
79
- all Antigravity summaries, searches and image generation use GitHub Copilot,
80
- including background work from Google-model sessions. Ordinary Gemini chat
79
+ unbound summaries, searches and image generation use GitHub Copilot. A known conversation retains its confirmed source, model and reasoning level for compression. Ordinary Gemini chat
81
80
  keeps its Google route. No OpenAI account or search fallback is used.
82
81
 
83
82
  `app list` includes Antigravity before its first WebUI visit and uses observed state without waiting for native App
@@ -90,7 +89,7 @@ Choose its exposed models on the Antigravity page or with
90
89
  The native Gemini catalog still uses distinct routing aliases for each level so its original selector can choose the intended effort. JSON model output retains those aliases for compatibility, with a `model` field identifying the actual model; the management status also includes `model_groups`. A model file accepts `{"models":["gemini-4-hydrogen"]}` to expose all of its advertised levels, or individual `ccdx-copilot-...-<effort>` aliases to choose a subset. Existing Carbon/Argon aliases remain valid. Models without declared reasoning levels use one plain alias.
91
90
  In the **New chat default** column, choose **Set default** on a Copilot model row, or choose **Use app default** to clear the preference on save. The row action uses `medium` if selected, otherwise the first selected level. `app antigravity models --edit` can choose an exact level; a model file can add `"default_model"` with a selected base ID or route alias, or `null` to clear. The gateway changes only the agent-default field in a compatible catalog; it leaves requests, existing conversation bindings, ordinary Gemini chat and background tasks unchanged. An unavailable saved default does not silently pick another Copilot model. The page reports when the catalog still needs to be loaded. Use **Reopen** in the Antigravity page when it indicates settings need loading. CCDX never reopens the app automatically. An observed connection or fetched catalog does not prove the app adopted the new default.
92
91
 
93
- On the **Antigravity** page, set **Copilot response-header timeout (s)** to 1–600 seconds and save, or leave it blank to use the shared default. The setting persists across restarts and applies when new Copilot generation requests send and wait for response headers. A wait already underway keeps its original deadline. When response headers arrive, the stream idle timer takes over. The same transition applies when the timeout uses its default. Queue, request-body, native Google, Codex and Claude retain their own limits. If `CCDX_ANTIGRAVITY_COPILOT_TIMEOUT_MS` is set at startup, the page shows that value and disables editing.
92
+ On the **Antigravity** page, set **Copilot response-header timeout (s)** to 1–600 seconds and save, or leave it blank to use 180 seconds. An explicitly configured `CCDX_UPSTREAM_TIMEOUT_MS` supplies the default when the field is blank. The setting persists across restarts and applies when new Copilot generation requests send and wait for response headers. A wait already underway keeps its original deadline. When response headers arrive, the stream idle timer takes over. The same transition applies when the timeout uses its default. Queue, request-body, native Google, Codex and Claude retain their own limits. If `CCDX_ANTIGRAVITY_COPILOT_TIMEOUT_MS` is set at startup, the page shows that value and disables editing.
94
93
 
95
94
  To use a custom Gemini API in Antigravity, add an API that declares **Gemini**. Its Gemini address is the versioned model-list URL, for example `https://generativelanguage.googleapis.com/v1beta/models`. Save an API key separately, read the model list, and save the desired Gemini deployments. In **Antigravity → Custom Gemini source**, choose the source and save. Its models appear in the client catalog alongside the existing models. Generation, streaming, and token counts use the selected source's Gemini API and key. CCDX does not send the App's Google credentials or switch an existing conversation to a different source. Reopen Antigravity only if the page shows a catalog reload is needed.
96
95
 
@@ -217,7 +216,7 @@ Recovery preserves human messages, system instructions, tool declarations, signe
217
216
 
218
217
  Codex gateway summaries use authenticated local compression states. Only CCDX expands its own states after local authorization; vendor states stay opaque and retain their connection ownership. Source-native states carrying private placeholders preserve the required restoration map in an authenticated gateway envelope. Maps are never sent upstream or stored as plaintext files. Gateway-owned states require CCDX 1.4 or later; keep the complete local transcript before any downgrade, since older gateways cannot directly expand this versioned state. Imported maps retain the existing mapping limits and are released with their request. A changed client identity or connection cannot silently reuse the state.
219
218
 
220
- Antigravity compression follows a previously observed conversation source/model. Hashed source ownership also survives a service restart. When attribution is unavailable, the already-authorized background policy is retained; the gateway does not infer a Google route from a default background model name. Other title, search and image behavior is unchanged. The native Google route retains its existing privacy policy; Copilot compression stays inside the existing masking session.
219
+ Antigravity compression follows its last successfully confirmed conversation source and model, in request order. Locally rejected requests and failed streams leave the confirmed model in place. Hashed source ownership also survives a service restart. When attribution is unavailable, the already-authorized background policy is retained; the gateway does not infer a Google route from a default background model name. Other title, search and image behavior is unchanged. The native Google route retains its existing privacy policy; Copilot compression stays inside the existing masking session.
221
220
 
222
221
  Internal summary jobs record returned usage separately with purpose `compaction`, including reported partial usage before failure. The Codex aggregate response is not logged a second time. Missing counts remain unknown and genuine zero cache counts stay zero. `ccdx usage --purpose compaction` and the WebUI purpose filter show this work; every purpose remains in default totals. Observed native Claude/Antigravity compression tasks also appear in context observations when explicit session metadata is available. Summary output length is not presented as a verified post-compression context size.
223
222
 
@@ -830,7 +829,7 @@ The old external image provider, Qwen-specific generation/editing, `/mcp/image`,
830
829
  | `CCDX_MAX_UPSTREAM_BODY_BYTES` | `31457280` | Strict maximum forwarded Responses body size; larger payloads are adapted locally or rejected with `413` |
831
830
  | `CCDX_MAX_SSE_BUFFER_BYTES` | `8388608` | Maximum buffered bytes for one unterminated upstream SSE line or event |
832
831
  | `CCDX_UPSTREAM_TIMEOUT_MS` | `120000` | Per-phase timeout for Responses/Messages preparation and non-streaming upstream requests |
833
- | `CCDX_ANTIGRAVITY_COPILOT_TIMEOUT_MS` | `unset` | Startup override for Antigravity Copilot generation through response headers. If unset, use the saved value or the shared timeout. |
832
+ | `CCDX_ANTIGRAVITY_COPILOT_TIMEOUT_MS` | `unset` | Startup override for Antigravity Copilot generation through response headers. If unset, use the saved value, an explicit `CCDX_UPSTREAM_TIMEOUT_MS`, or 180 seconds. |
834
833
  | `CCDX_STREAM_HANDSHAKE_TIMEOUT_MS` | `120000` | Timeout while waiting for upstream streaming response headers |
835
834
  | `CCDX_STREAM_IDLE_TIMEOUT_MS` | `120000` | Maximum idle time between upstream streaming body chunks |
836
835
  | `CCDX_UPSTREAM_RETRIES` | `2` | Retries for safe requests and clearly pre-connect POST failures; capped at `5` |
@@ -1009,6 +1008,8 @@ Each request pins its masking choice, including compatibility retries. Checks no
1009
1008
 
1010
1009
  Streaming restoration emits argument fragments incrementally with JSON string escaping, keeps protocol identities and signed state opaque, and validates completion against argument snapshots or incremental JSON syntax. Only unfinished placeholder tails and structural metadata are retained; raw argument bytes per channel remain capped at 8 MiB, retained tails/metadata/validator state at 32 MiB and active channels at 1,024. Added tail deltas preserve increasing Responses sequence numbers. An incomplete or failed upstream response does not manufacture a completed tool call. Successful frame bytes remain unchanged when restoration is unnecessary. A timeout or busy check reports that nothing was sent, with `Retry-After` for temporary waits. Model readiness, the latest check and the latest protected reply are separate. WebUI and `ccdx config privacy status` report pending detection and reply-restoration errors; the CLI retains explicit enabled/disabled values, while graphical switches omit duplicate normal-state labels; request details retain bounded error/event/channel codes and buffer quantities, never their values. A loaded model or HTTP 200 does not establish that a request or client tool completed.
1011
1010
 
1011
+ Requests requiring no replacements use the original body. For large text checks, the full runtime status reports numeric scanning, detection (including queue wait), and merging durations in `local_privacy.last_check.timing`. The status contains no request text.
1012
+
1012
1013
  Turning masking off affects subsequent requests. Existing protected replies keep their restoration mappings until they finish. The downloaded component can then be deleted separately. Settings reset backs up and resets masking choices while keeping accounts, model selections, client connections, images and prediction access. Older settings backups inherit masking off.
1013
1014
 
1014
1015
  WebUI controls and `ccdx config privacy` use the same preparation transaction. While the service runs, `config set privacy_enabled true/false` and the personal-information preference use these same controls. Offline preference writes and backup restoration retain saved intent; they do not prove model readiness or download a missing model. Unavailable configured protection holds requests back. Use Enable/Retry or `config privacy enable` to prepare it.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.4.13",
3
+ "version": "1.4.14",
4
4
  "description": "Local gateway for Codex, Claude and Gemini Antigravity with Copilot, Microsoft 365 and custom APIs",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
package/src/adapter.mjs CHANGED
@@ -19,6 +19,7 @@ import { createLocalPrivacy } from "./local-privacy.mjs";
19
19
  import { status } from "./status.mjs";
20
20
  import { exportResponseHistory, importResponseHistory } from "./response-history.mjs";
21
21
  import { createTerminalActivityIndicator } from "./terminal-activity.mjs";
22
+ import {runtimeStatusSummary} from "./status-summary.mjs";
22
23
  import { ADAPTER_HEALTH_PATH, ADAPTER_PREDICTION_FIX_PATH, adapterHealthPayload } from "./running-adapter.mjs";
23
24
  import { ACTIVITY_EVENTS_PATH, createActivityEvents } from "./activity-events.mjs";
24
25
  import { runtimeUsageSnapshot } from "./usage-store.mjs";
@@ -249,6 +250,7 @@ export function createAdapterHandler(options = {}) {
249
250
  let statusSnapshot;
250
251
  const managementHandler = createManagementHandler({
251
252
  activityEvents,
253
+ summarySnapshot: () => runtimeStatusSummary(requestMetrics.snapshot(), nativeImages.stats().active),
252
254
  nativePredictionPac: options.nativePredictionPac, fixPrediction: options.fixPrediction, requestBodyTimeoutMs,
253
255
  statusSnapshot: statusSnapshot = () => {
254
256
  const snapshot = runtimeStatusPayload({ metrics: requestMetrics, streamPerformance: streamPerformanceMetrics, admission: acquireRequest,
@@ -0,0 +1,83 @@
1
+ import {createHmac} from "node:crypto";
2
+ import path from "node:path";
3
+ import {accessSettingsPath} from "./access-settings.mjs";
4
+ import {readClientGatewayKeys} from "./client-gateway-keys.mjs";
5
+ import {atomicWriteFile} from "./atomic-file.mjs";
6
+ import {withFileLock} from "./lock.mjs";
7
+ import {readBoundedFile} from "./bounded-file.mjs";
8
+ import {redactDiagnosticText} from "./diagnostic-text.mjs";
9
+ import {httpError} from "./http-errors.mjs";
10
+
11
+ export const validModel=id=>typeof id==="string"&&/^[\w][\w./:@+-]{0,159}$/.test(id)&&redactDiagnosticText(id)===id;
12
+
13
+ export function createAntigravityBindings(options,guard){
14
+ let compactionSalt,conversationRoutes,pending=0;
15
+ const routeFile=path.join(path.dirname(accessSettingsPath(options)),"antigravity-conversations.json");
16
+ const readRoutes=async()=>{
17
+ let value;
18
+ try{value=JSON.parse(await readBoundedFile(routeFile,{encoding:"utf8",maxBytes:128*1024}));}
19
+ catch(error){if(error.code==="ENOENT")return {};throw httpError("Antigravity conversation routing data could not be read",409);}
20
+ if(!value||typeof value!=="object"||Array.isArray(value)||Object.keys(value).length>256||
21
+ Object.entries(value).some(([id,item])=>!/^[a-f0-9]{64}$/.test(id)||!item||
22
+ !/^[a-f0-9]{64}$/.test(item.owner)||!validModel(item.model)||
23
+ item.startedAt!==undefined&&!Number.isFinite(item.startedAt)))throw httpError("Invalid Antigravity conversation routing data",409);
24
+ return value;
25
+ };
26
+ const conversationKey=body=>{
27
+ const id=body?.request?.labels?.root_cascade_id||body?.request?.labels?.cascade_id;
28
+ if(typeof id!=="string"||!id||id.length>160||/[\u0000-\u001f\u007f]/.test(id))return null;
29
+ compactionSalt||=readClientGatewayKeys({...options,create:false}).codex;
30
+ return createHmac("sha256",compactionSalt).update("antigravity-compression\0"+id).digest("hex");
31
+ };
32
+ const hashProfile=profile=>createHmac("sha256",compactionSalt).update(profile).digest("hex");
33
+ const store=(routes,key,entry)=>{
34
+ delete routes[key];routes[key]=entry;
35
+ const keys=Object.keys(routes);
36
+ for(const id of keys.slice(0,Math.max(0,keys.length-256)))delete routes[id];
37
+ };
38
+ return {
39
+ hashProfile,
40
+ prepare(body,profile,startedAt){
41
+ const key=conversationKey(body),model=body.model;
42
+ if(!key||!profile||!validModel(model))return;
43
+ const owner=hashProfile(profile);
44
+ return async signal=>{
45
+ if(signal.aborted)return;
46
+ const entry={owner,model,startedAt};
47
+ // Check the durable order inside the lock, including successful requests
48
+ // that use the same model. A late completion cannot change the binding.
49
+ const newer=routes=>routes?.[key]?.owner!==owner||(routes[key].startedAt??0)<startedAt;
50
+ if(!newer(conversationRoutes))return;
51
+ if(!pending&&conversationRoutes?.[key]?.owner===owner&&conversationRoutes[key].model===model){
52
+ store(conversationRoutes,key,entry);
53
+ return;
54
+ }
55
+ pending++;
56
+ try{
57
+ await withFileLock(routeFile+".lock",async()=>{
58
+ const routes=await readRoutes();
59
+ if(signal.aborted||!newer(conversationRoutes))return;
60
+ if(newer(routes)){
61
+ const stored=routes[key];
62
+ store(routes,key,entry);
63
+ if(stored?.owner!==owner||stored.model!==model)await atomicWriteFile(routeFile,JSON.stringify(routes)+"\n",{mode:0o600});
64
+ }
65
+ if(!conversationRoutes)conversationRoutes=routes;
66
+ else if(newer(conversationRoutes))store(conversationRoutes,key,routes[key]);
67
+ },{timeoutMs:1000,signal});
68
+ }catch{
69
+ if(!signal.aborted&&newer(conversationRoutes))store(conversationRoutes||={},key,entry);
70
+ }finally{pending--;}
71
+ };
72
+ },
73
+ async resolve(body){
74
+ const key=conversationKey(body);if(!key)return null;
75
+ const id=body.request.labels.root_cascade_id||body.request.labels.cascade_id;
76
+ const owner=await guard.owner("gemini",id,compactionSalt);
77
+ if(!owner)return null;
78
+ conversationRoutes ||= await readRoutes();
79
+ const entry=conversationRoutes[key];
80
+ return {owner,pinned:entry?.owner===owner?entry.model:null};
81
+ },
82
+ };
83
+ }
@@ -45,18 +45,24 @@ function groundedSearch(result,query){
45
45
 
46
46
  export function createAntigravityHandler({client,models=()=>[],selectedModels=()=>null,defaultModel=()=>null,enabled=()=>false,privacy,searchFn,imageFn,guardSource,acquireRequest=async()=>()=>{},sourceAdmission,applicationEvidence,
47
47
  nativeModels=()=>[],resolveNativeModel=()=>null,
48
- compaction,compactionProfile=()=>"github",rememberConversationSource=()=>{},resolveCompactionSource=()=>null,recordUsageFn=recordUsage,fetchGoogle=fetch,googleOrigin=GOOGLE_ORIGIN,requestBodyTimeoutMs=120000,upstreamTimeoutMs=180000,copilotTimeoutMs,streamIdleTimeoutMs=60000,
48
+ compaction,compactionProfile=()=>"github",prepareConversationBinding=()=>{},resolveCompactionSource=()=>null,recordUsageFn=recordUsage,fetchGoogle=fetch,googleOrigin=GOOGLE_ORIGIN,requestBodyTimeoutMs=120000,upstreamTimeoutMs=180000,copilotTimeoutMs,streamIdleTimeoutMs=60000,
49
49
  requestSettings,generationSettings=()=>({ selection:selectedModels(), copilotTimeoutMs, preferred:defaultModel() })}={}) {
50
50
  if(![GOOGLE_ORIGIN,"https://cloudcode-pa.googleapis.com"].includes(googleOrigin))throw new Error("Unrecognized Google control origin");
51
51
  const acquireControl=createRequestAdmission({maxBytes:4*CONTROL_BODY_BYTES,maxQueued:8});
52
52
  let active=0,observed=false,catalogModels=null,catalogDefaultSupported=null,catalogDefaultModel=null;const nativeWindows=new Map();
53
53
  const counts={total:0,google:0,copilot:0,search:0,images:0,failed:0};
54
54
  const handler=async(req,res)=>{
55
- const abort=createRequestAbort(req,res);let release=()=>{},releaseControl,session,body,request,converted,phase="validation",usageEvent=null,usageModel=null,outcome=null,usageMode,usageProvider;
55
+ const startedAt=performance.timeOrigin+performance.now(),abort=createRequestAbort(req,res);let commitBinding,release=()=>{},releaseControl,session,body,request,converted,phase="validation",usageEvent=null,usageModel=null,outcome=null,usageMode,usageProvider;
56
56
  const releaseInput=()=>{
57
57
  body=null;request=null;if(converted)converted.chat=null;if(session)session.body=null;
58
58
  const done=release;release=()=>{};done();
59
59
  };
60
+ const confirmBinding=()=>{
61
+ if(outcome==="completed"&&commitBinding&&!abort.signal.aborted){
62
+ abort.clearTimeout();
63
+ return commitBinding(abort.signal);
64
+ }
65
+ };
60
66
  const captureUsage=(event,usage=mergeChatUsage(null,event?.usage))=>{
61
67
  if(!event?.usage&&!event?.copilot_usage)return;
62
68
  const known=value=>Number.isSafeInteger(value)&&value>=0,u=usage||{};
@@ -154,8 +160,11 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
154
160
  }
155
161
  }}):null;
156
162
  res.writeHead(upstream.status,safeUpstreamResponseHeaders(upstream.headers));
157
- let observedEof=false;
158
- const finishObservation=()=>{if(observer?.finish().unavailable&&!usageEvent)markRequestObservation({usage_state:"unavailable"})};
163
+ let observedEof=false,unavailable=false;
164
+ const finishObservation=()=>{
165
+ unavailable=observer?.finish().unavailable===true;
166
+ if(unavailable&&!usageEvent)markRequestObservation({usage_state:"unavailable"});
167
+ };
159
168
  try{
160
169
  if(upstream.body){const reader=sourceResponseReader(upstream);try{while(true){
161
170
  let next;try{next=await reader.read()}catch(error){failSourceRead(reader);throw error}
@@ -166,6 +175,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
166
175
  }}finally{await cancelSourceReader(reader).catch(()=>{});releaseSourceReader(reader)}}
167
176
  }finally{if(!observedEof)finishObservation()}
168
177
  if(generation&&!upstream.ok)outcome="failed";
178
+ if(observedEof&&!unavailable&&commitBinding)await confirmBinding();
169
179
  if(outcome==="failed")counts.failed++;
170
180
  if(outcome)markResponseTerminal(outcome,outcome==="failed"?{origin:upstream.ok?"upstream_event":"upstream_http"}:undefined);
171
181
  res.end();
@@ -201,7 +211,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
201
211
  if(!selected)throw httpError("The selected Gemini source is unavailable",503);
202
212
  if(!["agent","checkpoint","summarization","title"].includes(body.requestType))throw httpError("Unsupported native Gemini request type",400);
203
213
  const profile=await guardSource?.(body,selected.source,abort.signal);
204
- if(body.requestType==="agent")await rememberConversationSource(body,selected.source,abort.signal,profile);
214
+ if(body.requestType==="agent")commitBinding=prepareConversationBinding(body,selected.source,profile,startedAt);
205
215
  const stream=method==="streamGenerateContent",source=selected.transport;
206
216
  usageProvider=selected.source;usageModel=selected.model;usageMode=stream?"sse":"json";
207
217
  if(context){context.provider=selected.source;context.streamPerformance?.setProvider?.(selected.source)}
@@ -238,7 +248,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
238
248
  if(candidates.some(candidate=>candidate.finishReason)){outcome=candidates.every(candidate=>candidate.finishReason==="STOP")?"completed":"incomplete";sourceResponseAccepted(upstream);}
239
249
  const wrapped=JSON.stringify({response:reply});
240
250
  if(stream){if(!await writeOrDrain(res,"data: "+wrapped+"\n\n",{signal:abort.signal}))throw httpError("Antigravity client disconnected",499);}
241
- else res.end(wrapped);
251
+ else {if(commitBinding)await confirmBinding();res.end(wrapped);}
242
252
  };
243
253
  try {
244
254
  if(!upstream.body||stream&&!/^text\/event-stream/i.test(upstream.headers.get("content-type")||""))throw httpError("Expected a Gemini response stream",502);
@@ -262,7 +272,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
262
272
  await emit(value);
263
273
  }
264
274
  if(!outcome)throw httpError("Gemini response ended without a terminal result",502);
265
- markResponseTerminal(outcome);if(stream)res.end();
275
+ markResponseTerminal(outcome);if(stream){if(commitBinding)await confirmBinding();res.end();}
266
276
  }catch(error){sourceResponseFailed(upstream);await cancelSourceResponse(upstream).catch(()=>{});markResponseErrorOrigin("upstream_event");throw error;}
267
277
  return;
268
278
  }
@@ -271,7 +281,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
271
281
  if(body.model.startsWith(ANTIGRAVITY_MODEL_PREFIX))throw httpError("The selected Copilot model is unavailable",503);
272
282
  const hasSession=body.requestType==="agent"||body.request?.labels?.root_cascade_id||body.request?.labels?.cascade_id;
273
283
  const profile=hasSession?await guardSource?.(body,"google",abort.signal):undefined;
274
- if(body.requestType==="agent")await rememberConversationSource(body,"google",abort.signal,profile);
284
+ if(body.requestType==="agent")commitBinding=prepareConversationBinding(body,"google",profile,startedAt);
275
285
  return await native();
276
286
  }
277
287
  const profile=body.requestType==="agent"||compactBinding?.source==="github"
@@ -309,7 +319,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
309
319
  }
310
320
  }
311
321
  if(!target)throw httpError(bound?"The conversation model is unavailable for Antigravity":"No eligible Copilot model is available for Antigravity background tasks",503);
312
- if(body.requestType==="agent")await rememberConversationSource(body,"github",abort.signal,profile);
322
+ if(body.requestType==="agent")commitBinding=prepareConversationBinding(body,"github",profile,startedAt);
313
323
  const stream=method==="streamGenerateContent";usageModel=target.model;usageMode=stream?"sse":"json";usageProvider="github";
314
324
  converted=antigravityToChat(request,{model:target.model,effort:target.effort,reasoningEfforts:target.effort?[target.effort]:[],stream});
315
325
  markResponseModel(target.model);markRequestObservation({usage_state:"pending",context_window_tokens:target.maxTokens,
@@ -337,7 +347,9 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
337
347
  const usage=mergeChatUsage(null,data.usage);captureUsage(data,usage);
338
348
  const result=chatToAntigravity(data,converted.originalNames,usage);markToolActivity(result,"gemini");
339
349
  outcome=result.candidates[0].finishReason==="STOP"?"completed":"incomplete";markResponseTerminal(outcome);
340
- res.writeHead(200,{"Content-Type":"application/json"});res.end(JSON.stringify({response:session.restoreValue(result)}));return;
350
+ const response=JSON.stringify({response:session.restoreValue(result)});
351
+ if(commitBinding)await confirmBinding();
352
+ res.writeHead(200,{"Content-Type":"application/json"});res.end(response);return;
341
353
  }
342
354
  if (!upstream.body) {
343
355
  sourceResponseFailed(upstream);
@@ -363,7 +375,8 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
363
375
  else if(typeof part.text==="string"&&!part.thought)part.text=text.push(part.text);
364
376
  }
365
377
  if(candidate?.finishReason){const tail=text.finish();if(tail)await emit({response:{candidates:[{index:0,content:{role:"model",parts:[{text:tail}]}}]}});outcome=candidate.finishReason==="STOP"?"completed":"incomplete";markResponseTerminal(outcome)}
366
- await emit(chunk);
378
+ if(candidate?.finishReason&&commitBinding)await confirmBinding();
379
+ if(!await emit(chunk))throw httpError("Antigravity client disconnected",499);
367
380
  }
368
381
  res.end();
369
382
  }catch(error){
@@ -1,5 +1,4 @@
1
1
  import fs from "node:fs";
2
- import {createHmac} from "node:crypto";
3
2
  import os from "node:os";
4
3
  import path from "node:path";
5
4
  import {execFile} from "node:child_process";
@@ -9,23 +8,22 @@ import {createAntigravityImages} from "./antigravity-images.mjs";
9
8
  import {createCopilotWeb} from "./copilot-web.mjs";
10
9
  import {inspectGeminiApp,planGeminiAppLaunch} from "./gemini-app.mjs";
11
10
  import {readUserSettings,userSettingsPath} from "./user-settings.mjs";
12
- import {accessSettingsPath,readAccessSettings} from "./access-settings.mjs";
11
+ import {readAccessSettings} from "./access-settings.mjs";
13
12
  import {readClientGatewayKeys} from "./client-gateway-keys.mjs";
14
13
  import {createConversationSourceGuard} from "./conversation-source-guard.mjs";
15
14
  import {readSavedGithubToken} from "./auth-credentials.mjs";
16
15
  import {githubTokenFingerprint} from "./github-identity.mjs";
17
- import {atomicWriteFile,atomicWriteFileIfChangedSync} from "./atomic-file.mjs";
18
- import {withFileLock,withFileLockSync} from "./lock.mjs";
19
- import {readBoundedFile} from "./bounded-file.mjs";
20
- import {redactDiagnosticText} from "./diagnostic-text.mjs";
16
+ import {atomicWriteFileIfChangedSync} from "./atomic-file.mjs";
17
+ import {withFileLockSync} from "./lock.mjs";
21
18
  import {httpError} from "./http-errors.mjs";
19
+ import {createAntigravityBindings, validModel} from "./antigravity-bindings.mjs";
20
+ import {parseTimerMs} from "./runtime-config.mjs";
22
21
  import {antigravityCopilotModels,ANTIGRAVITY_MODEL_PREFIX,ANTIGRAVITY_NATIVE_PREFIX} from "./antigravity-models.mjs";
23
22
 
24
23
  const execute=promisify(execFile),key="gemini_antigravity_enabled",modelKey="gemini_antigravity_models",defaultKey="gemini_antigravity_default_model";
25
24
  const timeoutKey="gemini_antigravity_copilot_timeout_seconds";
26
25
  const nativeSourceKey="gemini_antigravity_native_source";
27
26
  const validTimeout=value=>Number.isSafeInteger(value)&&value>=1&&value<=600;
28
- const validModel=id=>typeof id==="string"&&/^[\w][\w./:@+-]{0,159}$/.test(id)&&redactDiagnosticText(id)===id;
29
27
  const validAlias=id=>typeof id==="string"&&/^ccdx-copilot-[a-z0-9._-]{1,140}$/.test(id);
30
28
 
31
29
  export function createAntigravityRuntime({client,models=()=>[],refreshModels,privacy,home=os.homedir(),env=process.env,inspect=inspectGeminiApp,
@@ -33,23 +31,8 @@ export function createAntigravityRuntime({client,models=()=>[],refreshModels,pri
33
31
  upstreamTimeoutMs=180000,copilotTimeoutMs,nativeSources=()=>[],getSource=()=>null,...timeouts}={}) {
34
32
  const options={home,env},guard=createConversationSourceGuard(options);
35
33
  const web=searchFn?null:createCopilotWeb({client,readToken});
36
- let app={status:"unknown"},route=null,lastOperation=null,compactionSalt,conversationRoutes;
37
- const routeFile=path.join(path.dirname(accessSettingsPath(options)),"antigravity-conversations.json");
38
- const readRoutes=async()=>{
39
- let value;
40
- try{value=JSON.parse(await readBoundedFile(routeFile,{encoding:"utf8",maxBytes:128*1024}));}
41
- catch(error){if(error.code==="ENOENT")return {};throw httpError("Antigravity conversation routing data could not be read",409);}
42
- if(!value||typeof value!=="object"||Array.isArray(value)||Object.keys(value).length>256||
43
- Object.entries(value).some(([id,item])=>!/^[a-f0-9]{64}$/.test(id)||!item||
44
- !/^[a-f0-9]{64}$/.test(item.owner)||!validModel(item.model)))throw httpError("Invalid Antigravity conversation routing data",409);
45
- return value;
46
- };
47
- const conversationKey=body=>{
48
- const id=body?.request?.labels?.root_cascade_id||body?.request?.labels?.cascade_id;
49
- if(typeof id!=="string"||!id||id.length>160||/[\u0000-\u001f\u007f]/.test(id))return null;
50
- compactionSalt||=readClientGatewayKeys({...options,create:false}).codex;
51
- return createHmac("sha256",compactionSalt).update("antigravity-compression\0"+id).digest("hex");
52
- };
34
+ let app={status:"unknown"},route=null,lastOperation=null;
35
+ const bindings=createAntigravityBindings(options,guard);
53
36
  const settings=()=>{
54
37
  const saved=readUserSettings({...options,strict:true});
55
38
  if(saved[key]!==undefined&&typeof saved[key]!=="boolean")throw httpError("Invalid Gemini integration setting",409);
@@ -58,7 +41,8 @@ export function createAntigravityRuntime({client,models=()=>[],refreshModels,pri
58
41
  return {configured:Object.hasOwn(saved,key),enabled:saved[key]===true,selected_models:saved[modelKey]??null,default_model:saved[defaultKey]??null,
59
42
  copilot_timeout_seconds:validTimeout(saved[timeoutKey])?saved[timeoutKey]:null,native_source:typeof saved[nativeSourceKey]==="string"?saved[nativeSourceKey]:null};
60
43
  };
61
- const configuredTimeout=saved=>copilotTimeoutMs??(saved.copilot_timeout_seconds===null?undefined:saved.copilot_timeout_seconds*1000);
44
+ const defaultCopilotTimeoutMs=parseTimerMs(env.CCDX_UPSTREAM_TIMEOUT_MS,180000);
45
+ const effectiveCopilotTimeoutMs=saved=>copilotTimeoutMs??(saved.copilot_timeout_seconds===null?defaultCopilotTimeoutMs:saved.copilot_timeout_seconds*1000);
62
46
  const available=(saved=settings())=>saved.enabled&&readAccessSettings(options).providers.github?models():[];
63
47
  const nativeModels=(sourceId=settings().native_source)=>{
64
48
  if(!sourceId)return [];
@@ -70,7 +54,6 @@ export function createAntigravityRuntime({client,models=()=>[],refreshModels,pri
70
54
  };
71
55
  const profileFor=source=>source==="github"?"codex:"+githubTokenFingerprint(readToken()||"")
72
56
  :source==="google"?"google:gemini-native":getSource(source)?.profileId("gemini");
73
- const hashProfile=profile=>createHmac("sha256",compactionSalt).update(profile).digest("hex");
74
57
  const sourceGuard=guardSource||(async(body,source,signal)=>{
75
58
  const labels=body.request?.labels||{},id=labels.root_cascade_id||labels.cascade_id;
76
59
  if(typeof id!=="string"||!id||id.length>160)throw httpError("Antigravity request has no stable conversation identifier",400);
@@ -88,52 +71,28 @@ export function createAntigravityRuntime({client,models=()=>[],refreshModels,pri
88
71
  const source=getSource(model.source);return source?.client?.gemini?{...model,transport:source}:null;
89
72
  },
90
73
  imageFn:imageFn||createAntigravityImages({client,models:available,privacy}),guardSource:sourceGuard,compactionProfile:()=>githubTokenFingerprint(readToken()||""),
91
- async rememberConversationSource(body,source,signal,observedProfile){
92
- const key=conversationKey(body);if(!key||!validModel(body.model))return;
93
- const profile=typeof observedProfile==="string"?observedProfile:profileFor(source);if(!profile)return;
94
- const owner=hashProfile(profile), cached=conversationRoutes?.[key];
95
- if(cached?.owner===owner&&cached.model===body.model)return;
96
- const remember=routes=>{
97
- delete routes[key];routes[key]={owner,model:body.model};
98
- const keys=Object.keys(routes);for(const id of keys.slice(0,Math.max(0,keys.length-256)))delete routes[id];
99
- };
100
- try{
101
- await withFileLock(routeFile+".lock",async()=>{
102
- const routes=await readRoutes();signal?.throwIfAborted();
103
- if(routes[key]?.owner!==owner||routes[key].model!==body.model){
104
- remember(routes);
105
- await atomicWriteFile(routeFile,JSON.stringify(routes)+"\n",{mode:0o600});
106
- }
107
- conversationRoutes=routes;
108
- },{timeoutMs:1000,signal});
109
- }catch{
110
- signal?.throwIfAborted();
111
- // Existing source ownership still governs routing if this optional model record cannot be saved.
112
- remember(conversationRoutes||={});
113
- }
74
+ prepareConversationBinding(body,source,profile,startedAt){
75
+ return bindings.prepare(body,profile||profileFor(source),startedAt);
114
76
  },
115
77
  async resolveCompactionSource(body,saved=settings()){
116
- const key=conversationKey(body);if(!key)return null;
117
- const id=body.request.labels.root_cascade_id||body.request.labels.cascade_id;
118
- const owner=await guard.owner("gemini",id,compactionSalt);
119
- if(!owner)return null;
120
- conversationRoutes ||= await readRoutes();
121
- const entry=conversationRoutes[key], pinned=entry?.owner===owner?entry.model:null;
122
- if(owner===hashProfile(profileFor("google"))){
78
+ const binding=await bindings.resolve(body);
79
+ if(!binding)return null;
80
+ const {owner,pinned}=binding;
81
+ if(owner===bindings.hashProfile(profileFor("google"))){
123
82
  const model=pinned||body.model;
124
83
  if(!validModel(model)||model.startsWith(ANTIGRAVITY_MODEL_PREFIX)||model.startsWith(ANTIGRAVITY_NATIVE_PREFIX))throw httpError("The conversation belongs to another model source",409);
125
84
  return{source:"google",model};
126
85
  }
127
- if(owner===hashProfile(profileFor("github"))){
86
+ if(owner===bindings.hashProfile(profileFor("github"))){
128
87
  const model=pinned||(validAlias(body.model)?body.model:null);
129
88
  return model?{source:"github",model}:{source:"github",background:true};
130
89
  }
131
90
  const selected=saved.native_source, profile=selected&&profileFor(selected);
132
- const model=profile&&owner===hashProfile(profile)&&nativeModels(selected).find(entry=>entry.id===(pinned||body.model));
91
+ const model=profile&&owner===bindings.hashProfile(profile)&&nativeModels(selected).find(entry=>entry.id===(pinned||body.model));
133
92
  if(model)return{source:selected,model:model.id};
134
93
  throw httpError("The conversation belongs to another model source",409);
135
94
  },fetchGoogle:googleFetch,acquireRequest,upstreamTimeoutMs,...timeouts,generationSettings(saved){
136
- return { selection:saved.selected_models, copilotTimeoutMs:configuredTimeout(saved), preferred:saved.default_model };
95
+ return { selection:saved.selected_models, copilotTimeoutMs:effectiveCopilotTimeoutMs(saved), preferred:saved.default_model };
137
96
  }});
138
97
  function snapshot(){
139
98
  const config=settings(),sourceEnabled=readAccessSettings(options).providers.github,activity=handler.snapshot(config);
@@ -151,7 +110,7 @@ export function createAntigravityRuntime({client,models=()=>[],refreshModels,pri
151
110
  const defaultUnavailable=config.default_model!==null&&(!desiredDefault||activity.catalog_default_supported===false);
152
111
  const current=applicationControl?.snapshot().antigravity;
153
112
  const visibleApp=current?{status:current.status,version:current.version||null,pids:current.pid?[current.pid]:[]}:app;
154
- return {source:"gemini_antigravity",...config,native_sources:sources.map(({id,name})=>({id,name})),copilot_timeout:{effective_ms:configuredTimeout(config)??upstreamTimeoutMs,default_ms:upstreamTimeoutMs,locked:copilotTimeoutMs!==undefined},
113
+ return {source:"gemini_antigravity",...config,native_sources:sources.map(({id,name})=>({id,name})),copilot_timeout:{effective_ms:effectiveCopilotTimeoutMs(config),default_ms:defaultCopilotTimeoutMs,locked:copilotTimeoutMs!==undefined},
155
114
  source_enabled:sourceEnabled,default_model_unavailable:defaultUnavailable,models_reload_required:reload,app:visibleApp,application:current||null,route_observed:activity.observed,
156
115
  model_source:["Google",...(config.enabled&&sourceEnabled?["GitHub Copilot"]:[]),...(selectedNative?[selectedNative.name]:[])].join(" + "),background_source:"GitHub Copilot",ordinary_chat_source:"Google (unchanged)",
157
116
  compaction_source:"Observed conversation source; existing background policy when unassigned",
@@ -0,0 +1,169 @@
1
+ import { CLI_CLIENTS } from "./cli-command-spec.mjs";
2
+ import { projectTerminalState, retainedRequests, clientSetup, TERMINAL_CLIENT_NAMES } from "./terminal-state.mjs";
3
+ import { terminalCell } from "./cli-table.mjs";
4
+ import { deploymentModelId } from "./model-capabilities.mjs";
5
+
6
+ export async function runAppCommand({ path, ids, flags, output, request, readStatus, ask, print, confirm,
7
+ choose, connection, requireManagement, save, getClient, clientBody, readFile }) {
8
+ const action = path.at(-1);
9
+ if (path.length === 3 && ["open", "focus", "restart", "check"].includes(action)) {
10
+ const id = ["antigravity", "gemini"].includes(path[1]) ? "antigravity" : CLI_CLIENTS[ids.app || path[1]];
11
+ if (!["codex", "claude_app", "antigravity"].includes(id)) throw new Error("This command opens desktop apps. Run Claude Code in your terminal.");
12
+ const settings = await request({ path: "settings?application=" + id + "&fresh=1", timeoutMs: 15000 }), app = settings.applications?.[id];
13
+ if (!app) throw new Error("This command needs the updated running service; no app was changed.");
14
+ if (action === "check" || flags.preview) return print({ id, ...app, ...(flags.preview ? { action, performed: false } : {}) });
15
+ if (action === "restart") await confirm("Reopen " + path[1] + "? This may interrupt its current tasks.");
16
+ const result = await request({ path: "settings", body: { action: "application", id, operation: action,
17
+ ...(action === "restart" ? { confirmed: true, ...(app.pid ? { expected_pid: app.pid, expected_started: app.started } : {}) } : {}) }, timeoutMs: 65000 });
18
+ return print(result.last_operation?.result || result.applications?.[id]);
19
+ }
20
+ if (["gemini", "antigravity"].includes(path[1])) {
21
+ if (["enable", "disable"].includes(action)) {
22
+ const preview = { action, background_source: "GitHub Copilot (all Antigravity summaries, searches and image generation)", ordinary_Gemini_chat: "Google; no routing change" };
23
+ if (flags.preview) return print(preview);
24
+ output.write(print(preview) + "\n");await confirm(action === "enable" ? "Enable this Antigravity-only routing scope?" : "Pause Copilot access? Reopen Gemini afterward to restore its native route.");
25
+ }
26
+ if(action==="models"&&flags.edit){
27
+ const state=await request({path:"gemini",...(flags.refresh?{body:{action:"refresh"},timeoutMs:20000}:{})});
28
+ let ids, preferred;
29
+ if(flags.file){
30
+ const file=readFile(),listed=file.models;preferred=file.default_model;if(!Array.isArray(listed))throw new Error("Model files require a models array.");
31
+ ids=listed.flatMap(id=>state.model_groups?.find(model=>model.id===id)?.efforts.map(item=>item.id)||[id]);
32
+ }
33
+ else if(Array.isArray(state.model_groups)){
34
+ const groups=state.model_groups,selected=await choose(groups.map(model=>model.name),groups.flatMap((model,index)=>model.efforts.some(item=>item.selected)?[index]:[]));
35
+ ids=[];
36
+ for(const index of selected){
37
+ const model=groups[index],previous=model.efforts.flatMap((item,i)=>item.selected?[i]:[]);
38
+ const efforts=await choose(model.efforts.map(item=>model.name+" / "+(item.effort||"default")),previous.length?previous:model.efforts.map((_,i)=>i));
39
+ ids.push(...efforts.map(i=>model.efforts[i].id));
40
+ }
41
+ }else ids=(await choose(state.models.map(model=>model.name),state.models.flatMap((model,index)=>model.selected!==false?[index]:[]))).map(index=>state.models[index].id);
42
+ if(!Array.isArray(ids)||new Set(ids).size!==ids.length||ids.some(id=>!state.models.some(model=>model.id===id)))throw new Error("Choose listed Antigravity model IDs.");
43
+ const available=state.models.filter(model=>ids.includes(model.id));
44
+ if(!flags.file&&available.length&&Object.hasOwn(state,"default_model")){
45
+ available.forEach((model,index)=>output.write(`${index+1}. ${terminalCell(model.name)}${model.id===state.default_model?" (default)":""}\n`));
46
+ const answer=(await ask("Default model number (Enter keeps it; none uses the app default): ")).trim();
47
+ if(answer==="none")preferred=null;
48
+ else if(answer){if(!/^\d+$/.test(answer)||!available[Number(answer)-1])throw new Error("Choose a listed default model number.");preferred=available[Number(answer)-1].id;}
49
+ }
50
+ if(preferred!==undefined&&preferred!==null&&!ids.includes(preferred)){
51
+ const choices=available.filter(item=>item.model===preferred);
52
+ preferred=(choices.find(item=>item.effort==="medium")||choices[0])?.id;
53
+ if(!preferred)throw new Error("Choose a selected Antigravity model as the default.");
54
+ }
55
+ const body={models:ids,...(preferred!==undefined?{default_model:preferred}:{})};
56
+ if(flags.preview)return print({...body,saved:false});
57
+ await confirm("Save Antigravity model settings? Reopen Gemini afterward to reload them.");
58
+ return print(await request({path:"gemini",body:{action:"models",...body}}));
59
+ }
60
+ const state = await request({ path: "gemini", ...(action==="models"&&flags.refresh?{body:{action:"refresh"},timeoutMs:20000}:["status", "models"].includes(action) ? {} : { body: { action: flags.preview ? "preview" : action, ...(action === "enable" ? { accept_background_copilot: true } : {}) }, timeoutMs: 20000 }) });
61
+ if(action==="models"&&flags.format!=="json"&&state.model_groups)return print(state.model_groups.map(model=>({model:model.name,id:model.id,source:"GitHub Copilot",context:model.context_window,default:model.default===true,
62
+ efforts:model.efforts.map(item=>(item.effort||"default")+(item.selected?" ✓":"")).join(" / ")})),[["model","Model"],["id","ID"],["source","Source"],["context","Context"],["efforts","Reasoning (selected ✓)"],["default","Default"]]);
63
+ return print(action === "models" ? state.models : state);
64
+ }
65
+ const graph = await connection(), snapshot = (await readStatus()).data, view = projectTerminalState(snapshot);
66
+ if (action === "list") {
67
+ const clients=[...view.clients];
68
+ if(!clients.some(client=>client.id==="antigravity"))clients.push({id:"antigravity",name:"Antigravity",setup:"Not checked",active:null});
69
+ return print(clients, [["id", "ID"], ["name", "Client"], ["setup", "Setup"], ["active", "Active"]]);
70
+ }
71
+ const id = ids.app ? CLI_CLIENTS[ids.app] : "codex", client = getClient(graph, id), modelPlan = client.model_plan;
72
+ if (!flags.preview && (flags.edit || ["sync", "enable", "disable"].includes(action))) requireManagement();
73
+ const feature = path.length > 3 ? path[2] : null;
74
+ if (feature || action === "status") {
75
+ const settings = id === "codex" && (flags.details || feature) ? await request({ path: "settings" }) : null;
76
+ const preference = settings?.providers?.[client.source || "github"]?.preference || {};
77
+ const locked = preference.source === "environment";
78
+ const reviewId = (locked ? preference.model : client.auto_review_model || preference.auto_review_model || preference.model) || null;
79
+ const reviewModel = modelPlan?.models.find(model => [model.id, model.public_id, model.route_id].includes(reviewId));
80
+ const details = { predictions: snapshot.client_integrations?.prediction || null, images: settings?.effective?.image_enabled || null,
81
+ auto_review: { model: reviewModel?.id || reviewId, source: reviewModel?.source || client.source,
82
+ ...(locked ? { mode: "Startup override" } : preference.followModel ? { mode: "Follow conversation model" } : {}),
83
+ effort: (locked && client.auto_review_model !== reviewModel?.route_id ? undefined : client.auto_review_effort)
84
+ ?? (locked ? undefined : preference.auto_review_effort ?? preference.reasoningEffort)
85
+ ?? (reviewModel?.capability?.values?.reasoning_efforts?.includes("low") ? "low if omitted" : "Follows client") }, memory_model: client.memory_model || { model: null } };
86
+ if (feature) return print({ client: "Codex", feature, state: details[{ prediction: "predictions", image: "images", review: "auto_review" }[feature]] });
87
+ const observed = retainedRequests(snapshot).filter(row => id === "codex" ? ["codex", "codex_app", "codex_cli"].includes(row.application) : row.application === id).at(-1);
88
+ return print({ id: ids.app, access: client.enabled ? clientSetup(client) === "Paused" ? "Paused" : "Enabled" : "Disabled", setup: view.clients.find(row => row.id === id)?.setup || clientSetup(client),
89
+ selected_models: Array.isArray(client.deployments) ? client.deployments.length : modelPlan?.models.length ?? null, unavailable_selection: (modelPlan?.unavailable || []).filter(model => !modelPlan?.available.some(candidate => candidate.source === model.source && candidate.id === model.id)),
90
+ app_adoption: view.clients.find(row => row.id === id)?.active > 0 ? "Active gateway request observed; process liveness not checked" : observed ? `Gateway request observed${observed.at || observed.time ? ` at ${observed.at || observed.time}` : ""}; process liveness not checked` : client.observed_at ? `Gateway request observed at ${client.observed_at}; process liveness not checked` : "Not observed",
91
+ active: view.clients.find(row => row.id === id)?.active ?? null, ...(id.startsWith("claude_") && flags.details ? { capability_support: modelPlan?.support, capability_adoption: client.capability_adoption, capability_sync: modelPlan?.sync } : {}), ...(id === "codex" && flags.details ? { features: details, chatgpt_sign_in: "Managed by Codex; not inferred from GitHub credentials" } : {}) });
92
+ }
93
+ if (action === "models" && !flags.edit) {
94
+ if (flags.format === "json") return print(modelPlan);
95
+ return print([...(modelPlan?.models || []).map(model => ({ source: model.source, model: model.display_name || model.id, id: model.id, state: "Selected", default: [model.route_id, model.public_id].includes(modelPlan.default_model) })),
96
+ ...(id === "codex" ? (modelPlan?.image?.models || []).map(model => ({ source: "github", model: model.name, id: model.id, state: modelPlan.image.selected_model === model.id ? "Selected image" : "Image", default: false })) : []),
97
+ ...(id === "codex" && modelPlan?.image?.selected_model && !modelPlan.image.selected_available ? [{ source: "github", model: modelPlan.image.selected_model, id: modelPlan.image.selected_model, state: "Image unavailable; retained", default: false }] : []),
98
+ ...(modelPlan?.unavailable || []).map(model => ({ source: model.source, model: model.id, id: model.id, state: !client.enabled && modelPlan?.available.some(item => item.source === model.source && item.id === model.id) ? "Retained; access disabled" : "Unavailable; retained", default: model.route_id === modelPlan.default_model }))], [["model", "Model"], ["source", "Source"], ["state", "Selection"], ["default", "Default"]]);
99
+ }
100
+ if (action === "sync") {
101
+ const preview = { client: ids.app, models: modelPlan?.models.map(model => ({ source: model.source, model: model.display_name || model.id, id: model.id, context_window: model.capability?.values.context_window ?? null, reasoning_efforts: model.capability?.values.reasoning_efforts ?? null })), unavailable: modelPlan?.unavailable, default_model: modelPlan?.default_model, image: modelPlan?.image,
102
+ current_setup: clientSetup(client), note: "Model/configuration plan only, not a byte-level file diff. Ownership is rechecked on sync; no App is restarted." };
103
+ if (flags.preview) return print(preview);output.write(print(preview) + "\n");await confirm("Write CCDX-owned client settings now?");
104
+ const result = await save({ operation: "sync_client", id, client_revision: client.revision });return print({ client: ids.app, setup: getClient(result, id).setup, image: getClient(result, id).model_plan?.image, app_adoption: "Not verified by writing configuration" });
105
+ }
106
+ if (["enable", "disable"].includes(action)) {
107
+ const enabled = action === "enable", preview = { client: ids.app, access: enabled ? "Enabled" : "Disabled", retained_source: client.source,
108
+ retained_models: client.deployments || "Legacy source binding retained", note: "Only gateway access changes; the client program stays open." };
109
+ if (flags.preview) return print(preview);output.write(print(preview) + "\n");
110
+ await confirm(enabled ? "Enable gateway access with the saved selection?" : "Disable gateway access? Later turns may fail; saved selections are retained.");
111
+ const result = await save({ operation: "client_state", id, enabled, client_revision: client.revision });
112
+ return print({ client: ids.app, setup: getClient(result, id).setup, saved: true, app_adoption: "Not verified" });
113
+ }
114
+ const body = clientBody(client);
115
+ if (action === "models") {
116
+ if (flags.file) {
117
+ const file = readFile();if (Object.keys(file).some(key => !["deployments", "default_model", "auto_sync", "image_model"].includes(key))) throw new Error("Model files allow deployments, default_model, auto_sync and image_model only.");
118
+ if (!Array.isArray(file.deployments)) throw new Error("Model files require an explicit deployments array; use [] to pause access.");
119
+ Object.assign(body, file);if (!body.deployments.length) body.default_model = null;
120
+ } else {
121
+ const available = [...(modelPlan?.available || [])], selected = Array.isArray(client.deployments) ? client.deployments : modelPlan?.models.map(model => ({ source: model.source, model: model.id })) || [];
122
+ for (const old of selected) if (!available.some(row => row.source === old.source && row.id === old.model)) available.push({ source: old.source, id: old.model, unavailable: true });
123
+ const indexes = await choose(available.map(row => `${row.source} / ${row.id}${row.unavailable ? " (unavailable; selection retained)" : ""}`), available.flatMap((row, index) => selected.some(item => item.source === row.source && item.model === row.id) ? [index] : []));
124
+ body.deployments = indexes.map(index => ({ ...selected.find(item => item.source === available[index].source && item.model === available[index].id), source: available[index].source, model: available[index].id }));
125
+ body.default_model = client.default_model || modelPlan?.default_model || null;
126
+ if (body.deployments.length) {
127
+ const defaults = body.deployments.map(item => deploymentModelId(item.source, item.model));
128
+ output.write(body.deployments.map((item, index) => `${index + 1} ${item.source} / ${item.model}`).join("\n") + "\n");
129
+ const value = (await ask(`Default model number [${Math.max(1, defaults.indexOf(body.default_model) + 1)}]: `)).trim();
130
+ if (value && (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > defaults.length)) throw new Error("Choose a listed default model number.");
131
+ body.default_model = defaults[value ? Number(value) - 1 : Math.max(0, defaults.indexOf(body.default_model))];
132
+ } else body.default_model = null;
133
+ if (id === "claude_app") for (const item of body.deployments) {
134
+ const entry = available.find(row => row.source === item.source && row.id === item.model), levels = entry?.capability?.values.reasoning_efforts || [];
135
+ if (entry?.effort_control !== "gateway" && item.reasoning_effort === undefined) continue;
136
+ output.write(`Reasoning for ${item.source} / ${item.model}: follow-app${levels.length ? ", " + levels.join(", ") : ""}\n`);
137
+ const answer = (await ask(`Default when the app omits effort [${item.reasoning_effort || "follow-app"}]: `)).trim();
138
+ if (answer === "follow-app") delete item.reasoning_effort;
139
+ else if (answer) { if (!levels.includes(answer)) throw new Error("Choose a declared reasoning level or follow-app.");item.reasoning_effort = answer; }
140
+ }
141
+ }
142
+ if (id === "codex" && !flags.file && modelPlan?.image?.models?.length) {
143
+ const images = modelPlan.image.models, current = images.findIndex(model => model.id === modelPlan.image.selected_model);
144
+ output.write(images.map((model, i) => `${i + 1} ${model.name || model.id} [Image]`).join("\n") + "\n");
145
+ const answer = (await ask(`Image model number [${Math.max(1, current + 1)}]: `)).trim();
146
+ if (answer && (!/^\d+$/.test(answer) || Number(answer) < 1 || Number(answer) > images.length)) throw new Error("Choose a listed image model number.");
147
+ body.image_model = images[answer ? Number(answer) - 1 : Math.max(0, current)].id;
148
+ }
149
+ if (body.deployments?.some(item => modelPlan?.unavailable.some(row => row.source === item.source && row.id === item.model))) throw new Error("Unavailable selections were kept. Wait for the catalog or explicitly deselect them before saving a changed plan.");
150
+ } else throw new Error("Unsupported client action.");
151
+ const memory = id === "codex" ? client.memory_model?.model : null;
152
+ const memoryModels = [...(modelPlan?.models || []), ...(modelPlan?.available || []), ...(modelPlan?.unavailable || [])].filter(row => [row.id, row.route_id, row.public_id].includes(memory));
153
+ const memoryPairs = new Set(memoryModels.map(row => row.source + "\0" + row.id));
154
+ const memoryMatch = row => memoryPairs.size ? memoryPairs.has(row.source + "\0" + (row.model || row.id)) : [row.model, row.id, row.route_id, row.public_id].includes(memory);
155
+ if (memory && (client.deployments || modelPlan?.models || []).some(memoryMatch) && Array.isArray(body.deployments) && !body.deployments.some(memoryMatch)) {
156
+ output.write(`Warning: ${terminalCell(memory)} is an observed memory dependency; memory writing may fail if it is unselected.\n`);
157
+ }
158
+ const previousModels = client.deployments || modelPlan?.models.map(model => ({ source: model.source, model: model.id })) || [];
159
+ const previousKeys = new Set(previousModels.map(item => item.source + "\0" + item.model));
160
+ const previousDefault = client.default_model || modelPlan?.models.find(model => model.public_id === modelPlan.default_model)?.route_id || null;
161
+ const imageOnly = id === "codex" && body.image_model && body.image_model !== modelPlan?.image?.selected_model
162
+ && body.deployments?.length === previousKeys.size && body.deployments.every(item => previousKeys.has(item.source + "\0" + item.model))
163
+ && body.default_model === previousDefault && (body.auto_sync !== false) === (client.auto_sync !== false);
164
+ const checked = await save({ ...body, operation: "preview_client" });
165
+ output.write(print({ client: ids.app, planned_models: checked.preview?.models.map(model => ({ source: model.source, id: model.id })), change: action, enabled: body.enabled, deployments: body.deployments, default_model: body.default_model }) + "\n");
166
+ if (flags.preview) return "Preview only; no settings changed.";
167
+ await confirm(body.enabled ? "Save this client selection?" : "Disable gateway access? Later turns may fail; the client program stays open.");
168
+ const result = await save(imageOnly ? { operation: "image_model", id: "codex", model: body.image_model, client_revision: client.revision } : body);return print({ client: ids.app, setup: getClient(result, id).setup, saved: true, app_adoption: "Not verified" });
169
+ }
@@ -3,14 +3,13 @@ import { createInterface } from "node:readline/promises";
3
3
  import { dashboardToolRequest } from "./cli-tools.mjs";
4
4
  import { readAdapterStatus } from "./cli-status.mjs";
5
5
  import { CLI_CLIENTS } from "./cli-command-spec.mjs";
6
- import { projectTerminalState, retainedRequests, clientSetup, TERMINAL_CLIENT_NAMES, terminalUptime, terminalRequestState } from "./terminal-state.mjs";
6
+ import { projectTerminalState, retainedRequests, TERMINAL_CLIENT_NAMES, terminalUptime, terminalRequestState } from "./terminal-state.mjs";
7
7
  import { formatResponsiveCliTable, cliOutputWidth, terminalCell } from "./cli-table.mjs";
8
8
  import { redactDiagnosticText } from "./diagnostic-text.mjs";
9
9
  import { settingsPreferencesSnapshot, writeSettingsPreferences, checkedPreferenceValues } from "./settings-preferences.mjs";
10
10
  import { checkedApi } from "./access-settings.mjs";
11
11
  import { hiddenQuestion } from "./cli-secret.mjs";
12
12
  import { readBoundedFileSync } from "./bounded-file.mjs";
13
- import { deploymentModelId } from "./model-capabilities.mjs";
14
13
  import { TERMINAL_COLOR_THEMES } from "./terminal-colors.mjs";
15
14
  import { previewSourceImport } from "./source-import.mjs";
16
15
  import { readAccessSettings } from "./access-settings.mjs";
@@ -217,168 +216,10 @@ export async function runManagementCommand(command, options = {}) {
217
216
  if (running) { const result = await request({ path: "settings", body });return print({ saved: result.preferences.values, effective: effective(result), nightly_update: result.nightly_update, effect: "Saved; restart requirements are shown in effective state" }); }
218
217
  writeSettingsPreferences(body, preferenceOptions);return print({ saved: settingsPreferencesSnapshot(preferenceOptions).values, effect: "Saved for the next CCDX start; no service was started" });
219
218
  }
220
- if (group === "app") {
221
- if (path.length === 3 && ["open", "focus", "restart", "check"].includes(action)) {
222
- const id = ["antigravity", "gemini"].includes(path[1]) ? "antigravity" : CLI_CLIENTS[ids.app || path[1]];
223
- if (!["codex", "claude_app", "antigravity"].includes(id)) throw new Error("This command opens desktop apps. Run Claude Code in your terminal.");
224
- const settings = await request({ path: "settings?application=" + id + "&fresh=1", timeoutMs: 15000 }), app = settings.applications?.[id];
225
- if (!app) throw new Error("This command needs the updated running service; no app was changed.");
226
- if (action === "check" || flags.preview) return print({ id, ...app, ...(flags.preview ? { action, performed: false } : {}) });
227
- if (action === "restart") await confirm("Reopen " + path[1] + "? This may interrupt its current tasks.");
228
- const result = await request({ path: "settings", body: { action: "application", id, operation: action,
229
- ...(action === "restart" ? { confirmed: true, ...(app.pid ? { expected_pid: app.pid, expected_started: app.started } : {}) } : {}) }, timeoutMs: 65000 });
230
- return print(result.last_operation?.result || result.applications?.[id]);
231
- }
232
- if (["gemini", "antigravity"].includes(path[1])) {
233
- if (["enable", "disable"].includes(action)) {
234
- const preview = { action, background_source: "GitHub Copilot (all Antigravity summaries, searches and image generation)", ordinary_Gemini_chat: "Google; no routing change" };
235
- if (flags.preview) return print(preview);
236
- output.write(print(preview) + "\n");await confirm(action === "enable" ? "Enable this Antigravity-only routing scope?" : "Pause Copilot access? Reopen Gemini afterward to restore its native route.");
237
- }
238
- if(action==="models"&&flags.edit){
239
- const state=await request({path:"gemini",...(flags.refresh?{body:{action:"refresh"},timeoutMs:20000}:{})});
240
- let ids, preferred;
241
- if(flags.file){
242
- const file=readFile(),listed=file.models;preferred=file.default_model;if(!Array.isArray(listed))throw new Error("Model files require a models array.");
243
- ids=listed.flatMap(id=>state.model_groups?.find(model=>model.id===id)?.efforts.map(item=>item.id)||[id]);
244
- }
245
- else if(Array.isArray(state.model_groups)){
246
- const groups=state.model_groups,selected=await choose(groups.map(model=>model.name),groups.flatMap((model,index)=>model.efforts.some(item=>item.selected)?[index]:[]));
247
- ids=[];
248
- for(const index of selected){
249
- const model=groups[index],previous=model.efforts.flatMap((item,i)=>item.selected?[i]:[]);
250
- const efforts=await choose(model.efforts.map(item=>model.name+" / "+(item.effort||"default")),previous.length?previous:model.efforts.map((_,i)=>i));
251
- ids.push(...efforts.map(i=>model.efforts[i].id));
252
- }
253
- }else ids=(await choose(state.models.map(model=>model.name),state.models.flatMap((model,index)=>model.selected!==false?[index]:[]))).map(index=>state.models[index].id);
254
- if(!Array.isArray(ids)||new Set(ids).size!==ids.length||ids.some(id=>!state.models.some(model=>model.id===id)))throw new Error("Choose listed Antigravity model IDs.");
255
- const available=state.models.filter(model=>ids.includes(model.id));
256
- if(!flags.file&&available.length&&Object.hasOwn(state,"default_model")){
257
- available.forEach((model,index)=>output.write(`${index+1}. ${terminalCell(model.name)}${model.id===state.default_model?" (default)":""}\n`));
258
- const answer=(await ask("Default model number (Enter keeps it; none uses the app default): ")).trim();
259
- if(answer==="none")preferred=null;
260
- else if(answer){if(!/^\d+$/.test(answer)||!available[Number(answer)-1])throw new Error("Choose a listed default model number.");preferred=available[Number(answer)-1].id;}
261
- }
262
- if(preferred!==undefined&&preferred!==null&&!ids.includes(preferred)){
263
- const choices=available.filter(item=>item.model===preferred);
264
- preferred=(choices.find(item=>item.effort==="medium")||choices[0])?.id;
265
- if(!preferred)throw new Error("Choose a selected Antigravity model as the default.");
266
- }
267
- const body={models:ids,...(preferred!==undefined?{default_model:preferred}:{})};
268
- if(flags.preview)return print({...body,saved:false});
269
- await confirm("Save Antigravity model settings? Reopen Gemini afterward to reload them.");
270
- return print(await request({path:"gemini",body:{action:"models",...body}}));
271
- }
272
- const state = await request({ path: "gemini", ...(action==="models"&&flags.refresh?{body:{action:"refresh"},timeoutMs:20000}:["status", "models"].includes(action) ? {} : { body: { action: flags.preview ? "preview" : action, ...(action === "enable" ? { accept_background_copilot: true } : {}) }, timeoutMs: 20000 }) });
273
- if(action==="models"&&flags.format!=="json"&&state.model_groups)return print(state.model_groups.map(model=>({model:model.name,id:model.id,source:"GitHub Copilot",context:model.context_window,default:model.default===true,
274
- efforts:model.efforts.map(item=>(item.effort||"default")+(item.selected?" ✓":"")).join(" / ")})),[["model","Model"],["id","ID"],["source","Source"],["context","Context"],["efforts","Reasoning (selected ✓)"],["default","Default"]]);
275
- return print(action === "models" ? state.models : state);
276
- }
277
- const graph = await connection(), snapshot = (await readStatus()).data, view = projectTerminalState(snapshot);
278
- if (action === "list") {
279
- const clients=[...view.clients];
280
- if(!clients.some(client=>client.id==="antigravity"))clients.push({id:"antigravity",name:"Antigravity",setup:"Not checked",active:null});
281
- return print(clients, [["id", "ID"], ["name", "Client"], ["setup", "Setup"], ["active", "Active"]]);
282
- }
283
- const id = ids.app ? CLI_CLIENTS[ids.app] : "codex", client = getClient(graph, id), modelPlan = client.model_plan;
284
- if (!flags.preview && (flags.edit || ["sync", "enable", "disable"].includes(action))) requireManagement();
285
- const feature = path.length > 3 ? path[2] : null;
286
- if (feature || action === "status") {
287
- const settings = id === "codex" && (flags.details || feature) ? await request({ path: "settings" }) : null;
288
- const preference = settings?.providers?.[client.source || "github"]?.preference || {};
289
- const locked = preference.source === "environment";
290
- const reviewId = (locked ? preference.model : client.auto_review_model || preference.auto_review_model || preference.model) || null;
291
- const reviewModel = modelPlan?.models.find(model => [model.id, model.public_id, model.route_id].includes(reviewId));
292
- const details = { predictions: snapshot.client_integrations?.prediction || null, images: settings?.effective?.image_enabled || null,
293
- auto_review: { model: reviewModel?.id || reviewId, source: reviewModel?.source || client.source,
294
- ...(locked ? { mode: "Startup override" } : preference.followModel ? { mode: "Follow conversation model" } : {}),
295
- effort: (locked && client.auto_review_model !== reviewModel?.route_id ? undefined : client.auto_review_effort)
296
- ?? (locked ? undefined : preference.auto_review_effort ?? preference.reasoningEffort)
297
- ?? (reviewModel?.capability?.values?.reasoning_efforts?.includes("low") ? "low if omitted" : "Follows client") }, memory_model: client.memory_model || { model: null } };
298
- if (feature) return print({ client: "Codex", feature, state: details[{ prediction: "predictions", image: "images", review: "auto_review" }[feature]] });
299
- const observed = retainedRequests(snapshot).filter(row => id === "codex" ? ["codex", "codex_app", "codex_cli"].includes(row.application) : row.application === id).at(-1);
300
- return print({ id: ids.app, access: client.enabled ? clientSetup(client) === "Paused" ? "Paused" : "Enabled" : "Disabled", setup: view.clients.find(row => row.id === id)?.setup || clientSetup(client),
301
- selected_models: Array.isArray(client.deployments) ? client.deployments.length : modelPlan?.models.length ?? null, unavailable_selection: (modelPlan?.unavailable || []).filter(model => !modelPlan?.available.some(candidate => candidate.source === model.source && candidate.id === model.id)),
302
- app_adoption: view.clients.find(row => row.id === id)?.active > 0 ? "Active gateway request observed; process liveness not checked" : observed ? `Gateway request observed${observed.at || observed.time ? ` at ${observed.at || observed.time}` : ""}; process liveness not checked` : client.observed_at ? `Gateway request observed at ${client.observed_at}; process liveness not checked` : "Not observed",
303
- active: view.clients.find(row => row.id === id)?.active ?? null, ...(id.startsWith("claude_") && flags.details ? { capability_support: modelPlan?.support, capability_adoption: client.capability_adoption, capability_sync: modelPlan?.sync } : {}), ...(id === "codex" && flags.details ? { features: details, chatgpt_sign_in: "Managed by Codex; not inferred from GitHub credentials" } : {}) });
304
- }
305
- if (action === "models" && !flags.edit) {
306
- if (flags.format === "json") return print(modelPlan);
307
- return print([...(modelPlan?.models || []).map(model => ({ source: model.source, model: model.display_name || model.id, id: model.id, state: "Selected", default: [model.route_id, model.public_id].includes(modelPlan.default_model) })),
308
- ...(id === "codex" ? (modelPlan?.image?.models || []).map(model => ({ source: "github", model: model.name, id: model.id, state: modelPlan.image.selected_model === model.id ? "Selected image" : "Image", default: false })) : []),
309
- ...(id === "codex" && modelPlan?.image?.selected_model && !modelPlan.image.selected_available ? [{ source: "github", model: modelPlan.image.selected_model, id: modelPlan.image.selected_model, state: "Image unavailable; retained", default: false }] : []),
310
- ...(modelPlan?.unavailable || []).map(model => ({ source: model.source, model: model.id, id: model.id, state: !client.enabled && modelPlan?.available.some(item => item.source === model.source && item.id === model.id) ? "Retained; access disabled" : "Unavailable; retained", default: model.route_id === modelPlan.default_model }))], [["model", "Model"], ["source", "Source"], ["state", "Selection"], ["default", "Default"]]);
311
- }
312
- if (action === "sync") {
313
- const preview = { client: ids.app, models: modelPlan?.models.map(model => ({ source: model.source, model: model.display_name || model.id, id: model.id, context_window: model.capability?.values.context_window ?? null, reasoning_efforts: model.capability?.values.reasoning_efforts ?? null })), unavailable: modelPlan?.unavailable, default_model: modelPlan?.default_model, image: modelPlan?.image,
314
- current_setup: clientSetup(client), note: "Model/configuration plan only, not a byte-level file diff. Ownership is rechecked on sync; no App is restarted." };
315
- if (flags.preview) return print(preview);output.write(print(preview) + "\n");await confirm("Write CCDX-owned client settings now?");
316
- const result = await save({ operation: "sync_client", id, client_revision: client.revision });return print({ client: ids.app, setup: getClient(result, id).setup, image: getClient(result, id).model_plan?.image, app_adoption: "Not verified by writing configuration" });
317
- }
318
- if (["enable", "disable"].includes(action)) {
319
- const enabled = action === "enable", preview = { client: ids.app, access: enabled ? "Enabled" : "Disabled", retained_source: client.source,
320
- retained_models: client.deployments || "Legacy source binding retained", note: "Only gateway access changes; the client program stays open." };
321
- if (flags.preview) return print(preview);output.write(print(preview) + "\n");
322
- await confirm(enabled ? "Enable gateway access with the saved selection?" : "Disable gateway access? Later turns may fail; saved selections are retained.");
323
- const result = await save({ operation: "client_state", id, enabled, client_revision: client.revision });
324
- return print({ client: ids.app, setup: getClient(result, id).setup, saved: true, app_adoption: "Not verified" });
325
- }
326
- const body = clientBody(client);
327
- if (action === "models") {
328
- if (flags.file) {
329
- const file = readFile();if (Object.keys(file).some(key => !["deployments", "default_model", "auto_sync", "image_model"].includes(key))) throw new Error("Model files allow deployments, default_model, auto_sync and image_model only.");
330
- if (!Array.isArray(file.deployments)) throw new Error("Model files require an explicit deployments array; use [] to pause access.");
331
- Object.assign(body, file);if (!body.deployments.length) body.default_model = null;
332
- } else {
333
- const available = [...(modelPlan?.available || [])], selected = Array.isArray(client.deployments) ? client.deployments : modelPlan?.models.map(model => ({ source: model.source, model: model.id })) || [];
334
- for (const old of selected) if (!available.some(row => row.source === old.source && row.id === old.model)) available.push({ source: old.source, id: old.model, unavailable: true });
335
- const indexes = await choose(available.map(row => `${row.source} / ${row.id}${row.unavailable ? " (unavailable; selection retained)" : ""}`), available.flatMap((row, index) => selected.some(item => item.source === row.source && item.model === row.id) ? [index] : []));
336
- body.deployments = indexes.map(index => ({ ...selected.find(item => item.source === available[index].source && item.model === available[index].id), source: available[index].source, model: available[index].id }));
337
- body.default_model = client.default_model || modelPlan?.default_model || null;
338
- if (body.deployments.length) {
339
- const defaults = body.deployments.map(item => deploymentModelId(item.source, item.model));
340
- output.write(body.deployments.map((item, index) => `${index + 1} ${item.source} / ${item.model}`).join("\n") + "\n");
341
- const value = (await ask(`Default model number [${Math.max(1, defaults.indexOf(body.default_model) + 1)}]: `)).trim();
342
- if (value && (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > defaults.length)) throw new Error("Choose a listed default model number.");
343
- body.default_model = defaults[value ? Number(value) - 1 : Math.max(0, defaults.indexOf(body.default_model))];
344
- } else body.default_model = null;
345
- if (id === "claude_app") for (const item of body.deployments) {
346
- const entry = available.find(row => row.source === item.source && row.id === item.model), levels = entry?.capability?.values.reasoning_efforts || [];
347
- if (entry?.effort_control !== "gateway" && item.reasoning_effort === undefined) continue;
348
- output.write(`Reasoning for ${item.source} / ${item.model}: follow-app${levels.length ? ", " + levels.join(", ") : ""}\n`);
349
- const answer = (await ask(`Default when the app omits effort [${item.reasoning_effort || "follow-app"}]: `)).trim();
350
- if (answer === "follow-app") delete item.reasoning_effort;
351
- else if (answer) { if (!levels.includes(answer)) throw new Error("Choose a declared reasoning level or follow-app.");item.reasoning_effort = answer; }
352
- }
353
- }
354
- if (id === "codex" && !flags.file && modelPlan?.image?.models?.length) {
355
- const images = modelPlan.image.models, current = images.findIndex(model => model.id === modelPlan.image.selected_model);
356
- output.write(images.map((model, i) => `${i + 1} ${model.name || model.id} [Image]`).join("\n") + "\n");
357
- const answer = (await ask(`Image model number [${Math.max(1, current + 1)}]: `)).trim();
358
- if (answer && (!/^\d+$/.test(answer) || Number(answer) < 1 || Number(answer) > images.length)) throw new Error("Choose a listed image model number.");
359
- body.image_model = images[answer ? Number(answer) - 1 : Math.max(0, current)].id;
360
- }
361
- if (body.deployments?.some(item => modelPlan?.unavailable.some(row => row.source === item.source && row.id === item.model))) throw new Error("Unavailable selections were kept. Wait for the catalog or explicitly deselect them before saving a changed plan.");
362
- } else throw new Error("Unsupported client action.");
363
- const memory = id === "codex" ? client.memory_model?.model : null;
364
- const memoryModels = [...(modelPlan?.models || []), ...(modelPlan?.available || []), ...(modelPlan?.unavailable || [])].filter(row => [row.id, row.route_id, row.public_id].includes(memory));
365
- const memoryPairs = new Set(memoryModels.map(row => row.source + "\0" + row.id));
366
- const memoryMatch = row => memoryPairs.size ? memoryPairs.has(row.source + "\0" + (row.model || row.id)) : [row.model, row.id, row.route_id, row.public_id].includes(memory);
367
- if (memory && (client.deployments || modelPlan?.models || []).some(memoryMatch) && Array.isArray(body.deployments) && !body.deployments.some(memoryMatch)) {
368
- output.write(`Warning: ${terminalCell(memory)} is an observed memory dependency; memory writing may fail if it is unselected.\n`);
369
- }
370
- const previousModels = client.deployments || modelPlan?.models.map(model => ({ source: model.source, model: model.id })) || [];
371
- const previousKeys = new Set(previousModels.map(item => item.source + "\0" + item.model));
372
- const previousDefault = client.default_model || modelPlan?.models.find(model => model.public_id === modelPlan.default_model)?.route_id || null;
373
- const imageOnly = id === "codex" && body.image_model && body.image_model !== modelPlan?.image?.selected_model
374
- && body.deployments?.length === previousKeys.size && body.deployments.every(item => previousKeys.has(item.source + "\0" + item.model))
375
- && body.default_model === previousDefault && (body.auto_sync !== false) === (client.auto_sync !== false);
376
- const checked = await save({ ...body, operation: "preview_client" });
377
- output.write(print({ client: ids.app, planned_models: checked.preview?.models.map(model => ({ source: model.source, id: model.id })), change: action, enabled: body.enabled, deployments: body.deployments, default_model: body.default_model }) + "\n");
378
- if (flags.preview) return "Preview only; no settings changed.";
379
- await confirm(body.enabled ? "Save this client selection?" : "Disable gateway access? Later turns may fail; the client program stays open.");
380
- const result = await save(imageOnly ? { operation: "image_model", id: "codex", model: body.image_model, client_revision: client.revision } : body);return print({ client: ids.app, setup: getClient(result, id).setup, saved: true, app_adoption: "Not verified" });
381
- }
219
+ if (group === "app") return (await import("./cli-management-app.mjs")).runAppCommand({
220
+ path, ids, flags, output, request, readStatus, ask, print, confirm, choose,
221
+ connection, requireManagement, save, getClient, clientBody, readFile,
222
+ });
382
223
  if (group !== "source") throw new Error("Unknown management command.");
383
224
  if (action === "import") {
384
225
  if (Boolean(flags.file) === Boolean(flags.from)) throw new Error("Use --file FILE or --from cc-switch|magpie.");
@@ -58,7 +58,7 @@ export function createLocalPrivacy(options = {}) {
58
58
  if (disposed) throw privacyFailure("engine_unavailable");
59
59
  loadKey();
60
60
  const start = performance.now();
61
- const deadline = new AbortController();let session, timer, textKeys, budget = options.checkTimeoutMs ?? 15000;
61
+ const deadline = new AbortController();let session, timer, textKeys, timing, budget = options.checkTimeoutMs ?? 15000;
62
62
  const arm = () => {
63
63
  clearTimeout(timer);timer = setTimeout(() => deadline.abort(privacyFailure("check_timeout", "waiting")), Math.max(1, budget - (performance.now() - start)));
64
64
  timer.unref?.();
@@ -72,7 +72,7 @@ export function createLocalPrivacy(options = {}) {
72
72
  };
73
73
  try { session = await maskPrivacyRequest(body, { protocol, client, personal: saved.personal, secret,
74
74
  find: (texts, context) => detection.find(texts, { ...context, onKey(text, key) { if (text.length >= 256) (textKeys ||= new Map()).set(text, key); } }),
75
- rules: (text, personal) => rules.find(text, personal, textKeys?.get(text)), onPlan,
75
+ rules: (text, personal) => rules.find(text, personal, textKeys?.get(text)), onPlan, onTiming: value => { timing=value; },
76
76
  signal: signal ? AbortSignal.any([signal, deadline.signal]) : deadline.signal }); }
77
77
  catch (error) {
78
78
  const failure = deadline.signal.aborted && !signal?.aborted ? privacyFailure("check_timeout", "waiting") : error;
@@ -83,7 +83,7 @@ export function createLocalPrivacy(options = {}) {
83
83
  } finally { clearTimeout(timer);textKeys?.clear(); }
84
84
  if (signal?.aborted) { session.release();throw signal.reason; }
85
85
  markRequestObservation({ privacy_count: session.count, privacy_ms: Math.round(performance.now() - start), privacy_state: "checked" });
86
- actionError = null;lastCheck = { state: "checked", at: new Date().toISOString(), elapsed_ms: Math.round(performance.now() - start), count: session.count, wait_budget_ms: budget };changes.changed();
86
+ actionError = null;lastCheck = { state: "checked", at: new Date().toISOString(), elapsed_ms: Math.round(performance.now() - start), count: session.count, wait_budget_ms: budget, ...(timing ? {timing} : {}) };changes.changed();
87
87
  if (onSession) { onSession(session);return session.body; }
88
88
  if (res && session.count) attachSession(res, session);
89
89
  return session.body;
@@ -13,7 +13,7 @@ export function isManagementRoute(method, pathname) {
13
13
 
14
14
  // Management retains its own access checks; it receives snapshots and explicit
15
15
  // actions, never an inference client or a second integration lifecycle.
16
- export function createManagementHandler({ statusSnapshot, activityEvents, nativePredictionPac, fixPrediction, requestBodyTimeoutMs } = {}) {
16
+ export function createManagementHandler({ statusSnapshot, summarySnapshot, activityEvents, nativePredictionPac, fixPrediction, requestBodyTimeoutMs } = {}) {
17
17
  const options = { nativePredictionPac, fixPrediction };
18
18
  return async (req, res, pathname) => {
19
19
  if (req.method === "GET" && pathname === ACTIVITY_EVENTS_PATH) {
@@ -32,8 +32,8 @@ export function createManagementHandler({ statusSnapshot, activityEvents, native
32
32
  return;
33
33
  }
34
34
  res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
35
- const snapshot = statusSnapshot();
36
- res.end(JSON.stringify(new URL(req.url, "http://localhost").searchParams.get("scope") === "summary" ? statusSummary(snapshot) : snapshot));
35
+ const summary = new URL(req.url, "http://localhost").searchParams.get("scope") === "summary";
36
+ res.end(JSON.stringify(summary ? (summarySnapshot ? summarySnapshot() : statusSummary(statusSnapshot())) : statusSnapshot()));
37
37
  return;
38
38
  }
39
39
 
@@ -165,6 +165,14 @@ function safeClientRuntimeStatus(client) {
165
165
  };
166
166
  }
167
167
 
168
+ export function activeModels(requests, activeImages) {
169
+ const activityCounts = ["responses", "responses_compact", "messages", "search", "antigravity"].map(route => requests.by_route[route]?.active || 0);
170
+ activityCounts.push(activeImages);
171
+ const active = activityCounts.every(value => Number.isSafeInteger(value) && value >= 0)
172
+ && Number.isSafeInteger(activityCounts.reduce((sum, value) => sum + value, 0)) ? activityCounts.reduce((sum, value) => sum + value, 0) : null;
173
+ return active;
174
+ }
175
+
168
176
  export function runtimeStatusPayload({
169
177
  metrics,
170
178
  streamPerformance,
@@ -200,10 +208,7 @@ export function runtimeStatusPayload({
200
208
  }
201
209
  const history = responseHistoryStats();
202
210
  const requests = metrics?.snapshot?.() || createRequestMetrics().snapshot();
203
- const activityCounts = ["responses", "responses_compact", "messages", "search", "antigravity"].map(route => requests.by_route[route]?.active || 0);
204
- activityCounts.push(imageGeneration?.active ?? 0);
205
- const active = activityCounts.every(value => Number.isSafeInteger(value) && value >= 0)
206
- && Number.isSafeInteger(activityCounts.reduce((sum, value) => sum + value, 0)) ? activityCounts.reduce((sum, value) => sum + value, 0) : null;
211
+ const active = activeModels(requests, imageGeneration?.active ?? 0);
207
212
  return {
208
213
  ...adapterHealthPayload(),
209
214
  uptime_ms: Math.round(process.uptime() * 1000),
@@ -165,10 +165,16 @@ function cloneGemini(value) {
165
165
  if (!value || typeof value !== "object" || JSON.isRawJSON(value)) return value;
166
166
  return Array.isArray(value) ? value.map(cloneGemini) : Object.fromEntries(Object.entries(value).map(([key, item]) => [key, cloneGemini(item)]));
167
167
  }
168
- export async function maskPrivacyRequest(body, { protocol, client = "api", personal = false, secret, find, signal, onPlan, rules = ruleSpans, seedMappings }) {
169
- const copy = protocol === "gemini" ? cloneGemini(body) : structuredClone(body), { items, nested } = requestTexts(copy, protocol), texts = items.map(item => item.text);
170
- if (items.length > 8192 || texts.reduce((n, text) => n + Buffer.byteLength(text), 0) > 8 * 1024 * 1024) throw privacyFailure("request_too_large");
171
- const found = texts.length ? await find(texts, { signal, onPlan }) : [], values = new Map(seedMappings), kinds = {}, total = { count: 0, bytes: 0 };
168
+ export async function maskPrivacyRequest(body, { protocol, client = "api", personal = false, secret, find, signal, onPlan, onTiming, rules = ruleSpans, seedMappings }) {
169
+ const started=onTiming&&performance.now();
170
+ const { items } = requestTexts(body, protocol), texts = items.map(item => item.text);
171
+ let copy=body, target;
172
+ const bytes=texts.reduce((n,text)=>n+Buffer.byteLength(text),0);
173
+ if (items.length > 8192 || bytes > 8 * 1024 * 1024) throw privacyFailure("request_too_large");
174
+ const measure=onTiming&&bytes>=512*1024;
175
+ const scanEnd=measure&&performance.now();
176
+ const found=texts.length?await find(texts,{signal,onPlan}):[];
177
+ const detectionEnd=measure&&performance.now(),values=new Map(seedMappings),kinds={},total={count:0,bytes:0};
172
178
  if (!Array.isArray(found) || found.length !== texts.length) throw privacyFailure("engine_invalid");
173
179
  for (let i = 0; i < items.length; i++) {
174
180
  const item = items[i], spans = rules(item.text, personal);let bytes;
@@ -192,13 +198,22 @@ export async function maskPrivacyRequest(body, { protocol, client = "api", perso
192
198
  if (!values.has(token)) { total.bytes += Buffer.byteLength(value);if (values.size >= 8192 || total.bytes > 4 * 1024 * 1024) throw privacyFailure("mapping_limit");values.set(token, value); }
193
199
  output += item.text.slice(end, span.start) + token;end = span.end;total.count++;kinds[span.kind] = (kinds[span.kind] || 0) + 1;
194
200
  }
195
- if (end) item.parent[item.key] = output + item.text.slice(end);
201
+ if(end){
202
+ if(!target){
203
+ copy=protocol==="gemini"?cloneGemini(body):structuredClone(body);
204
+ target=requestTexts(copy,protocol);
205
+ }
206
+ const field=target.items[i];
207
+ field.parent[field.key]=output+item.text.slice(end);
208
+ }
196
209
  }
197
- if (total.count) for (const item of nested) {
210
+ if(target)for(const item of target.nested){
198
211
  const ordinary = JSON.stringify(item.value), original = item.parent[item.key];
199
212
  item.parent[item.key] = ordinary !== original && possibleLossyNumber.test(original)
200
213
  ? JSON.stringify(overlayToolStrings(parseToolArguments(original), item.value)) : ordinary;
201
214
  }
215
+ if(measure)onTiming({ scan_ms: Math.round(scanEnd-started), detection_ms: Math.round(detectionEnd-scanEnd),
216
+ merge_ms: Math.round(performance.now()-detectionEnd) });
202
217
  const restoreText = text => text.replace(tokenPattern, token => values.get(token) ?? token);
203
218
  function restoreValue(value, inToolData = false) {
204
219
  if (typeof value === "string") return restoreText(value);
@@ -1,3 +1,16 @@
1
+ import {adapterHealthPayload} from "./running-adapter.mjs";
2
+ import {activeModels} from "./observability.mjs";
3
+ import {runtimeUsageSnapshot} from "./usage.mjs";
4
+
5
+ export function runtimeStatusSummary(requests, activeImages) {
6
+ return statusSummary({
7
+ ...adapterHealthPayload(),
8
+ uptime_ms: Math.round(process.uptime() * 1000),
9
+ model_activity: { active: activeModels(requests, activeImages) },
10
+ runtime_usage: runtimeUsageSnapshot(),
11
+ });
12
+ }
13
+
1
14
  // An explicit projection, never a partial replacement for the full diagnostic
2
15
  // snapshot. Old callers keep the complete status contract by default.
3
16
  export function statusSummary(snapshot) {