codex-copilot-dx 1.3.28 → 1.4.0

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 (43) hide show
  1. package/README.md +3 -1
  2. package/docs/ARCHITECTURE.md +17 -1
  3. package/docs/REFERENCE.md +25 -3
  4. package/package.json +1 -1
  5. package/src/adapter.mjs +13 -3
  6. package/src/antigravity-handler.mjs +38 -13
  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 +19 -3
  11. package/src/cli-command-spec.mjs +7 -3
  12. package/src/cli-management.mjs +21 -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 +1 -1
  21. package/src/conversation-source-guard.mjs +15 -5
  22. package/src/dashboard/index.html +7 -1
  23. package/src/dashboard/language.js +4 -0
  24. package/src/dashboard/preferences.js +1 -1
  25. package/src/http-transport.mjs +1 -1
  26. package/src/local-privacy.mjs +15 -7
  27. package/src/lock.mjs +9 -2
  28. package/src/privacy-detection.mjs +4 -3
  29. package/src/privacy-transform.mjs +20 -6
  30. package/src/provider-runtime.mjs +8 -5
  31. package/src/providers/api.mjs +15 -4
  32. package/src/request-context.mjs +1 -1
  33. package/src/responses-bridge.mjs +12 -5
  34. package/src/responses-handler.mjs +79 -1
  35. package/src/responses-proxy.mjs +18 -5
  36. package/src/responses-request.mjs +11 -4
  37. package/src/safe-upstream-error.mjs +29 -11
  38. package/src/service-control.mjs +8 -1
  39. package/src/settings-preferences.mjs +3 -3
  40. package/src/stream-performance.mjs +3 -2
  41. package/src/upstream-body.mjs +1 -1
  42. package/src/upstream-error-capture.mjs +29 -0
  43. 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;
@@ -232,7 +232,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
232
232
  const activeId = ++activeSequence;
233
233
  const safeRequestId = typeof requestId === "string" && /^[a-zA-Z0-9_-]{1,80}$/.test(requestId) ? requestId : null;
234
234
  const client = applicationLabel(application);
235
- const purposeLabel = requestPurpose(purpose);
235
+ let purposeLabel = requestPurpose(purpose);
236
236
  activeTotal++;
237
237
  let upstreamStartedAt = null;
238
238
  let firstOutputAt = null;
@@ -342,13 +342,14 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
342
342
  if (next !== model) { model = next;changes.changed(); }
343
343
  },
344
344
  setProvider: assignProvider,
345
+ setPurpose(value) { if (!finished) { purposeLabel = requestPurpose(value);changes.changed(); } },
345
346
  observeSession(key) { if (!finished && typeof key === "string" && /^[a-f0-9]{64}$/.test(key)) session = key; },
346
347
  attemptCount() { return attempts; },
347
348
  attemptTimings() { return attemptTimings.map(attempt => ({ ...attempt })); },
348
349
  observeContext(values) {
349
350
  if (finished || !values || typeof values !== "object") return;
350
351
  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"]) {
352
+ 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
353
  const value = values[key];
353
354
  if (["reasoning_effort_requested", "reasoning_effort_sent"].includes(key)) { if (["none", "minimal", "low", "medium", "high", "xhigh", "max"].includes(value)) context[key] = value;continue; }
354
355
  if (key === "requested_model") { if (typeof value === "string" && /^[\w][\w./:@+-]{0,159}$/.test(value) && redactDiagnosticText(value) === value) context[key] = value;continue; }
@@ -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 };