codex-copilot-dx 1.4.19 → 1.4.21

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/bin/cli.mjs CHANGED
@@ -25,6 +25,12 @@ if (CLI.command === "version") {
25
25
  console.log(CLI_BANNER);
26
26
  process.exit(0);
27
27
  }
28
+ if (CLI.command === "antigravity-stop-hook") {
29
+ const { signalAntigravityStop } = await import("../src/antigravity-stop-hook.mjs");
30
+ await signalAntigravityStop(process.stdin).catch(() => {});
31
+ await new Promise(resolve => process.stdout.write('{"decision":"stop"}\n', resolve));
32
+ process.exit(0);
33
+ }
28
34
  if (CLI.command === "manage") {
29
35
  try {
30
36
  const { runManagementCommand } = await import("../src/cli-management.mjs");
package/docs/REFERENCE.md CHANGED
@@ -170,6 +170,8 @@ Model details show exclusion reasons only when applicable: app/source disabled,
170
170
 
171
171
  ## Claude capability adaptation
172
172
 
173
+ When a Messages client selects Anthropic API version `2026-10-21`, CCDX reports an invalid request if generation or token counting includes `temperature`, `top_p`, or `top_k`. Remove the indicated parameter. Requests using the older version keep their existing behavior.
174
+
173
175
  On macOS, CCDX reads bounded declarations and their consumers from the installed Claude App. It checks model-list fields, behavior hints, native effort options and maximum-effort handling. Installation changes trigger a coalesced background recheck; the existing refresh cadence also covers missed file events. No application code is executed during inspection and no per-request application scan runs.
174
176
 
175
177
  Verified newer contracts keep stable source-qualified model IDs. Both the native profile and `/v1/models` publish the same behavior hint and maximum effort. Legacy conversation IDs remain accepted. Model order, 1M preferences, manual settings and the existing automatic-sync choice retain their ownership protection. Shared capability maps merge unchanged managed entries and preserve manual entries. A changed native configuration requires a normal Claude restart; CCDX does not interrupt running conversations.
@@ -284,10 +286,26 @@ The initial internal ceiling is 128 concurrent requests per source/account. This
284
286
 
285
287
  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.
286
288
 
289
+ Use the button beside the CCDX wordmark to collapse the sidebar to icons. The browser remembers the layout for this dashboard address. The current page stays selected when the sidebar changes width.
290
+
287
291
  **Settings → Bark notifications** is collapsed by default. 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. Leave the title and description blank to use the name of the app that finished. The phone retrieves the matching public PNG from [Lobe Icons](https://github.com/lobehub/lobe-icons).
288
292
 
293
+ New Bark URLs require HTTPS. Existing HTTP addresses remain usable with a settings warning. If a custom reverse-proxy prefix makes a copied URL ambiguous, use `https://host/prefix/push?device_key=KEY`. CCDX removes the query before sending and passes the key in the push body.
294
+
289
295
  CCDX checks local Codex turns, Claude Desktop sessions in Code mode, and Antigravity sessions with a complete local transcript and a fully idle main conversation. Each source must provide matching start and completion evidence. Intermediate API responses, cancelled turns and background subagents are skipped. The notification carries the configured text and a client icon. Prompt and response content stay local, and the push URL stays in the OS credential store. Cloud-only sessions and ordinary Claude Chat and Cowork sessions lack these local completion records.
290
296
 
297
+ The Antigravity App can ask CCDX to check for a completed turn immediately with its [official Stop hook](https://antigravity.google/docs/hooks#stop). Merge the following entry into `~/.gemini/config/hooks.json`. Use the absolute path to the `ccdx` launcher if the App does not have it on PATH. If CCDX uses a custom `XDG_CONFIG_HOME`, set the same value in the hook command.
298
+
299
+ ```json
300
+ {
301
+ "ccdx-bark": {
302
+ "Stop": [{ "type": "command", "command": "ccdx app antigravity stop-hook", "timeout": 5 }]
303
+ }
304
+ }
305
+ ```
306
+
307
+ Only a fully idle model stop wakes the reader. The normal scan remains available when the hook is absent or local completion records arrive later. Both paths apply the same duration threshold and deduplication. The hook stores an empty local marker and does not record its input.
308
+
291
309
  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.
292
310
 
293
311
  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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.4.19",
3
+ "version": "1.4.21",
4
4
  "description": "Local gateway for Codex, Claude and Gemini Antigravity with Copilot, Microsoft 365 and custom APIs",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
@@ -4,6 +4,7 @@ import { MAX_UPSTREAM_CHAT_SUCCESS_BODY_BYTES } from "./http-transport.mjs";
4
4
  import { ToolArgumentDeltaGuard, upstreamChatStreamError } from "./stream-contract.mjs";
5
5
  import { observeSourceStreamFailure } from "./source-admission.mjs";
6
6
  import { sourceResponseAccepted } from "./source-response.mjs";
7
+ import { MAX_OPAQUE_LENGTH } from "./antigravity-opaque-reasoning.mjs";
7
8
 
8
9
  const object = value => value !== null && typeof value === "object" && !Array.isArray(value);
9
10
  const names = /^[A-Za-z0-9_-]{1,64}$/;
@@ -181,7 +182,16 @@ export function mergeChatUsage(previous, value) {
181
182
  }
182
183
 
183
184
  export function chatReasoningTokens(usage) {
184
- return usage?.completion_tokens_details?.reasoning_tokens ?? usage?.reasoning_tokens;
185
+ const reasoning = usage?.completion_tokens_details?.reasoning_tokens ?? usage?.reasoning_tokens;
186
+ return validCount(reasoning) && (!validCount(usage.completion_tokens) || reasoning <= usage.completion_tokens) ? reasoning : undefined;
187
+ }
188
+
189
+ function emptyChatReply(usage) {
190
+ const facts = [];
191
+ if (validCount(usage?.completion_tokens)) facts.push("output tokens: " + usage.completion_tokens);
192
+ const reasoning = chatReasoningTokens(usage);
193
+ if (reasoning !== undefined) facts.push("reasoning tokens: " + reasoning);
194
+ return invalid("Copilot reply contained no text or tool calls" + (facts.length ? " (" + facts.join(", ") + ")" : "") + ".", 502);
185
195
  }
186
196
 
187
197
  function geminiUsage(usage) {
@@ -205,14 +215,15 @@ export function chatToAntigravity(response, originalNames, usage = mergeChatUsag
205
215
  if (typeof message.content === "string" && message.content) parts.push({ text: message.content });
206
216
  if (Array.isArray(message.tool_calls)) for (const call of message.tool_calls) parts.push(chatFunctionPart(call, originalNames));
207
217
  const finish = { stop: "STOP", tool_calls: "STOP", length: "MAX_TOKENS", content_filter: "SAFETY" }[choice.finish_reason];
208
- if (!finish || finish === "STOP" && !parts.some(part => !part.thought)) throw invalid("Upstream Chat response did not complete", 502);
218
+ if (!finish) throw invalid("Upstream Chat response did not complete", 502);
219
+ if (finish === "STOP" && !parts.some(part => !part.thought)) throw emptyChatReply(usage);
209
220
  return { candidates: [{ content: { role: "model", parts }, finishReason: finish, index: 0 }],
210
221
  ...geminiUsage(usage) };
211
222
  }
212
223
 
213
- export async function* chatStreamToAntigravity(response, originalNames, { onChunk, onUsage, onError } = {}) {
224
+ export async function* chatStreamToAntigravity(response, originalNames, { onChunk, onUsage, onError, onOpaque } = {}) {
214
225
  if (!response?.body) throw invalid("Upstream Chat stream has no body", 502);
215
- const calls = new Map(), data = [], guard = new ToolArgumentDeltaGuard();let done = false, finish = null, usage = null, bytes = 0, visible = false;
226
+ const calls = new Map(), data = [], guard = new ToolArgumentDeltaGuard();let done = false, finish = null, usage = null, bytes = 0, visible = false, opaque;
216
227
  const frame = async function* () {
217
228
  if (!data.length) return;
218
229
  const raw = data.join("\n");data.length = 0;
@@ -230,6 +241,10 @@ export async function* chatStreamToAntigravity(response, originalNames, { onChun
230
241
  if (!choice) return;
231
242
  if (choice.finish_reason) { finish = choice.finish_reason;sourceResponseAccepted(response); }
232
243
  const delta = choice.delta || {};
244
+ if (onOpaque && typeof delta.reasoning_opaque === "string" && delta.reasoning_opaque) {
245
+ // Copilot sends a full replacement value in each such delta.
246
+ opaque = delta.reasoning_opaque.length <= MAX_OPAQUE_LENGTH ? delta.reasoning_opaque : undefined;
247
+ }
233
248
  for (const [key, thought] of [["reasoning_content", true], ["content", false], ["refusal", false]]) {
234
249
  if (delta[key] === undefined || delta[key] === null || delta[key] === "") continue;
235
250
  if (typeof delta[key] !== "string") throw invalid("Unsupported upstream Chat stream content", 502);
@@ -266,13 +281,18 @@ export async function* chatStreamToAntigravity(response, originalNames, { onChun
266
281
  if (line.startsWith("data:")) data.push(line.slice(5).replace(/^ /, ""));
267
282
  }
268
283
  if (!done && data.length) yield* frame();
269
- if (!done || !finish) throw invalid("Upstream Chat stream ended before completion", 502);
284
+ if (!done || !finish) {
285
+ if (!visible && !calls.size && validCount(usage?.completion_tokens) && usage.completion_tokens > 0) throw emptyChatReply(usage);
286
+ throw invalid("Upstream Chat stream ended before completion", 502);
287
+ }
270
288
  const finishReason = { stop: "STOP", tool_calls: "STOP", length: "MAX_TOKENS", content_filter: "SAFETY" }[finish];
271
- if (!finishReason || finish === "tool_calls" && !calls.size || finish !== "tool_calls" && calls.size || finish === "stop" && !visible)
289
+ if (finish === "stop" && !visible && !calls.size) throw emptyChatReply(usage);
290
+ if (!finishReason || finish === "tool_calls" && !calls.size || finish !== "tool_calls" && calls.size)
272
291
  throw invalid("Invalid upstream Chat stream completion", 502);
273
292
  for (const [, call] of [...calls].sort(([a], [b]) => a - b)) {
274
293
  yield { response: { candidates: [{ index: 0, content: { role: "model", parts: [chatFunctionPart(call, originalNames)] } }] } };
275
294
  }
276
295
  yield { response: { candidates: [{ index: 0, finishReason }],
277
296
  ...geminiUsage(usage) } };
297
+ if (opaque && finish === "tool_calls") onOpaque(opaque, [...calls.values()].map(call => call.id));
278
298
  }
@@ -5,6 +5,7 @@ import {createRequestAbort,abortErrorStatusCode,readJsonBody,readBoundedResponse
5
5
  import {safeUpstreamResponseHeaders,upstreamRejectionHeaders} from "./upstream-headers.mjs";
6
6
  import {isLoopbackAddress,isLoopbackHostHeader} from "./security.mjs";
7
7
  import {antigravityToChat,chatToAntigravity,chatStreamToAntigravity,mergeChatUsage,chatReasoningTokens,parseAntigravityJSON} from "./antigravity-chat-bridge.mjs";
8
+ import {createAntigravityOpaqueReasoning} from "./antigravity-opaque-reasoning.mjs";
8
9
  import {ANTIGRAVITY_MODEL_PREFIX,ANTIGRAVITY_NATIVE_PREFIX,antigravityCopilotModels,hasAntigravityAgentDefault,mergeAntigravityModels} from "./antigravity-models.mjs";
9
10
  import {createPrivacyTextFragments} from "./privacy-stream.mjs";
10
11
  import {createGoogleResponseObserver,googleUsageEvent} from "./antigravity-usage.mjs";
@@ -59,6 +60,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
59
60
  requestSettings,generationSettings=()=>({ selection:selectedModels(), copilotTimeoutMs, preferred:defaultModel() })}={}) {
60
61
  if(![GOOGLE_ORIGIN,"https://cloudcode-pa.googleapis.com"].includes(googleOrigin))throw new Error("Unrecognized Google control origin");
61
62
  const acquireControl=createRequestAdmission({maxBytes:4*CONTROL_BODY_BYTES,maxQueued:8});
63
+ const opaqueReasoning=createAntigravityOpaqueReasoning();
62
64
  let active=0,observed=false,catalogModels=null,catalogDefaultSupported=null,catalogDefaultModel=null;const nativeWindows=new Map();
63
65
  const counts={total:0,google:0,copilot:0,search:0,images:0,failed:0};
64
66
  const handler=async(req,res)=>{
@@ -332,6 +334,13 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
332
334
  if(!target)throw httpError(bound?"The conversation model is unavailable for Antigravity":"No eligible Copilot model is available for Antigravity background tasks",503);
333
335
  if(body.requestType==="agent")commitBinding=prepareConversationBinding(body,"github",profile,startedAt);
334
336
  const stream=method==="streamGenerateContent";usageModel=target.model;usageMode=stream?"sse":"json";usageProvider="github";
337
+ const conversation=request.labels?.root_cascade_id||request.labels?.cascade_id;
338
+ const scope=body.requestType==="agent"&&typeof profile==="string"&&profile&&typeof conversation==="string"&&conversation.length<=160
339
+ ?[profile,target.model,conversation]:null;
340
+ const onOpaque=scope?(value,ids)=>{
341
+ if(!abort.signal.aborted)opaqueReasoning.remember(scope,value,ids);
342
+ }:undefined;
343
+ const chatCompletions=(input,options)=>client.chatCompletions(scope?opaqueReasoning.attach(scope,input):input,options);
335
344
  converted=antigravityToChat(request,{model:target.model,effort:target.effort,reasoningEfforts:target.effort?[target.effort]:[],stream});
336
345
  const reasoningEffort=converted.chat.reasoning_effort;
337
346
  markResponseModel(target.model);markRequestObservation({usage_state:"pending",context_window_tokens:target.maxTokens,
@@ -347,8 +356,8 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
347
356
  }};
348
357
  phase="upstream";
349
358
  const upstream=compacting&&compaction?await compaction.run({body:session.body,protocol:"chat",scope:JSON.stringify(["gemini","github",compactionProfile()]),source:"github",client:"gemini",
350
- inputLimit:target.maxTokens,outputAllowance:session.body.max_completion_tokens||session.body.max_tokens||0,native:client.chatCompletions,options:callOptions,
351
- summarize:compactionSummarizer(session.body,"chat",client.chatCompletions,{requireChatDone:true}),onActivity:()=>abort.setTimeout(streamIdleTimeoutMs,"compaction_idle_timeout")}):await client.chatCompletions(session.body,callOptions);
359
+ inputLimit:target.maxTokens,outputAllowance:session.body.max_completion_tokens||session.body.max_tokens||0,native:chatCompletions,options:callOptions,
360
+ summarize:compactionSummarizer(session.body,"chat",client.chatCompletions,{requireChatDone:true}),onActivity:()=>abort.setTimeout(streamIdleTimeoutMs,"compaction_idle_timeout")}):await chatCompletions(session.body,callOptions);
352
361
  releaseInput();
353
362
  markUpstreamHeaders(upstream.status);
354
363
  applicationEvidence?.accept(req,"antigravity","inference");
@@ -366,6 +375,9 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
366
375
  outcome=result.candidates[0].finishReason==="STOP"?"completed":"incomplete";markResponseTerminal(outcome,geminiTerminalDetails(result.candidates[0].finishReason));
367
376
  const response=JSON.stringify({response:session.restoreValue(result)});
368
377
  if(commitBinding)await confirmBinding();
378
+ const choice=data.choices[0];
379
+ if(onOpaque&&choice.finish_reason==="tool_calls"&&choice.message.tool_calls?.length)
380
+ onOpaque(choice.message.reasoning_opaque,choice.message.tool_calls.map(call=>call.id));
369
381
  res.writeHead(200,{"Content-Type":"application/json"});res.end(response);return;
370
382
  }
371
383
  if (!upstream.body) {
@@ -376,7 +388,7 @@ export function createAntigravityHandler({client,models=()=>[],selectedModels=()
376
388
  const text=session.count?createPrivacyTextFragments(session):{push:value=>value,finish:()=>""};
377
389
  res.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache"});
378
390
  const emit=chunk=>writeOrDrain(res,"data: "+JSON.stringify(chunk)+"\n\n",{signal:abort.signal});
379
- for await(const chunk of chatStreamToAntigravity(upstream,converted.originalNames,{onChunk:()=>abort.setTimeout(streamIdleTimeoutMs,"stream_idle_timeout"),onUsage:captureUsage,onError:(error,detail)=>{
391
+ for await(const chunk of chatStreamToAntigravity(upstream,converted.originalNames,{onChunk:()=>abort.setTimeout(streamIdleTimeoutMs,"stream_idle_timeout"),onUsage:captureUsage,onOpaque,onError:(error,detail)=>{
380
392
  markResponseErrorOrigin("upstream_event");
381
393
  const reason=safeUpstreamReason(detail?.code,200,{stream:true})||safeUpstreamReason(detail?.type,200,{stream:true});
382
394
  const headers=upstream.headers;
@@ -0,0 +1,48 @@
1
+ export const MAX_OPAQUE_LENGTH = 1024 * 1024;
2
+ const MAX_CACHE_BYTES = 8 * 1024 * 1024;
3
+ const MAX_AGE_MS = 60 * 60 * 1000;
4
+
5
+ export function createAntigravityOpaqueReasoning() {
6
+ const entries = new Map();
7
+ let bytes = 0;
8
+ const remove = key => {
9
+ bytes -= entries.get(key).bytes;
10
+ entries.delete(key);
11
+ };
12
+ // Match the entire parallel tool turn in the same conversation and account.
13
+ const keyFor = (scope, ids) => ids.length && ids.length <= 256
14
+ && ids.every(id => typeof id === "string" && id.length && id.length <= 256)
15
+ ? JSON.stringify([scope, [...new Set(ids)].sort()]) : null;
16
+ return {
17
+ attach(scope, body) {
18
+ if (!entries.size) return body;
19
+ const now = Date.now();
20
+ let messages;
21
+ for (const [index, message] of body.messages.entries()) {
22
+ if (message.role !== "assistant" || Object.hasOwn(message, "reasoning_opaque") || !message.tool_calls?.length) continue;
23
+ const key = keyFor(scope, message.tool_calls.map(call => call.id));
24
+ const entry = entries.get(key);
25
+ if (!entry) continue;
26
+ if (entry.expires <= now) { remove(key);continue; }
27
+ messages ||= body.messages.slice();
28
+ messages[index] = { ...message, reasoning_opaque: entry.value };
29
+ }
30
+ return messages ? { ...body, messages } : body;
31
+ },
32
+ remember(scope, value, ids) {
33
+ if (typeof value !== "string" || !value || value.length > MAX_OPAQUE_LENGTH) return;
34
+ const key = keyFor(scope, ids);
35
+ if (!key) return;
36
+ if (entries.has(key)) remove(key);
37
+ const size = Buffer.byteLength(value) + Buffer.byteLength(key);
38
+ const now = Date.now();
39
+ while (entries.size) {
40
+ const [oldest, entry] = entries.entries().next().value;
41
+ if (entry.expires > now && bytes + size <= MAX_CACHE_BYTES && entries.size < 256) break;
42
+ remove(oldest);
43
+ }
44
+ entries.set(key, { value, bytes: size, expires: now + MAX_AGE_MS });
45
+ bytes += size;
46
+ },
47
+ };
48
+ }
@@ -33,13 +33,23 @@ export function createAntigravityRuntime({client,models=()=>[],refreshModels,pri
33
33
  const web=searchFn?null:createCopilotWeb({client,readToken});
34
34
  let app={status:"unknown"},route=null,lastOperation=null;
35
35
  const bindings=createAntigravityBindings(options,guard);
36
+ const settingsFile=userSettingsPath(options);
37
+ let settingsVersion, settingsSnapshot;
36
38
  const settings=()=>{
39
+ let version;
40
+ try {
41
+ const stat=fs.statSync(settingsFile,{bigint:true});
42
+ if(stat.isFile())version=[stat.dev,stat.ino,stat.size,stat.mtimeNs,stat.ctimeNs].join(":");
43
+ } catch { /* The strict reader still decides whether the current file is usable. */ }
44
+ if(version!==undefined&&settingsVersion===version)return settingsSnapshot;
37
45
  const saved=readUserSettings({...options,strict:true});
38
46
  if(saved[key]!==undefined&&typeof saved[key]!=="boolean")throw httpError("Invalid Gemini integration setting",409);
39
47
  if(saved[modelKey]!==undefined&&(!Array.isArray(saved[modelKey])||saved[modelKey].length>100||new Set(saved[modelKey]).size!==saved[modelKey].length||saved[modelKey].some(id=>!validAlias(id))))throw httpError("Invalid Antigravity model selection",409);
40
48
  if(saved[defaultKey]!==undefined&&!validAlias(saved[defaultKey]))throw httpError("Invalid Antigravity default model",409);
41
- return {configured:Object.hasOwn(saved,key),enabled:saved[key]===true,selected_models:saved[modelKey]??null,default_model:saved[defaultKey]??null,
49
+ const snapshot={configured:Object.hasOwn(saved,key),enabled:saved[key]===true,selected_models:saved[modelKey]??null,default_model:saved[defaultKey]??null,
42
50
  copilot_timeout_seconds:validTimeout(saved[timeoutKey])?saved[timeoutKey]:null,native_source:typeof saved[nativeSourceKey]==="string"?saved[nativeSourceKey]:null};
51
+ settingsVersion=version;settingsSnapshot=snapshot;
52
+ return snapshot;
43
53
  };
44
54
  const defaultCopilotTimeoutMs=parseTimerMs(env.CCDX_UPSTREAM_TIMEOUT_MS,180000);
45
55
  const effectiveCopilotTimeoutMs=saved=>copilotTimeoutMs??(saved.copilot_timeout_seconds===null?defaultCopilotTimeoutMs:saved.copilot_timeout_seconds*1000);
@@ -0,0 +1,26 @@
1
+ import path from "node:path";
2
+ import { atomicWriteFileSync } from "./atomic-file.mjs";
3
+ import { userSettingsPath } from "./user-settings.mjs";
4
+
5
+ export const ANTIGRAVITY_STOP_SIGNAL = "antigravity-stop.signal";
6
+ const MAX_HOOK_BYTES = 1024 * 1024;
7
+ const CONVERSATION_ID = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
8
+
9
+ export async function signalAntigravityStop(input, options) {
10
+ const chunks = [];
11
+ let bytes = 0;
12
+ for await (const chunk of input) {
13
+ const data = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
14
+ bytes += data.length;
15
+ if (bytes > MAX_HOOK_BYTES) return false;
16
+ chunks.push(data);
17
+ }
18
+ const event = JSON.parse(Buffer.concat(chunks).toString("utf8"));
19
+ if (event?.terminationReason !== "model_stop" || event.fullyIdle !== true || event.error
20
+ || !Number.isSafeInteger(event.executionNum) || event.executionNum < 0
21
+ || typeof event.conversationId !== "string" || !CONVERSATION_ID.test(event.conversationId)) return false;
22
+ // The marker only wakes the Bark reader. No payload from the hook is persisted.
23
+ const folder = path.dirname(userSettingsPath(options));
24
+ atomicWriteFileSync(path.join(folder, ANTIGRAVITY_STOP_SIGNAL), "", { mode: 0o600 });
25
+ return true;
26
+ }
@@ -11,6 +11,7 @@ import { withFileLockSync } from "./lock.mjs";
11
11
  import { readBoundedFile, readBoundedFileSync } from "./bounded-file.mjs";
12
12
  import { readBoundedResponseText } from "./http-transport.mjs";
13
13
  import { userSettingsPath } from "./user-settings.mjs";
14
+ import { ANTIGRAVITY_STOP_SIGNAL } from "./antigravity-stop-hook.mjs";
14
15
 
15
16
  const DEFAULTS = { enabled: false, minutes: 30, title: "", body: "", language: "en" };
16
17
  const ID = /^[a-zA-Z0-9-]{1,120}$/;
@@ -33,8 +34,18 @@ export function parseBarkUrl(value) {
33
34
  if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hash) throw invalid();
34
35
  // Accept the copied test URL as well as the short URL ending at the key.
35
36
  const parts = url.pathname.split("/").slice(1);
36
- const keyIndex = parts.findIndex(part => /^[A-Za-z0-9_-]{16,128}$/.test(part));
37
- if (keyIndex < 0 || parts.length > keyIndex + 4) throw invalid();
37
+ const isKey = part => /^[A-Za-z0-9_-]{16,128}$/.test(part);
38
+ const explicit = url.searchParams.get("device_key");
39
+ if (parts.at(-1) === "push" && explicit !== null) {
40
+ if (!isKey(explicit) || url.searchParams.getAll("device_key").length !== 1) throw invalid();
41
+ url.search = "";
42
+ return { endpoint: url.href, deviceKey: explicit };
43
+ }
44
+ const indices = parts.flatMap((part, index) => index >= parts.length - 4 && isKey(part) ? [index] : []);
45
+ const standard = indices.filter(index => /^[A-Za-z0-9]{22}$/.test(parts[index]));
46
+ const candidates = standard.length ? standard : indices;
47
+ if (candidates.length !== 1) throw invalid();
48
+ const [keyIndex] = candidates;
38
49
  url.pathname = "/" + [...parts.slice(0, keyIndex), "push"].join("/");
39
50
  url.search = "";
40
51
  return { endpoint: url.href, deviceKey: parts[keyIndex] };
@@ -128,9 +139,7 @@ async function antigravityCompletion(file, size, row, since) {
128
139
  } finally { await handle.close(); }
129
140
  }
130
141
 
131
- async function antigravityIdleConversations(root) {
132
- const file = path.join(root, "conversation_summaries.db");
133
- if (!(await files.lstat(file)).isFile()) return [];
142
+ async function antigravityIdleConversations(file) {
134
143
  const { DatabaseSync } = await import("node:sqlite");
135
144
  const db = new DatabaseSync(file, { readOnly: true });
136
145
  try {
@@ -155,7 +164,8 @@ export function createBarkNotifications({ env = process.env, home = os.homedir()
155
164
  ];
156
165
  const antigravity = path.join(home, ".gemini", "antigravity");
157
166
  let timer, lastResult = null, closed = false, running = false, watching = false, since = now();
158
- let settings = readSettings();
167
+ let settings = readSettings(), antigravityCatalog, insecureRef;
168
+ let stopWatcher, antigravityScan;
159
169
  const scanned = new Map();
160
170
 
161
171
  function readSettings() {
@@ -169,17 +179,22 @@ export function createBarkNotifications({ env = process.env, home = os.homedir()
169
179
  const zh = value.language === "zh" || legacy && ["Codex 任务完成", "一个 Codex 长任务已完成。"].some(word => word === value.title || word === value.body);
170
180
  const title = legacy && ["Codex task completed", "Codex 任务完成"].includes(value.title) ? "" : value.title;
171
181
  const body = legacy && ["A long Codex task has finished.", "一个 Codex 长任务已完成。"].includes(value.body) ? "" : value.body;
172
- return { enabled: value.enabled && Boolean(ref), minutes: value.minutes, title, body, language: zh ? "zh" : "en", ref };
182
+ return { enabled: value.enabled && Boolean(ref), minutes: value.minutes, title, body, language: zh ? "zh" : "en", ref,
183
+ transport: value.transport === "https" ? "https" : undefined };
173
184
  } catch { return { ...DEFAULTS }; }
174
185
  }
175
186
 
176
187
  function claim(event) {
177
188
  return withFileLockSync(ledger + ".lock", () => {
178
- let sent = [];
179
- try { sent = JSON.parse(readBoundedFileSync(ledger, { encoding: "utf8", maxBytes: 64 * 1024 })); }
180
- catch (error) { if (error.code !== "ENOENT") throw error; }
181
- if (sent.some(entry => entry.id === event.id)) return false;
182
- sent = sent.filter(entry => entry.time >= now() - 86400000).slice(-255);
189
+ let raw;
190
+ try { raw = record(readBoundedFileSync(ledger, { encoding: "utf8", maxBytes: 64 * 1024 })); }
191
+ catch (error) {
192
+ if (error.code !== "ENOENT" && !(error.code === "ccdx_local_file_limit" && fs.lstatSync(ledger).isFile())) throw error;
193
+ }
194
+ const valid = Array.isArray(raw) ? raw.filter(entry => entry && typeof entry.id === "string"
195
+ && /^[a-f0-9]{64}$/.test(entry.id) && Number.isSafeInteger(entry.time)) : [];
196
+ if (valid.some(entry => entry.id === event.id)) return false;
197
+ const sent = valid.filter(entry => entry.time >= now() - 86400000).slice(-255);
183
198
  sent.push({ id: event.id, time: event.time });
184
199
  atomicWriteFileSync(ledger, JSON.stringify(sent), { mode: 0o600 });
185
200
  return true;
@@ -192,6 +207,12 @@ export function createBarkNotifications({ env = process.env, home = os.homedir()
192
207
  const snapshot = settings;
193
208
  let foundSource = false;
194
209
  try {
210
+ if (snapshot.ref && !snapshot.transport && insecureRef?.ref !== snapshot.ref) {
211
+ try {
212
+ const destination = parseBarkUrl(await secretStore.get(snapshot.ref));
213
+ if (snapshot === settings) insecureRef = { ref: snapshot.ref, http: destination.endpoint.startsWith("http:") };
214
+ } catch { /* Delivery reports credential and address errors. */ }
215
+ }
195
216
  for (const source of sources) {
196
217
  if (closed || snapshot !== settings) return;
197
218
  const root = await files.realpath(source.directory).catch(() => null);
@@ -214,7 +235,9 @@ export function createBarkNotifications({ env = process.env, home = os.homedir()
214
235
  if (closed || snapshot !== settings || event.duration < snapshot.minutes * 60000) return;
215
236
  try {
216
237
  const destination = parseBarkUrl(await secretStore.get(snapshot.ref));
217
- if (closed || snapshot !== settings || !claim(event)) return;
238
+ if (closed || snapshot !== settings) return;
239
+ try { if (!claim(event)) return; }
240
+ catch { lastResult = "ledger_failed";return; }
218
241
  const result = await fetchImpl(destination.endpoint, {
219
242
  method: "POST", headers: { "Content-Type": "application/json" }, redirect: "error", signal: AbortSignal.timeout(5000),
220
243
  body: JSON.stringify({ device_key: destination.deviceKey, ...notificationMessage(snapshot, event) }),
@@ -226,12 +249,27 @@ export function createBarkNotifications({ env = process.env, home = os.homedir()
226
249
  }
227
250
  }
228
251
 
229
- async function scanAntigravity(snapshot) {
252
+ function scanAntigravity(snapshot) {
253
+ antigravityScan ||= readAntigravity(snapshot).finally(() => { antigravityScan = undefined; });
254
+ return antigravityScan;
255
+ }
256
+
257
+ async function readAntigravity(snapshot) {
230
258
  let root, rows;
231
259
  try {
232
260
  root = await files.realpath(antigravity);
233
- rows = await antigravityIdleConversations(root);
234
- } catch { return false; }
261
+ const file = path.join(root, "conversation_summaries.db");
262
+ const db = await files.lstat(file, { bigint: true });
263
+ if (!db.isFile()) { antigravityCatalog = undefined;return false; }
264
+ const wal = await files.lstat(file + "-wal", { bigint: true }).catch(error => {
265
+ if (error.code !== "ENOENT") throw error;
266
+ return null;
267
+ });
268
+ const stamp = [file, db.dev, db.ino, db.size, db.mtimeNs, db.ctimeNs,
269
+ wal?.dev, wal?.ino, wal?.size, wal?.mtimeNs, wal?.ctimeNs].join(":");
270
+ if (antigravityCatalog?.stamp !== stamp) antigravityCatalog = { stamp, rows: await antigravityIdleConversations(file) };
271
+ rows = antigravityCatalog.rows;
272
+ } catch { antigravityCatalog = undefined;return false; }
235
273
  for (const row of rows) {
236
274
  if (closed || snapshot !== settings) break;
237
275
  if (!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(row.conversation_id || "")
@@ -257,13 +295,26 @@ export function createBarkNotifications({ env = process.env, home = os.homedir()
257
295
  async function scanSource(source, root, snapshot) {
258
296
  try {
259
297
  const entries = (await files.readdir(root, { recursive: true, withFileTypes: true }))
260
- .filter(entry => entry.isFile() && source.pattern.test(entry.name)).sort((a, b) => b.name.localeCompare(a.name)).slice(0, 4096);
298
+ .filter(entry => entry.isFile() && source.pattern.test(entry.name));
261
299
  if (closed || snapshot !== settings) return;
262
- for (const entry of entries) {
300
+ const selected = [];
301
+ if (entries.length > 4096) {
302
+ for (const entry of entries) {
303
+ if (closed || snapshot !== settings) return;
304
+ const file = path.join(entry.parentPath, entry.name);
305
+ const stat = await files.stat(file).catch(() => null);
306
+ if (stat?.isFile()) selected.push({ file, stat });
307
+ }
308
+ selected.sort((a, b) => b.stat.mtimeMs - a.stat.mtimeMs);
309
+ selected.length = Math.min(selected.length, 4096);
310
+ } else {
311
+ for (const entry of entries) selected.push({ file: path.join(entry.parentPath, entry.name) });
312
+ }
313
+ for (const entry of selected) {
263
314
  if (closed || snapshot !== settings) break;
264
315
  try {
265
- const file = path.join(entry.parentPath, entry.name);
266
- const stat = await files.stat(file);
316
+ const { file } = entry;
317
+ const stat = entry.stat ?? await files.stat(file);
267
318
  if (source.application === "codex" && stat.mtimeMs < since - 1000) continue;
268
319
  const stamp = [stat.ino, stat.size, stat.mtimeMs].join(":");
269
320
  const previous = scanned.get(file);
@@ -284,11 +335,28 @@ export function createBarkNotifications({ env = process.env, home = os.homedir()
284
335
  if (!closed && settings.enabled) timer = setTimeout(() => { void scan(); }, interval).unref();
285
336
  }
286
337
 
338
+ function watchAntigravityStop() {
339
+ stopWatcher?.close();
340
+ stopWatcher = undefined;
341
+ if (!settings.enabled) return;
342
+ try {
343
+ const watcher = fs.watch(folder, { persistent: false }, (_event, file) => {
344
+ if (!closed && settings.enabled && file === ANTIGRAVITY_STOP_SIGNAL) {
345
+ void scanAntigravity(settings).catch(() => {});
346
+ }
347
+ });
348
+ watcher.on("error", () => watcher.close());
349
+ stopWatcher = watcher;
350
+ } catch { /* The regular scan continues when file notifications are unavailable. */ }
351
+ }
352
+
287
353
  function snapshot() {
288
354
  const { enabled, minutes, title, body, ref } = settings;
289
- return { enabled, minutes, title, body, sources: Object.keys(APPS), configured: Boolean(ref), watching, delivery: lastResult };
355
+ return { enabled, minutes, title, body, sources: Object.keys(APPS), configured: Boolean(ref), watching, delivery: lastResult,
356
+ insecure: Boolean(ref && insecureRef?.ref === ref && insecureRef.http) };
290
357
  }
291
358
 
359
+ watchAntigravityStop();
292
360
  schedule(0);
293
361
  return {
294
362
  snapshot,
@@ -298,11 +366,12 @@ export function createBarkNotifications({ env = process.env, home = os.homedir()
298
366
  || typeof url !== "string" || !["en", "zh"].includes(language)) throw invalid();
299
367
  const prior = settings.ref;
300
368
  const replacement = url.trim() !== "";
301
- if (replacement) parseBarkUrl(url);
369
+ if (replacement && !parseBarkUrl(url).endpoint.startsWith("https:")) throw new Error("ccdx_bark_https_required");
302
370
  if (enabled && !replacement && !prior) throw invalid();
303
371
  const ref = replacement ? randomBytes(16).toString("hex") : prior;
304
372
  if (replacement) await secretStore.set(ref, url.trim());
305
- const next = { enabled, minutes, title: title.trim(), body: body.trim(), language, ref };
373
+ const next = { enabled, minutes, title: title.trim(), body: body.trim(), language, ref,
374
+ transport: replacement ? "https" : settings.transport };
306
375
  try {
307
376
  fs.mkdirSync(folder, { recursive: true, mode: 0o700 });
308
377
  atomicWriteFileSync(file, JSON.stringify(next), { mode: 0o600 });
@@ -311,9 +380,11 @@ export function createBarkNotifications({ env = process.env, home = os.homedir()
311
380
  throw error;
312
381
  }
313
382
  if (replacement && prior) await secretStore.remove(prior).catch(() => {});
314
- watching = false;lastResult = null;settings = next;since = now();scanned.clear();schedule(0);
383
+ watching = false;lastResult = null;settings = next;since = now();scanned.clear();
384
+ watchAntigravityStop();
385
+ schedule(0);
315
386
  return snapshot();
316
387
  },
317
- close() { closed = true;clearTimeout(timer);secretStore.close?.(); },
388
+ close() { closed = true;clearTimeout(timer);stopWatcher?.close();secretStore.close?.(); },
318
389
  };
319
390
  }
@@ -260,6 +260,17 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
260
260
  if (!body || typeof body.model !== "string" || !Array.isArray(body.messages)) {
261
261
  send(res, 400, apiError("ccdx_messages_invalid", "Expected a model and messages array"));return;
262
262
  }
263
+ const apiVersion = req.headers["anthropic-version"];
264
+ if (typeof apiVersion === "string" && apiVersion.trim() === "2026-10-21") {
265
+ const parameter = ["temperature", "top_p", "top_k"].find(name => Object.hasOwn(body, name));
266
+ if (parameter) {
267
+ failureStatus = 400;
268
+ send(res, failureStatus, { type: "error", error: { type: "invalid_request_error",
269
+ code: "ccdx_messages_sampling_removed", param: parameter,
270
+ message: `${parameter} is unsupported in Anthropic API version 2026-10-21. Remove this parameter before retrying.` } });
271
+ return;
272
+ }
273
+ }
263
274
  const healthProbe = Boolean(resolveRequest && privacyClient === "claude_app" && !countTokens
264
275
  && !compacting && isClaudeHealthProbe(body, req.headers));
265
276
  if (healthProbe) {
@@ -286,7 +297,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
286
297
  if (desktopAliases && !configuredModel) throw Object.assign(new Error("The selected model is unavailable"), { code: "ccdx_api_model_unavailable", statusCode: 400 });
287
298
  if (desktopAliases && configuredModel !== model) { clientModel = model;model = configuredModel;body = { ...body, model }; }
288
299
  const requestedEffort = body.output_config?.effort;
289
- if (!countTokens) body = messagesWithEffortDefault(body, selectedEffortDefault, selectedCapability);
300
+ if (!countTokens && !healthProbe) body = messagesWithEffortDefault(body, selectedEffortDefault, selectedCapability);
290
301
  stats.last_model = model;
291
302
  context.model = configuredModel || model;
292
303
  if (!countTokens) {
@@ -115,6 +115,7 @@ export const MANAGED_COMMANDS = [
115
115
  command("app <app> status", "Show configuration, not process liveness", { ...read, "--details": "flag" }),
116
116
  ...["open", "focus", "restart", "check"].map(action => command(`app <app> ${action}`, ({ open: "Open the native app or focus its current process", focus: "Focus the current app without relaunching", restart: "Confirm and gracefully reopen the app", check: "Inspect the current app without inference or writes" })[action], { ...read, ...confirm })),
117
117
  ...["focus", "restart", "check"].map(action => command(`app antigravity ${action}`, "Control or inspect the current Antigravity app", { ...read, ...confirm })),
118
+ command("app antigravity stop-hook", "Read a native Stop event from stdin for Bark notifications", {}, () => ({ command: "antigravity-stop-hook" })),
118
119
  command("app <app> models", "Show or edit the client's selected model plan", {
119
120
  ...read,
120
121
  "--edit": "flag",
@@ -20,6 +20,42 @@ import { status } from "./status.mjs";
20
20
  import { markUpstreamHeaders } from "./stream-performance.mjs";
21
21
  import { adaptCallLessContext, isMissingCallIdError } from "./responses-tool-output.mjs";
22
22
 
23
+ function rejectedBareToolName(status, text) {
24
+ if (status !== 400) return null;
25
+ const match = /Missing namespace for function_call '([^'\r\n]{1,256})'\.\s*It does not exist in the default namespace\./i.exec(text);
26
+ return match?.[1] || null;
27
+ }
28
+
29
+ function preserveUnresolvedToolCall(context, status, text) {
30
+ const name = rejectedBareToolName(status, text), input = context.body.input;
31
+ if (!name || context.surface === "responses_compact" || !Array.isArray(input)) return null;
32
+ const results = new Map();
33
+ for (const [index, item] of input.entries()) {
34
+ if (item?.type === "function_call_output") results.set(item.call_id, index);
35
+ }
36
+ let declared = false, namespaced = false, adjusted;
37
+ function observe(tools) {
38
+ if (!Array.isArray(tools)) return;
39
+ for (const tool of tools) {
40
+ if (tool?.type === "namespace" && Array.isArray(tool.tools)
41
+ && tool.tools.some(member => member?.name === name)) namespaced = true;
42
+ if ((tool?.type === "custom" || tool?.type === "function") && tool.name === name) {
43
+ if (typeof tool.namespace === "string" && tool.namespace) namespaced = true;
44
+ else declared = true;
45
+ }
46
+ }
47
+ }
48
+ observe(context.body.tools);
49
+ for (const [index, item] of input.entries()) {
50
+ if (item?.type === "additional_tools" || item?.type === "tool_search_output") observe(item.tools);
51
+ if (item?.type !== "function_call" || item.name !== name || item.namespace !== undefined
52
+ || typeof item.call_id !== "string" || !(results.get(item.call_id) > index) || declared || !namespaced) continue;
53
+ adjusted ||= input.slice();
54
+ adjusted[index] = { ...item, namespace: null };
55
+ }
56
+ return adjusted ? { ...context, body: { ...context.body, input: adjusted } } : null;
57
+ }
58
+
23
59
  // Ordered Copilot-only fallbacks. Each policy is single-use and must be gated
24
60
  // by an exact upstream failure plus a request transformation that changes the
25
61
  // payload. Generic Responses preparation does not decide whether to retry.
@@ -36,6 +72,12 @@ const RETRY_POLICIES = Object.freeze([
36
72
  apply: sanitizeImageNamespaceCollisionRequest,
37
73
  warning: "image_gen namespace rejected by upstream; retrying without the conflicting image tool",
38
74
  }),
75
+ Object.freeze({
76
+ id: "unresolved-function-namespace",
77
+ matches: rejectedBareToolName,
78
+ apply: preserveUnresolvedToolCall,
79
+ warning: "Copilot rejected a replayed unqualified tool call; retrying with its unresolved namespace explicit",
80
+ }),
39
81
  Object.freeze({
40
82
  id: "encrypted-replay-rejected",
41
83
  matches: (statusCode, text) => !isConnectionOwnedInputError(statusCode, text) && isEncryptedContentVerificationError(statusCode, text),
@@ -56,7 +98,7 @@ export function selectCopilotResponseRetry(
56
98
  ) {
57
99
  for (const policy of RETRY_POLICIES) {
58
100
  if (usedPolicies.has(policy.id) || !policy.matches(statusCode, errorText)) continue;
59
- const candidate = policy.apply(reqContext);
101
+ const candidate = policy.apply(reqContext, statusCode, errorText);
60
102
  if (!candidate) continue;
61
103
  usedPolicies.add(policy.id);
62
104
  return {
@@ -5,7 +5,7 @@
5
5
  const fieldset = form.querySelector("fieldset"), status = el("bark-status"), fields = form.elements;
6
6
  let dirty = false, saving = false, notice;
7
7
  const words = (node, key, prop) => globalThis.ccdxLanguage.set(node, key, {}, prop);
8
- function sync(data) {
8
+ function sync(data, justSaved = false) {
9
9
  if (!data || dirty || saving) return;
10
10
  for (const key of ["minutes", "title", "body"]) fields[key].value = data[key];
11
11
  fields.enabled.checked = data.enabled;
@@ -14,7 +14,10 @@
14
14
  if (apps) globalThis.ccdxLanguage.set(el("bark-sources"), "bark_active_sources", { apps });
15
15
  if (data.configured) words(fields.url, "bark_url_saved", "placeholder");
16
16
  else { fields.url.removeAttribute("data-i18n-placeholder");fields.url.placeholder = "https://bark.example/…"; }
17
- const message = data.delivery === "sent" ? "bark_sent" : data.delivery === "failed" ? "bark_failed"
17
+ const transportWarning = el("bark-transport-warning");
18
+ if (transportWarning) transportWarning.hidden = !data.insecure;
19
+ const message = justSaved ? "bark_saved" : data.delivery === "sent" ? "bark_sent"
20
+ : data.delivery === "ledger_failed" ? "bark_ledger_failed" : data.delivery === "failed" ? "bark_failed"
18
21
  : data.enabled && !data.watching ? "bark_waiting" : notice;
19
22
  if (message) words(status, message);
20
23
  else { status.removeAttribute("data-i18n");status.textContent = ""; }
@@ -30,10 +33,13 @@
30
33
  data = await api({ action: "bark", enabled: fields.enabled.checked, minutes: fields.minutes.valueAsNumber,
31
34
  title: fields.title.value, body: fields.body.value, url: fields.url.value,
32
35
  language: document.documentElement.lang.startsWith("zh") ? "zh" : "en" });
33
- dirty = false;notice = "api_saved";
34
- } catch (error) { words(status, error.message === "ccdx_bark_invalid" ? "bark_invalid" : "bark_save_failed"); }
36
+ dirty = false;notice = "bark_saved";
37
+ } catch (error) {
38
+ words(status, error.message === "ccdx_bark_https_required" ? "bark_https_required"
39
+ : error.message === "ccdx_bark_invalid" ? "bark_invalid" : "bark_save_failed");
40
+ }
35
41
  finally { saving = false;fieldset.disabled = false; }
36
- if (data) sync(data.bark);
42
+ if (data) sync(data.bark, true);
37
43
  });
38
44
  return { sync };
39
45
  }
@@ -14,8 +14,13 @@
14
14
  <body>
15
15
  <div class="shell">
16
16
  <aside class="sidebar">
17
+ <div class="sidebar-header">
17
18
  <a class="sidebar-brand" href="#overview"><svg id="status-icon" class="status-icon" viewBox="0 0 64 64" aria-hidden="true" focusable="false"><g fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round"><ellipse cx="32" cy="32" rx="26" ry="10"/><ellipse cx="32" cy="32" rx="26" ry="10" transform="rotate(60 32 32)"/><ellipse cx="32" cy="32" rx="26" ry="10" transform="rotate(120 32 32)"/></g><circle cx="32" cy="32" r="4.5" fill="currentColor"/></svg><span class="brand-name">CCDX</span></a>
18
- <nav aria-label="Navigation" data-i18n-label="main_navigation">
19
+ <button class="icon-button sidebar-toggle" id="sidebar-toggle" type="button" aria-controls="sidebar-navigation" aria-expanded="true" aria-label="Collapse sidebar" title="Collapse sidebar">
20
+ <svg class="nav-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><rect x="3" y="4" width="18" height="16" rx="2"/><path d="M9 4v16"/><path class="sidebar-chevron" d="m16 9-3 3 3 3"/></svg>
21
+ </button>
22
+ </div>
23
+ <nav id="sidebar-navigation" aria-label="Navigation" data-i18n-label="main_navigation">
19
24
  <a href="#overview" data-route="overview" aria-current="page"><svg class="nav-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg><span data-i18n="overview">Overview</span></a>
20
25
  <span class="nav-group" data-i18n="clients">Apps</span>
21
26
  <a class="nav-child" href="#codex" data-route="codex"><svg class="nav-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="m7 8 4 4-4 4m7 0h3"/></svg><span>Codex</span></a>
@@ -539,6 +544,7 @@
539
544
  <label for="bark-title" data-i18n="bark_title">Notification title</label><input id="bark-title" name="title" maxlength="160" data-i18n-placeholder="bark_title_default" placeholder="Automatic">
540
545
  <label for="bark-body" data-i18n="bark_body">Notification description</label><input id="bark-body" name="body" maxlength="500" data-i18n-placeholder="bark_body_default" placeholder="Automatic">
541
546
  </div>
547
+ <p id="bark-transport-warning" class="hint" data-i18n="bark_insecure" hidden>This saved Bark URL uses HTTP. Replace it with HTTPS to protect the device key.</p>
542
548
  <div class="section-actions"><button type="submit" data-i18n="api_save">Save</button><span id="bark-status" role="status" aria-live="polite"></span></div>
543
549
  </fieldset>
544
550
  </form>
@@ -17,6 +17,10 @@
17
17
  bark_waiting: ["Waiting for local completion records.", "正在等待本机任务完成记录。"],
18
18
  bark_sent: ["Last notification accepted by Bark.", "Bark 已接收最近一条通知。"],
19
19
  bark_failed: ["Bark delivery failed.", "Bark 推送失败。"],
20
+ bark_saved: ["Saved.", "已保存。"],
21
+ bark_ledger_failed: ["CCDX could not access its local Bark delivery record.", "CCDX 无法访问本地 Bark 发送记录。"],
22
+ bark_insecure: ["This saved Bark URL uses HTTP. Replace it with HTTPS to protect the device key.", "已保存的 Bark URL 使用 HTTP。请改用 HTTPS 保护设备 key。"],
23
+ bark_https_required: ["New Bark URLs must use HTTPS.", "新 Bark URL 必须使用 HTTPS。"],
20
24
  bark_invalid: ["Check the Bark URL and minimum duration.", "请检查 Bark URL 和最短任务时长。"],
21
25
  bark_save_failed: ["Could not save Bark settings.", "无法保存 Bark 设置。"],
22
26
  "tool_heading": ["Tool and agent activity","工具与代理活动"],
@@ -959,6 +963,8 @@
959
963
  "usage_and_diagnostics": ["Usage", "用量统计"],
960
964
  "system_and_settings": ["Settings", "设置"],
961
965
  "main_navigation": ["Navigation", "页面导航"],
966
+ "sidebar_collapse": ["Collapse sidebar", "收起侧栏"],
967
+ "sidebar_expand": ["Expand sidebar", "展开侧栏"],
962
968
  "local_control": ["LOCAL CONTROL", "本机控制"],
963
969
  "terminal_appearance": ["Terminal appearance", "终端外观"],
964
970
  "configuration_observation": ["SETUP AND ACTIVITY", "接入状态"],
@@ -6,7 +6,8 @@
6
6
  const phrase = (key, values = {}) => globalThis.ccdxLanguage.format(key, values);
7
7
  const text = (id, key, values) => globalThis.ccdxLanguage.set(el(id), key, values);
8
8
  const state = { scene: "idle", style: "production" };
9
- const drawMachine = ctx && globalThis.ccdxToolMachines(ctx);
9
+ const dashboardScript = document.currentScript.src;
10
+ let drawMachine, machineRequested = false;
10
11
  try { const saved = localStorage.getItem(storageKey);if (styles.has(saved)) state.style = saved; } catch {}
11
12
  const motion = globalThis.matchMedia?.("(prefers-reduced-motion: reduce)") || { matches: false, addEventListener() {} };
12
13
  let records = [], fresh = false, supported = false, visible = true, raf = 0, last = 0, start = performance.now(), expiry = null;
@@ -39,10 +40,23 @@
39
40
  }
40
41
  function refreshAnimation() {
41
42
  cancelAnimationFrame(raf);raf = 0;
42
- root.dataset.paused = String(!shown() || motion.matches || !animating() || state.style === "off");
43
- if (!shown() || state.style === "off") return;
43
+ root.dataset.paused = String(!drawMachine || !shown() || motion.matches || !animating() || state.style === "off");
44
+ if (!shown() || state.style === "off" || !drawMachine) return;
44
45
  draw();if (!motion.matches && animating()) raf = requestAnimationFrame(animate);
45
46
  }
47
+ function loadMachine() {
48
+ if (!ctx || state.style === "off" || machineRequested) return;
49
+ machineRequested = true;
50
+ const asset = new URL(dashboardScript);
51
+ asset.pathname = "/tool-activity-machines.js";
52
+ const script = document.createElement("script");
53
+ script.src = asset.href;
54
+ script.addEventListener("load", () => {
55
+ drawMachine = globalThis.ccdxToolMachines(ctx);
56
+ refreshAnimation();
57
+ }, { once: true });
58
+ document.head.append(script);
59
+ }
46
60
  function category(name) {
47
61
  const value = String(name || "").toLowerCase().split(/__|\./).at(-1);
48
62
  if (["read_file", "readfile", "view_file", "open_file", "get_file_content"].includes(value)) return "tool_action_read";
@@ -56,6 +70,7 @@
56
70
  const sourceName = id => id === "github" ? "GitHub Copilot" : id === "m365" ? "Microsoft 365" : id === "google" ? "Google" : globalThis.ccdxConnectionNames?.[id] || phrase("flow_source_unknown");
57
71
  function render(force = false) {
58
72
  if (root.closest("[hidden]")) { signature = "";refreshAnimation();return; }
73
+ loadMachine();
59
74
  const time = performance.now();
60
75
  if (requestDeadline && time >= requestDeadline) { requests = [];requestDeadline = 0;fresh = false; }
61
76
  for (const row of records) if (row.until <= time && pending(row.state)) { row.state = "unknown";row.until = time + 300000; }
@@ -238,8 +238,12 @@ footer { display: flex; flex-wrap: wrap; align-items: center; gap: 16px; color:
238
238
  [hidden] { display: none !important; }
239
239
  .shell { max-width: 1520px; min-height: 100vh; display: grid; grid-template-columns: 204px minmax(0, 1fr); grid-template-rows: 64px minmax(0, 1fr) auto; column-gap: 34px; padding: 0 28px; }
240
240
  .sidebar { grid-row: 1 / 4; position: sticky; top: 0; height: 100vh; display: flex; flex-direction: column; padding: 28px 22px 24px 0; border-right: 1px solid var(--border); }
241
+ .sidebar-header { display: flex; align-items: center; gap: 12px; min-height: 44px; }
241
242
  .sidebar-brand { display: grid; grid-template-columns: 44px minmax(0, 1fr); align-items: center; column-gap: 12px; color: var(--accent); text-decoration: none; font-size: 23px; font-weight: 750; letter-spacing: .04em; }
242
243
  .sidebar-brand > .status-icon, .sidebar-brand > .brand-name { grid-row: 1; }
244
+ .sidebar-toggle { color: var(--accent); }
245
+ .sidebar-toggle:hover { background: var(--option-hover); }
246
+ .sidebar-toggle:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
243
247
 
244
248
  .sidebar nav { display: flex; flex-direction: column; gap: 5px; margin-top: 28px; }
245
249
  .sidebar nav a { color: var(--muted); text-decoration: none; padding: 8px 12px; font-size: 13px; border-left: 2px solid transparent; }
@@ -321,6 +325,26 @@ input[role="switch"]:disabled { opacity: .5; cursor: wait; }
321
325
  .section-actions > label { flex: 1 1 180px; }
322
326
  .section-actions select { max-width: 100%; }
323
327
  }
328
+ @media (min-width: 641px) and (max-width: 900px) {
329
+ .sidebar-header { gap: 8px; }
330
+ .sidebar-brand { column-gap: 8px; font-size: 21px; }
331
+ }
332
+ [data-sidebar-collapsed] .shell { grid-template-columns: 64px minmax(0, 1fr); column-gap: 20px; }
333
+ [data-sidebar-collapsed] .sidebar { padding-inline-end: 8px; }
334
+ [data-sidebar-collapsed] .sidebar-header { justify-content: center; }
335
+ [data-sidebar-collapsed] :is(.sidebar-brand, .nav-group) { display: none; }
336
+ [data-sidebar-collapsed] .sidebar-chevron { transform: scaleX(-1); transform-origin: 14.5px 12px; }
337
+ [data-sidebar-collapsed] .sidebar nav a { position: relative; justify-content: center; gap: 0; padding-inline: 0; min-height: 36px; border-inline-end: 2px solid transparent; }
338
+ [data-sidebar-collapsed] .sidebar nav a > span { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
339
+ @media (max-width: 640px) {
340
+ [data-sidebar-collapsed] .sidebar { padding-inline-end: 0; }
341
+ [data-sidebar-collapsed] .sidebar-header { justify-content: flex-start; }
342
+ [data-sidebar-collapsed] .sidebar nav a { width: 36px; }
343
+ }
344
+ @media (pointer: coarse) {
345
+ .sidebar-toggle { min-width: 44px; min-height: 44px; }
346
+ [data-sidebar-collapsed] .sidebar nav a { min-width: 44px; min-height: 44px; }
347
+ }
324
348
 
325
349
  /* Independent color palettes; green remains the unchanged default. */
326
350
  :root[data-palette="klein"][data-theme="light"] {
@@ -58,6 +58,33 @@ element("refresh").addEventListener("click", () => {
58
58
  });
59
59
  document.querySelector(".sidebar-brand").addEventListener("click", animateLogo);
60
60
 
61
+ const sidebarPreference = "ccdx.dashboard.sidebar";
62
+ const sidebarToggle = element("sidebar-toggle");
63
+ const sidebarLinks = element("sidebar-navigation").querySelectorAll("a");
64
+ function setSidebarCollapsed(collapsed) {
65
+ if (collapsed) document.documentElement.dataset.sidebarCollapsed = "true";
66
+ else delete document.documentElement.dataset.sidebarCollapsed;
67
+ sidebarToggle.setAttribute("aria-expanded", String(!collapsed));
68
+ const label = collapsed ? "sidebar_expand" : "sidebar_collapse";
69
+ localize(sidebarToggle, label, {}, "aria-label");
70
+ localize(sidebarToggle, label, {}, "title");
71
+ for (const link of sidebarLinks) {
72
+ const name = link.querySelector("span");
73
+ localize(link, collapsed ? name.dataset.i18n || name.textContent : "", {}, "title");
74
+ }
75
+ }
76
+ try { setSidebarCollapsed(localStorage.getItem(sidebarPreference) === "collapsed"); }
77
+ catch { setSidebarCollapsed(false); }
78
+ sidebarToggle.addEventListener("click", () => {
79
+ const collapsed = sidebarToggle.getAttribute("aria-expanded") === "true";
80
+ setSidebarCollapsed(collapsed);
81
+ try { localStorage.setItem(sidebarPreference, collapsed ? "collapsed" : "expanded"); }
82
+ catch { /* The tab still keeps its own choice. */ }
83
+ });
84
+ globalThis.addEventListener?.("storage", event => {
85
+ if (event.key === sidebarPreference) setSidebarCollapsed(event.newValue === "collapsed");
86
+ });
87
+
61
88
  const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
62
89
  const animationView = globalThis.ccdxViewBoundary.create("animation-settings", () => globalThis.ccdxDashboardAnimation.create({ element, phrase, localize, text, reducedMotion,
63
90
  getRefresh: () => dashboardRefresh, document }), ["apply", "load", "save", "sync", "stop", "select"]);
package/src/dashboard.mjs CHANGED
@@ -43,8 +43,8 @@ function assets() {
43
43
  })).then(async entries => {
44
44
  const installed = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
45
45
  if (installed.version !== ADAPTER_VERSION) throw new Error("Dashboard files changed; restart CCDX before loading the new dashboard");
46
- // Shared globals and their consumers execute together, without partial script loading.
47
- const scripts = entries.filter(([name, asset]) => asset.type.startsWith("text/javascript") && !["/language.js", "/theme.js"].includes(name));
46
+ // The Requests view loads its drawing code separately. Shared view code remains bundled.
47
+ const scripts = entries.filter(([name, asset]) => asset.type.startsWith("text/javascript") && !["/language.js", "/theme.js", "/tool-activity-machines.js"].includes(name));
48
48
  const body = Buffer.concat(scripts.flatMap(([name, asset]) => [Buffer.from("// " + name + "\n"), asset.body, Buffer.from("\n;\n")]));
49
49
  return new Map([...entries, ["/dashboard.js", { body, type: "text/javascript; charset=utf-8", etag: `"${createHash("sha256").update(body).digest("hex")}"` }]]);
50
50
  }).catch(error => { bundle = null;throw error; });
@@ -1,4 +1,4 @@
1
- export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/live.js", "/time.js", "/animation.js", "/status.js", "/view-boundary.js", "/activity.js", "/flow.js", "/usage.js", "/context.js", "/ui.js", "/console.js", "/updates.js", "/preferences.js", "/features.js", "/icons.js", "/disclosure.js", "/tools.js", "/connections.js", "/privacy.js"]);
1
+ export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/live.js", "/time.js", "/animation.js", "/status.js", "/view-boundary.js", "/activity.js", "/flow.js", "/tool-activity-machines.js", "/usage.js", "/context.js", "/ui.js", "/console.js", "/updates.js", "/preferences.js", "/features.js", "/icons.js", "/disclosure.js", "/tools.js", "/connections.js", "/privacy.js"]);
2
2
  export const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth", "/_ccdx/ui/providers", "/_ccdx/ui/settings", "/_ccdx/ui/m365/accounts", "/_ccdx/ui/updates", "/_ccdx/ui/account", "/_ccdx/ui/checks", "/_ccdx/ui/connections", "/_ccdx/ui/context", "/_ccdx/ui/privacy"]);
3
3
 
4
4
  DASHBOARD_PATHS.add("/gemini.js");
@@ -20,7 +20,7 @@ import { markRequestObservation } from "../stream-performance.mjs";
20
20
  import { createAbortAwareSingleflight } from "../bounded-result-cache.mjs";
21
21
  import { createApiTokenCounter } from "./api-token-count.mjs";
22
22
  import { apiModelDisplay } from "../api-model-display.mjs";
23
- import { adaptCallLessContext, CALL_LESS_TOOL_RETRIED, normalizeCallLessToolOutputs } from "../responses-tool-output.mjs";
23
+ import { adaptCallLessContext, CALL_LESS_TOOL_RETRIED, normalizeCallLessToolOutputs, regroupKimiImageOutputs } from "../responses-tool-output.mjs";
24
24
  import { adaptMessagesToolSchemas, hasRootToolSchema, MESSAGES_TOOL_GUARD } from "../messages-tool-schema.mjs";
25
25
  import { loadRuntimeConfig } from "../runtime-config.mjs";
26
26
  import { currentRequestContext } from "../request-context.mjs";
@@ -51,6 +51,8 @@ export function createApiProvider({ config, secrets, env = process.env, platform
51
51
  const admissionAccount = `api:${config.id}:${config.secret_ref || fingerprint}`;
52
52
  const admissionRevision = createHash("sha256").update(JSON.stringify(profiles)).digest("hex");
53
53
  const modelsUrl = config.base_url.replace(/\/+$/, "") + "/models", geminiModelsUrl = config.endpoints.gemini && new URL(config.endpoints.gemini).href;
54
+ const responsesUrl = config.endpoints.responses && new URL(config.endpoints.responses);
55
+ const kimiResponses = responsesUrl?.origin === "https://api.kimi.com" && responsesUrl.pathname === "/coding/v1/responses";
54
56
  const targets = [...Object.values(config.endpoints), modelsUrl];
55
57
  if (config.endpoints.messages) targets.push(config.endpoints.messages.replace(/\/+$/, "") + "/count_tokens");
56
58
  if (config.endpoints.responses) targets.push(config.endpoints.responses.replace(/\/+$/, "") + "/compact");
@@ -229,6 +231,7 @@ export function createApiProvider({ config, secrets, env = process.env, platform
229
231
  getCachedModelEndpoints: id => catalog.find(model => model.id === id)?.supported_endpoints || null,
230
232
  async responses(body, options = {}) {
231
233
  selected(body.model, "responses");
234
+ if (kimiResponses) body = regroupKimiImageOutputs(body);
232
235
  const prepared = await prepareResponsesPayload(body, { ...options.payloadOptions, assertActive: options.assertActive,
233
236
  currentInputStart: options.currentInputStart || 0, signal: options.signal, profiles: options.payloadPrepared ? [] : options.payloadOptions?.profiles,
234
237
  skipInitialOptimization: options.payloadPrepared || options.payloadOptions?.skipInitialOptimization });
@@ -40,3 +40,38 @@ export function isMissingCallIdError(status, text) {
40
40
  || /^Missing required parameter:\s*[`'"]input\[\d+\]\.call_id[`'"]\.?\s*$/i.test(message)
41
41
  || /^Invalid Value:\s*[`'"]input\.call_id[`'"]\. Function call output requires call_id\.?\s*$/i.test(message);
42
42
  }
43
+ export function regroupKimiImageOutputs(body) {
44
+ const input = body.input;
45
+ if (!Array.isArray(input)) return body;
46
+ let adjusted;
47
+ for (let index = 0; index < input.length; index++) {
48
+ if (input[index]?.type !== "function_call" || input[index].name !== "view_image") continue;
49
+ const start = index;
50
+ const pending = new Set();
51
+ while (input[index]?.type === "function_call" && input[index].name === "view_image"
52
+ && typeof input[index].call_id === "string" && !pending.has(input[index].call_id)) {
53
+ pending.add(input[index++].call_id);
54
+ }
55
+ if (pending.size < 2) { index = Math.max(start, index - 1);continue; }
56
+ const first = index;
57
+ const outputs = [], notices = [];
58
+ for (let at = first; at < input.length && pending.size; at++) {
59
+ const item = input[at];
60
+ if (item?.type === "function_call_output" && pending.has(item.call_id)) {
61
+ pending.delete(item.call_id);
62
+ outputs.push(item);
63
+ } else if (outputs.length && item?.type === "message" && item.role === "developer"
64
+ && (typeof item.content === "string" ? item.content.includes("<image_resize_notice>")
65
+ : Array.isArray(item.content) && item.content.some(part => part?.type === "input_text" && typeof part.text === "string"
66
+ && part.text.includes("<image_resize_notice>")))) {
67
+ notices.push(item);
68
+ } else break;
69
+ }
70
+ if (!pending.size && notices.length) {
71
+ adjusted ||= input.slice();
72
+ adjusted.splice(first, outputs.length + notices.length, ...outputs, ...notices);
73
+ }
74
+ index = first - 1;
75
+ }
76
+ return adjusted ? { ...body, input: adjusted } : body;
77
+ }
@@ -1,6 +1,6 @@
1
1
  import path from "node:path";
2
2
  import fs from "node:fs/promises";
3
- import { summarizeUsage, summarizeUsageLogs, usageLogPath, usageSummaryVersion, subscribeUsageAppends, usageProvider, mergeUsageSummary } from "./usage-store.mjs";
3
+ import { accumulateUsageRecord, summarizeUsageLogs, usageLogPath, usageSummaryVersion, subscribeUsageAppends, usageProvider } from "./usage-store.mjs";
4
4
  import { createUsageAnalytics } from "./usage-analytics.mjs";
5
5
  import { createAbortAwareSingleflight } from "./bounded-result-cache.mjs";
6
6
  import { createUsageQuery } from "./usage-query.mjs";
@@ -80,11 +80,12 @@ export async function analyzeUsageLogs(filePath = usageLogPath(), { timeZone = "
80
80
  cached.analytics.advanceTime(now);
81
81
  for (const line of cached.pending) {
82
82
  const record = JSON.parse(line);
83
- if (provider && provider !== usageProvider(record)) continue;
84
- const label = provider ? record.model || "unknown" : `${usageProvider(record)} / ${record.model || "unknown"}`;
83
+ const source = usageProvider(record);
84
+ if (provider && provider !== source) continue;
85
+ const label = provider ? record.model || "unknown" : `${source} / ${record.model || "unknown"}`;
85
86
  if (cached.models.size < 100) cached.models.add(label);else if (!cached.models.has(label)) cached.modelsTruncated = true;
86
87
  if (!selection.matches(record)) continue;
87
- const one = summarizeUsage([record]);mergeUsageSummary(cached.summary, one);cached.analytics.record(record, one);
88
+ accumulateUsageRecord(cached.summary, record, source, cached.analytics.record);
88
89
  }
89
90
  cached.pending = [];cached.pendingBytes = 0;
90
91
  const snapshot = cached.analytics.snapshot();
@@ -96,10 +97,19 @@ export async function analyzeUsageLogs(filePath = usageLogPath(), { timeZone = "
96
97
  cache.delete(query);prune();
97
98
  const analytics = createUsageAnalytics({ timeZone, now, qualifyProviders: !provider, from: selection.filters.from, to: selection.filters.to }), models = new Set();
98
99
  let warned = false, modelsTruncated = false;
99
- const summary = await summarizeUsageLogs(filePath, { provider, onRecord: analytics.record, recordFilter: record => {
100
+ const observeModel = record => {
100
101
  const label = provider ? record.model || "unknown" : `${usageProvider(record)} / ${record.model || "unknown"}`;
101
102
  if (models.size < 100) models.add(label);else if (!models.has(label)) modelsTruncated = true;
102
- return selection.matches(record);
103
+ };
104
+ // Keep a day of margin on either side of the civil-date window so all
105
+ // supported time zones retain boundary records. Unindexed archives scan normally.
106
+ const { from, to } = selection.filters, day = 86400000;
107
+ const lower = from ? Date.parse(from) - day : -Infinity;
108
+ const upper = to ? Date.parse(to) + 2 * day : Infinity;
109
+ const archiveSelection = { observeModel, excludes: ({ first, last }) =>
110
+ Boolean(from || to) && (last < lower || first >= upper) };
111
+ const summary = await summarizeUsageLogs(filePath, { provider, onRecordTotals: analytics.record, archiveSelection, recordFilter: record => {
112
+ observeModel(record);return selection.matches(record);
103
113
  },
104
114
  warn(message) { warned = true;warn(message); } });
105
115
  const snapshot = analytics.snapshot();
@@ -9,7 +9,14 @@ export const USAGE_ARCHIVE_MAX_BYTES = 256 * 1024 * 1024;
9
9
  export const USAGE_ARCHIVE_DAYS = 365;
10
10
  const archivePattern = /^\d{13}-[a-f0-9]{32}\.jsonl\.gz$/;
11
11
  const directoryFor = file => path.resolve(file) + ".archive";
12
- const identity = stat => createHash("sha256").update([stat.dev, stat.ino, stat.size, stat.ctimeNs].join(":")).digest("hex").slice(0, 32);
12
+ const identity = fields => createHash("sha256").update(fields.join(":")).digest("hex").slice(0, 32);
13
+ // Renames and permission changes can update ctime without changing this generation.
14
+ const backupKey = stat => identity([stat.dev, stat.ino, stat.size, stat.birthtimeNs, stat.mtimeNs]);
15
+
16
+ function matchingBackup(archive, stat) {
17
+ const key = backupKey(stat), legacy = identity([stat.dev, stat.ino, stat.size, stat.ctimeNs]);
18
+ return archive.find(name => name.endsWith("-" + key + ".jsonl.gz") || name.endsWith("-" + legacy + ".jsonl.gz"));
19
+ }
13
20
 
14
21
  async function segments(file) {
15
22
  const directory = directoryFor(file);
@@ -24,8 +31,7 @@ export async function usageArchiveFiles(file) {
24
31
  }
25
32
 
26
33
  export async function archivedUsageBackup(file, archive, stat) {
27
- const key = identity(stat ?? await fs.promises.stat(file + ".1", { bigint: true }));
28
- return archive.some(name => name.endsWith("-" + key + ".jsonl.gz"));
34
+ return Boolean(matchingBackup(archive, stat ?? await fs.promises.stat(file + ".1", { bigint: true })));
29
35
  }
30
36
 
31
37
  async function verifyCompressedUsage(file, size, expected) {
@@ -49,8 +55,8 @@ export async function sealUsageBackup(file) {
49
55
  const directory = directoryFor(file);
50
56
  await fs.promises.mkdir(directory, { recursive: true, mode: 0o700 });
51
57
  const archive = await usageArchiveFiles(file);
52
- const matching = archive.find(name => name.endsWith("-" + identity(stat) + ".jsonl.gz"));
53
- const sealed = matching || path.join(directory, `${Date.now()}-${identity(stat)}.jsonl.gz`);
58
+ const matching = matchingBackup(archive, stat);
59
+ const sealed = matching || path.join(directory, `${Date.now()}-${backupKey(stat)}.jsonl.gz`);
54
60
  const temporary = path.join(directory, `.seal-${randomUUID()}.tmp`);
55
61
  const hash = createHash("sha256");
56
62
  try {
@@ -363,36 +363,60 @@ export function summarizeUsage(records, { provider = "" } = {}) {
363
363
  for (const record of records) {
364
364
  const source = usageProvider(record);
365
365
  if (provider && provider !== source) continue;
366
- summary.providers[source] = (summary.providers[source] || 0) + 1;
367
- summary.requests += 1;
368
- let observed = record.usage;
369
- if (observed?.cached_input_tokens != null && observed?.cache_read_input_tokens != null) {
370
- observed = { ...observed };delete observed.cache_read_input_tokens;
371
- if (cacheReadTokens(record.usage) === undefined) delete observed.cached_input_tokens;
372
- }
373
- addUsageTotals(summary.totals, observed);
374
- if (record.copilot_usage) {
375
- summary.totals.copilot_total_tokens = (summary.totals.copilot_total_tokens || 0) + (record.copilot_usage.total_tokens || 0);
376
- summary.totals.total_nano_aiu = (summary.totals.total_nano_aiu || 0) + (record.copilot_usage.total_nano_aiu || 0);
377
- }
378
- const model = record.model || "unknown";
379
- if (!Object.hasOwn(summary.byModel, model)) Object.defineProperty(summary.byModel, model, { value: { requests: 0 }, enumerable: true, configurable: true, writable: true });
380
- const modelTotals = summary.byModel[model];
381
- modelTotals.requests += 1;
382
- addUsageTotals(modelTotals, observed);
383
- const qualified = `${source} / ${model}`;
384
- if (!Object.hasOwn(summary.bySourceModel, qualified)) summary.bySourceModel[qualified] = { requests: 0 };
385
- const sourceTotals = summary.bySourceModel[qualified];
386
- sourceTotals.requests++;
387
- addUsageTotals(sourceTotals, observed);
388
- for (const target of [summary.totals, modelTotals, sourceTotals]) {
389
- addCacheEvidence(target, record.usage || {});
390
- }
366
+ accumulateUsageRecord(summary, record, source);
391
367
  }
392
368
  return summary;
393
369
  }
394
370
 
395
- async function summarizeUsageLogFiles(filePath, { warn = console.error, onRecord, recordFilter, provider = "" } = {}) {
371
+ function addRecordTotals(totals, record, observed, evidence) {
372
+ addUsageTotals(totals, observed);
373
+ if (record.copilot_usage) {
374
+ const tokens = record.copilot_usage.total_tokens || 0;
375
+ const nanoAiu = record.copilot_usage.total_nano_aiu || 0;
376
+ if (Number.isFinite(tokens)) totals.copilot_total_tokens = (totals.copilot_total_tokens || 0) + tokens;
377
+ if (Number.isFinite(nanoAiu)) totals.total_nano_aiu = (totals.total_nano_aiu || 0) + nanoAiu;
378
+ }
379
+ addCacheEvidence(totals, record.usage || {}, evidence);
380
+ }
381
+
382
+ export function accumulateUsageRecord(summary, record, source, onRecordTotals) {
383
+ summary.providers[source] = (summary.providers[source] || 0) + 1;
384
+ summary.requests += 1;
385
+ const usage = record.usage || {}, evidence = usageCacheEvidence(usage);
386
+ let observed = record.usage;
387
+ if (observed?.cached_input_tokens != null && observed?.cache_read_input_tokens != null) {
388
+ observed = { ...observed };delete observed.cache_read_input_tokens;
389
+ if (evidence.cached === undefined) delete observed.cached_input_tokens;
390
+ }
391
+ addRecordTotals(summary.totals, record, observed, evidence);
392
+ const model = record.model || "unknown";
393
+ if (!Object.hasOwn(summary.byModel, model)) Object.defineProperty(summary.byModel, model, { value: { requests: 0 }, enumerable: true, configurable: true, writable: true });
394
+ const modelTotals = summary.byModel[model];
395
+ modelTotals.requests += 1;
396
+ addUsageTotals(modelTotals, observed);
397
+ const qualified = `${source} / ${model}`;
398
+ if (!Object.hasOwn(summary.bySourceModel, qualified)) summary.bySourceModel[qualified] = { requests: 0 };
399
+ const sourceTotals = summary.bySourceModel[qualified];
400
+ sourceTotals.requests++;
401
+ addUsageTotals(sourceTotals, observed);
402
+ addCacheEvidence(modelTotals, usage, evidence);
403
+ addCacheEvidence(sourceTotals, usage, evidence);
404
+ if (onRecordTotals) {
405
+ const totals = {};
406
+ addRecordTotals(totals, record, observed, evidence);
407
+ onRecordTotals(record, { totals });
408
+ }
409
+ }
410
+
411
+ const archiveReadIndex = new Map();
412
+ async function archiveReadStamp(file) {
413
+ try {
414
+ const stat = await fs.promises.stat(file, { bigint: true });
415
+ if (stat.isFile()) return [stat.dev, stat.ino, stat.size, stat.mtimeNs, stat.ctimeNs].join(":");
416
+ } catch { /* The full reader retains its normal error handling. */ }
417
+ }
418
+
419
+ async function summarizeUsageLogFiles(filePath, { warn = console.error, onRecord, onRecordTotals, recordFilter, archiveSelection, provider = "" } = {}) {
396
420
  const summary = summarizeUsage([], { provider });
397
421
  const archive = await usageArchiveFiles(filePath);
398
422
  let archivedBackup = false;
@@ -402,13 +426,43 @@ async function summarizeUsageLogFiles(filePath, { warn = console.error, onRecord
402
426
  }
403
427
  for (const candidate of [...archive, ...(archivedBackup ? [] : [rotatedFilePath(filePath)]), filePath]) {
404
428
  const compressed = archive.includes(candidate);
429
+ const stamp = compressed && archiveSelection && await archiveReadStamp(candidate);
430
+ const indexed = stamp && archiveReadIndex.get(candidate);
431
+ if (indexed && indexed.stamp === stamp && archiveSelection.excludes(indexed)) {
432
+ for (const row of indexed.models.values()) {
433
+ if (!provider || provider === usageProvider(row)) archiveSelection.observeModel(row);
434
+ }
435
+ continue;
436
+ }
437
+ let index = stamp && indexed?.stamp !== stamp ? { stamp, first: Infinity, last: -Infinity, models: new Map() } : null;
405
438
  try {
406
- for await (const record of iterateUsageRecords(candidate, { warn, compressed })) {
407
- if (provider && provider !== usageProvider(record)) continue;
439
+ for await (const record of iterateUsageRecords(candidate, { compressed, warn(message) { index = null;warn(message); } })) {
440
+ const source = usageProvider(record);
441
+ if (index) {
442
+ const time = typeof record.ts === "string" ? Date.parse(record.ts) : NaN;
443
+ if (Number.isFinite(time)) { index.first = Math.min(index.first, time);index.last = Math.max(index.last, time); }
444
+ const model = record.model || "unknown";
445
+ if (typeof model !== "string" || model.length > 200) index = null;
446
+ else {
447
+ const label = source + " / " + model;
448
+ if (!index.models.has(label)) {
449
+ if (index.models.size >= 256) index = null;
450
+ else index.models.set(label, { model, provider: source });
451
+ }
452
+ }
453
+ }
454
+ if (provider && provider !== source) continue;
408
455
  if (recordFilter && !recordFilter(record)) continue;
409
- const one = summarizeUsage([record]);
410
- onRecord?.(record, one);
411
- mergeUsageSummary(summary, one);
456
+ if (onRecord) {
457
+ const one = summarizeUsage([record]);
458
+ onRecord(record, one);
459
+ onRecordTotals?.(record, { totals: one.totals });
460
+ mergeUsageSummary(summary, one);
461
+ } else accumulateUsageRecord(summary, record, source, onRecordTotals);
462
+ }
463
+ if (index && await archiveReadStamp(candidate) === stamp) {
464
+ if (!archiveReadIndex.has(candidate) && archiveReadIndex.size >= 32) archiveReadIndex.delete(archiveReadIndex.keys().next().value);
465
+ archiveReadIndex.set(candidate, index);
412
466
  }
413
467
  } catch (error) {
414
468
  if (!compressed) throw error;
@@ -455,9 +509,10 @@ export async function usageSummaryVersion(filePath, { settled = true } = {}) {
455
509
  } catch { return null; } // Uncacheable metadata never replaces the normal read/error path.
456
510
  }
457
511
 
458
- export async function summarizeUsageLogs(filePath = usageLogPath(), { warn = console.error, onRecord, recordFilter, provider = "", signal } = {}) {
512
+ export async function summarizeUsageLogs(filePath = usageLogPath(), { warn = console.error, onRecord, onRecordTotals, recordFilter, archiveSelection, provider = "", signal } = {}) {
459
513
  if (provider && !isProviderId(provider)) throw new Error("Usage provider must be a valid provider ID");
460
- if (onRecord || recordFilter || warn !== console.error) return summarizeUsageLogFiles(filePath, { warn, onRecord, recordFilter, provider });
514
+ if (onRecord || onRecordTotals || recordFilter || archiveSelection || warn !== console.error)
515
+ return summarizeUsageLogFiles(filePath, { warn, onRecord, onRecordTotals, recordFilter, archiveSelection, provider });
461
516
  const fileVersion = await usageSummaryVersion(filePath);
462
517
  const version = fileVersion === null ? null : `${fileVersion}\0${provider}`;
463
518
  if (version === null) {
@@ -508,8 +563,8 @@ export function usageCacheHitRate(usage = {}) {
508
563
  return cached / input;
509
564
  }
510
565
 
511
- function addCacheEvidence(target, usage) {
512
- const { cached, unknown, invalid } = usageCacheEvidence(usage);
566
+ function addCacheEvidence(target, usage, evidence = usageCacheEvidence(usage)) {
567
+ const { cached, unknown, invalid } = evidence;
513
568
  if (unknown) target.cache_hit_unknown_requests = (target.cache_hit_unknown_requests || 0) + 1;
514
569
  else {
515
570
  target.cache_hit_known_requests = (target.cache_hit_known_requests || 0) + 1;
package/src/usage.mjs CHANGED
@@ -18,6 +18,7 @@ export {
18
18
  readUsageRecords,
19
19
  summarizeUsage,
20
20
  summarizeUsageLogs,
21
+ accumulateUsageRecord,
21
22
  mergeUsageSummary,
22
23
  subscribeUsageAppends,
23
24
  cacheReadTokens,