codex-copilot-dx 1.3.28 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +4 -1
  2. package/docs/ARCHITECTURE.md +23 -1
  3. package/docs/REFERENCE.md +34 -3
  4. package/package.json +1 -1
  5. package/src/adapter.mjs +13 -3
  6. package/src/antigravity-handler.mjs +44 -15
  7. package/src/antigravity-runtime.mjs +22 -2
  8. package/src/claude-capability-config.mjs +3 -2
  9. package/src/claude-client-config.mjs +2 -2
  10. package/src/claude-gateway.mjs +22 -4
  11. package/src/cli-command-spec.mjs +9 -4
  12. package/src/cli-management.mjs +28 -0
  13. package/src/cli-options.mjs +1 -1
  14. package/src/connection-routing.mjs +1 -0
  15. package/src/connection-runtime.mjs +11 -0
  16. package/src/context-compaction-plan.mjs +122 -0
  17. package/src/context-compaction-seal.mjs +56 -0
  18. package/src/context-compaction-wire.mjs +137 -0
  19. package/src/context-compaction.mjs +161 -0
  20. package/src/context-metrics.mjs +3 -2
  21. package/src/conversation-source-guard.mjs +15 -5
  22. package/src/dashboard/console.js +1 -1
  23. package/src/dashboard/index.html +14 -1
  24. package/src/dashboard/language.js +33 -0
  25. package/src/dashboard/preferences.js +1 -1
  26. package/src/dashboard/status.js +2 -2
  27. package/src/dashboard/tool-activity.js +153 -0
  28. package/src/dashboard/ui.css +26 -0
  29. package/src/dashboard/ui.js +2 -2
  30. package/src/dashboard.mjs +1 -0
  31. package/src/http-transport.mjs +1 -1
  32. package/src/local-privacy.mjs +15 -7
  33. package/src/lock.mjs +9 -2
  34. package/src/privacy-detection.mjs +4 -3
  35. package/src/privacy-transform.mjs +20 -6
  36. package/src/provider-runtime.mjs +8 -5
  37. package/src/providers/api.mjs +15 -4
  38. package/src/request-context.mjs +1 -1
  39. package/src/responses-bridge.mjs +14 -5
  40. package/src/responses-handler.mjs +81 -1
  41. package/src/responses-proxy.mjs +22 -5
  42. package/src/responses-request.mjs +11 -4
  43. package/src/safe-upstream-error.mjs +29 -11
  44. package/src/service-control.mjs +8 -1
  45. package/src/settings-preferences.mjs +3 -3
  46. package/src/stream-performance.mjs +19 -2
  47. package/src/tool-activity.mjs +135 -0
  48. package/src/upstream-body.mjs +1 -1
  49. package/src/upstream-error-capture.mjs +29 -0
  50. package/src/user-settings.mjs +1 -1
@@ -1,9 +1,9 @@
1
1
  import { isMissingCallIdError } from "./responses-tool-output.mjs";
2
2
  import { isRootToolSchemaError } from "./messages-tool-schema.mjs";
3
- import { redactDiagnosticText } from "./diagnostic-text.mjs";
3
+ import { redactDiagnosticText, boundedDiagnosticText } from "./diagnostic-text.mjs";
4
4
 
5
- // Only fixed, documented-shaped codes leave this module; vendor messages and
6
- // request data are never returned or logged.
5
+ // Default evidence contains only fixed categories. A separately authorized
6
+ // one-shot capture can retain a bounded, redacted technical message.
7
7
  const reasons = new Map([
8
8
  ["credit_balance_exhausted", { statuses: [429], message: "The source account has no remaining credits." }],
9
9
  ["insufficient_quota", { statuses: [429], message: "The source account has insufficient quota." }],
@@ -14,6 +14,8 @@ const reasons = new Map([
14
14
  ["context_window_exceeded", { statuses: [400, 413, 422], message: "The source reports that the context is too long." }],
15
15
  ["content_policy_violation", { statuses: [400, 403, 422], message: "The source rejected the request under its content policy." }],
16
16
  ["invalid_request_error", { statuses: [400, 422], message: "The source rejected the request parameters." }],
17
+ ["input_length_invalid", { statuses: [400, 413, 422], message: "The source rejected the input length." }],
18
+ ["compaction_unavailable", { statuses: [400, 404, 405, 501], message: "The source does not support this compression operation." }],
17
19
  ["unsupported_parameter", { statuses: [400, 422], message: "The source does not support a requested parameter." }],
18
20
  ["output_limit_invalid", { statuses: [400, 422], message: "The source rejected the output token limit." }],
19
21
  ["tool_limit_exceeded", { statuses: [400, 422], message: "The source rejected the number of tool definitions." }],
@@ -41,22 +43,32 @@ export function classifyUpstreamError(value,status){
41
43
  const error=value?.error??value,text=typeof error==="string"?error:typeof error?.message==="string"?error.message:"";
42
44
  if(text.length>65536)return null;
43
45
  const param=safeUpstreamParameter(error?.param||error?.parameter);
46
+ const range = /^Range of input length should be\s*\[\s*1\s*,\s*(\d{1,9})\s*\]\.?\s*$/i.exec(text.trim());
44
47
  let code;
45
- if([400,413,422].includes(status)&&/(context (?:length|window)|input tokens|上下文).{0,80}(?:exceed|too (?:long|large)|超|超过)|(?:exceed|超).{0,60}(?:context|上下文)/i.test(text))code="context_length_exceeded";
48
+ if([400,404,405,501].includes(status)&&(["unsupported_compaction","compaction_not_supported"].includes(error?.code)
49
+ || /^(?:unsupported|unknown|unrecognized) (?:input item(?: type)?|parameter|type)\s*[:=]?\s*["']?compaction_trigger["']?\.?$/i.test(text.trim())
50
+ || param?.endsWith(".type")&&/compaction_trigger/i.test(text)&&/unsupported|not supported|supported values|unknown type/i.test(text)))code="compaction_unavailable";
51
+ else if([400,413,422].includes(status)&&range&&Number(range[1])>0&&Number(range[1])<=100000000)code="input_length_invalid";
52
+ else if([400,413,422].includes(status)&&/(context (?:length|window)|input tokens?|input token count|上下文).{0,80}(?:exceed|too (?:long|large)|超|超过)|(?:exceed|超).{0,60}(?:context|上下文)/i.test(text))code="context_length_exceeded";
46
53
  else if([400,422].includes(status)&&/max_(?:completion_)?tokens|max_output_tokens|output token limit|输出.{0,12}(?:上限|限制)/i.test(text)&&/(?:maximum|at most|less than|exceed|between|invalid|unsupported|最多|超过|不支持)/i.test(text))code="output_limit_invalid";
47
54
  else if([400,422].includes(status)&&/(?:too many|maximum number of|at most).{0,40}tools|工具.{0,20}(?:过多|超过)/i.test(text))code="tool_limit_exceeded";
48
55
  else if([400,422].includes(status)&&/(?:effort|thinking|reasoning).{0,60}(?:not support|unsupported)|not support.{0,60}(?:effort|thinking|reasoning)/i.test(text))code="reasoning_parameter_unsupported";
49
- const selected=safeUpstreamReason(code,status)||safeUpstreamReason(error?.code,status)||safeUpstreamReason(error?.type,status);
56
+ const selected=safeUpstreamReason(code,status)||safeUpstreamReason(error?.code,status)||safeUpstreamReason(error?.upstream_code,status)||safeUpstreamReason(error?.type,status);
50
57
  if(!selected)return null;
51
58
  const inferred = code === "output_limit_invalid" ? /\b(max_(?:completion_)?tokens|max_output_tokens)\b/i.exec(text)?.[1]?.toLowerCase() : code === "tool_limit_exceeded" ? "tools" : undefined;
52
59
  const bounds = {};
60
+ if (code === "input_length_invalid") bounds.maximum = Number(range[1]);
61
+ if (["input_length_invalid", "output_limit_invalid", "tool_limit_exceeded", "context_length_exceeded", "context_window_exceeded"].includes(selected.code)
62
+ && Number.isSafeInteger(error?.maximum) && error.maximum > 0 && error.maximum <= 100000000) bounds.maximum = error.maximum;
53
63
  if (["output_limit_invalid", "tool_limit_exceeded", "context_length_exceeded"].includes(selected.code)) {
54
- const maximum = /(?:maximum(?: (?:context length|number of tools|tokens))?(?: is| of)?|at most|must be (?:less than or equal to|<=)|最多|上限(?:为)?)\s*[:=]?\s*(\d[\d,]{0,11})(?![\d,])/i.exec(text)?.[1];
64
+ const maximum = /maximum number of tokens allowed\s*\((\d[\d,]{0,11})\)/i.exec(text)?.[1]
65
+ || /(?:maximum(?: (?:context length|number of tools|tokens))?(?: is| of)?|at most|must be (?:less than or equal to|<=)|最多|上限(?:为)?)\s*[:=]?\s*(\d[\d,]{0,11})(?![\d,])/i.exec(text)?.[1];
55
66
  const n = maximum && Number(maximum.replaceAll(",", ""));
56
67
  if (Number.isSafeInteger(n) && n > 0 && n <= 100000000) bounds.maximum = n;
57
68
  }
58
69
  return { ...selected, ...(param || inferred ? { parameter: param || inferred } : {}), ...bounds,
59
- message: selected.message + (param ? " Parameter: " + param + "." : "") + (bounds.maximum ? " Reported maximum: " + bounds.maximum + "." : "") };
70
+ message: code === "input_length_invalid" ? `Range of input length should be [1, ${bounds.maximum}].`
71
+ : selected.message + (param ? " Parameter: " + param + "." : "") + (bounds.maximum ? " Reported maximum: " + bounds.maximum + "." : "") };
60
72
  }
61
73
 
62
74
  function readChunk(reader, signal) {
@@ -73,7 +85,7 @@ function readChunk(reader, signal) {
73
85
 
74
86
  // Failure responses only. A stalled body or a stalled cancellation cannot delay
75
87
  // the caller beyond the budget. The original request's cancellation wins.
76
- export async function readSafeUpstreamReason(response, { signal, timeoutMs = 200, maxBytes = 64 * 1024, missingCallId = false, rootToolSchema = false } = {}) {
88
+ export async function readSafeUpstreamReason(response, { signal, timeoutMs = 200, maxBytes = 64 * 1024, missingCallId = false, rootToolSchema = false, diagnosticRedact } = {}) {
77
89
  if (signal?.aborted) {
78
90
  cancelBody(response?.body);
79
91
  signal.throwIfAborted();
@@ -99,10 +111,16 @@ export async function readSafeUpstreamReason(response, { signal, timeoutMs = 200
99
111
  chunks.push(chunk);
100
112
  }
101
113
  const text = Buffer.concat(chunks, bytes).toString("utf8");
102
- if (missingCallId && isMissingCallIdError(response.status, text)) return { code: "ccdx_missing_call_id", message: "The source requires a tool call ID." };
103
- if (rootToolSchema && isRootToolSchemaError(response.status, text)) return { code: "ccdx_tool_schema_root_unsupported", message: "The source rejected a tool's root schema." };
104
114
  let value;try { value = JSON.parse(text); } catch { value=text; }
105
- return classifyUpstreamError(value,response.status);
115
+ const reason = missingCallId && isMissingCallIdError(response.status, text)
116
+ ? { code: "ccdx_missing_call_id", message: "The source requires a tool call ID." }
117
+ : rootToolSchema && isRootToolSchemaError(response.status, text)
118
+ ? { code: "ccdx_tool_schema_root_unsupported", message: "The source rejected a tool's root schema." }
119
+ : classifyUpstreamError(value,response.status);
120
+ if (!diagnosticRedact) return reason;
121
+ const error = value?.error ?? value, message = typeof error === "string" ? error : error?.message;
122
+ if (typeof message !== "string") return reason;
123
+ return { ...reason, diagnostic_message: boundedDiagnosticText(diagnosticRedact(message), { maxChars: 512 }) };
106
124
  } catch (error) {
107
125
  if (signal?.aborted) signal.throwIfAborted();
108
126
  return null;
@@ -32,8 +32,11 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
32
32
  return { source: "service_settings", saved, theme, color_theme, preferences: settingsPreferencesSnapshot(options), local_privacy: localPrivacy,
33
33
  features: { prediction: { ...featureSnapshot(predictionControlSnapshot), bridge: prediction?.bridge || "stopped", active: prediction?.active === true }, image: { ...image, runtime: imageHostState.snapshot() } },
34
34
  decoded_body: decodedBodyLimitPreference(options), manual_update: { available: typeof manualUpdate === "function" }, last_operation: lastOperation,
35
+ ...(providerRuntime?.errorCaptureSnapshot ? { error_capture: providerRuntime.errorCaptureSnapshot() } : {}),
36
+ ...(providerRuntime?.compaction ? { compaction: providerRuntime.compaction.snapshot() } : {}),
35
37
  nightly_update: { enabled, ...nightly, effect: enabled && !nightly ? "next_start" : "immediate" },
36
38
  effective: {
39
+ context_compaction_enabled: { value: saved.context_compaction_enabled && Boolean(providerRuntime?.compaction), state: providerRuntime?.compaction ? saved.context_compaction_enabled ? "ready" : "off" : "unavailable" },
37
40
  privacy_enabled: { value: localPrivacy?.effective_enabled === true, state: !localPrivacy ? "unavailable" : !localPrivacy.enabled ? "off" : localPrivacy.state === "ready" ? "ready" : "not_ready" },
38
41
  terminal_animation_enabled: { value: terminal?.enabled === true && saved.terminal_animation_enabled && !/^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || ""),
39
42
  state: terminal?.enabled === true ? "immediate" : "terminal_unavailable", locked: /^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || "") },
@@ -51,11 +54,15 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
51
54
  prediction: ["action", "operation"], image: ["action", "operation", "model", "evidence", "confirmed"],
52
55
  codex_app: ["action", "operation", "intent", "confirmed"],
53
56
  update: ["action", "confirmed"], decoded_limit: ["action", "mib"],
57
+ error_capture: ["action", "operation", "source", "model"],
54
58
  preferences: ["action", "values", "revision"], reset_preferences: ["action", "revision", "backup_id", "scope"], restore_preferences: ["action", "revision", "backup_id", "scope"],
55
59
  provider: ["action", "operation", "provider", "model", "auto_review_model", "auto_review_effort", "account_id"] }[input.action];
56
60
  if (!allowed || Object.keys(input).some(key => !allowed.includes(key))) throw new Error("Unknown setting action or field");
57
61
  lastOperation = null;
58
- if (input.action === "codex_app") {
62
+ if (input.action === "error_capture") {
63
+ if (!providerRuntime?.captureUpstreamError) throw new Error("This service cannot capture upstream errors.");
64
+ lastOperation = { feature: "error_capture", result: providerRuntime.captureUpstreamError(input) };
65
+ } else if (input.action === "codex_app") {
59
66
  lastOperation = { feature: "codex_app", result: await codexLaunchControl(input.operation, { ...options, host: adapterHost, port: adapterPort,
60
67
  integration: clientIntegration, state: imageHostState, intent: input.intent, confirmed: input.confirmed, models: providerRuntime?.imageModels?.().models || [] }) };
61
68
  } else if (input.action === "prediction") {
@@ -9,7 +9,7 @@ import { atomicWriteFileIfChangedSync, atomicWriteFilePairSync } from "./atomic-
9
9
  import { withFileLockSync } from "./lock.mjs";
10
10
 
11
11
  export const SETTINGS_DEFAULTS = Object.freeze({ terminal_color_theme: "green", terminal_animation: DEFAULT_TERMINAL_ANIMATION_THEME,
12
- terminal_animation_enabled: true, open_webui: true, nightly_updates: false, auto_save_settings: true, privacy_enabled: false, privacy_personal: false });
12
+ terminal_animation_enabled: true, open_webui: true, nightly_updates: false, auto_save_settings: true, privacy_enabled: false, privacy_personal: false, context_compaction_enabled: true });
13
13
  const keys = Object.keys(SETTINGS_DEFAULTS);
14
14
  const fail = (code, message, statusCode = 409) => Object.assign(new Error(message), { code, statusCode });
15
15
  const idValid = value => typeof value === "string" && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(value);
@@ -30,8 +30,8 @@ function readBackup(options) {
30
30
  const value = JSON.parse(readBoundedFileSync(settingsBackupPath(options), { encoding: "utf8", maxBytes: 8192 }));
31
31
  if (value?.version !== 1 || !idValid(value.id) || typeof value.created_at !== "string" || !Number.isFinite(Date.parse(value.created_at))
32
32
  || Object.keys(value).some(key => !["version", "id", "created_at", "values"].includes(key))
33
- || keys.filter(key => !key.startsWith("privacy_")).some(key => !Object.hasOwn(value.values || {}, key))) throw Error();
34
- value.values = { privacy_enabled: false, privacy_personal: false, ...value.values };
33
+ || keys.filter(key => !key.startsWith("privacy_") && key !== "context_compaction_enabled").some(key => !Object.hasOwn(value.values || {}, key))) throw Error();
34
+ value.values = { privacy_enabled: false, privacy_personal: false, context_compaction_enabled: true, ...value.values };
35
35
  checkedPreferenceValues(value.values);return value;
36
36
  } catch (error) {
37
37
  if (error.code === "ENOENT") return null;
@@ -5,6 +5,7 @@ import { applicationLabel } from "./request-application.mjs";
5
5
  import { createContextMetrics } from "./context-metrics.mjs";
6
6
  import { createChangeSignal } from "./activity-events.mjs";
7
7
  import { redactDiagnosticText } from "./diagnostic-text.mjs";
8
+ import { createToolActivity, isToolActivityOutput } from "./tool-activity.mjs";
8
9
 
9
10
  const PERFORMANCE_ROUTES = Object.freeze(["responses", "responses_compact"]);
10
11
  const PREPARATION_STAGES = Object.freeze(["admission", "body", "history", "images", "serialization"]);
@@ -217,6 +218,7 @@ function routeSnapshot(route) {
217
218
 
218
219
  export function createStreamPerformanceMetrics({ now = () => performance.now(), wallNow = () => new Date().toISOString(), routeNames = PERFORMANCE_ROUTES } = {}) {
219
220
  const changes = createChangeSignal();
221
+ const toolActivity = createToolActivity({ now, changed: changes.changed });
220
222
  const routes = Object.fromEntries(routeNames.map((name) => [name, createRoutePerformance()]));
221
223
  const recentRequests = [];
222
224
  const contexts = createContextMetrics();
@@ -232,7 +234,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
232
234
  const activeId = ++activeSequence;
233
235
  const safeRequestId = typeof requestId === "string" && /^[a-zA-Z0-9_-]{1,80}$/.test(requestId) ? requestId : null;
234
236
  const client = applicationLabel(application);
235
- const purposeLabel = requestPurpose(purpose);
237
+ let purposeLabel = requestPurpose(purpose);
236
238
  activeTotal++;
237
239
  let upstreamStartedAt = null;
238
240
  let firstOutputAt = null;
@@ -260,6 +262,9 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
260
262
  let terminalAt = null;
261
263
  const context = { payload_bytes: null, images: null, input_tokens: null, context_window_tokens: null, output_tokens: null, max_output_tokens_requested: null, max_output_tokens_sent: null };
262
264
  let stopReason = null;
265
+ let toolObserver = null;
266
+ const tools = () => toolObserver ||= toolActivity.request(() => ({ application: client, session,
267
+ provider: provider || currentRequestContext()?.provider, model: model === "other" ? currentRequestContext()?.requestedModel || model : model }));
263
268
  const elapsed = (time) => time === null ? null : Number(Math.max(0, time - requestStartedAt).toFixed(1));
264
269
  if (activeRequests.size < MAX_ACTIVE_REQUESTS) activeRequests.set(activeId, () => ({
265
270
  request_id: safeRequestId, session_id: session ? session.slice(0, 16) : null, application: client, purpose: purposeLabel, route: routeName, provider, model, phase,
@@ -299,6 +304,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
299
304
  },
300
305
  upstreamStarted(streaming = true) {
301
306
  if (finished) return;
307
+ if (attempts && toolObserver) { toolObserver.finish("unknown");toolObserver = null; }
302
308
  const time = now();
303
309
  attempts += 1;
304
310
  if (attemptTimings.length === 3) attemptTimings.splice(1, 1);
@@ -322,6 +328,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
322
328
  },
323
329
  upstreamActivity() {
324
330
  if (finished) return;
331
+ toolObserver?.activity();
325
332
  lastActivityAt = now();
326
333
  if (phase !== "upstream_stream") { phase = "upstream_stream";changes.changed(); }
327
334
  },
@@ -342,13 +349,16 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
342
349
  if (next !== model) { model = next;changes.changed(); }
343
350
  },
344
351
  setProvider: assignProvider,
352
+ setPurpose(value) { if (!finished) { purposeLabel = requestPurpose(value);changes.changed(); } },
345
353
  observeSession(key) { if (!finished && typeof key === "string" && /^[a-f0-9]{64}$/.test(key)) session = key; },
354
+ observeToolInput(body, protocol) { if (!finished && purposeLabel === "conversation" && toolActivity.size) tools().input(body, protocol); },
355
+ observeToolOutput(value, protocol) { if (!finished && purposeLabel === "conversation" && isToolActivityOutput(value, protocol)) tools().output(value, protocol); },
346
356
  attemptCount() { return attempts; },
347
357
  attemptTimings() { return attemptTimings.map(attempt => ({ ...attempt })); },
348
358
  observeContext(values) {
349
359
  if (finished || !values || typeof values !== "object") return;
350
360
  if (Number.isSafeInteger(values.cached_input_tokens) && values.cached_input_tokens >= 0) cachedInput = values.cached_input_tokens;
351
- for (const key of [...Object.keys(context), "requested_model", "reasoning_effort_requested", "reasoning_effort_sent", "usage_state", "capability_revision", "capability_constraints", "privacy_count", "privacy_ms", "privacy_state", "privacy_pending_bytes", "privacy_new_bytes", "privacy_pending_windows", "privacy_wait_budget_ms", "privacy_error", "privacy_event_type", "privacy_channel_type", "privacy_buffered_bytes", "privacy_terminal_seen", "client_tool_errors_received"]) {
361
+ for (const key of [...Object.keys(context), "compaction", "requested_model", "reasoning_effort_requested", "reasoning_effort_sent", "usage_state", "capability_revision", "capability_constraints", "privacy_count", "privacy_ms", "privacy_state", "privacy_pending_bytes", "privacy_new_bytes", "privacy_pending_windows", "privacy_wait_budget_ms", "privacy_error", "privacy_event_type", "privacy_channel_type", "privacy_buffered_bytes", "privacy_terminal_seen", "client_tool_errors_received"]) {
352
362
  const value = values[key];
353
363
  if (["reasoning_effort_requested", "reasoning_effort_sent"].includes(key)) { if (["none", "minimal", "low", "medium", "high", "xhigh", "max"].includes(value)) context[key] = value;continue; }
354
364
  if (key === "requested_model") { if (typeof value === "string" && /^[\w][\w./:@+-]{0,159}$/.test(value) && redactDiagnosticText(value) === value) context[key] = value;continue; }
@@ -389,6 +399,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
389
399
  changes.changed();
390
400
  failed ||= finishFailed;
391
401
  const outcome = terminalOutcome || (aborted ? "cancelled" : "unknown");
402
+ toolObserver?.finish(aborted ? "cancelled" : statusCode >= 400 ? "failed" : outcome);
392
403
  const emptyStreamCompletion = outcome === "completed" && upstreamStartedAt !== null
393
404
  && firstOutputAt === null && outputTokens === 0;
394
405
  if (emptyStreamCompletion) route.empty_stream_completions += 1;
@@ -463,6 +474,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
463
474
  contextSnapshot: () => contexts.snapshot(),
464
475
  activitySnapshot() {
465
476
  return {
477
+ tool_activity: toolActivity.snapshot(),
466
478
  by_route: Object.fromEntries(routeNames.map(name => [name, {
467
479
  terminal_outcomes: { totals: { ...routes[name].terminalTotals } },
468
480
  by_provider: Object.fromEntries([...routes[name].providers].map(([id, value]) => [id, {
@@ -476,6 +488,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
476
488
  },
477
489
  snapshot() {
478
490
  return {
491
+ tool_activity: toolActivity.snapshot(),
479
492
  by_route: Object.fromEntries(routeNames.map((name) => [name, routeSnapshot(routes[name])])),
480
493
  active_requests: [...activeRequests.values()].map(snapshot => snapshot()),
481
494
  active_total: activeTotal,
@@ -556,3 +569,7 @@ export function markResponseErrorOrigin(origin) {
556
569
  export function markResponseTerminal(outcome, options) {
557
570
  tracker()?.terminal?.(outcome, options);
558
571
  }
572
+
573
+ export function markToolActivity(value, protocol = "responses") {
574
+ tracker()?.observeToolOutput?.(value, protocol);
575
+ }
@@ -0,0 +1,135 @@
1
+ import { hash } from "node:crypto";
2
+ import { redactDiagnosticText } from "./diagnostic-text.mjs";
3
+
4
+ export const TOOL_ACTIVITY_LIMITS = Object.freeze({ retained: 128, visible: 32, per_request: 32, stale_ms: 90_000, terminal_ms: 15_000, unknown_ms: 300_000 });
5
+ const pending = state => state === "preparing" || state === "waiting";
6
+ const nameOf = value => typeof value === "string" && /^[\w./:@-]{1,80}$/.test(value) && redactDiagnosticText(value) === value ? value : null;
7
+ const idOf = value => typeof value === "string" && value.length > 0 && value.length <= 256 ? value : null;
8
+ const toolTypes = new Set(["function_call", "custom_tool_call", "web_search_call", "file_search_call", "computer_call", "tool_search_call", "mcp_call", "shell_call", "image_generation_call", "program", "multi_agent_call"]);
9
+ const hostedTools = new Set(["web_search_call", "file_search_call", "mcp_call", "image_generation_call"]);
10
+ const messageResult = value => typeof value?.type === "string" && value.type.endsWith("_tool_result") && idOf(value.tool_use_id);
11
+ const items = value => Array.isArray(value) ? value.slice(0, 64) : [];
12
+ export function isToolActivityOutput(value, protocol = "responses") {
13
+ if (!value || typeof value !== "object") return false;
14
+ if (protocol === "messages") return ["tool_use", "server_tool_use", "mcp_tool_use"].includes((value.content_block || value).type) || Boolean(messageResult(value.content_block || value))
15
+ || items(value.content).some(item => ["tool_use", "server_tool_use", "mcp_tool_use"].includes(item?.type) || messageResult(item));
16
+ if (protocol === "gemini") return Boolean(value.functionCall) || items((value.response || value).candidates).some(candidate => items(candidate?.content?.parts).some(part => part?.functionCall));
17
+ return toolTypes.has((value.item || value).type) || items(value.response?.output || value.output).some(item => toolTypes.has(item?.type));
18
+ }
19
+
20
+ // Metadata only: arguments, input/output text and raw conversation/call IDs never leave the request.
21
+ export function createToolActivity({ now = Date.now, changed = () => {} } = {}) {
22
+ const entries = new Map();let sequence = 0;
23
+ function sweep() {
24
+ const time = now();
25
+ for (const [key, entry] of entries) {
26
+ if (pending(entry.state) && time - entry.updated >= TOOL_ACTIVITY_LIMITS.stale_ms) { entry.state = "unknown";entry.updated = time; }
27
+ if (!pending(entry.state) && time - entry.updated >= (entry.state === "unknown" ? TOOL_ACTIVITY_LIMITS.unknown_ms : TOOL_ACTIVITY_LIMITS.terminal_ms)) entries.delete(key);
28
+ }
29
+ }
30
+ const change = (entry, state) => {
31
+ if (!entry || entry.state === state || !pending(entry.state) && entry.state !== "unknown") return;
32
+ entry.state = state;entry.updated = now();changed();
33
+ };
34
+ return {
35
+ get size() { return entries.size; },
36
+ request(metadata) {
37
+ const aliases = new Map(), owned = new Set(), local = ++sequence;
38
+ let lastNotice = now();
39
+ const scope = () => { const m = metadata();return m.session ? `${m.application}\0${m.session}` : `request:${local}`; };
40
+ const keyFor = id => hash("sha256", `${scope()}\0${id}`, "hex");
41
+ function record(id, name, alias, resultId) {
42
+ id = idOf(id);const known = aliases.get(id) || aliases.get(alias);
43
+ if (known) { const next = nameOf(name);if (next && known.name !== next) { known.name = next;changed(); }if (id) aliases.set(id, known);if (idOf(resultId)) known.result_key = keyFor(resultId);return known; }
44
+ if (owned.size >= TOOL_ACTIVITY_LIMITS.per_request) return null;
45
+ sweep();const key = keyFor(id || `anonymous:${local}:${owned.size}`), m = metadata();
46
+ if (entries.has(key) && pending(entries.get(key).state)) return entries.get(key);
47
+ const entry = { id: `tool-${++sequence}`, application: m.application, provider: m.provider || "unknown", model: m.model,
48
+ name: nameOf(name), state: "preparing", updated: now(), key, scope: scope(), ...(idOf(resultId) ? { result_key: keyFor(resultId) } : {}) };
49
+ entries.set(key, entry);owned.add(entry);if (id) aliases.set(id, entry);if (alias !== undefined) aliases.set(alias, entry);
50
+ while (entries.size > TOOL_ACTIVITY_LIMITS.retained) entries.delete(entries.keys().next().value);
51
+ changed();return entry;
52
+ }
53
+ function output(value, protocol = "responses") {
54
+ if (!value || typeof value !== "object") return;
55
+ if (protocol === "messages") {
56
+ const block = value.type === "content_block_start" ? value.content_block : value;
57
+ if (["tool_use", "server_tool_use", "mcp_tool_use"].includes(block?.type)) record(block.id, block.name, value.index);
58
+ else if (messageResult(block)) change(aliases.get(block.tool_use_id), block.is_error === true ? "failed" : "returned");
59
+ else if (Array.isArray(value.content)) for (const item of value.content.slice(0, 64)) output(item, protocol);
60
+ return;
61
+ }
62
+ if (protocol === "gemini") {
63
+ if (value.functionCall) {
64
+ const id = idOf(value.functionCall.id), name = nameOf(value.functionCall.name);
65
+ if (!id && !name) return;
66
+ const alias = id ? undefined : `gemini:${name}:${value.index ?? 0}`;
67
+ const prior = alias === undefined ? null : aliases.get(alias);
68
+ if (prior) prior.ambiguous = true;
69
+ record(id, name, alias);
70
+ }
71
+ else for (const candidate of items((value.response || value).candidates)) for (const [index, part] of items(candidate?.content?.parts).entries()) {
72
+ if (part?.functionCall) output({ functionCall: part.functionCall, index }, protocol);
73
+ }
74
+ return;
75
+ }
76
+ const item = value.item || value;
77
+ if (toolTypes.has(item.type)) {
78
+ const entry = record(item.call_id || item.id, item.name || item.type, value.output_index ?? item.id, item.call_id);
79
+ if (["completed", "failed", "cancelled"].includes(item.status) && hostedTools.has(item.type)) {
80
+ change(entry, item.status === "completed" ? "returned" : item.status);
81
+ }
82
+ } else if (value.response?.output || value.output) {
83
+ for (const item of items(value.response?.output || value.output)) output(item, protocol);
84
+ }
85
+ }
86
+ return {
87
+ output,
88
+ activity() {
89
+ const time = now();let active = false;
90
+ for (const entry of owned) if (entry.state === "preparing") { entry.updated = time;active = true; }
91
+ if (active && time - lastNotice >= 1000) { lastNotice = time;changed(); }
92
+ },
93
+ input(body, protocol) {
94
+ if (!entries.size || !metadata().session || !body || typeof body !== "object") return;
95
+ const results = [];
96
+ const inspect = part => {
97
+ if (["function_call_output", "custom_tool_call_output", "computer_call_output", "shell_call_output"].includes(part?.type)) results.push({ id: part.call_id });
98
+ else if (part?.type === "tool_result") results.push({ id: part.tool_use_id, error: part.is_error === true });
99
+ else if (part?.role === "tool") results.push({ id: part.tool_call_id });
100
+ else if (part?.functionResponse) results.push({ id: part.functionResponse.id, name: nameOf(part.functionResponse.name) });
101
+ };
102
+ if (Array.isArray(body.input)) for (const item of body.input.slice(-64)) inspect(item);
103
+ else if (Array.isArray(body.messages)) for (const message of body.messages.slice(-8)) {
104
+ inspect(message);if (Array.isArray(message?.content)) for (const part of message.content.slice(-64)) inspect(part);
105
+ }
106
+ else if (protocol === "gemini" && Array.isArray(body.contents)) for (const message of body.contents.slice(-8)) {
107
+ for (const part of items(message?.parts)) inspect(part);
108
+ }
109
+ for (const result of results) {
110
+ const resultKey = idOf(result.id) ? keyFor(result.id) : null;
111
+ let entry = resultKey ? entries.get(resultKey) || [...entries.values()].find(item => item.result_key === resultKey) : null;
112
+ if (!entry && result.name) {
113
+ const matches = [...entries.values()].filter(item => pending(item.state) && item.scope === scope() && item.name === result.name);
114
+ if (matches.length === 1) entry = matches[0];
115
+ }
116
+ change(entry, result.error ? "failed" : "returned");
117
+ }
118
+ },
119
+ finish(outcome) {
120
+ for (const entry of owned) {
121
+ entry.scope = scope();
122
+ change(entry, outcome === "completed" ? metadata().session && !entry.ambiguous ? "waiting" : "unknown" : ["failed", "cancelled"].includes(outcome) ? outcome : "unknown");
123
+ }
124
+ },
125
+ };
126
+ },
127
+ snapshot() {
128
+ sweep();const time = now(), all = [...entries.values()].reverse();
129
+ all.sort((a, b) => Number(pending(b.state)) - Number(pending(a.state)));
130
+ return { items: all.slice(0, TOOL_ACTIVITY_LIMITS.visible).map(({ key, scope, result_key, ambiguous, updated, ...entry }) => ({ ...entry,
131
+ expires_in_ms: Math.max(0, (pending(entry.state) ? TOOL_ACTIVITY_LIMITS.stale_ms : entry.state === "unknown" ? TOOL_ACTIVITY_LIMITS.unknown_ms : TOOL_ACTIVITY_LIMITS.terminal_ms) - (time - updated)) })),
132
+ omitted: Math.max(0, all.length - TOOL_ACTIVITY_LIMITS.visible), limits: TOOL_ACTIVITY_LIMITS };
133
+ },
134
+ };
135
+ }
@@ -41,7 +41,7 @@ function responseAbortError(signal) {
41
41
  return error;
42
42
  }
43
43
 
44
- function readResponseChunk(reader, signal) {
44
+ export function readResponseChunk(reader, signal) {
45
45
  if (!signal) return reader.read();
46
46
  if (signal.aborted) return Promise.reject(responseAbortError(signal));
47
47
  return new Promise((resolve, reject) => {
@@ -0,0 +1,29 @@
1
+ import { boundedDiagnosticText } from "./diagnostic-text.mjs";
2
+
3
+ // Explicit, process-local consent for one failed Messages request. Only the
4
+ // bounded, redacted error message is retained; request bodies are never copied.
5
+ export function createUpstreamErrorCapture({ now = Date.now } = {}) {
6
+ let state = { state: "off" };
7
+ const expire = () => { if (state.state === "armed" && now() >= state.expires_at_ms) state = { ...state, state: "expired" }; };
8
+ return {
9
+ snapshot() { expire();return { ...state }; },
10
+ arm(source, model) {
11
+ expire();
12
+ if (["armed", "reading"].includes(state.state)) throw Object.assign(new Error("An error capture is already pending; cancel it before arming another."), { statusCode: 409 });
13
+ state = { state: "armed", source, model, expires_at_ms: now() + 10 * 60 * 1000 };
14
+ return { ...state };
15
+ },
16
+ cancel() { state = { state: "off" };return { ...state }; },
17
+ claim(source, model, protocol, status, requestId) {
18
+ expire();
19
+ if (state.state !== "armed" || source !== state.source || model !== state.model || protocol !== "messages" || ![400, 422].includes(status)) return null;
20
+ const claimed = state = { ...state, state: "reading", request_id: requestId || null };
21
+ return message => {
22
+ if (state !== claimed) return false;
23
+ state = { ...state, state: message ? "captured" : "unavailable",
24
+ ...(message ? { diagnostic_message: boundedDiagnosticText(message, { maxChars: 512 }) } : {}) };
25
+ return true;
26
+ };
27
+ },
28
+ };
29
+ }
@@ -23,7 +23,7 @@ const AUTO_REVIEW_REASONING_KEY = "auto_review_reasoning";
23
23
  const TERMINAL_ANIMATION_KEY = "terminal_animation";
24
24
  const RESPONSE_HISTORY_MAX_MIB_KEY = "response_history_max_mib";
25
25
  const DECODED_BODY_LIMIT_MIB_KEY = "decoded_body_limit_mib";
26
- const SERVICE_FLAGS = ["terminal_animation_enabled", "open_webui", "image_enabled", "prediction_enabled"];
26
+ const SERVICE_FLAGS = ["terminal_animation_enabled", "open_webui", "image_enabled", "prediction_enabled", "context_compaction_enabled"];
27
27
  export const DECODED_BODY_LIMIT_MIN_MIB = RUNTIME_DEFAULTS.maxDecodedBodyBytes / MIB;
28
28
  export const DECODED_BODY_LIMIT_MAX_MIB = 512;
29
29
  export { RESPONSE_HISTORY_MAX_MIB, RESPONSE_HISTORY_MIN_MIB };