codex-copilot-dx 1.4.12 → 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.
- package/README.md +3 -3
- package/docs/ARCHITECTURE.md +8 -0
- package/docs/REFERENCE.md +17 -15
- package/package.json +1 -1
- package/src/access-settings.mjs +1 -0
- package/src/adapter.mjs +2 -0
- package/src/antigravity-bindings.mjs +83 -0
- package/src/antigravity-chat-bridge.mjs +38 -8
- package/src/antigravity-handler.mjs +70 -37
- package/src/antigravity-runtime.mjs +44 -35
- package/src/cli-command-spec.mjs +1 -1
- package/src/cli-management-app.mjs +169 -0
- package/src/cli-management.mjs +7 -164
- package/src/connection-management.mjs +2 -0
- package/src/connection-routing.mjs +14 -5
- package/src/context-compaction-wire.mjs +6 -6
- package/src/dashboard/connections.js +13 -3
- package/src/dashboard/features.js +2 -2
- package/src/dashboard/index.html +41 -37
- package/src/dashboard/language.js +32 -17
- package/src/dashboard/status.js +20 -28
- package/src/dashboard/tool-activity-machines.js +362 -0
- package/src/dashboard/tool-activity.js +24 -115
- package/src/dashboard/tools.js +3 -4
- package/src/dashboard/ui.css +24 -3
- package/src/dashboard/ui.js +14 -0
- package/src/dashboard/usage.js +9 -1
- package/src/dashboard.mjs +1 -0
- package/src/local-privacy.mjs +3 -3
- package/src/management-routes.mjs +3 -3
- package/src/observability.mjs +9 -4
- package/src/privacy-transform.mjs +21 -6
- package/src/response-failures.mjs +7 -3
- package/src/safe-upstream-error.mjs +2 -2
- package/src/status-summary.mjs +13 -0
- package/src/stream-performance.mjs +1 -1
- package/src/terminal-state.mjs +8 -2
|
@@ -4,13 +4,14 @@ import {buildResponsesUsageRecord,recordUsage} from "./usage-store.mjs";
|
|
|
4
4
|
import {createRequestAbort,abortErrorStatusCode,readJsonBody,readBoundedResponseText,writeOrDrain,httpError,sendJsonError,sendUpstreamError} from "./http-transport.mjs";
|
|
5
5
|
import {safeUpstreamResponseHeaders,upstreamRejectionHeaders} from "./upstream-headers.mjs";
|
|
6
6
|
import {isLoopbackAddress,isLoopbackHostHeader} from "./security.mjs";
|
|
7
|
-
import {antigravityToChat,chatToAntigravity,chatStreamToAntigravity,parseAntigravityJSON} from "./antigravity-chat-bridge.mjs";
|
|
7
|
+
import {antigravityToChat,chatToAntigravity,chatStreamToAntigravity,mergeChatUsage,parseAntigravityJSON} from "./antigravity-chat-bridge.mjs";
|
|
8
8
|
import {ANTIGRAVITY_MODEL_PREFIX,ANTIGRAVITY_NATIVE_PREFIX,antigravityCopilotModels,hasAntigravityAgentDefault,mergeAntigravityModels} from "./antigravity-models.mjs";
|
|
9
9
|
import {createPrivacyTextFragments} from "./privacy-stream.mjs";
|
|
10
10
|
import {createGoogleResponseObserver,googleUsageEvent} from "./antigravity-usage.mjs";
|
|
11
11
|
import {currentRequestContext,observeRequestedModel} from "./request-context.mjs";
|
|
12
12
|
import {measureRequestStageAsync,markUpstreamStarted,markUpstreamHeaders,markFirstOutput,markOutputTokens,markRequestObservation,markResponseModel,markResponseErrorOrigin,markResponseTerminal,markToolActivity} from "./stream-performance.mjs";
|
|
13
13
|
import {isCompactionRequest} from "./context-compaction.mjs";
|
|
14
|
+
import {safeUpstreamReason} from "./safe-upstream-error.mjs";
|
|
14
15
|
import {compactionSummarizer} from "./context-compaction-wire.mjs";
|
|
15
16
|
import {requestPurpose} from "./request-context.mjs";
|
|
16
17
|
import {observeContextSession} from "./context-metrics.mjs";
|
|
@@ -44,23 +45,27 @@ function groundedSearch(result,query){
|
|
|
44
45
|
|
|
45
46
|
export function createAntigravityHandler({client,models=()=>[],selectedModels=()=>null,defaultModel=()=>null,enabled=()=>false,privacy,searchFn,imageFn,guardSource,acquireRequest=async()=>()=>{},sourceAdmission,applicationEvidence,
|
|
46
47
|
nativeModels=()=>[],resolveNativeModel=()=>null,
|
|
47
|
-
compaction,compactionProfile=()=>"github",
|
|
48
|
-
generationSettings=()=>({ selection:selectedModels(), copilotTimeoutMs })}={}) {
|
|
48
|
+
compaction,compactionProfile=()=>"github",prepareConversationBinding=()=>{},resolveCompactionSource=()=>null,recordUsageFn=recordUsage,fetchGoogle=fetch,googleOrigin=GOOGLE_ORIGIN,requestBodyTimeoutMs=120000,upstreamTimeoutMs=180000,copilotTimeoutMs,streamIdleTimeoutMs=60000,
|
|
49
|
+
requestSettings,generationSettings=()=>({ selection:selectedModels(), copilotTimeoutMs, preferred:defaultModel() })}={}) {
|
|
49
50
|
if(![GOOGLE_ORIGIN,"https://cloudcode-pa.googleapis.com"].includes(googleOrigin))throw new Error("Unrecognized Google control origin");
|
|
50
51
|
const acquireControl=createRequestAdmission({maxBytes:4*CONTROL_BODY_BYTES,maxQueued:8});
|
|
51
52
|
let active=0,observed=false,catalogModels=null,catalogDefaultSupported=null,catalogDefaultModel=null;const nativeWindows=new Map();
|
|
52
53
|
const counts={total:0,google:0,copilot:0,search:0,images:0,failed:0};
|
|
53
54
|
const handler=async(req,res)=>{
|
|
54
|
-
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;
|
|
55
56
|
const releaseInput=()=>{
|
|
56
57
|
body=null;request=null;if(converted)converted.chat=null;if(session)session.body=null;
|
|
57
58
|
const done=release;release=()=>{};done();
|
|
58
59
|
};
|
|
59
|
-
const
|
|
60
|
+
const confirmBinding=()=>{
|
|
61
|
+
if(outcome==="completed"&&commitBinding&&!abort.signal.aborted){
|
|
62
|
+
abort.clearTimeout();
|
|
63
|
+
return commitBinding(abort.signal);
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
const captureUsage=(event,usage=mergeChatUsage(null,event?.usage))=>{
|
|
60
67
|
if(!event?.usage&&!event?.copilot_usage)return;
|
|
61
|
-
const known=value=>Number.isSafeInteger(value)&&value>=0,u={
|
|
62
|
-
for(const key of ["prompt_tokens","completion_tokens","total_tokens"])if(known(incoming?.[key]))u[key]=incoming[key];
|
|
63
|
-
for(const [key,field]of [["prompt_tokens_details","cached_tokens"],["completion_tokens_details","reasoning_tokens"]])if(known(incoming?.[key]?.[field]))u[key]={[field]:incoming[key][field]};
|
|
68
|
+
const known=value=>Number.isSafeInteger(value)&&value>=0,u=usage||{};
|
|
64
69
|
const billing=Array.isArray(event.copilot_usage?.token_details)?event.copilot_usage:undefined;
|
|
65
70
|
usageEvent={...usageEvent,...(Object.keys(u).length?{usage:u}:{}),...(billing?{copilot_usage:billing}:{}),
|
|
66
71
|
...(typeof event.id==="string"?{id:event.id}:{}),...(typeof event.model==="string"?{model:event.model}:{})};
|
|
@@ -72,8 +77,9 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
72
77
|
};
|
|
73
78
|
active++;counts.total++;
|
|
74
79
|
try{
|
|
75
|
-
if(!enabled())throw httpError("Antigravity integration is disabled",503);
|
|
76
80
|
if(!isLoopbackAddress(req.socket?.remoteAddress)||!isLoopbackHostHeader(req.headers.host)||Object.hasOwn(req.headers,"origin"))throw httpError("Antigravity requires a native local client",403);
|
|
81
|
+
const config=requestSettings?.();
|
|
82
|
+
if(!enabled(config))throw httpError("Antigravity integration is disabled",503);
|
|
77
83
|
if(!["POST","GET"].includes(req.method))throw httpError("Unsupported Antigravity method",405);
|
|
78
84
|
const local=new URL(req.url,"http://localhost"),route=local.pathname.slice(PREFIX.length);
|
|
79
85
|
const match=/^\/v1internal(?::|\/)([A-Za-z][A-Za-z0-9]*)$/.exec(route);
|
|
@@ -99,7 +105,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
99
105
|
if(compacting&&context){context.purpose=requestPurpose(req.headers["x-ccdx-purpose"],"compaction");context.streamPerformance?.setPurpose(context.purpose)}
|
|
100
106
|
if(compacting)markRequestObservation({compaction:1});
|
|
101
107
|
if(body?.model)observeRequestedModel(body);
|
|
102
|
-
const compactBinding=compacting?await resolveCompactionSource(body):null;
|
|
108
|
+
const compactBinding=compacting?await resolveCompactionSource(body,config):null;
|
|
103
109
|
if(compactBinding?.model)body={...body,model:compactBinding.model};
|
|
104
110
|
markRequestObservation({requested_model:context?.requestedModel});
|
|
105
111
|
abort.setTimeout(upstreamTimeoutMs,"upstream_timeout");
|
|
@@ -134,7 +140,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
134
140
|
if(method==="fetchAvailableModels"&&upstream.ok){
|
|
135
141
|
const value=JSON.parse(await readBoundedResponseText(upstream,{maxBytes:8*1024*1024,signal:abort.signal,label:"Google model catalog"}));
|
|
136
142
|
nativeWindows.clear();for(const[id,entry]of Object.entries(value.models||{}).slice(0,256))if(Number.isSafeInteger(entry?.maxTokens)&&entry.maxTokens>0){nativeWindows.set(id,entry.maxTokens);if(typeof entry.model==="string")nativeWindows.set(entry.model,entry.maxTokens)}
|
|
137
|
-
const merged=mergeAntigravityModels(value,models(),selectedModels(),defaultModel(),nativeModels());
|
|
143
|
+
const merged=mergeAntigravityModels(value,models(config),selectedModels(config),defaultModel(config),nativeModels(config));
|
|
138
144
|
catalogDefaultSupported=hasAntigravityAgentDefault(value);
|
|
139
145
|
catalogDefaultModel=catalogDefaultSupported&&merged.defaultAgentModelId.startsWith(ANTIGRAVITY_MODEL_PREFIX)?merged.defaultAgentModelId:null;
|
|
140
146
|
catalogModels=Object.keys(merged.models).filter(id=>id.startsWith(ANTIGRAVITY_MODEL_PREFIX)||id.startsWith(ANTIGRAVITY_NATIVE_PREFIX));
|
|
@@ -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=()=>{
|
|
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,12 +175,13 @@ 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();
|
|
172
182
|
};
|
|
173
183
|
if(method==="countTokens"&&req.method==="POST"&&typeof body?.model==="string"&&body.model.startsWith(ANTIGRAVITY_NATIVE_PREFIX)){
|
|
174
|
-
const selected=resolveNativeModel(body.model);
|
|
184
|
+
const selected=resolveNativeModel(body.model,config);
|
|
175
185
|
if(!selected)throw httpError("The selected Gemini source is unavailable",503);
|
|
176
186
|
if(!body.request)throw httpError("Invalid Gemini token count request",400);
|
|
177
187
|
if(body.request.labels?.root_cascade_id||body.request.labels?.cascade_id)await guardSource?.(body,selected.source,abort.signal);
|
|
@@ -195,13 +205,13 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
195
205
|
observed=true;return await native();
|
|
196
206
|
}
|
|
197
207
|
if(req.method!=="POST"||!body||typeof body.model!=="string"||!body.request)throw httpError("Invalid Antigravity generation request",400);
|
|
198
|
-
const { selection, copilotTimeoutMs:requestCopilotTimeoutMs }=generationSettings();
|
|
208
|
+
const { selection, copilotTimeoutMs:requestCopilotTimeoutMs, preferred }=generationSettings(config);
|
|
199
209
|
if(body.model.startsWith(ANTIGRAVITY_NATIVE_PREFIX)){
|
|
200
|
-
const selected=resolveNativeModel(body.model);
|
|
210
|
+
const selected=resolveNativeModel(body.model,config);
|
|
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
|
-
await guardSource?.(body,selected.source,abort.signal);
|
|
204
|
-
if(body.requestType==="agent")
|
|
213
|
+
const profile=await guardSource?.(body,selected.source,abort.signal);
|
|
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,19 +272,20 @@ 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
|
}
|
|
269
|
-
const copilotModels=antigravityCopilotModels(models()),selected=copilotModels.find(model=>model.id===body.model&&(selection===null||selection.includes(model.id)));
|
|
279
|
+
const copilotModels=antigravityCopilotModels(models(config)),selected=copilotModels.find(model=>model.id===body.model&&(selection===null||selection.includes(model.id)));
|
|
270
280
|
if((body.requestType==="agent"||compactBinding?.source==="google")&&!selected){
|
|
271
281
|
if(body.model.startsWith(ANTIGRAVITY_MODEL_PREFIX))throw httpError("The selected Copilot model is unavailable",503);
|
|
272
|
-
|
|
273
|
-
|
|
282
|
+
const hasSession=body.requestType==="agent"||body.request?.labels?.root_cascade_id||body.request?.labels?.cascade_id;
|
|
283
|
+
const profile=hasSession?await guardSource?.(body,"google",abort.signal):undefined;
|
|
284
|
+
if(body.requestType==="agent")commitBinding=prepareConversationBinding(body,"google",profile,startedAt);
|
|
274
285
|
return await native();
|
|
275
286
|
}
|
|
276
|
-
|
|
277
|
-
|
|
287
|
+
const profile=body.requestType==="agent"||compactBinding?.source==="github"
|
|
288
|
+
?await guardSource?.(body,"github",abort.signal):undefined;
|
|
278
289
|
if(!copilotModels.length)throw httpError("Copilot access for Antigravity is paused or unavailable",503);
|
|
279
290
|
observed=true;counts.copilot++;
|
|
280
291
|
if(context){context.provider="github";context.streamPerformance?.setProvider?.("github")}
|
|
@@ -298,11 +309,21 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
298
309
|
res.writeHead(200,{"Content-Type":"application/json"});res.end(JSON.stringify({response}));return;
|
|
299
310
|
}
|
|
300
311
|
if(!["agent","checkpoint","summarization","title"].includes(body.requestType))throw httpError("Unsupported Antigravity inference type",400);
|
|
301
|
-
const
|
|
302
|
-
|
|
312
|
+
const bound=body.requestType==="agent"||compactBinding&&!compactBinding.background;
|
|
313
|
+
let target=selected;
|
|
314
|
+
if(!bound){
|
|
315
|
+
target=copilotModels.find(model=>model.model==="gemini-4-carbon"&&model.effort==="low");
|
|
316
|
+
if(!target){
|
|
317
|
+
const eligible=copilotModels.filter(model=>selection===null||selection.includes(model.id));
|
|
318
|
+
target=eligible.find(model=>model.id===preferred)||eligible.find(model=>model.effort==="low")||eligible[0];
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
if(!target)throw httpError(bound?"The conversation model is unavailable for Antigravity":"No eligible Copilot model is available for Antigravity background tasks",503);
|
|
322
|
+
if(body.requestType==="agent")commitBinding=prepareConversationBinding(body,"github",profile,startedAt);
|
|
303
323
|
const stream=method==="streamGenerateContent";usageModel=target.model;usageMode=stream?"sse":"json";usageProvider="github";
|
|
304
324
|
converted=antigravityToChat(request,{model:target.model,effort:target.effort,reasoningEfforts:target.effort?[target.effort]:[],stream});
|
|
305
|
-
markResponseModel(target.model);markRequestObservation({usage_state:"pending",context_window_tokens:target.maxTokens
|
|
325
|
+
markResponseModel(target.model);markRequestObservation({usage_state:"pending",context_window_tokens:target.maxTokens,
|
|
326
|
+
routing_reason:bound?"conversation_model":target.model==="gemini-4-carbon"&&target.effort==="low"?"background_default":"background_available"});
|
|
306
327
|
session=privacy?.prepareSession?await privacy.prepareSession(converted.chat,{protocol:"chat",client:"gemini",signal:abort.signal}):passthrough(converted.chat);
|
|
307
328
|
const callOptions={signal:abort.signal,sourceBodyManaged:true,observeBodyWrite:true,retryOptions:{retries:0},
|
|
308
329
|
...(compacting?{}:{onBodySent:releaseInput}),
|
|
@@ -310,7 +331,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
310
331
|
phase="upstream";
|
|
311
332
|
const upstream=compacting&&compaction?await compaction.run({body:session.body,protocol:"chat",scope:JSON.stringify(["gemini","github",compactionProfile()]),source:"github",client:"gemini",
|
|
312
333
|
inputLimit:target.maxTokens,outputAllowance:session.body.max_completion_tokens||session.body.max_tokens||0,native:client.chatCompletions,options:callOptions,
|
|
313
|
-
summarize:compactionSummarizer(session.body,"chat",client.chatCompletions),onActivity:()=>abort.setTimeout(streamIdleTimeoutMs,"compaction_idle_timeout")}):await client.chatCompletions(session.body,callOptions);
|
|
334
|
+
summarize:compactionSummarizer(session.body,"chat",client.chatCompletions,{requireChatDone:true}),onActivity:()=>abort.setTimeout(streamIdleTimeoutMs,"compaction_idle_timeout")}):await client.chatCompletions(session.body,callOptions);
|
|
314
335
|
releaseInput();
|
|
315
336
|
markUpstreamHeaders(upstream.status);
|
|
316
337
|
applicationEvidence?.accept(req,"antigravity","inference");
|
|
@@ -320,12 +341,15 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
320
341
|
abort.signal.throwIfAborted();counts.failed++;outcome="failed";markResponseTerminal(outcome,{origin:"upstream_http"});
|
|
321
342
|
sendUpstreamError(res,{status,headers},JSON.stringify({error:"Copilot generation was refused (HTTP "+status+")"}));return;
|
|
322
343
|
}
|
|
323
|
-
|
|
344
|
+
abort.setTimeout(stream?streamIdleTimeoutMs:upstreamTimeoutMs,stream?"stream_idle_timeout":"upstream_timeout");
|
|
324
345
|
if(!stream){
|
|
325
|
-
const data=JSON.parse(await readBoundedResponseText(upstream,{maxBytes:MAX_REPLY,signal:abort.signal,label:"Copilot response"}));
|
|
326
|
-
const
|
|
346
|
+
const data=JSON.parse(await readBoundedResponseText(upstream,{maxBytes:MAX_REPLY,signal:abort.signal,label:"Copilot response"}));
|
|
347
|
+
const usage=mergeChatUsage(null,data.usage);captureUsage(data,usage);
|
|
348
|
+
const result=chatToAntigravity(data,converted.originalNames,usage);markToolActivity(result,"gemini");
|
|
327
349
|
outcome=result.candidates[0].finishReason==="STOP"?"completed":"incomplete";markResponseTerminal(outcome);
|
|
328
|
-
|
|
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;
|
|
329
353
|
}
|
|
330
354
|
if (!upstream.body) {
|
|
331
355
|
sourceResponseFailed(upstream);
|
|
@@ -335,7 +359,14 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
335
359
|
const text=session.count?createPrivacyTextFragments(session):{push:value=>value,finish:()=>""};
|
|
336
360
|
res.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache"});
|
|
337
361
|
const emit=chunk=>writeOrDrain(res,"data: "+JSON.stringify(chunk)+"\n\n",{signal:abort.signal});
|
|
338
|
-
for await(const chunk of chatStreamToAntigravity(upstream,converted.originalNames,{onChunk:()=>abort.setTimeout(streamIdleTimeoutMs,"stream_idle_timeout"),onUsage:captureUsage
|
|
362
|
+
for await(const chunk of chatStreamToAntigravity(upstream,converted.originalNames,{onChunk:()=>abort.setTimeout(streamIdleTimeoutMs,"stream_idle_timeout"),onUsage:captureUsage,onError:(error,detail)=>{
|
|
363
|
+
markResponseErrorOrigin("upstream_event");
|
|
364
|
+
const reason=safeUpstreamReason(detail?.code,200,{stream:true})||safeUpstreamReason(detail?.type,200,{stream:true});
|
|
365
|
+
const headers=upstream.headers;
|
|
366
|
+
currentRequestContext()?.onHttpError?.({code:error.code,origin:"upstream_event",model_error:true,headers,
|
|
367
|
+
...(reason?{upstream_code:reason.code}:{})});
|
|
368
|
+
error.message=reason?.message||"The model source reported an error while streaming.";
|
|
369
|
+
}})){
|
|
339
370
|
markToolActivity(chunk,"gemini");
|
|
340
371
|
const candidate=chunk.response?.candidates?.[0];
|
|
341
372
|
for(const part of candidate?.content?.parts||[]){
|
|
@@ -344,7 +375,8 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
344
375
|
else if(typeof part.text==="string"&&!part.thought)part.text=text.push(part.text);
|
|
345
376
|
}
|
|
346
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)}
|
|
347
|
-
await
|
|
378
|
+
if(candidate?.finishReason&&commitBinding)await confirmBinding();
|
|
379
|
+
if(!await emit(chunk))throw httpError("Antigravity client disconnected",499);
|
|
348
380
|
}
|
|
349
381
|
res.end();
|
|
350
382
|
}catch(error){
|
|
@@ -357,6 +389,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
357
389
|
if(!cancelled||!["completed","incomplete"].includes(outcome))outcome=cancelled?"cancelled":"failed";
|
|
358
390
|
const origin=outcome==="cancelled"?"client_disconnect":currentRequestContext()?.errorOrigin||(abort.reason||phase==="admission"?"transport":["privacy","source_admission"].includes(error.origin)?error.origin:error.statusCode<500?"client_validation":"transport");
|
|
359
391
|
markResponseErrorOrigin(origin);markResponseTerminal(outcome,{origin});
|
|
392
|
+
if(res.headersSent&&outcome==="failed"&&abort.reason)currentRequestContext()?.onHttpError?.({code:error.code,origin,model_error:true});
|
|
360
393
|
if(res.headersSent&&!res.writableEnded&&!res.destroyed){res.end("data: "+JSON.stringify({error:{code:error.statusCode||502,message:error.message}})+"\n\n");}
|
|
361
394
|
else sendJsonError(res,error,error.statusCode||502);
|
|
362
395
|
}finally{
|
|
@@ -375,9 +408,9 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
375
408
|
}
|
|
376
409
|
}
|
|
377
410
|
};
|
|
378
|
-
handler.snapshot=()=>{
|
|
411
|
+
handler.snapshot=(config)=>{
|
|
379
412
|
const queue=acquireControl.diagnostics();
|
|
380
|
-
return {enabled:enabled(),observed,catalog_models:catalogModels,catalog_default_supported:catalogDefaultSupported,catalog_default_model:catalogDefaultModel,active,...counts,
|
|
413
|
+
return {enabled:enabled(config),observed,catalog_models:catalogModels,catalog_default_supported:catalogDefaultSupported,catalog_default_model:catalogDefaultModel,active,...counts,
|
|
381
414
|
short_control_queue:{active:queue.activeRequests,waiting:queue.queued,queued_total:queue.queuedTotal,rejected:queue.rejected,timed_out:queue.timedOut,wait_ms_max:queue.waitMsMax}};
|
|
382
415
|
};
|
|
383
416
|
return handler;
|
|
@@ -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";
|
|
@@ -17,7 +16,9 @@ import {githubTokenFingerprint} from "./github-identity.mjs";
|
|
|
17
16
|
import {atomicWriteFileIfChangedSync} from "./atomic-file.mjs";
|
|
18
17
|
import {withFileLockSync} from "./lock.mjs";
|
|
19
18
|
import {httpError} from "./http-errors.mjs";
|
|
20
|
-
import {
|
|
19
|
+
import {createAntigravityBindings, validModel} from "./antigravity-bindings.mjs";
|
|
20
|
+
import {parseTimerMs} from "./runtime-config.mjs";
|
|
21
|
+
import {antigravityCopilotModels,ANTIGRAVITY_MODEL_PREFIX,ANTIGRAVITY_NATIVE_PREFIX} from "./antigravity-models.mjs";
|
|
21
22
|
|
|
22
23
|
const execute=promisify(execFile),key="gemini_antigravity_enabled",modelKey="gemini_antigravity_models",defaultKey="gemini_antigravity_default_model";
|
|
23
24
|
const timeoutKey="gemini_antigravity_copilot_timeout_seconds";
|
|
@@ -30,13 +31,8 @@ export function createAntigravityRuntime({client,models=()=>[],refreshModels,pri
|
|
|
30
31
|
upstreamTimeoutMs=180000,copilotTimeoutMs,nativeSources=()=>[],getSource=()=>null,...timeouts}={}) {
|
|
31
32
|
const options={home,env},guard=createConversationSourceGuard(options);
|
|
32
33
|
const web=searchFn?null:createCopilotWeb({client,readToken});
|
|
33
|
-
let app={status:"unknown"},route=null,lastOperation=null
|
|
34
|
-
const
|
|
35
|
-
const id=body?.request?.labels?.root_cascade_id||body?.request?.labels?.cascade_id;
|
|
36
|
-
if(typeof id!=="string"||!id||id.length>160||/[\u0000-\u001f\u007f]/.test(id))return null;
|
|
37
|
-
compactionSalt||=readClientGatewayKeys({...options,create:false}).codex;
|
|
38
|
-
return createHmac("sha256",compactionSalt).update("antigravity-compression\0"+id).digest("hex");
|
|
39
|
-
};
|
|
34
|
+
let app={status:"unknown"},route=null,lastOperation=null;
|
|
35
|
+
const bindings=createAntigravityBindings(options,guard);
|
|
40
36
|
const settings=()=>{
|
|
41
37
|
const saved=readUserSettings({...options,strict:true});
|
|
42
38
|
if(saved[key]!==undefined&&typeof saved[key]!=="boolean")throw httpError("Invalid Gemini integration setting",409);
|
|
@@ -45,8 +41,9 @@ export function createAntigravityRuntime({client,models=()=>[],refreshModels,pri
|
|
|
45
41
|
return {configured:Object.hasOwn(saved,key),enabled:saved[key]===true,selected_models:saved[modelKey]??null,default_model:saved[defaultKey]??null,
|
|
46
42
|
copilot_timeout_seconds:validTimeout(saved[timeoutKey])?saved[timeoutKey]:null,native_source:typeof saved[nativeSourceKey]==="string"?saved[nativeSourceKey]:null};
|
|
47
43
|
};
|
|
48
|
-
const
|
|
49
|
-
const
|
|
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);
|
|
46
|
+
const available=(saved=settings())=>saved.enabled&&readAccessSettings(options).providers.github?models():[];
|
|
50
47
|
const nativeModels=(sourceId=settings().native_source)=>{
|
|
51
48
|
if(!sourceId)return [];
|
|
52
49
|
const source=nativeSources().find(item=>item.id===sourceId);
|
|
@@ -55,38 +52,50 @@ export function createAntigravityRuntime({client,models=()=>[],refreshModels,pri
|
|
|
55
52
|
displayName:`${model.display_name||model.id} (${source.name})`,maxTokens:model.capability?.values.context_window,
|
|
56
53
|
maxOutputTokens:model.capability?.values.max_output_tokens,supportsImages:model.capability?.values.input_modalities?.includes("image")===true}));
|
|
57
54
|
};
|
|
58
|
-
const
|
|
55
|
+
const profileFor=source=>source==="github"?"codex:"+githubTokenFingerprint(readToken()||"")
|
|
56
|
+
:source==="google"?"google:gemini-native":getSource(source)?.profileId("gemini");
|
|
57
|
+
const sourceGuard=guardSource||(async(body,source,signal)=>{
|
|
59
58
|
const labels=body.request?.labels||{},id=labels.root_cascade_id||labels.cascade_id;
|
|
60
59
|
if(typeof id!=="string"||!id||id.length>160)throw httpError("Antigravity request has no stable conversation identifier",400);
|
|
61
|
-
const profile=
|
|
60
|
+
const profile=profileFor(source);
|
|
62
61
|
if(!profile)throw httpError("Antigravity source is unavailable",503);
|
|
63
|
-
|
|
62
|
+
await guard("gemini",profile,{messages:[]},{session_id:id},readClientGatewayKeys({...options,create:false}).codex,undefined,signal);
|
|
63
|
+
return profile;
|
|
64
64
|
});
|
|
65
|
-
const handler=createAntigravityHandler({client,models:available,selectedModels:(
|
|
66
|
-
|
|
65
|
+
const handler=createAntigravityHandler({client,models:available,selectedModels:(saved=settings())=>saved.selected_models,
|
|
66
|
+
defaultModel:(saved=settings())=>saved.default_model,enabled:(saved=settings())=>saved.configured||saved.native_source!==null,
|
|
67
|
+
requestSettings:settings,privacy,searchFn:searchFn||web.search,
|
|
68
|
+
nativeModels:(saved=settings())=>nativeModels(saved.native_source),
|
|
69
|
+
resolveNativeModel(id,saved=settings()){
|
|
70
|
+
const model=nativeModels(saved.native_source).find(entry=>entry.id===id);if(!model)return null;
|
|
71
|
+
const source=getSource(model.source);return source?.client?.gemini?{...model,transport:source}:null;
|
|
72
|
+
},
|
|
67
73
|
imageFn:imageFn||createAntigravityImages({client,models:available,privacy}),guardSource:sourceGuard,compactionProfile:()=>githubTokenFingerprint(readToken()||""),
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
const
|
|
73
|
-
if(
|
|
74
|
-
|
|
75
|
-
|
|
74
|
+
prepareConversationBinding(body,source,profile,startedAt){
|
|
75
|
+
return bindings.prepare(body,profile||profileFor(source),startedAt);
|
|
76
|
+
},
|
|
77
|
+
async resolveCompactionSource(body,saved=settings()){
|
|
78
|
+
const binding=await bindings.resolve(body);
|
|
79
|
+
if(!binding)return null;
|
|
80
|
+
const {owner,pinned}=binding;
|
|
81
|
+
if(owner===bindings.hashProfile(profileFor("google"))){
|
|
82
|
+
const model=pinned||body.model;
|
|
83
|
+
if(!validModel(model)||model.startsWith(ANTIGRAVITY_MODEL_PREFIX)||model.startsWith(ANTIGRAVITY_NATIVE_PREFIX))throw httpError("The conversation belongs to another model source",409);
|
|
84
|
+
return{source:"google",model};
|
|
76
85
|
}
|
|
77
|
-
if(owner===
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
const model=nativeModels(selected).find(entry=>entry.id===body.model);
|
|
81
|
-
if(profile&&owner===profileHash(profile)&&model)return{source:selected,model:model.id};
|
|
82
|
-
throw httpError("The conversation belongs to another model source",409);
|
|
86
|
+
if(owner===bindings.hashProfile(profileFor("github"))){
|
|
87
|
+
const model=pinned||(validAlias(body.model)?body.model:null);
|
|
88
|
+
return model?{source:"github",model}:{source:"github",background:true};
|
|
83
89
|
}
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
90
|
+
const selected=saved.native_source, profile=selected&&profileFor(selected);
|
|
91
|
+
const model=profile&&owner===bindings.hashProfile(profile)&&nativeModels(selected).find(entry=>entry.id===(pinned||body.model));
|
|
92
|
+
if(model)return{source:selected,model:model.id};
|
|
93
|
+
throw httpError("The conversation belongs to another model source",409);
|
|
94
|
+
},fetchGoogle:googleFetch,acquireRequest,upstreamTimeoutMs,...timeouts,generationSettings(saved){
|
|
95
|
+
return { selection:saved.selected_models, copilotTimeoutMs:effectiveCopilotTimeoutMs(saved), preferred:saved.default_model };
|
|
87
96
|
}});
|
|
88
97
|
function snapshot(){
|
|
89
|
-
const config=settings(),sourceEnabled=readAccessSettings(options).providers.github,activity=handler.snapshot();
|
|
98
|
+
const config=settings(),sourceEnabled=readAccessSettings(options).providers.github,activity=handler.snapshot(config);
|
|
90
99
|
const sources=nativeSources(), selectedNative=sources.find(item=>item.id===config.native_source);
|
|
91
100
|
const listed=antigravityCopilotModels(models()).map(({id,model,displayName,effort,maxTokens})=>({id,model,name:displayName,effort,context_window:maxTokens,default:id===config.default_model,selected:config.selected_models===null||config.selected_models.includes(id)}));
|
|
92
101
|
const groups=new Map();
|
|
@@ -101,7 +110,7 @@ export function createAntigravityRuntime({client,models=()=>[],refreshModels,pri
|
|
|
101
110
|
const defaultUnavailable=config.default_model!==null&&(!desiredDefault||activity.catalog_default_supported===false);
|
|
102
111
|
const current=applicationControl?.snapshot().antigravity;
|
|
103
112
|
const visibleApp=current?{status:current.status,version:current.version||null,pids:current.pid?[current.pid]:[]}:app;
|
|
104
|
-
return {source:"gemini_antigravity",...config,native_sources:sources.map(({id,name})=>({id,name})),copilot_timeout:{effective_ms:
|
|
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},
|
|
105
114
|
source_enabled:sourceEnabled,default_model_unavailable:defaultUnavailable,models_reload_required:reload,app:visibleApp,application:current||null,route_observed:activity.observed,
|
|
106
115
|
model_source:["Google",...(config.enabled&&sourceEnabled?["GitHub Copilot"]:[]),...(selectedNative?[selectedNative.name]:[])].join(" + "),background_source:"GitHub Copilot",ordinary_chat_source:"Google (unchanged)",
|
|
107
116
|
compaction_source:"Observed conversation source; existing background policy when unassigned",
|
package/src/cli-command-spec.mjs
CHANGED
|
@@ -295,7 +295,7 @@ const extras = {
|
|
|
295
295
|
config:
|
|
296
296
|
"Only service and terminal preferences are in scope. Browser appearance stays in WebUI.\nReset keeps accounts, keys, model plans and chats and stores a pre-reset backup.\nSaved and effective values can differ; restart requirements remain explicit.",
|
|
297
297
|
requests:
|
|
298
|
-
"Only retained records are available. Use requests tools to inspect observed tool metadata without model calls. Unknown clients are not guessed from an API route.\nApp filters: codex, claude-app, claude-code, antigravity.\n--failed filters failed model outcomes and
|
|
298
|
+
"Only retained records are available. Use requests tools to inspect observed tool metadata without model calls. Unknown clients are not guessed from an API route.\nApp filters: codex, claude-app, claude-code, antigravity.\n--failed filters failed model outcomes and request errors. Token-count and access notices stay in the unfiltered list.\nUsage records, HTTP calls and model outcomes are distinct counters.",
|
|
299
299
|
status:
|
|
300
300
|
"Default interactive status is brief; --details retains the complete diagnostic view.\nThe installed package version can differ from the running service.\nA listening gateway does not prove upstream model access.",
|
|
301
301
|
usage:
|
|
@@ -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
|
+
}
|