codex-copilot-dx 1.4.15 → 1.4.17
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/docs/ARCHITECTURE.md +2 -0
- package/docs/REFERENCE.md +10 -4
- package/package.json +1 -1
- package/src/adapter.mjs +9 -5
- package/src/antigravity-handler.mjs +19 -6
- package/src/bark-notifications.mjs +184 -0
- package/src/claude-gateway.mjs +17 -1
- package/src/cli-management-app.mjs +2 -2
- package/src/cli-status.mjs +4 -0
- package/src/connection-routing.mjs +2 -0
- package/src/connection-runtime.mjs +19 -3
- package/src/dashboard/bark-codex.png +0 -0
- package/src/dashboard/bark.js +38 -0
- package/src/dashboard/console.js +2 -1
- package/src/dashboard/index.html +45 -27
- package/src/dashboard/language.js +26 -4
- package/src/dashboard/preferences.js +1 -1
- package/src/dashboard/status.js +3 -2
- package/src/dashboard/theme.js +3 -2
- package/src/dashboard/tool-activity-machines.js +351 -344
- package/src/dashboard/tool-activity.js +37 -18
- package/src/dashboard/ui.css +48 -1
- package/src/dashboard/usage.js +20 -3
- package/src/dashboard-api.mjs +2 -2
- package/src/dashboard.mjs +6 -1
- package/src/file-rotation.mjs +2 -1
- package/src/providers/api.mjs +21 -3
- package/src/providers/claude-health-probes.mjs +97 -0
- package/src/response-failures.mjs +2 -1
- package/src/service-control.mjs +9 -4
- package/src/source-admission.mjs +7 -5
- package/src/stream-performance.mjs +10 -2
- package/src/terminal-console.mjs +7 -5
- package/src/terminal-state.mjs +5 -1
- package/src/usage-analysis.mjs +13 -2
- package/src/usage-archive.mjs +90 -0
- package/src/usage-store.mjs +66 -16
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -75,6 +75,8 @@ Explicit concurrency rejections contract once per observed burst. Stable success
|
|
|
75
75
|
|
|
76
76
|
The upstream references are deliberately narrow: [Floway's model-scoped quota correction](https://github.com/Menci/Floway/commit/49813611aac1f7d0cccb10cfd343c1df7541790e) and [single Chat output cap](https://github.com/Menci/Floway/commit/63f1100af6bc2823e7f0f478fbd785aa56dc0cd7), [Magpie's quota/compaction boundary](https://github.com/yetone/magpie/issues/2725), and [LiteLLM's disconnect outcome report](https://github.com/BerriAI/litellm/issues/51978). CCDX preserves an already observed terminal result while marking delivery cancellation separately; an unfinished stream is not promoted to success. The existing CC Switch-style separation of configuration, discovery and application activation is retained. No upstream runtime, distributed queue or automatic account rotation is introduced.
|
|
77
77
|
|
|
78
|
+
A deployment epoch distinguishes a newly applied configuration from an earlier activation with the same revision. Old leases still release their slots, while their feedback cannot train the current deployment. Privacy settings read failures are reported within the activity snapshot without dropping other activity.
|
|
79
|
+
|
|
78
80
|
Antigravity's management views group per-effort catalog entries only when the record declares a valid `base_model_id` and `reasoning_effort`. Group selection continues to store the existing individual aliases. Requests keep the original model IDs and capabilities.
|
|
79
81
|
|
|
80
82
|
### Manual connection graph
|
package/docs/REFERENCE.md
CHANGED
|
@@ -180,6 +180,8 @@ CCDX renders the complete declared set independently of the native menu. When th
|
|
|
180
180
|
|
|
181
181
|
A saved fallback is applied as Messages `output_config.effort` only when the App omits that field. Effort and thinking mode stay separate; the gateway does not enable, disable or rewrite `thinking`. Explicit App values are retained and pass through the existing capability validation; unsupported values are never mapped to nearby levels. Existing output-format fields, model IDs, history and tool permissions are preserved. Count-token requests and other clients do not receive the fallback. If the source stops advertising the saved level, the value remains visible as unavailable and generation needing that default fails with `ccdx_client_effort_unavailable` until it is corrected or cleared. Native configuration synchronization remains independent of this request preference; changing the preference does not add native model metadata or require an App restart for the parameter itself.
|
|
182
182
|
|
|
183
|
+
Claude App's native one-token health checks share an identical request while it is in flight and can reuse a successful result for 250 milliseconds. The scope includes the effective endpoint, credential, headers and body. A reused check has zero outbound attempts of its own and does not record usage a second time. Failed responses do not enter the reuse window. Ordinary messages, token counts and other clients retain their usual behavior.
|
|
184
|
+
|
|
183
185
|
## API import and request validation
|
|
184
186
|
|
|
185
187
|
**Model sources → Import** and `ccdx source import --file FILE` preview explicitly supplied JSON. Supported shapes are CCDX API metadata/connection exports, CC Switch Claude provider JSON (`settingsConfig.env`), and Magpie `providers.json` with native API bases. Cached deployment evidence, foreign route aliases, account rotation, commands and tool permissions are not adopted. Credential values are not copied; use a private key input or `key_env` when saving. Client access remains a separate explicit choice.
|
|
@@ -282,7 +284,11 @@ The initial internal ceiling is 128 concurrent requests per source/account. This
|
|
|
282
284
|
|
|
283
285
|
Settings separates saved preferences from effective state. Auto-save applies changes by default; required restarts remain explicit. Restore-defaults creates a backup first and keeps accounts, keys, model plans and chats. CLI preference reset/restore uses its own service-only backup; it does not change browser appearance or replace the Web UI's backup.
|
|
284
286
|
|
|
285
|
-
|
|
287
|
+
**Settings → Bark notifications** sends one notification after a supported local Codex turn finishes. Enable it and paste the URL containing the device key from Bark. The minimum duration defaults to 30 minutes. Zero includes every eligible completed turn. Title and description are optional. The Codex icon comes from [Lobe Icons](https://github.com/lobehub/lobe-icons) and is included in the settings page. The phone retrieves the public icon URL separately.
|
|
288
|
+
|
|
289
|
+
CCDX checks recent local Codex session files while the service runs. It uses the recorded turn duration. Intermediate API responses, cancelled turns and background subagents are skipped. The notification carries the selected title and description, with no prompt or response content. The saved push URL stays in the OS credential store. Cloud-only sessions, Claude and Antigravity are outside this version's notification coverage.
|
|
290
|
+
|
|
291
|
+
Web and terminal colors are independent. Web appearance is browser-local. **Settings → Web appearance → Grid paper** gives the light theme a warm paper color and faint gray grid, with a matching dark variant. The terminal keeps its selected color and animation; NO_COLOR, dumb/non-TTY and narrow output remain supported. Reduced motion disables decorative movement. Closed tabs and hidden views stop scheduled work. Model/usage data loads on demand; the Web UI adds no inference calls.
|
|
286
292
|
|
|
287
293
|
Activity, flow and current-run counters use one visible-page SSE connection at `/_ccdx/activity`. TUI activity subscribes to the same in-process notifications. Request starts, model/provider selection, first output, retries and completion coalesce within 50 ms; ordinary output chunks do not trigger pushes. A connection starts with current memory-only state, including the existing recent-request limits. Reconnection restores current state and totals; it does not replay animations or recover arbitrary old history. No replay buffer or durable event store is added.
|
|
288
294
|
|
|
@@ -861,7 +867,7 @@ The old external image provider, Qwen-specific generation/editing, `/mcp/image`,
|
|
|
861
867
|
| `CCDX_RESPONSE_HISTORY_MAX_BYTES` | `67108864` | Higher-precedence total in-memory byte budget for locally expanded Responses history; `ccdx doctor cache --limit` provides a persistent 16–1024 MiB setting when this is unset |
|
|
862
868
|
| `CCDX_RESPONSE_HISTORY_MAX_ENTRIES` | `4096` | Maximum stored incremental Responses history nodes |
|
|
863
869
|
| `CCDX_USAGE_PATH` | `~/.local/share/codex-copilot-dx/usage.jsonl` | Local JSONL token-usage log |
|
|
864
|
-
| `CCDX_USAGE_MAX_BYTES` | `33554432` | Rotate the usage log at this size
|
|
870
|
+
| `CCDX_USAGE_MAX_BYTES` | `33554432` | Rotate the usage log at this size; older backups enter the verified archive. Set to `0` to disable rotation |
|
|
865
871
|
| `CCDX_DISABLE_USAGE` | unset | Set to `1` to disable usage logging |
|
|
866
872
|
| `CCDX_SHUTDOWN_TIMEOUT_MS` | `5000` | Time to drain active HTTP connections before forcing shutdown |
|
|
867
873
|
|
|
@@ -875,7 +881,7 @@ When upstream responses contain usage fields, CCDX records token counts, model n
|
|
|
875
881
|
ccdx usage
|
|
876
882
|
```
|
|
877
883
|
|
|
878
|
-
The summary
|
|
884
|
+
The summary reads the current log, the last rotated backup, and verified compressed archives. Rotation preserves the outgoing backup before replacing it. The archive retains up to 365 days and targets 256 MiB; an oversized latest segment is preserved. Usage trends start at the first retained date within the selected range. The activity calendar retains the full date grid and distinguishes unavailable days from zero usage. The CLI and Web UI report possible write gaps and unreadable archives.
|
|
879
885
|
|
|
880
886
|
M365 preserves system instructions at their original mid-conversation position. This avoids moving each new reminder ahead of the already cached history. Other Claude App API endpoints keep legacy behavior unless the model's `mid_conversation_system` capability is explicitly true. A false override selects legacy hoisting; Responses and Chat use their existing paths. This preserves instruction priority rather than converting system messages to user text.
|
|
881
887
|
|
|
@@ -887,7 +893,7 @@ Usage writes are asynchronous and batched under the existing cross-process rotat
|
|
|
887
893
|
|
|
888
894
|
On Windows, asynchronous lock acquisition retries a transient `EPERM` within the existing lock deadline. It does not replay a protected write or remove another live owner's lock; persistent denial retains its original error.
|
|
889
895
|
|
|
890
|
-
Repeated plain usage summaries reuse one bounded entry when retained files are unchanged, with the existing two-second recent-write guard and 256 KiB/128-group limit. Dashboard analytics keeps up to two independent aggregate checkpoints within 2 MiB. Its first read scans
|
|
896
|
+
Repeated plain usage summaries reuse one bounded entry when retained files are unchanged, with the existing two-second recent-write guard and 256 KiB/128-group limit. Dashboard analytics keeps up to two independent aggregate checkpoints within 2 MiB. Its first read scans the retained logs and archive segments. Later reads apply only append batches witnessed by this process under the existing write lock, with a 256 KiB pending-delta limit per checkpoint. Another process's writes, rotation, truncation, replacement, incomplete tails, warnings, future/undated records and oversized results fall back to a complete read. Queries remain scoped by source, time zone and local date; returned results are cloned and identical concurrent reads share work. The asynchronous writer supplies file-version evidence only while analytics checkpoints exist. There is no persistent index, background poll or added model request.
|
|
891
897
|
|
|
892
898
|
Diagnostic redaction removes Basic authorization payloads and URL userinfo, and consumes escaped quotes inside sensitive JSON fields. Ordinary Basic-related prose, safe host/path information and error codes are retained. These protections apply to existing failure/status/debug diagnostics, not forwarded requests or upstream response bodies. They do not make arbitrary upstream prose guaranteed safe to share.
|
|
893
899
|
|
package/package.json
CHANGED
package/src/adapter.mjs
CHANGED
|
@@ -234,13 +234,17 @@ export function createAdapterHandler(options = {}) {
|
|
|
234
234
|
providerStateFn: () => options.providerRuntime.dashboardProviders(),
|
|
235
235
|
providerAccountsFn: () => options.providerRuntime.action({ action: "accounts" }),
|
|
236
236
|
connectionsFn: input => options.providerRuntime.manageConnections(input) } : {}) } });
|
|
237
|
+
function privacyStatus() {
|
|
238
|
+
try { return privacy.snapshot(); }
|
|
239
|
+
catch { return { state: "error", error: "ccdx_privacy_settings_invalid" }; }
|
|
240
|
+
}
|
|
237
241
|
const activityEvents = createActivityEvents({
|
|
238
242
|
sources: [requestMetrics, streamPerformanceMetrics, options.providerRuntime?.claudePerformance, privacy],
|
|
239
243
|
snapshot: () => {
|
|
240
244
|
const requests = requestMetrics.snapshot(), image = nativeImages.stats();
|
|
241
245
|
const active = ["responses", "responses_compact", "messages", "search", "antigravity"].reduce((sum, route) => sum + (requests.by_route[route]?.active || 0), image?.active || 0);
|
|
242
246
|
const claude = options.providerRuntime?.claudePerformance?.activitySnapshot?.();
|
|
243
|
-
return { ...adapterHealthPayload(), scope: "activity", uptime_ms: Math.round(process.uptime() * 1000), local_privacy:
|
|
247
|
+
return { ...adapterHealthPayload(), scope: "activity", uptime_ms: Math.round(process.uptime() * 1000), local_privacy: privacyStatus(),
|
|
244
248
|
model_activity: { active }, requests, runtime_usage: runtimeUsageSnapshot(),
|
|
245
249
|
stream_performance: streamPerformanceMetrics.activitySnapshot(),
|
|
246
250
|
...(claude ? { providers: { claude: { requests: { performance: claude } } } } : {}),
|
|
@@ -269,8 +273,7 @@ export function createAdapterHandler(options = {}) {
|
|
|
269
273
|
snapshot.routing = { ...snapshot.routing, responses: providers.codex_provider };
|
|
270
274
|
snapshot.models = { ...snapshot.models, provider: providers.codex_provider, source: "configured", models: source?.codex_model_count || 0, refresh_in_flight: false };
|
|
271
275
|
}
|
|
272
|
-
|
|
273
|
-
catch { snapshot.local_privacy = { state: "error", error: "ccdx_privacy_settings_invalid" }; }
|
|
276
|
+
snapshot.local_privacy = privacyStatus();
|
|
274
277
|
let gemini;
|
|
275
278
|
try { const saved=readUserSettings({env:options.env,home:options.dashboardOptions?.home});gemini=antigravity?antigravity.snapshot():{configured:Object.hasOwn(saved,"gemini_antigravity_enabled"),enabled:saved.gemini_antigravity_enabled===true,route_observed:false}; }
|
|
276
279
|
catch { gemini={enabled:false,error:"ccdx_antigravity_settings_invalid"}; }
|
|
@@ -536,7 +539,8 @@ export function createAdapterHandler(options = {}) {
|
|
|
536
539
|
request_options: context?.requestOptions, upstream_attempts: streamPerformance?.attemptCount?.() ?? context?.upstreamAttempts ?? 0,
|
|
537
540
|
attempt_timings: streamPerformance?.attemptTimings?.(),
|
|
538
541
|
requested_model: context?.requestedModel, provider: context?.provider, application: context?.application || requestApplication(req.headers),
|
|
539
|
-
|
|
542
|
+
verified_application: context?.verifiedApplication,
|
|
543
|
+
capability_cached: context?.countObservation?.cached, shared_upstream: context?.countObservation?.shared || context?.claudeHealthProbe?.reused,
|
|
540
544
|
})); } catch {}
|
|
541
545
|
}
|
|
542
546
|
try { complete({ statusCode, aborted }); } catch {}
|
|
@@ -614,7 +618,7 @@ export function createAdapterHandler(options = {}) {
|
|
|
614
618
|
if (state?.version !== 1) throw new Error("Unsupported service-state version");
|
|
615
619
|
importResponseHistory(state.history);await optionalRoutes.importState(state.optional);
|
|
616
620
|
};
|
|
617
|
-
handler.cleanup = () => { activityEvents.close();optionalRoutes.dispose();copilotWeb?.close();antigravity?.close();if (!options.providerRuntime?.privacy) privacy.close(); };
|
|
621
|
+
handler.cleanup = () => { activityEvents.close();optionalRoutes.dispose();options.dashboardOptions?.serviceControl?.closeNotifications?.();copilotWeb?.close();antigravity?.close();if (!options.providerRuntime?.privacy) privacy.close(); };
|
|
618
622
|
return handler;
|
|
619
623
|
}
|
|
620
624
|
|
|
@@ -43,6 +43,16 @@ function groundedSearch(result,query){
|
|
|
43
43
|
groundingMetadata:{webSearchQueries:[query],groundingChunks:sources.map(item=>({web:{uri:item.url,title:item.title||item.url}}))}}]};
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
+
function geminiTerminalDetails(finish) {
|
|
47
|
+
if (finish === "MAX_TOKENS") return { stopReason: "max_tokens", reason: "max_output_tokens" };
|
|
48
|
+
if (finish === "SAFETY" || finish === "RECITATION" || finish === "PROHIBITED_CONTENT") return { stopReason: "content_filter", reason: "content_filter" };
|
|
49
|
+
return finish === "STOP" ? { stopReason: "end_turn" } : undefined;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function geminiFinish(candidates) {
|
|
53
|
+
return candidates.find(candidate => candidate.finishReason && candidate.finishReason !== "STOP")?.finishReason || candidates.find(candidate => candidate.finishReason)?.finishReason;
|
|
54
|
+
}
|
|
55
|
+
|
|
46
56
|
export function createAntigravityHandler({client,models=()=>[],selectedModels=()=>null,defaultModel=()=>null,enabled=()=>false,privacy,searchFn,imageFn,guardSource,acquireRequest=async()=>()=>{},sourceAdmission,applicationEvidence,
|
|
47
57
|
nativeModels=()=>[],resolveNativeModel=()=>null,
|
|
48
58
|
compaction,compactionProfile=()=>"github",prepareConversationBinding=()=>{},resolveCompactionSource=()=>null,recordUsageFn=recordUsage,fetchGoogle=fetch,googleOrigin=GOOGLE_ORIGIN,requestBodyTimeoutMs=120000,upstreamTimeoutMs=180000,copilotTimeoutMs,streamIdleTimeoutMs=60000,
|
|
@@ -52,7 +62,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
52
62
|
let active=0,observed=false,catalogModels=null,catalogDefaultSupported=null,catalogDefaultModel=null;const nativeWindows=new Map();
|
|
53
63
|
const counts={total:0,google:0,copilot:0,search:0,images:0,failed:0};
|
|
54
64
|
const handler=async(req,res)=>{
|
|
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;
|
|
65
|
+
const startedAt=performance.timeOrigin+performance.now(),abort=createRequestAbort(req,res);let commitBinding,release=()=>{},releaseControl,session,body,request,converted,finish,phase="validation",usageEvent=null,usageModel=null,outcome=null,usageMode,usageProvider;
|
|
56
66
|
const releaseInput=()=>{
|
|
57
67
|
body=null;request=null;if(converted)converted.chat=null;if(session)session.body=null;
|
|
58
68
|
const done=release;release=()=>{};done();
|
|
@@ -156,6 +166,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
156
166
|
if(response?.error){outcome="failed";markResponseErrorOrigin("upstream_event");sourceResponseFailed(upstream)}
|
|
157
167
|
else if(outcome!=="failed"&&candidates.some(candidate=>candidate.finishReason)){
|
|
158
168
|
sourceResponseAccepted(upstream);
|
|
169
|
+
finish=geminiFinish(candidates);
|
|
159
170
|
outcome=candidates.every(candidate=>candidate.finishReason==="STOP")?"completed":"incomplete";
|
|
160
171
|
}
|
|
161
172
|
}}):null;
|
|
@@ -177,7 +188,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
177
188
|
if(generation&&!upstream.ok)outcome="failed";
|
|
178
189
|
if(observedEof&&!unavailable&&commitBinding)await confirmBinding();
|
|
179
190
|
if(outcome==="failed")counts.failed++;
|
|
180
|
-
if(outcome)markResponseTerminal(outcome,outcome==="failed"?{origin:upstream.ok?"upstream_event":"upstream_http"}:
|
|
191
|
+
if(outcome)markResponseTerminal(outcome,outcome==="failed"?{origin:upstream.ok?"upstream_event":"upstream_http"}:geminiTerminalDetails(finish));
|
|
181
192
|
res.end();
|
|
182
193
|
};
|
|
183
194
|
if(method==="countTokens"&&req.method==="POST"&&typeof body?.model==="string"&&body.model.startsWith(ANTIGRAVITY_NATIVE_PREFIX)){
|
|
@@ -245,7 +256,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
245
256
|
const reply=session.restoreValue(value),candidates=reply?.candidates||[];
|
|
246
257
|
markToolActivity(reply,"gemini");
|
|
247
258
|
if(candidates.some(candidate=>candidate.content?.parts?.some(part=>part.functionCall||!part.thought&&part.text)))markFirstOutput("delta");
|
|
248
|
-
if(candidates.some(candidate=>candidate.finishReason)){outcome=candidates.every(candidate=>candidate.finishReason==="STOP")?"completed":"incomplete";sourceResponseAccepted(upstream);}
|
|
259
|
+
if(candidates.some(candidate=>candidate.finishReason)){finish=geminiFinish(candidates);outcome=candidates.every(candidate=>candidate.finishReason==="STOP")?"completed":"incomplete";sourceResponseAccepted(upstream);}
|
|
249
260
|
const wrapped=JSON.stringify({response:reply});
|
|
250
261
|
if(stream){if(!await writeOrDrain(res,"data: "+wrapped+"\n\n",{signal:abort.signal}))throw httpError("Antigravity client disconnected",499);}
|
|
251
262
|
else {if(commitBinding)await confirmBinding();res.end(wrapped);}
|
|
@@ -272,7 +283,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
272
283
|
await emit(value);
|
|
273
284
|
}
|
|
274
285
|
if(!outcome)throw httpError("Gemini response ended without a terminal result",502);
|
|
275
|
-
markResponseTerminal(outcome);if(stream){if(commitBinding)await confirmBinding();res.end();}
|
|
286
|
+
markResponseTerminal(outcome,geminiTerminalDetails(finish));if(stream){if(commitBinding)await confirmBinding();res.end();}
|
|
276
287
|
}catch(error){sourceResponseFailed(upstream);await cancelSourceResponse(upstream).catch(()=>{});markResponseErrorOrigin("upstream_event");throw error;}
|
|
277
288
|
return;
|
|
278
289
|
}
|
|
@@ -323,6 +334,8 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
323
334
|
const stream=method==="streamGenerateContent";usageModel=target.model;usageMode=stream?"sse":"json";usageProvider="github";
|
|
324
335
|
converted=antigravityToChat(request,{model:target.model,effort:target.effort,reasoningEfforts:target.effort?[target.effort]:[],stream});
|
|
325
336
|
markResponseModel(target.model);markRequestObservation({usage_state:"pending",context_window_tokens:target.maxTokens,
|
|
337
|
+
max_output_tokens_requested:request.generationConfig?.maxOutputTokens,
|
|
338
|
+
max_output_tokens_sent:converted.chat.max_completion_tokens??converted.chat.max_tokens,
|
|
326
339
|
routing_reason:bound?"conversation_model":target.model==="gemini-4-carbon"&&target.effort==="low"?"background_default":"background_available"});
|
|
327
340
|
session=privacy?.prepareSession?await privacy.prepareSession(converted.chat,{protocol:"chat",client:"gemini",signal:abort.signal}):passthrough(converted.chat);
|
|
328
341
|
const callOptions={signal:abort.signal,sourceBodyManaged:true,observeBodyWrite:true,retryOptions:{retries:0},
|
|
@@ -346,7 +359,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
346
359
|
const data=JSON.parse(await readBoundedResponseText(upstream,{maxBytes:MAX_REPLY,signal:abort.signal,label:"Copilot response"}));
|
|
347
360
|
const usage=mergeChatUsage(null,data.usage);captureUsage(data,usage);
|
|
348
361
|
const result=chatToAntigravity(data,converted.originalNames,usage);markToolActivity(result,"gemini");
|
|
349
|
-
outcome=result.candidates[0].finishReason==="STOP"?"completed":"incomplete";markResponseTerminal(outcome);
|
|
362
|
+
outcome=result.candidates[0].finishReason==="STOP"?"completed":"incomplete";markResponseTerminal(outcome,geminiTerminalDetails(result.candidates[0].finishReason));
|
|
350
363
|
const response=JSON.stringify({response:session.restoreValue(result)});
|
|
351
364
|
if(commitBinding)await confirmBinding();
|
|
352
365
|
res.writeHead(200,{"Content-Type":"application/json"});res.end(response);return;
|
|
@@ -374,7 +387,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
|
|
|
374
387
|
if(part.functionCall){const tail=text.finish();if(tail)await emit({response:{candidates:[{index:0,content:{role:"model",parts:[{text:tail}]}}]}});Object.assign(part,session.restoreToolValue(part));}
|
|
375
388
|
else if(typeof part.text==="string"&&!part.thought)part.text=text.push(part.text);
|
|
376
389
|
}
|
|
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)}
|
|
390
|
+
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,geminiTerminalDetails(candidate.finishReason))}
|
|
378
391
|
if(candidate?.finishReason&&commitBinding)await confirmBinding();
|
|
379
392
|
if(!await emit(chunk))throw httpError("Antigravity client disconnected",499);
|
|
380
393
|
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import files from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
5
|
+
import { createApiSecretStore } from "./api-secrets.mjs";
|
|
6
|
+
import { atomicWriteFileSync } from "./atomic-file.mjs";
|
|
7
|
+
import { codexPaths } from "./codex-paths.mjs";
|
|
8
|
+
import { withFileLockSync } from "./lock.mjs";
|
|
9
|
+
import { readBoundedFileSync } from "./bounded-file.mjs";
|
|
10
|
+
import { readBoundedResponseText } from "./http-transport.mjs";
|
|
11
|
+
import { userSettingsPath } from "./user-settings.mjs";
|
|
12
|
+
|
|
13
|
+
const DEFAULTS = { enabled: false, minutes: 30, title: "", body: "" };
|
|
14
|
+
const ID = /^[a-zA-Z0-9-]{1,120}$/;
|
|
15
|
+
const ROLLOUT = /^rollout-[^/\\]+\.jsonl$/;
|
|
16
|
+
const MB = 1024 * 1024;
|
|
17
|
+
const ICON = "https://cdn.jsdelivr.net/npm/@lobehub/icons-static-png/light/codex-color.png";
|
|
18
|
+
|
|
19
|
+
function invalid() { return new Error("ccdx_bark_invalid"); }
|
|
20
|
+
|
|
21
|
+
export function parseBarkUrl(value) {
|
|
22
|
+
if (typeof value !== "string" || value.length > 2048) throw invalid();
|
|
23
|
+
let url;
|
|
24
|
+
try { url = new URL(value.trim()); } catch { throw invalid(); }
|
|
25
|
+
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hash) throw invalid();
|
|
26
|
+
// Accept the copied test URL as well as the short URL ending at the key.
|
|
27
|
+
const parts = url.pathname.split("/").slice(1);
|
|
28
|
+
const keyIndex = parts.findIndex(part => /^[A-Za-z0-9_-]{16,128}$/.test(part));
|
|
29
|
+
if (keyIndex < 0 || parts.length > keyIndex + 4) throw invalid();
|
|
30
|
+
url.pathname = "/" + [...parts.slice(0, keyIndex), "push"].join("/");
|
|
31
|
+
url.search = "";
|
|
32
|
+
return { endpoint: url.href, deviceKey: parts[keyIndex] };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function record(text) {
|
|
36
|
+
try { return JSON.parse(text); } catch { return null; }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function completions(file, since) {
|
|
40
|
+
const stat = await files.lstat(file);
|
|
41
|
+
if (!stat.isFile() || !stat.size) return [];
|
|
42
|
+
const handle = await files.open(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
|
|
43
|
+
try {
|
|
44
|
+
const current = await handle.stat();
|
|
45
|
+
if (!current.isFile() || current.ino !== stat.ino) return [];
|
|
46
|
+
const head = Buffer.alloc(Math.min(current.size, 64 * 1024));
|
|
47
|
+
const { bytesRead } = await handle.read(head, 0, head.length, 0);
|
|
48
|
+
const first = head.subarray(0, bytesRead).toString("utf8").split("\n", 1)[0];
|
|
49
|
+
const meta = record(first), source = meta?.payload?.source;
|
|
50
|
+
if (meta?.type !== "session_meta" || !ID.test(meta.payload?.id || "")
|
|
51
|
+
|| source && typeof source === "object" && Object.hasOwn(source, "subagent") || source === "subagent") return [];
|
|
52
|
+
const tail = Buffer.alloc(Math.min(current.size, MB));
|
|
53
|
+
const offset = current.size - tail.length;
|
|
54
|
+
const read = await handle.read(tail, 0, tail.length, offset);
|
|
55
|
+
const rows = tail.subarray(0, read.bytesRead).toString("utf8").split("\n");
|
|
56
|
+
if (offset) rows.shift();
|
|
57
|
+
rows.pop(); // Only complete lines are eligible.
|
|
58
|
+
return rows.flatMap(line => {
|
|
59
|
+
if (!line.includes('"task_complete"') && !line.includes('"turn_complete"')) return [];
|
|
60
|
+
const row = record(line), turn = row?.payload, time = Date.parse(row?.timestamp);
|
|
61
|
+
if (row?.type !== "event_msg" || !["task_complete", "turn_complete"].includes(turn?.type)
|
|
62
|
+
|| !Number.isFinite(time) || time < since || !ID.test(turn.turn_id || "")
|
|
63
|
+
|| !Number.isSafeInteger(turn.duration_ms) || turn.duration_ms < 0
|
|
64
|
+
|| typeof turn.last_agent_message !== "string" || !turn.last_agent_message.trim()
|
|
65
|
+
|| turn.root_turn_id && turn.root_turn_id !== turn.turn_id
|
|
66
|
+
|| turn.status != null && turn.status !== "completed") return [];
|
|
67
|
+
const id = createHash("sha256").update(meta.payload.id + "/" + turn.turn_id).digest("hex");
|
|
68
|
+
return [{ id, time, duration: turn.duration_ms }];
|
|
69
|
+
});
|
|
70
|
+
} finally { await handle.close(); }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function createBarkNotifications({ env = process.env, home, platform = process.platform, fetchImpl = fetch,
|
|
74
|
+
secretStore = createApiSecretStore({ env, home, platform }), now = Date.now, scanIntervalMs = 10000 } = {}) {
|
|
75
|
+
const folder = path.dirname(userSettingsPath({ env, home }));
|
|
76
|
+
const file = path.join(folder, "bark.json"), ledger = path.join(folder, "bark-delivered.json");
|
|
77
|
+
const sessions = path.join(codexPaths({ env, home }).directory, "sessions");
|
|
78
|
+
let timer, lastResult = null, closed = false, running = false, watching = false, since = now();
|
|
79
|
+
let settings = readSettings();
|
|
80
|
+
const scanned = new Map();
|
|
81
|
+
|
|
82
|
+
function readSettings() {
|
|
83
|
+
try {
|
|
84
|
+
const value = JSON.parse(readBoundedFileSync(file, { encoding: "utf8", maxBytes: 8192 }));
|
|
85
|
+
if (!value || typeof value.enabled !== "boolean" || !Number.isSafeInteger(value.minutes)
|
|
86
|
+
|| value.minutes < 0 || value.minutes > 10080 || typeof value.title !== "string" || typeof value.body !== "string") return { ...DEFAULTS };
|
|
87
|
+
const ref = /^[a-f0-9]{32}$/.test(value.ref || "") ? value.ref : undefined;
|
|
88
|
+
return { enabled: value.enabled && Boolean(ref), minutes: value.minutes, title: value.title, body: value.body, ref };
|
|
89
|
+
} catch { return { ...DEFAULTS }; }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function claim(event) {
|
|
93
|
+
return withFileLockSync(ledger + ".lock", () => {
|
|
94
|
+
let sent = [];
|
|
95
|
+
try { sent = JSON.parse(readBoundedFileSync(ledger, { encoding: "utf8", maxBytes: 64 * 1024 })); }
|
|
96
|
+
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
97
|
+
if (sent.some(entry => entry.id === event.id)) return false;
|
|
98
|
+
sent = sent.filter(entry => entry.time >= now() - 86400000).slice(-255);
|
|
99
|
+
sent.push({ id: event.id, time: event.time });
|
|
100
|
+
atomicWriteFileSync(ledger, JSON.stringify(sent), { mode: 0o600 });
|
|
101
|
+
return true;
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function scan() {
|
|
106
|
+
if (running) return;
|
|
107
|
+
running = true;
|
|
108
|
+
const snapshot = settings;
|
|
109
|
+
try {
|
|
110
|
+
const root = await files.realpath(sessions);
|
|
111
|
+
const entries = (await files.readdir(root, { recursive: true, withFileTypes: true }))
|
|
112
|
+
.filter(entry => entry.isFile() && ROLLOUT.test(entry.name)).sort((a, b) => b.name.localeCompare(a.name)).slice(0, 4096);
|
|
113
|
+
if (closed || snapshot !== settings) return;
|
|
114
|
+
watching = true;
|
|
115
|
+
for (const entry of entries) {
|
|
116
|
+
if (closed || snapshot !== settings) break;
|
|
117
|
+
try {
|
|
118
|
+
const file = path.join(entry.parentPath, entry.name);
|
|
119
|
+
const stat = await files.stat(file);
|
|
120
|
+
if (stat.mtimeMs < since - 1000) continue;
|
|
121
|
+
const stamp = [stat.ino, stat.size, stat.mtimeMs].join(":");
|
|
122
|
+
if (scanned.get(file) === stamp) continue;
|
|
123
|
+
if (!(await files.realpath(file)).startsWith(root + path.sep)) continue;
|
|
124
|
+
for (const event of await completions(file, since)) {
|
|
125
|
+
if (closed || snapshot !== settings || event.duration < snapshot.minutes * 60000) continue;
|
|
126
|
+
const destination = parseBarkUrl(await secretStore.get(snapshot.ref));
|
|
127
|
+
if (closed || snapshot !== settings || !claim(event)) continue;
|
|
128
|
+
const result = await fetchImpl(destination.endpoint, {
|
|
129
|
+
method: "POST", headers: { "Content-Type": "application/json" }, redirect: "error", signal: AbortSignal.timeout(5000),
|
|
130
|
+
body: JSON.stringify({ device_key: destination.deviceKey, title: snapshot.title || "Codex task completed",
|
|
131
|
+
body: snapshot.body || "A long Codex task has finished.", icon: ICON, group: "CCDX" }),
|
|
132
|
+
});
|
|
133
|
+
// Bark can report an application error with HTTP success.
|
|
134
|
+
const reply = await readBoundedResponseText(result, { maxBytes: 4096, label: "Bark response" });
|
|
135
|
+
if (snapshot === settings) lastResult = result.ok && record(reply)?.code === 200 ? "sent" : "failed";
|
|
136
|
+
}
|
|
137
|
+
if (snapshot === settings) {
|
|
138
|
+
scanned.set(file, stamp);
|
|
139
|
+
if (scanned.size > 4096) scanned.delete(scanned.keys().next().value);
|
|
140
|
+
}
|
|
141
|
+
} catch (error) { if (error.code !== "ENOENT" && snapshot === settings) lastResult = "failed"; }
|
|
142
|
+
}
|
|
143
|
+
} catch { watching = false; }
|
|
144
|
+
finally { running = false;schedule(); }
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function schedule(interval = scanIntervalMs) {
|
|
148
|
+
clearTimeout(timer);
|
|
149
|
+
if (!closed && settings.enabled) timer = setTimeout(() => { void scan(); }, interval).unref();
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function snapshot() {
|
|
153
|
+
const { enabled, minutes, title, body, ref } = settings;
|
|
154
|
+
return { enabled, minutes, title, body, configured: Boolean(ref), watching, delivery: lastResult };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
schedule(0);
|
|
158
|
+
return {
|
|
159
|
+
snapshot,
|
|
160
|
+
async save({ enabled, minutes, title, body, url = "" }) {
|
|
161
|
+
if (typeof enabled !== "boolean" || !Number.isSafeInteger(minutes) || minutes < 0 || minutes > 10080
|
|
162
|
+
|| typeof title !== "string" || title.length > 160 || typeof body !== "string" || body.length > 500
|
|
163
|
+
|| typeof url !== "string") throw invalid();
|
|
164
|
+
const prior = settings.ref;
|
|
165
|
+
const replacement = url.trim() !== "";
|
|
166
|
+
if (replacement) parseBarkUrl(url);
|
|
167
|
+
if (enabled && !replacement && !prior) throw invalid();
|
|
168
|
+
const ref = replacement ? randomBytes(16).toString("hex") : prior;
|
|
169
|
+
if (replacement) await secretStore.set(ref, url.trim());
|
|
170
|
+
const next = { enabled, minutes, title: title.trim(), body: body.trim(), ref };
|
|
171
|
+
try {
|
|
172
|
+
fs.mkdirSync(folder, { recursive: true, mode: 0o700 });
|
|
173
|
+
atomicWriteFileSync(file, JSON.stringify(next), { mode: 0o600 });
|
|
174
|
+
} catch (error) {
|
|
175
|
+
if (replacement) await secretStore.remove(ref).catch(() => {});
|
|
176
|
+
throw error;
|
|
177
|
+
}
|
|
178
|
+
if (replacement && prior) await secretStore.remove(prior).catch(() => {});
|
|
179
|
+
watching = false;lastResult = null;settings = next;since = now();scanned.clear();schedule(0);
|
|
180
|
+
return snapshot();
|
|
181
|
+
},
|
|
182
|
+
close() { closed = true;clearTimeout(timer);secretStore.close?.(); },
|
|
183
|
+
};
|
|
184
|
+
}
|
package/src/claude-gateway.mjs
CHANGED
|
@@ -25,6 +25,7 @@ import { isCompactionRequest, compactionScope } from "./context-compaction.mjs";
|
|
|
25
25
|
import { compactionSummarizer } from "./context-compaction-wire.mjs";
|
|
26
26
|
import { requestPurpose } from "./request-context.mjs";
|
|
27
27
|
import { messagesWithEffortDefault } from "./client-effort.mjs";
|
|
28
|
+
import { isClaudeHealthProbe } from "./providers/claude-health-probes.mjs";
|
|
28
29
|
import { sourceResponseReader, observeSourceRead, failSourceRead, cancelSourceReader, releaseSourceReader, cancelSourceResponse, sourceResponseAccepted } from "./source-response.mjs";
|
|
29
30
|
|
|
30
31
|
function observeMessagesWindow(provider, model, capability, entry) {
|
|
@@ -245,6 +246,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
245
246
|
if (!countTokens) context.purpose = purpose;
|
|
246
247
|
context.provider = selectedProvider.id;context.application = requestApplication(req.headers, "claude");
|
|
247
248
|
context.streamPerformance = tracker;context.route = countTokens ? "messages_count_tokens" : "messages";
|
|
249
|
+
if (context.verifiedApplication) tracker?.observeContext({ verified_application: context.verifiedApplication });
|
|
248
250
|
await runWithRequestContext(context, async () => {
|
|
249
251
|
try {
|
|
250
252
|
release = await acquireRequest(req, { signal: abort.signal, streamingBody: true });
|
|
@@ -258,6 +260,13 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
258
260
|
if (!body || typeof body.model !== "string" || !Array.isArray(body.messages)) {
|
|
259
261
|
send(res, 400, apiError("ccdx_messages_invalid", "Expected a model and messages array"));return;
|
|
260
262
|
}
|
|
263
|
+
const healthProbe = Boolean(resolveRequest && privacyClient === "claude_app" && !countTokens
|
|
264
|
+
&& !compacting && isClaudeHealthProbe(body, req.headers));
|
|
265
|
+
if (healthProbe) {
|
|
266
|
+
context.purpose = "diagnostic";
|
|
267
|
+
tracker?.setPurpose("diagnostic");
|
|
268
|
+
markRequestObservation({ health_probe_state: "recognized" });
|
|
269
|
+
}
|
|
261
270
|
if (resolveRequest) {
|
|
262
271
|
const resolved = await resolveRequest(body, req);
|
|
263
272
|
selectedProvider = resolved.provider;finishProvider = resolved.finish || finishProvider;
|
|
@@ -299,6 +308,11 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
299
308
|
const call = privacy?.wrap(sourceCall, { res, protocol: "messages", client: privacyClient }) || sourceCall;
|
|
300
309
|
let upstreamHeadersObserved = false;
|
|
301
310
|
const callOptions = { headers: req.headers, countTokens, signal: abort.signal, sourceBodyManaged: true,
|
|
311
|
+
...(healthProbe ? { onClaudeHealthProbe(result) {
|
|
312
|
+
context.claudeHealthProbe = result;
|
|
313
|
+
markRequestObservation({ health_probe_state: result.state, health_probe_shape: result.shape,
|
|
314
|
+
health_probe_group: result.group, ...(result.reused ? { health_probe_reused: 1 } : {}) });
|
|
315
|
+
} } : {}),
|
|
302
316
|
onUpstreamErrorHeaders(status) { upstreamHeadersObserved = true;tracker?.upstreamHeaders(status);body = null;release();release = () => {}; },
|
|
303
317
|
onCountObservation(value) {
|
|
304
318
|
context.countObservation = { ...context.countObservation, ...value };
|
|
@@ -450,7 +464,9 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
450
464
|
tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });tracker?.setOutputTokens(usage?.output_tokens);
|
|
451
465
|
tracker?.terminal(outcome, { origin: failedEvent ? "upstream_event" : terminalOrigin, stopReason, reason: stopReason === "max_tokens" ? "max_output_tokens" : undefined });
|
|
452
466
|
tracker?.finish({ failed: outcome === "failed" || outcome === "cancelled" || deliveryCancelled, aborted: deliveryCancelled, statusCode: failureStatus || res.statusCode, rejectionReason });
|
|
453
|
-
|
|
467
|
+
if (!context.claudeHealthProbe || usageRecord && context.claudeHealthProbe.claimUsage()) {
|
|
468
|
+
try { void Promise.resolve(record(usageRecord)).catch(() => {}); } catch {}
|
|
469
|
+
}
|
|
454
470
|
}
|
|
455
471
|
}
|
|
456
472
|
});
|
|
@@ -31,11 +31,11 @@ export async function runAppCommand({ path, ids, flags, output, request, readSta
|
|
|
31
31
|
ids=listed.flatMap(id=>state.model_groups?.find(model=>model.id===id)?.efforts.map(item=>item.id)||[id]);
|
|
32
32
|
}
|
|
33
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]:[]));
|
|
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]:[]),"Choose models");
|
|
35
35
|
ids=[];
|
|
36
36
|
for(const index of selected){
|
|
37
37
|
const model=groups[index],previous=model.efforts.flatMap((item,i)=>item.selected?[i]:[]);
|
|
38
|
-
const efforts=await choose(model.efforts.map(item=>
|
|
38
|
+
const efforts=await choose(model.efforts.map(item=>item.effort||"default"),previous.length?previous:model.efforts.map((_,i)=>i),`Reasoning levels for ${model.name}`);
|
|
39
39
|
ids.push(...efforts.map(i=>model.efforts[i].id));
|
|
40
40
|
}
|
|
41
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);
|
package/src/cli-status.mjs
CHANGED
|
@@ -190,6 +190,10 @@ export function formatAdapterStatus({ baseUrl, data }, { commandName = "ccdx", c
|
|
|
190
190
|
if (logging?.enabled === false) continue;
|
|
191
191
|
lines.push(status(logging.dropped_records || logging.write_failures ? "warn" : "info",
|
|
192
192
|
`${name === "usage" ? "Usage" : "Debug"} logging: ${count(logging.pending_records)} pending (${mebibytes(logging.pending_bytes)}), ${count(logging.dropped_records)} dropped, ${count(logging.write_failures)} write failures`));
|
|
193
|
+
if (name === "usage" && logging.archive_days) {
|
|
194
|
+
lines.push(status("info", `Usage archive: up to ${count(logging.archive_days)} days, ${mebibytes(logging.archive_max_bytes)}`));
|
|
195
|
+
if (logging.unconfirmed_records) lines.push(status("warn", `Usage records with unconfirmed writes: ${count(logging.unconfirmed_records)}`));
|
|
196
|
+
}
|
|
193
197
|
}
|
|
194
198
|
}
|
|
195
199
|
if (responseFailures && typeof responseFailures === "object") {
|
|
@@ -164,6 +164,8 @@ export function createConnectionRouting({ legacy, legacyClaudeAccess, isManaged,
|
|
|
164
164
|
}
|
|
165
165
|
const id = gatewayClient(req.headers, identities());
|
|
166
166
|
if (!id || id === "codex") throw accessError("ccdx_client_credential_required", 401);
|
|
167
|
+
const caller = currentRequestContext();
|
|
168
|
+
if (caller) caller.verifiedApplication = id;
|
|
167
169
|
if (id === "claude_app" && catalogRequest) applicationEvidence?.notice(req, res, id, "catalog");
|
|
168
170
|
const compiled = plan(id);
|
|
169
171
|
if (!binding(id).enabled || !compiled.models.length)
|
|
@@ -149,19 +149,35 @@ export function createConnectionRuntime({
|
|
|
149
149
|
}
|
|
150
150
|
const codexRequiresKey = () => codexAccessMode() === "gateway";
|
|
151
151
|
function requireCodexKey(req) {
|
|
152
|
-
if (gatewayClient(req.headers, identities()) === "codex")
|
|
152
|
+
if (gatewayClient(req.headers, identities()) === "codex") {
|
|
153
|
+
const context = currentRequestContext();
|
|
154
|
+
if (context) {
|
|
155
|
+
context.verifiedApplication = "codex";
|
|
156
|
+
context.streamPerformance?.observeContext({ verified_application: "codex" });
|
|
157
|
+
}
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
153
160
|
// An old native process may still send its ChatGPT bearer. A local access
|
|
154
161
|
// denial must not trigger recovery/replacement of that unrelated sign-in.
|
|
155
162
|
throw accessError("ccdx_client_credential_required", req.headers?.authorization ? 403 : 401);
|
|
156
163
|
}
|
|
157
164
|
const permitted = (id, source) =>
|
|
158
165
|
binding(id)?.enabled && binding(id).allowed.includes(source) && enabled(source);
|
|
166
|
+
const sourceRevisions = new WeakMap();
|
|
167
|
+
function revisionFor(config) {
|
|
168
|
+
const envValue = config.key_env ? env[config.key_env] || "" : "";
|
|
169
|
+
const previous = sourceRevisions.get(config);
|
|
170
|
+
if (previous?.envValue === envValue) return previous.revision;
|
|
171
|
+
const revision = deploymentRevision(config, env);
|
|
172
|
+
sourceRevisions.set(config, { envValue, revision });
|
|
173
|
+
return revision;
|
|
174
|
+
}
|
|
159
175
|
function getSource(id) {
|
|
160
176
|
if (!id?.startsWith("api_")) return legacy.source(id);
|
|
161
177
|
const config = settings.apis.find(value => value.id === id);
|
|
162
178
|
if (!config) return null;
|
|
163
179
|
const previous = instances.get(id),
|
|
164
|
-
revision =
|
|
180
|
+
revision = revisionFor(config);
|
|
165
181
|
if (previous?.config === config && previous.revision === revision) return previous.source;
|
|
166
182
|
const signature = JSON.stringify(config) + revision;
|
|
167
183
|
if (previous?.signature === signature) return previous.source;
|
|
@@ -264,7 +280,7 @@ export function createConnectionRuntime({
|
|
|
264
280
|
const current = settings.apis.find(api => api.id === id);
|
|
265
281
|
if (
|
|
266
282
|
!current?.enabled ||
|
|
267
|
-
JSON.stringify(current) +
|
|
283
|
+
JSON.stringify(current) + revisionFor(current) !== item.signature
|
|
268
284
|
) {
|
|
269
285
|
instances.delete(id);
|
|
270
286
|
retire(item.source);
|
|
Binary file
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
(() => {
|
|
2
|
+
function create({ api, element: el }) {
|
|
3
|
+
const form = el("bark-settings");
|
|
4
|
+
if (!form) return null;
|
|
5
|
+
const fieldset = form.querySelector("fieldset"), status = el("bark-status"), fields = form.elements;
|
|
6
|
+
let dirty = false, saving = false, notice;
|
|
7
|
+
const words = (node, key, prop) => globalThis.ccdxLanguage.set(node, key, {}, prop);
|
|
8
|
+
function sync(data) {
|
|
9
|
+
if (!data || dirty || saving) return;
|
|
10
|
+
for (const key of ["minutes", "title", "body"]) fields[key].value = data[key];
|
|
11
|
+
fields.enabled.checked = data.enabled;
|
|
12
|
+
fields.url.value = "";
|
|
13
|
+
if (data.configured) words(fields.url, "bark_url_saved", "placeholder");
|
|
14
|
+
else { fields.url.removeAttribute("data-i18n-placeholder");fields.url.placeholder = "https://bark.example/…"; }
|
|
15
|
+
const message = data.delivery === "sent" ? "bark_sent" : data.delivery === "failed" ? "bark_failed"
|
|
16
|
+
: data.enabled && !data.watching ? "bark_waiting" : notice;
|
|
17
|
+
if (message) words(status, message);
|
|
18
|
+
else { status.removeAttribute("data-i18n");status.textContent = ""; }
|
|
19
|
+
fieldset.disabled = false;
|
|
20
|
+
}
|
|
21
|
+
form.addEventListener("input", () => { dirty = true;notice = null; });
|
|
22
|
+
form.addEventListener("submit", async event => {
|
|
23
|
+
event.preventDefault();
|
|
24
|
+
if (saving) return;
|
|
25
|
+
saving = true;fieldset.disabled = true;
|
|
26
|
+
let data;
|
|
27
|
+
try {
|
|
28
|
+
data = await api({ action: "bark", enabled: fields.enabled.checked, minutes: fields.minutes.valueAsNumber,
|
|
29
|
+
title: fields.title.value.trim() || fields.title.placeholder, body: fields.body.value.trim() || fields.body.placeholder, url: fields.url.value });
|
|
30
|
+
dirty = false;notice = "api_saved";
|
|
31
|
+
} catch (error) { words(status, error.message === "ccdx_bark_invalid" ? "bark_invalid" : "bark_save_failed"); }
|
|
32
|
+
finally { saving = false;fieldset.disabled = false; }
|
|
33
|
+
if (data) sync(data.bark);
|
|
34
|
+
});
|
|
35
|
+
return { sync };
|
|
36
|
+
}
|
|
37
|
+
globalThis.ccdxBarkSettings = { create };
|
|
38
|
+
})();
|
package/src/dashboard/console.js
CHANGED
|
@@ -87,6 +87,7 @@
|
|
|
87
87
|
selectAnimation: theme => animationView.select(theme),
|
|
88
88
|
refreshAnimation() { dashboardRefresh.invalidate("animation");if (current === "system") void dashboardRefresh.refresh("animation", { force: true }); } });
|
|
89
89
|
globalThis.ccdxSettingsPreferences = preferences;
|
|
90
|
+
const bark = globalThis.ccdxBarkSettings?.create({ element: el, api });
|
|
90
91
|
const features = globalThis.ccdxDashboardFeatures?.create({ element: el, api, apply: applySettings, change, localize: label });
|
|
91
92
|
const applications = globalThis.ccdxApplications?.create({ element: el, change, localize: label, isBusy: () => settingsPending });
|
|
92
93
|
globalThis.ccdxApplicationControls = applications;
|
|
@@ -193,7 +194,7 @@
|
|
|
193
194
|
}
|
|
194
195
|
}
|
|
195
196
|
el("process-notice").textContent = data.terminal?.last_notice || "";
|
|
196
|
-
preferences?.sync(data, meta);
|
|
197
|
+
preferences?.sync(data, meta);bark?.sync(data.bark);
|
|
197
198
|
applications?.sync(data);
|
|
198
199
|
}
|
|
199
200
|
window.addEventListener("ccdx:connections", event => { if (current === "codex" && event.detail?.imageChanged) void loadSettings(); });
|