codex-copilot-dx 1.3.27 → 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.
- package/README.md +7 -2
- package/bin/cli.mjs +4 -1
- package/docs/ARCHITECTURE.md +32 -3
- package/docs/REFERENCE.md +51 -5
- package/package.json +1 -1
- package/src/adapter.mjs +17 -5
- package/src/antigravity-handler.mjs +38 -13
- package/src/antigravity-runtime.mjs +22 -2
- package/src/claude-app-contract.mjs +96 -0
- package/src/claude-capability-config.mjs +28 -11
- package/src/claude-client-config.mjs +58 -9
- package/src/claude-gateway.mjs +25 -7
- package/src/claude-models.mjs +4 -2
- package/src/cli-command-spec.mjs +13 -3
- package/src/cli-management.mjs +47 -6
- package/src/cli-options.mjs +1 -1
- package/src/connection-client-sync.mjs +1 -0
- package/src/connection-management.mjs +5 -0
- package/src/connection-policy.mjs +2 -2
- package/src/connection-routing.mjs +3 -1
- package/src/connection-runtime.mjs +37 -2
- package/src/connection-view.mjs +11 -2
- package/src/context-compaction-plan.mjs +122 -0
- package/src/context-compaction-seal.mjs +56 -0
- package/src/context-compaction-wire.mjs +137 -0
- package/src/context-compaction.mjs +161 -0
- package/src/context-metrics.mjs +1 -1
- package/src/conversation-source-guard.mjs +15 -5
- package/src/dashboard/connections.js +33 -3
- package/src/dashboard/index.html +9 -1
- package/src/dashboard/language.js +28 -0
- package/src/dashboard/preferences.js +1 -1
- package/src/dashboard/ui.js +3 -0
- package/src/dashboard-api.mjs +2 -2
- package/src/doctor-compat.mjs +1 -1
- package/src/http-transport.mjs +1 -1
- package/src/local-privacy.mjs +15 -7
- package/src/lock.mjs +9 -2
- package/src/model-capabilities.mjs +17 -4
- package/src/privacy-detection.mjs +4 -3
- package/src/privacy-transform.mjs +20 -6
- package/src/provider-cooldown.mjs +43 -0
- package/src/provider-runtime.mjs +8 -5
- package/src/providers/api-model-metadata.mjs +7 -0
- package/src/providers/api.mjs +44 -12
- package/src/request-context.mjs +5 -0
- package/src/response-failures.mjs +4 -2
- package/src/responses-bridge.mjs +12 -5
- package/src/responses-handler.mjs +79 -1
- package/src/responses-proxy.mjs +18 -5
- package/src/responses-request.mjs +11 -4
- package/src/safe-upstream-error.mjs +59 -9
- package/src/service-control.mjs +8 -1
- package/src/settings-preferences.mjs +3 -3
- package/src/source-import.mjs +51 -0
- package/src/stream-performance.mjs +8 -5
- package/src/upstream-body.mjs +1 -1
- package/src/upstream-error-capture.mjs +29 -0
- package/src/usage-analysis.mjs +2 -2
- package/src/usage-query.mjs +5 -2
- package/src/usage-store.mjs +2 -1
- package/src/user-settings.mjs +1 -1
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import { watch } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { readBoundedFile } from "./bounded-file.mjs";
|
|
6
|
+
|
|
7
|
+
const MAX_HEADER = 4 * 1024 * 1024, MAX_SOURCE = 16 * 1024 * 1024;
|
|
8
|
+
const cache = new Map();
|
|
9
|
+
const version = text => /<key>CFBundleShortVersionString<\/key>\s*<string>([^<]+)<\/string>/.exec(text)?.[1];
|
|
10
|
+
const stamp = stat => [stat.dev, stat.ino, stat.size, stat.mtimeMs].join(":");
|
|
11
|
+
|
|
12
|
+
export function watchClaudeAppContract({ platform = process.platform, appPath = "/Applications/Claude.app", onChange = () => {}, watchFile = watch } = {}) {
|
|
13
|
+
const watchers = [];let timer, closed = false;
|
|
14
|
+
const schedule = () => {
|
|
15
|
+
clearTimeout(timer);
|
|
16
|
+
timer = setTimeout(() => { if (!closed) void Promise.resolve().then(onChange).catch(() => {}); }, 250);timer.unref?.();
|
|
17
|
+
};
|
|
18
|
+
if (platform === "darwin") for (const [directory, name] of [[path.dirname(appPath), path.basename(appPath)], [path.join(appPath, "Contents"), "Info.plist"], [path.join(appPath, "Contents", "Resources"), "app.asar"]]) {
|
|
19
|
+
try {
|
|
20
|
+
const watcher = watchFile(directory, { persistent: false }, (_event, file) => { if (!file || String(file) === name) schedule(); });
|
|
21
|
+
watcher.on("error", () => watcher.close());watchers.push(watcher);
|
|
22
|
+
} catch { /* Existing periodic inspection also covers replacement/watch failure. */ }
|
|
23
|
+
}
|
|
24
|
+
return { close() { closed = true;clearTimeout(timer);for (const watcher of watchers) watcher.close(); } };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function archiveFiles(node, prefix = "", output = []) {
|
|
28
|
+
for (const [name, entry] of Object.entries(node.files || {})) {
|
|
29
|
+
const file = prefix + name;
|
|
30
|
+
if (entry.files) archiveFiles(entry, file + "/", output);
|
|
31
|
+
else if (!entry.unpacked && Number.isSafeInteger(entry.size) && /^\d+$/.test(entry.offset || "")) output.push({ name: file, ...entry });
|
|
32
|
+
}
|
|
33
|
+
return output;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Read declarations and their consumers, not a release-number allowlist.
|
|
37
|
+
// No application code is executed and no user profile or credential is read.
|
|
38
|
+
export function parseClaudeAppContract(source) {
|
|
39
|
+
const profiles = [];
|
|
40
|
+
for (const match of source.matchAll(/"(claude-[a-z]+-[0-9][0-9.-]*)":\{effortLevels:\[([^\]]{0,120})\]/g)) {
|
|
41
|
+
const values = match[2].match(/"(?:low|medium|high|xhigh|max)"/g)?.map(value => JSON.parse(value));
|
|
42
|
+
if (values?.length && values.join(",") === match[2].replaceAll('"', "").replaceAll(" ", "") && new Set(values).size === values.length)
|
|
43
|
+
profiles.push({ model: match[1], efforts: values });
|
|
44
|
+
}
|
|
45
|
+
const fields = {
|
|
46
|
+
models: /flatKey:"inferenceModels"/.test(source) && /readers:\["desktop","m365","code"\]/.test(source),
|
|
47
|
+
discovery: /flatKey:"modelDiscoveryEnabled"/.test(source),
|
|
48
|
+
behaves_as: /\.find\(\(\w+=>\w+\.behavesAs\)\)\?\.behavesAs/.test(source),
|
|
49
|
+
effort_cap: /maxEffortLevel/.test(source) && /\.effort_options/.test(source) && /\.maxEffort/.test(source),
|
|
50
|
+
context: /autoCompactWindow/.test(source) && /1000000/.test(source),
|
|
51
|
+
output: /CLAUDE_CODE_MAX_OUTPUT_TOKENS/.test(source),
|
|
52
|
+
};
|
|
53
|
+
const picker = profiles.length > 0 && fields.models && fields.behaves_as && fields.effort_cap;
|
|
54
|
+
const facts = { fields, profiles: profiles.sort((a, b) => a.model.localeCompare(b.model)) };
|
|
55
|
+
return { status: picker ? "verified" : "unverified", ...facts,
|
|
56
|
+
fingerprint: createHash("sha256").update(JSON.stringify(facts)).digest("hex").slice(0, 24) };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export async function inspectClaudeAppContract({ platform = process.platform, appPath = "/Applications/Claude.app", appSource } = {}) {
|
|
60
|
+
if (typeof appSource === "string") return parseClaudeAppContract(appSource);
|
|
61
|
+
if (platform !== "darwin") return { status: "unavailable", fields: {}, profiles: [], fingerprint: null };
|
|
62
|
+
const archive = path.join(appPath, "Contents", "Resources", "app.asar");let handle;
|
|
63
|
+
try {
|
|
64
|
+
const info = await readBoundedFile(path.join(appPath, "Contents", "Info.plist"), { maxBytes: 65536, encoding: "utf8" });
|
|
65
|
+
if (!/<key>CFBundleIdentifier<\/key>\s*<string>com\.anthropic\.claudefordesktop<\/string>/.test(info)) throw Error("Unrecognized App");
|
|
66
|
+
const before = await fs.stat(archive), key = stamp(before), previous = cache.get(archive);
|
|
67
|
+
if (previous?.key === key) return { ...structuredClone(previous.value), app_version: version(info) || null };
|
|
68
|
+
handle = await fs.open(archive, "r");const prefix = Buffer.alloc(16);await handle.read(prefix, 0, 16, 0);
|
|
69
|
+
const headerSize = prefix.readUInt32LE(12), base = 8 + prefix.readUInt32LE(4);
|
|
70
|
+
if (headerSize <= 0 || headerSize > MAX_HEADER || base > before.size) throw Error("Invalid archive");
|
|
71
|
+
const header = Buffer.alloc(headerSize);await handle.read(header, 0, headerSize, 16);
|
|
72
|
+
const files = archiveFiles(JSON.parse(header.toString("utf8"))).filter(file => /^\.vite\/build\/index(?:\.chunk[^/]*|\.pre)\.js$/.test(file.name)
|
|
73
|
+
&& file.size > 500000 && file.size <= MAX_SOURCE).sort((a, b) => b.size - a.size);
|
|
74
|
+
let result = { status: "unverified", fields: {}, profiles: [], fingerprint: null };
|
|
75
|
+
for (const file of files.slice(0, 6)) {
|
|
76
|
+
const offset = base + Number(file.offset);if (!Number.isSafeInteger(offset) || offset + file.size > before.size) continue;
|
|
77
|
+
const bytes = Buffer.alloc(file.size);await handle.read(bytes, 0, bytes.length, offset);
|
|
78
|
+
const candidate = parseClaudeAppContract(bytes.toString("utf8"));
|
|
79
|
+
if (candidate.status === "verified") { result = candidate;break; }
|
|
80
|
+
}
|
|
81
|
+
if (stamp(await fs.stat(archive)) !== key) throw Error("App changed during inspection");
|
|
82
|
+
const value = { ...result, app_version: version(info) || null, installation: key };
|
|
83
|
+
cache.set(archive, { key, value });if (cache.size > 2) cache.delete(cache.keys().next().value);
|
|
84
|
+
return structuredClone(value);
|
|
85
|
+
} catch { return { status: "unavailable", fields: {}, profiles: [], fingerprint: null }; }
|
|
86
|
+
finally { await handle?.close(); }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function claudeNativeModelHint(values = {}, contract) {
|
|
90
|
+
if (contract?.status !== "verified" || values.reasoning === false) return null;
|
|
91
|
+
const levels = values.reasoning_efforts || [], order = ["low", "medium", "high", "xhigh", "max"];
|
|
92
|
+
if (!levels.length || levels.some(level => !order.includes(level))) return null;
|
|
93
|
+
const sorted = order.filter(level => levels.includes(level)), maximum = sorted.at(-1);
|
|
94
|
+
const profile = contract.profiles?.find(profile => profile.efforts.filter(level => order.indexOf(level) <= order.indexOf(maximum)).join(",") === sorted.join(","));
|
|
95
|
+
return profile ? { behavesAs: profile.model, maxEffort: maximum } : null;
|
|
96
|
+
}
|
|
@@ -5,8 +5,10 @@ import { m365Paths, readM365Json } from "./m365-settings.mjs";
|
|
|
5
5
|
import { claudeEffortsExpressible, claudeEffortPrefix } from "./model-capabilities.mjs";
|
|
6
6
|
import { claudeModelEntries } from "./claude-models.mjs";
|
|
7
7
|
import { claudeClientPaths, reconcileClaudeConfiguration } from "./claude-client-config.mjs";
|
|
8
|
+
import { claudeNativeModelHint } from "./claude-app-contract.mjs";
|
|
9
|
+
import { claudeRouteAliases } from "./clients/claude-models.mjs";
|
|
8
10
|
|
|
9
|
-
export function inspectClaudeCapabilitySupport({ platform = process.platform, env = process.env, appVersion, codeVersion } = {}) {
|
|
11
|
+
export function inspectClaudeCapabilitySupport({ platform = process.platform, env = process.env, appVersion, codeVersion, appContract } = {}) {
|
|
10
12
|
if (!codeVersion) for (const directory of (env.PATH || "").split(path.delimiter).filter(Boolean)) {
|
|
11
13
|
try {
|
|
12
14
|
const executable = fs.realpathSync(path.join(directory, platform === "win32" ? "claude.exe" : "claude"));
|
|
@@ -23,22 +25,26 @@ export function inspectClaudeCapabilitySupport({ platform = process.platform, en
|
|
|
23
25
|
}
|
|
24
26
|
// The 3.x and 4.x App schema/host were independently inspected. Other versions keep
|
|
25
27
|
// working catalogs without claiming adoption of undocumented host controls.
|
|
26
|
-
|
|
28
|
+
const verified = appContract?.status === "verified";
|
|
29
|
+
return { app_version: appContract?.app_version || appVersion || null, app: verified || /^[34]\./.test(appVersion || ""),
|
|
30
|
+
app_aliases: !verified, ...(appContract ? { app_contract: appContract } : {}),
|
|
31
|
+
code_version: codeVersion || null, code: /^2\.1\./.test(codeVersion || "") && Number(codeVersion.split(".")[2]) >= 293 };
|
|
27
32
|
}
|
|
28
33
|
|
|
29
34
|
export function claudeSupportForSync(support, observations) {
|
|
30
35
|
const rows = Array.isArray(observations?.claude) ? observations.claude : [];
|
|
31
36
|
const app = rows.find(entry => entry.id === "claude_system_claude");
|
|
37
|
+
if (support.app_contract?.status === "verified" && (!app?.version || app.version === support.app_version)) return support;
|
|
32
38
|
return observations?.claude_unrecognized === true || app?.version && !/^[34]\./.test(app.version) ? { ...support, app: false } : support;
|
|
33
39
|
}
|
|
34
40
|
|
|
35
41
|
export function claudeSharedCapabilityPlan({ app = [], code = [], support = {} } = {}) {
|
|
36
|
-
const limitations = [], budgets = {}, caps = [], consumers = [...app.map(model => ({ model, app: true })), ...code.map(model => ({ model, app: false }))];
|
|
42
|
+
const limitations = [], budgets = {}, caps = [], preserveRefs = [], consumers = [...app.map(model => ({ model, app: true })), ...code.map(model => ({ model, app: false }))];
|
|
37
43
|
let context = 0, output = 0, safeContext = consumers.length > 0, knownAdapters = true;
|
|
38
44
|
for (const { model, app: desktop } of consumers) {
|
|
39
45
|
const entry = claudeModelEntries([model], { desktopAliases: desktop })[0], values = model.capability?.values || {};
|
|
40
46
|
const id = model.public_id || entry.name;
|
|
41
|
-
if (desktop ? !support.app : !support.code) { safeContext = false;knownAdapters = false;limitations.push({ model: model.id, code: "client_version_unknown" });continue; }
|
|
47
|
+
if (desktop ? !support.app : !support.code) { safeContext = false;knownAdapters = false;limitations.push({ model: model.id, code: "client_version_unknown" });preserveRefs.push(id, ...(model.route_id ? claudeRouteAliases(model, model.route_id, desktop) : []));continue; }
|
|
42
48
|
const window = values.context_window;
|
|
43
49
|
if (!window) { safeContext = false;limitations.push({ model: model.id, code: "context_unknown" }); }
|
|
44
50
|
else if (window < 100000 || window > 1000000) { safeContext = false;limitations.push({ model: model.id, code: "context_range_limited", value: window }); }
|
|
@@ -46,21 +52,26 @@ export function claudeSharedCapabilityPlan({ app = [], code = [], support = {} }
|
|
|
46
52
|
if (budgets[id] && budgets[id] < 100000) { safeContext = false;delete budgets[id];limitations.push({ model: model.id, code: "context_range_limited" }); }
|
|
47
53
|
output = Math.max(output, values.max_output_tokens || 0);
|
|
48
54
|
const efforts = values.reasoning === false ? [] : values.reasoning_efforts || [];
|
|
49
|
-
|
|
50
|
-
const
|
|
55
|
+
const hint = desktop ? claudeNativeModelHint(values, support.app_contract) : null;
|
|
56
|
+
const limited=desktop&&/^mythos-ccdx-\d+$/.test(id)?claudeEffortPrefix(values).length!==efforts.length:!claudeEffortsExpressible(values);
|
|
57
|
+
if (efforts.length && !hint && limited) limitations.push({ model: model.id, code: "reasoning_levels_limited" });
|
|
58
|
+
const visibleEfforts = hint ? efforts : desktop && /^mythos-ccdx-\d+$/.test(id) ? claudeEffortPrefix(values) : claudeEffortsExpressible(values) ? efforts : [];
|
|
51
59
|
if (visibleEfforts.length) caps.push(`${id.toLowerCase()}=${["effort", ...(visibleEfforts.includes("xhigh") ? ["xhigh_effort"] : []), ...(visibleEfforts.includes("max") ? ["max_effort"] : [])].join(",")}`);
|
|
60
|
+
else if(efforts.length)preserveRefs.push(id,...(model.route_id?claudeRouteAliases(model,model.route_id,desktop):[]));
|
|
52
61
|
if (values.web_search && !values.web_search.includes("messages")) limitations.push({ model: model.id, code: "search_messages_unavailable" });
|
|
53
62
|
}
|
|
54
63
|
if (!safeContext) context = 0;
|
|
55
64
|
const capabilities = caps.join(";");
|
|
56
65
|
if (capabilities.length > 8000) limitations.push({ code: "capability_list_limited" });
|
|
57
66
|
return { state: consumers.length ? "planned" : "not_configured", context_tokens: context || null,
|
|
58
|
-
|
|
67
|
+
preserve_refs: preserveRefs,
|
|
68
|
+
preserve_fields: [...(!knownAdapters ? ["env.CLAUDE_CODE_MAX_CONTEXT_TOKENS", "env.CLAUDE_CODE_GATEWAY_HINT_HEADERS"] : []), ...(!knownAdapters || support.app_contract && !support.app_contract.fields.output ? ["env.CLAUDE_CODE_MAX_OUTPUT_TOKENS"] : [])],
|
|
69
|
+
output_tokens: output && knownAdapters && (!support.app_contract || support.app_contract.fields.output) && consumers.every(({ model }) => model.capability?.values.max_output_tokens) ? Math.min(output, 128000) : null, budgets: context ? budgets : {},
|
|
59
70
|
capabilities: capabilities.length <= 8000 ? capabilities : "", limitations };
|
|
60
71
|
}
|
|
61
72
|
|
|
62
73
|
export function syncClaudeCapabilities(plan, options = {}) {
|
|
63
|
-
if (plan.limitations?.some(item => item.code === "client_version_unknown")) return { state: "partially_preserved", changed: false, preserved: 0, restart_required: false };
|
|
74
|
+
if (plan.limitations?.some(item => item.code === "client_version_unknown") && !plan.capabilities) return { state: "partially_preserved", changed: false, preserved: 0, restart_required: false };
|
|
64
75
|
const paths = claudeClientPaths(options), env = options.env || process.env;
|
|
65
76
|
let current = {};try { current = JSON.parse(readBoundedFileSync(paths.code, { maxBytes: 1024 * 1024, encoding: "utf8" })); }
|
|
66
77
|
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
@@ -71,16 +82,22 @@ export function syncClaudeCapabilities(plan, options = {}) {
|
|
|
71
82
|
const journal = readM365Json(m365Paths(options).ownership, { version: 1, operations: [] });
|
|
72
83
|
const ownsCodeBase = journal.operations?.some(op => op.file === paths.code && op.keys?.join(".") === "env.ANTHROPIC_BASE_URL" && op.after === base);
|
|
73
84
|
const conflict = Boolean(env.ANTHROPIC_BASE_URL || base && (!/^http:\/\/127\.0\.0\.1:\d+\/anthropic$/.test(base) || !ownsCodeBase));
|
|
74
|
-
const ownedFields = ["env.CLAUDE_CODE_MAX_CONTEXT_TOKENS", "env.CLAUDE_CODE_MAX_OUTPUT_TOKENS", "env.CLAUDE_CODE_MODEL_CAPABILITIES"];
|
|
85
|
+
const ownedFields = ["env.CLAUDE_CODE_MAX_CONTEXT_TOKENS", "env.CLAUDE_CODE_MAX_OUTPUT_TOKENS", "env.CLAUDE_CODE_MODEL_CAPABILITIES", "env.CLAUDE_CODE_GATEWAY_HINT_HEADERS"];
|
|
75
86
|
if (!conflict) {
|
|
87
|
+
if (plan.state === "planned" && !plan.limitations?.some(item => item.code === "client_version_unknown")) add(["env", "CLAUDE_CODE_GATEWAY_HINT_HEADERS"], "1");
|
|
76
88
|
for (const [key, value] of [["CLAUDE_CODE_MAX_CONTEXT_TOKENS", plan.context_tokens], ["CLAUDE_CODE_MAX_OUTPUT_TOKENS", plan.output_tokens], ["CLAUDE_CODE_MODEL_CAPABILITIES", plan.capabilities]]) {
|
|
77
|
-
|
|
89
|
+
let selected=value;
|
|
90
|
+
if(key==="CLAUDE_CODE_MODEL_CAPABILITIES"&&selected){
|
|
91
|
+
const keep=new Set(plan.preserve_refs||[]),previous=String(current.env?.[key]||"").split(";").filter(item=>keep.has(item.split("=")[0]));
|
|
92
|
+
selected=[selected,...previous].join(";");
|
|
93
|
+
}
|
|
94
|
+
if (selected && env[key] === undefined) operations.push({file:paths.code,keys:["env",key],value:String(selected),...(key==="CLAUDE_CODE_MODEL_CAPABILITIES"?{mergeCapabilities:true}:{})});
|
|
78
95
|
}
|
|
79
96
|
for (const [id, value] of Object.entries(plan.budgets)) add(["modelSettings", id, "autoCompactWindow"], value);
|
|
80
97
|
}
|
|
81
98
|
const active = new Set(operations.map(op => op.keys.join(".")));
|
|
82
99
|
const result = reconcileClaudeConfiguration(operations, { ...options,
|
|
83
|
-
restoreSelect: op => op.file === paths.code && (ownedFields.includes(op.keys.join(".")) || op.keys[0] === "modelSettings" && op.keys[2] === "autoCompactWindow") && !active.has(op.keys.join(".")) });
|
|
100
|
+
restoreSelect: op => op.file === paths.code && !plan.preserve_fields?.includes(op.keys.join(".")) && !plan.preserve_refs?.includes(op.keys[1]) && (ownedFields.includes(op.keys.join(".")) || op.keys[0] === "modelSettings" && op.keys[2] === "autoCompactWindow") && !active.has(op.keys.join(".")) });
|
|
84
101
|
return { state: conflict || result.preserved ? "partially_preserved" : operations.length ? "configured" : "limited",
|
|
85
102
|
changed: result.changed, preserved: result.preserved,
|
|
86
103
|
restart_required: result.changed };
|
|
@@ -10,6 +10,7 @@ import { withFileLockSync } from "./lock.mjs";
|
|
|
10
10
|
import { m365Paths, readM365Json, writeM365Json } from "./m365-settings.mjs";
|
|
11
11
|
import { claudeClientModelId, claudeModelEntries } from "./claude-models.mjs";
|
|
12
12
|
import { claudeRouteAliases } from "./clients/claude-models.mjs";
|
|
13
|
+
import { claudeNativeModelHint } from "./claude-app-contract.mjs";
|
|
13
14
|
|
|
14
15
|
export const M365_CLAUDE_PROFILE_ID = "00000000-0000-4000-8000-000000202700";
|
|
15
16
|
const M365_CLAUDE_PROFILE_NAME = "CCDX Microsoft 365";
|
|
@@ -115,16 +116,52 @@ function appModelsOwned(current, previous, desired, alreadyDesired) {
|
|
|
115
116
|
withoutAppPreference(recorded.filter(model => wanted.has(model.name))));
|
|
116
117
|
}
|
|
117
118
|
|
|
119
|
+
function capabilityMap(value){
|
|
120
|
+
if(typeof value!=="string")return null;const result=new Map();
|
|
121
|
+
for(const entry of value.split(";").filter(Boolean)){
|
|
122
|
+
const [id,flags,...extra]=entry.split("=");
|
|
123
|
+
if(extra.length||!/^[\w][\w./:@+\[\]-]{0,200}$/.test(id)||!flags||flags.split(",").some(flag=>!["effort","xhigh_effort","max_effort"].includes(flag))||result.has(id))return null;
|
|
124
|
+
result.set(id,flags);
|
|
125
|
+
}
|
|
126
|
+
return result;
|
|
127
|
+
}
|
|
128
|
+
const capabilityText = map => [...map].map(([id, flags]) => id + "=" + flags).join(";");
|
|
129
|
+
function mergeCapabilityMap(current, recorded, wanted, original) {
|
|
130
|
+
const actual = capabilityMap(current ?? ""), previous = capabilityMap(recorded), next = capabilityMap(wanted), before = capabilityMap(original?.value ?? "");
|
|
131
|
+
if (!actual || !previous || !next || !before) return null;
|
|
132
|
+
const result = new Map(actual), restoration = new Map(before);let preserved = false;
|
|
133
|
+
for (const id of new Set([...previous.keys(), ...actual.keys()])) if (actual.get(id) !== previous.get(id)) {
|
|
134
|
+
if (actual.has(id)) restoration.set(id, actual.get(id));else restoration.delete(id);
|
|
135
|
+
}
|
|
136
|
+
for (const [id, flags] of previous) if (actual.get(id) === flags && flags !== before.get(id) && !next.has(id)) result.delete(id);
|
|
137
|
+
for (const [id, flags] of next) {
|
|
138
|
+
if (actual.has(id) && actual.get(id) !== flags && (actual.get(id) !== previous.get(id) || actual.get(id) === before.get(id))) { preserved = true;continue; }
|
|
139
|
+
result.set(id, flags);
|
|
140
|
+
}
|
|
141
|
+
return { value: capabilityText(result), before: restoration.size || original?.exists ? { exists: true, value: capabilityText(restoration) } : { exists: false }, preserved };
|
|
142
|
+
}
|
|
143
|
+
function restoreCapabilityMap(current, operation) {
|
|
144
|
+
const actual = capabilityMap(current.value ?? ""), after = capabilityMap(operation.after), before = capabilityMap(operation.before?.value ?? "");
|
|
145
|
+
if (!actual || !after || !before) return null;
|
|
146
|
+
const result = new Map(actual);let preserved = false;
|
|
147
|
+
for (const [id, flags] of after) {
|
|
148
|
+
if (flags === before.get(id)) continue;
|
|
149
|
+
if (actual.get(id) !== flags) { preserved = true;continue; }
|
|
150
|
+
if (before.has(id)) result.set(id, before.get(id));else result.delete(id);
|
|
151
|
+
}
|
|
152
|
+
return { desired: result.size || operation.before?.exists ? { exists: true, value: capabilityText(result) } : { exists: false }, preserved };
|
|
153
|
+
}
|
|
154
|
+
|
|
118
155
|
export function reconcileClaudeConfiguration(operations, { restore = false, restoreFields = [], restoreSelect, ...options } = {}) {
|
|
119
156
|
const paths = claudeClientPaths(options), allowed = new Set(Object.values(paths)), journalPath = m365Paths(options).ownership;
|
|
120
157
|
fs.mkdirSync(path.dirname(journalPath), { recursive: true, mode: 0o700 });
|
|
121
158
|
return withFileLockSync(`${journalPath}.lock`, () => {
|
|
122
159
|
const journal = readM365Json(journalPath, { version: 1, operations: [] });
|
|
123
160
|
const keys = new Map([
|
|
124
|
-
[paths.code, new Set(["env.ANTHROPIC_BASE_URL", "env.ANTHROPIC_AUTH_TOKEN", "env.CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY", "env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS", "env.ANTHROPIC_CUSTOM_HEADERS", "env.ANTHROPIC_MODEL", "env.CLAUDE_CODE_MAX_CONTEXT_TOKENS", "env.CLAUDE_CODE_MAX_OUTPUT_TOKENS", "env.CLAUDE_CODE_MODEL_CAPABILITIES"])],
|
|
161
|
+
[paths.code, new Set(["env.ANTHROPIC_BASE_URL", "env.ANTHROPIC_AUTH_TOKEN", "env.CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY", "env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS", "env.ANTHROPIC_CUSTOM_HEADERS", "env.ANTHROPIC_MODEL", "env.CLAUDE_CODE_MAX_CONTEXT_TOKENS", "env.CLAUDE_CODE_MAX_OUTPUT_TOKENS", "env.CLAUDE_CODE_MODEL_CAPABILITIES", "env.CLAUDE_CODE_GATEWAY_HINT_HEADERS"])],
|
|
125
162
|
[paths.normal, new Set(["deploymentMode"])], [paths.threep, new Set(["deploymentMode"])],
|
|
126
163
|
[paths.meta, new Set(["entries", "appliedId"])],
|
|
127
|
-
[paths.profile, new Set(["inferenceProvider", "inferenceGatewayBaseUrl", "inferenceGatewayApiKey", "inferenceGatewayAuthScheme", "inferenceModels", "inferenceCustomHeaders"])],
|
|
164
|
+
[paths.profile, new Set(["inferenceProvider", "inferenceGatewayBaseUrl", "inferenceGatewayApiKey", "inferenceGatewayAuthScheme", "inferenceModels", "inferenceCustomHeaders", "modelDiscoveryEnabled"])],
|
|
128
165
|
]);
|
|
129
166
|
const safeKeys = op => Array.isArray(op.keys) && !op.keys.some(key => ["__proto__", "constructor", "prototype"].includes(key))
|
|
130
167
|
&& (keys.get(op.file)?.has(op.keys.join(".")) || op.file === paths.code && op.keys.length === 3 && op.keys[0] === "modelSettings"
|
|
@@ -135,7 +172,7 @@ export function reconcileClaudeConfiguration(operations, { restore = false, rest
|
|
|
135
172
|
throw new Error("Claude configuration ownership is invalid; files were preserved");
|
|
136
173
|
}
|
|
137
174
|
const states = new Map(), pending = [], nextJournal = structuredClone(journal), skipped = [];
|
|
138
|
-
const sharedOperation = op => op.file === paths.code && (op.keys[0] === "modelSettings" || ["CLAUDE_CODE_MAX_CONTEXT_TOKENS", "CLAUDE_CODE_MAX_OUTPUT_TOKENS", "CLAUDE_CODE_MODEL_CAPABILITIES"].includes(op.keys[1]));
|
|
175
|
+
const sharedOperation = op => op.file === paths.code && (op.keys[0] === "modelSettings" || ["CLAUDE_CODE_MAX_CONTEXT_TOKENS", "CLAUDE_CODE_MAX_OUTPUT_TOKENS", "CLAUDE_CODE_MODEL_CAPABILITIES", "CLAUDE_CODE_GATEWAY_HINT_HEADERS"].includes(op.keys[1]));
|
|
139
176
|
const forClient = op => (!options.selectOperation || options.selectOperation(op)) && (!options.client || (options.client === "claude_code" ? op.file === paths.code && !sharedOperation(op) : op.file !== paths.code))
|
|
140
177
|
&& (!options.fields || options.fields.includes(op.keys.join(".")));
|
|
141
178
|
const list = restore ? journal.operations.filter(forClient) : [
|
|
@@ -146,19 +183,27 @@ export function reconcileClaudeConfiguration(operations, { restore = false, rest
|
|
|
146
183
|
const state = states.get(operation.file);state.next ||= structuredClone(state.value);
|
|
147
184
|
const previous = journal.operations.find(op => op.file === operation.file && isDeepStrictEqual(op.keys, operation.keys) && op.itemId === operation.itemId);
|
|
148
185
|
const restoring = restore || operation.restore === true;
|
|
149
|
-
const current = operationValue(state.next, operation)
|
|
186
|
+
const current = operationValue(state.next, operation);let desired = restoring ? operation.before : { exists: true, value: operation.value };
|
|
187
|
+
const capabilityField = operation.file === paths.code && operation.keys.join(".") === "env.CLAUDE_CODE_MODEL_CAPABILITIES";
|
|
150
188
|
if (restoring) {
|
|
151
|
-
|
|
189
|
+
const capabilityRestore = capabilityField ? restoreCapabilityMap(current, operation) : null;
|
|
190
|
+
if (capabilityRestore) { desired = capabilityRestore.desired;if (capabilityRestore.preserved) skipped.push(operation.file); }
|
|
191
|
+
else if (!isDeepStrictEqual(current, { exists: true, value: operation.after })) { skipped.push(operation.file);continue; }
|
|
152
192
|
setOperation(state.next, operation, desired);
|
|
153
193
|
nextJournal.operations = nextJournal.operations.filter(op => !(op.file === operation.file && isDeepStrictEqual(op.keys, operation.keys) && op.itemId === operation.itemId));
|
|
154
194
|
} else {
|
|
195
|
+
const capabilityMerge = operation.mergeCapabilities && previous && capabilityField
|
|
196
|
+
? mergeCapabilityMap(current.value, previous.after, desired.value, previous.before) : null;
|
|
197
|
+
if(capabilityMerge){desired.value=capabilityMerge.value;operation.value=capabilityMerge.value;if(capabilityMerge.preserved)skipped.push(operation.file)}
|
|
155
198
|
const modelField = operation.file === paths.profile && operation.keys.join(".") === "inferenceModels";
|
|
156
199
|
const currentModels = modelField && parsedAppModels(current.value), desiredModels = modelField && parsedAppModels(desired.value);
|
|
157
200
|
const alreadyDesired = isDeepStrictEqual(current, desired)
|
|
158
201
|
|| Boolean(currentModels && desiredModels && isDeepStrictEqual(currentModels, desiredModels));
|
|
159
|
-
const owned = previous && (isDeepStrictEqual(current, { exists: true, value: previous.after })
|
|
202
|
+
const owned = previous && (Boolean(capabilityMerge)||isDeepStrictEqual(current, { exists: true, value: previous.after })
|
|
160
203
|
|| modelField && current.exists && appModelsOwned(current.value, previous.after, desired.value, alreadyDesired));
|
|
161
204
|
if (alreadyDesired) {
|
|
205
|
+
if (capabilityMerge) nextJournal.operations = nextJournal.operations.map(op => op.file === operation.file && isDeepStrictEqual(op.keys, operation.keys)
|
|
206
|
+
? { ...op, before: capabilityMerge.before, after: current.value } : op);
|
|
162
207
|
if (modelField && owned && previous.after !== current.value) {
|
|
163
208
|
nextJournal.operations = nextJournal.operations.map(op => op.file === operation.file
|
|
164
209
|
&& isDeepStrictEqual(op.keys, operation.keys) && op.itemId === operation.itemId ? { ...op, after: current.value } : op);
|
|
@@ -169,7 +214,7 @@ export function reconcileClaudeConfiguration(operations, { restore = false, rest
|
|
|
169
214
|
&& current.value === "1p";
|
|
170
215
|
if (current.exists && !replaceMode && !owned) { skipped.push(operation.file);continue; }
|
|
171
216
|
const entry = { file: operation.file, keys: operation.keys, ...(operation.itemId ? { itemId: operation.itemId } : {}),
|
|
172
|
-
before: previous?.before || current, after: operation.value };
|
|
217
|
+
before: capabilityMerge?.before || previous?.before || current, after: operation.value };
|
|
173
218
|
setOperation(state.next, operation, desired);
|
|
174
219
|
nextJournal.operations = nextJournal.operations.filter(op => !(op.file === operation.file && isDeepStrictEqual(op.keys, operation.keys) && op.itemId === operation.itemId));
|
|
175
220
|
nextJournal.operations.push(entry);
|
|
@@ -200,7 +245,7 @@ export function reconcileClaudeConfiguration(operations, { restore = false, rest
|
|
|
200
245
|
});
|
|
201
246
|
}
|
|
202
247
|
|
|
203
|
-
export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstalled, desktopManaged, desktopAliases = false, profileName = M365_CLAUDE_PROFILE_NAME, disableExperimentalBetas = true, defaultModel, ...options } = {}) {
|
|
248
|
+
export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstalled, desktopManaged, desktopAliases = false, appContract, profileName = M365_CLAUDE_PROFILE_NAME, disableExperimentalBetas = true, defaultModel, ...options } = {}) {
|
|
204
249
|
const entries = claudeModelEntries(models);
|
|
205
250
|
const paths = claudeClientPaths(options), ids = entries.map(model => model.name), operations = [], result = {};
|
|
206
251
|
const endpoint = new URL(baseUrl);
|
|
@@ -270,7 +315,10 @@ export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstall
|
|
|
270
315
|
const previousNames = models.map(model => model.route_id ? claudeRouteAliases(model, model.route_id, true).slice(2) : []);
|
|
271
316
|
const desktopEntries = (desktopAliases ? claudeModelEntries(models, { desktopAliases }) : entries).map((entry, index) => {
|
|
272
317
|
const previous = previousByName.get(entry.name) || previousNames[index].map(name => previousByName.get(name)).find(Boolean);
|
|
273
|
-
|
|
318
|
+
const hint = claudeNativeModelHint(models[index].capability?.values, appContract);
|
|
319
|
+
const controls = hint || (appContract && appContract.status !== "verified" && previous?.behavesAs && models[index].capability?.values.reasoning !== false
|
|
320
|
+
? { behavesAs: previous.behavesAs, ...(entry.maxEffort === undefined && previous.maxEffort ? { maxEffort: previous.maxEffort } : {}) } : {});
|
|
321
|
+
return { ...entry, ...controls, ...(entry.supports1m ? { prefer1m: typeof previous?.prefer1m === "boolean" ? previous.prefer1m : true } : {}) };
|
|
274
322
|
});
|
|
275
323
|
for (let index = 0; index < models.length; index++) {
|
|
276
324
|
const old = previousNames[index].map(name => order.get(name)).find(value => value !== undefined) ?? order.get(claudeClientModelId(models[index].id));
|
|
@@ -279,6 +327,7 @@ export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstall
|
|
|
279
327
|
const orderedEntries = [...desktopEntries].sort((left, right) => defaultModel && (left.name === defaultModel || right.name === defaultModel)
|
|
280
328
|
? left.name === defaultModel ? -1 : 1 : (order.get(left.name) ?? Infinity) - (order.get(right.name) ?? Infinity));
|
|
281
329
|
add(paths.profile, ["inferenceModels"], JSON.stringify(orderedEntries));
|
|
330
|
+
if(appContract?.fields.discovery)add(paths.profile,["modelDiscoveryEnabled"],true);
|
|
282
331
|
add(paths.profile, ["inferenceCustomHeaders"], JSON.stringify({ "X-CCDX-Client": "claude-app" }));
|
|
283
332
|
add(paths.meta, ["entries"], { id: M365_CLAUDE_PROFILE_ID, name: profileName }, M365_CLAUDE_PROFILE_ID);
|
|
284
333
|
add(paths.meta, ["appliedId"], M365_CLAUDE_PROFILE_ID);
|
package/src/claude-gateway.mjs
CHANGED
|
@@ -20,6 +20,9 @@ import { catalogCapabilities } from "./model-capabilities.mjs";
|
|
|
20
20
|
import { applyMessagesSystemPolicy } from "./messages-system-policy.mjs";
|
|
21
21
|
import { createApiTokenCounter } from "./providers/api-token-count.mjs";
|
|
22
22
|
import { MESSAGES_TOOL_GUARD } from "./messages-tool-schema.mjs";
|
|
23
|
+
import { isCompactionRequest, compactionScope } from "./context-compaction.mjs";
|
|
24
|
+
import { compactionSummarizer } from "./context-compaction-wire.mjs";
|
|
25
|
+
import { requestPurpose } from "./request-context.mjs";
|
|
23
26
|
|
|
24
27
|
function observeMessagesWindow(provider, model, capability, entry) {
|
|
25
28
|
try {
|
|
@@ -196,8 +199,8 @@ function createGuardedMessagesObserver(onEvent, maxBytes, clientModel, guard, re
|
|
|
196
199
|
return { write: chunk => run("write", chunk), finish: () => run("finish") };
|
|
197
200
|
}
|
|
198
201
|
|
|
199
|
-
export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases = false, messagesSystemMode = "passthrough", log = () => {}, onRequest = () => {}, env = process.env, performance: sharedPerformance, validateConversation,
|
|
200
|
-
resolveRequest, privacy, privacyClient = "claude", record = recordUsage, acquireRequest = createRequestAdmission({ maxBytes: 16 * 1024 * 1024, maxQueued: 8 }) } = {}) {
|
|
202
|
+
export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases = false, appContract, messagesSystemMode = "passthrough", log = () => {}, onRequest = () => {}, env = process.env, performance: sharedPerformance, validateConversation,
|
|
203
|
+
resolveRequest, privacy, compaction, privacyClient = "claude", record = recordUsage, acquireRequest = createRequestAdmission({ maxBytes: 16 * 1024 * 1024, maxQueued: 8 }) } = {}) {
|
|
201
204
|
if (!provider || !isProviderId(provider.id) || typeof apiKey !== "string" || apiKey.length < 32) throw new Error("Claude gateway requires a provider and private local key");
|
|
202
205
|
const config = loadRuntimeConfig(env), performance = sharedPerformance || createStreamPerformanceMetrics({ routeNames: ["messages"] });
|
|
203
206
|
const decodedLimit = decodedBodyLimitPreference({ env }).bytes;
|
|
@@ -212,7 +215,9 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
212
215
|
if (req.method === "GET" && pathname === "/v1/models") {
|
|
213
216
|
try {
|
|
214
217
|
const entries = provider.models("claude");
|
|
215
|
-
const models = claudeModelEntries(entries, { desktopAliases }).map((entry, index) => ({ id: entry.name, type: "model", ...(entry.supports1m ? { supports_1m: true } : {}),
|
|
218
|
+
const models = claudeModelEntries(entries, { desktopAliases, appContract }).map((entry, index) => ({ id: entry.name, type: "model", ...(entry.supports1m ? { supports_1m: true } : {}),
|
|
219
|
+
...(entry.behavesAs ? { behaves_as: entry.behavesAs, max_effort_level: entry.maxEffort } : {}),
|
|
220
|
+
display_name: entry.labelOverride || typeof entries[index].name === "string" && entries[index].name || entry.name }));
|
|
216
221
|
send(res, 200, { data: models, has_more: false, first_id: models[0]?.id || null, last_id: models.at(-1)?.id || null });
|
|
217
222
|
} catch (error) { send(res, 503, apiError(error.code || "ccdx_catalog_unavailable", "Claude model discovery is unavailable; refresh the provider catalog.")); }
|
|
218
223
|
return;
|
|
@@ -223,14 +228,17 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
223
228
|
const parent = currentRequestContext();
|
|
224
229
|
if (parent) parent.provider = provider.id;
|
|
225
230
|
const countTokens = pathname.endsWith("/count_tokens"), requestId = parent?.requestId || randomUUID();
|
|
226
|
-
const
|
|
231
|
+
const compacting = !countTokens && isCompactionRequest("messages", null, req.headers);
|
|
232
|
+
const purpose = requestPurpose(req.headers["x-ccdx-purpose"], compacting ? "compaction" : "conversation");
|
|
233
|
+
const tracker = countTokens ? parent?.streamPerformance : performance.begin("messages", { requestId, purpose, application: requestApplication(req.headers, "claude") });
|
|
227
234
|
if (!resolveRequest) tracker?.setProvider(provider.id);
|
|
228
235
|
const abort = createRequestAbort(req, res);
|
|
229
236
|
let release = () => {}, conversation, outcome = "failed", model = null, configuredModel = null, clientModel = null, responseId = null, usage = null, stopReason = null, streamed = false, sawStop = false, failedEvent = false;
|
|
230
237
|
let selectedModel, selectedCapability;
|
|
231
238
|
let terminalOrigin = "client_validation", failureStatus = null, countDeadline = null, rejectionReason;
|
|
232
239
|
if (!countTokens) { stats.total++;stats.active++;stats.last_request_at = new Date().toISOString(); }
|
|
233
|
-
const context = parent || { requestId };
|
|
240
|
+
const context = parent || { requestId, purpose: req.headers["x-ccdx-purpose"] };
|
|
241
|
+
if (!countTokens) context.purpose = purpose;
|
|
234
242
|
context.provider = selectedProvider.id;context.application = requestApplication(req.headers, "claude");
|
|
235
243
|
context.streamPerformance = tracker;context.route = countTokens ? "messages_count_tokens" : "messages";
|
|
236
244
|
await runWithRequestContext(context, async () => {
|
|
@@ -240,6 +248,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
240
248
|
let body = await readJsonBody(req, { admission: release, signal: abort.signal, maxBodyBytes: config.maxBodyBytes, maxDecodedBodyBytes: decodedLimit });
|
|
241
249
|
abort.setTimeout(config.upstreamTimeoutMs, "messages_prepare_timeout");
|
|
242
250
|
observeRequestedModel(body);
|
|
251
|
+
if (compacting) markRequestObservation({ compaction: 1 });
|
|
243
252
|
context.requestOptions = requestOptionsEvidence(body);
|
|
244
253
|
if (context.requestOptions.client_tool_errors_received) markRequestObservation({ client_tool_errors_received: context.requestOptions.client_tool_errors_received });
|
|
245
254
|
if (!body || typeof body.model !== "string" || !Array.isArray(body.messages)) {
|
|
@@ -265,14 +274,22 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
265
274
|
stats.last_model = model;
|
|
266
275
|
context.model = configuredModel || model;
|
|
267
276
|
if (!countTokens) {
|
|
268
|
-
markRequestObservation({ max_output_tokens_requested: body.max_tokens });
|
|
277
|
+
markRequestObservation({ max_output_tokens_requested: body.max_tokens, reasoning_effort_requested: body.output_config?.effort });
|
|
269
278
|
observeMessagesWindow(selectedProvider, configuredModel || model, selectedCapability, selectedModel);
|
|
270
279
|
}
|
|
271
280
|
tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });
|
|
272
281
|
conversation = await validateConversation?.(body, req.headers, selectedProvider, abort.signal);
|
|
273
282
|
if (!countTokens) observeContextSession(body, req.headers, selectedProvider, "messages");
|
|
274
283
|
terminalOrigin = "transport";
|
|
275
|
-
const
|
|
284
|
+
const sourceCall = compacting && compaction ? (value, options) => {
|
|
285
|
+
let limits = selectedCapability?.values;
|
|
286
|
+
if (!limits) try { const entry = selectedModel || resolveClaudeModel(selectedProvider.models("claude"), value.model);limits = entry?.protocol_capabilities?.messages?.values || entry?.capability?.values || catalogCapabilities(entry || {}); } catch { limits = {}; }
|
|
287
|
+
return compaction.run({ body: value, protocol: "messages", scope: compactionScope(selectedProvider, privacyClient, "messages"), source: selectedProvider.id,
|
|
288
|
+
client: privacyClient, inputLimit: limits.max_input_tokens || limits.context_window, outputAllowance: value.max_tokens || 0,
|
|
289
|
+
native: selectedProvider.client.messages, options, summarize: compactionSummarizer(value, "messages", selectedProvider.client.messages),
|
|
290
|
+
onActivity: () => abort.setTimeout(config.streamIdleTimeoutMs, "compaction_idle_timeout") });
|
|
291
|
+
} : selectedProvider.client.messages;
|
|
292
|
+
const call = privacy?.wrap(sourceCall, { res, protocol: "messages", client: privacyClient }) || sourceCall;
|
|
276
293
|
let upstreamHeadersObserved = false;
|
|
277
294
|
const callOptions = { headers: req.headers, countTokens, signal: abort.signal,
|
|
278
295
|
onUpstreamErrorHeaders(status) { upstreamHeadersObserved = true;tracker?.upstreamHeaders(status);body = null;release();release = () => {}; },
|
|
@@ -399,6 +416,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
399
416
|
context.onHttpError?.({ code: detail.code, origin: terminalOrigin, ...(rejectionReason ? { reason: rejectionReason } : {}), ...(diagnostic ? { transport: diagnostic } : {}) });
|
|
400
417
|
if (outcome === "cancelled") return;
|
|
401
418
|
if (!res.headersSent) {
|
|
419
|
+
if (typeof error.code === "string" && error.code.startsWith("ccdx_compaction_")) res.setHeader("x-should-retry", "false");
|
|
402
420
|
if (error.origin === "privacy" && Number.isInteger(error.retryAfter) && error.retryAfter > 0) res.setHeader("Retry-After", String(error.retryAfter));
|
|
403
421
|
const value = apiError(abort.reason || error.code || "ccdx_gateway_error", message);
|
|
404
422
|
if (rejectionReason) value.error.reason = rejectionReason;
|
package/src/claude-models.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import { modelReasoningEfforts } from "./provider-metadata.mjs";
|
|
|
2
2
|
import { createHash } from "node:crypto";
|
|
3
3
|
import { modelDisplayName } from "./model-display.mjs";
|
|
4
4
|
import { claudeEffortPrefix } from "./model-capabilities.mjs";
|
|
5
|
+
import { claudeNativeModelHint } from "./claude-app-contract.mjs";
|
|
5
6
|
|
|
6
7
|
const EFFORTS = ["low", "medium", "high", "xhigh", "max"];
|
|
7
8
|
|
|
@@ -19,7 +20,7 @@ function desktopModelId(id) {
|
|
|
19
20
|
return `ccdx/claude-compatible-${BigInt(`0x${digest}`).toString(10)}`;
|
|
20
21
|
}
|
|
21
22
|
|
|
22
|
-
export function claudeModelEntries(models, { desktopAliases = false } = {}) {
|
|
23
|
+
export function claudeModelEntries(models, { desktopAliases = false, appContract } = {}) {
|
|
23
24
|
const ids = new Set(), upstreamIds = new Set(models.map(model => model.id));
|
|
24
25
|
return models.map(model => {
|
|
25
26
|
const name = model.client_id || (desktopAliases ? desktopModelId(model.id) : claudeClientModelId(model.id));
|
|
@@ -28,7 +29,8 @@ export function claudeModelEntries(models, { desktopAliases = false } = {}) {
|
|
|
28
29
|
const advertised = model.capability?.values.reasoning === false ? [] : model.capability?.values.reasoning_efforts || modelReasoningEfforts(model);
|
|
29
30
|
const prefix = /^mythos-ccdx-\d+$/.test(name) ? claudeEffortPrefix(model.capability?.values) : [];
|
|
30
31
|
const maxEffort = prefix.at(-1) || EFFORTS.filter(value => advertised?.includes(value)).at(-1);
|
|
31
|
-
|
|
32
|
+
const hint = claudeNativeModelHint(model.capability?.values, appContract);
|
|
33
|
+
return { name, ...(hint || {}), ...(model.display_name || name !== claudeClientModelId(model.id) ? { labelOverride: modelDisplayName(model) } : {}),
|
|
32
34
|
...(model.capability?.values.context_window >= 1000000 ? { supports1m: true } : {}), ...(maxEffort ? { maxEffort } : {}) };
|
|
33
35
|
});
|
|
34
36
|
}
|
package/src/cli-command-spec.mjs
CHANGED
|
@@ -56,6 +56,9 @@ export const MANAGED_COMMANDS = [
|
|
|
56
56
|
)
|
|
57
57
|
),
|
|
58
58
|
command("source list", "List registered model sources", read),
|
|
59
|
+
command("source import", "Preview supplied CCDX, CC Switch or Magpie API metadata; apply one explicitly", {
|
|
60
|
+
...read, "--file": "value", "--select": "integer", "--apply": "flag", "--key-stdin": "flag", ...confirm,
|
|
61
|
+
}),
|
|
59
62
|
command("source add", "Save an API and read its model catalog", {
|
|
60
63
|
"--file": "value",
|
|
61
64
|
"--key-stdin": "flag",
|
|
@@ -176,15 +179,21 @@ export const MANAGED_COMMANDS = [
|
|
|
176
179
|
"--failed": "flag",
|
|
177
180
|
"--app": "value",
|
|
178
181
|
"--source": "value",
|
|
182
|
+
"--purpose": "purpose",
|
|
179
183
|
"--limit": "integer",
|
|
180
184
|
}),
|
|
181
185
|
command("requests show <request>", "Show a retained request and its original diagnostic fields", read),
|
|
186
|
+
command("requests diagnose", "Capture one redacted upstream Messages error; expires after ten minutes", { ...read, ...confirm, "--source": "value", "--model": "value", "--cancel": "flag" }),
|
|
187
|
+
command("compact status", "Show native and gateway compression observations without model calls", read),
|
|
188
|
+
command("compact enable", "Enable bounded recovery using the current source and model; uses quota", { ...read, ...confirm }),
|
|
189
|
+
command("compact disable", "Disable gateway compression fallback while keeping native compression", { ...read, ...confirm }),
|
|
182
190
|
command("status", "Show service state; expand diagnostics explicitly", { ...read, "--details": "flag" }),
|
|
183
191
|
command("usage", "Show all recorded usage or this service run", {
|
|
184
192
|
...read,
|
|
185
193
|
"--scope": "scope",
|
|
186
194
|
"--provider": "value",
|
|
187
195
|
"--model": "value",
|
|
196
|
+
"--purpose": "purpose",
|
|
188
197
|
"--days": "value",
|
|
189
198
|
"--from": "value",
|
|
190
199
|
"--to": "value",
|
|
@@ -226,6 +235,7 @@ function optionsFor(args, definition) {
|
|
|
226
235
|
if (type === "format" && !["table", "plain", "json"].includes(value))
|
|
227
236
|
throw new Error("Format must be table, plain or json");
|
|
228
237
|
if (type === "scope" && !["run", "all"].includes(value)) throw new Error("Scope must be run or all");
|
|
238
|
+
if (type === "purpose" && !["conversation", "compaction", "diagnostic", "compatibility", "unknown"].includes(value)) throw new Error("Purpose must be conversation, compaction, diagnostic, compatibility or unknown");
|
|
229
239
|
if (type === "integer" && (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 100))
|
|
230
240
|
throw new Error("Limit must be an integer from 1 to 100");
|
|
231
241
|
values[key] = type === "integer" ? Number(value) : value;
|
|
@@ -276,7 +286,7 @@ export function parseManagedCommand(args) {
|
|
|
276
286
|
|
|
277
287
|
const extras = {
|
|
278
288
|
source:
|
|
279
|
-
"Status reads local/cached evidence. check/--refresh may contact the source; no inference.\nSource access grants do not select client models. Disable previews affected clients.\nGitHub login and company-account selection are source-specific.\nChoose visible models and defaults with app <app> models --edit.",
|
|
289
|
+
"Status reads local/cached evidence. check/--refresh may contact the source; no inference.\nsource import --file FILE previews supplied metadata. --select N --apply saves one source using private key input; no client access is granted.\nSource access grants do not select client models. Disable previews affected clients.\nGitHub login and company-account selection are source-specific.\nChoose visible models and defaults with app <app> models --edit.",
|
|
280
290
|
app: "Configured is not App adoption or process liveness. Unknown stays unknown.\nmodels shows the selected plan; source <id> models shows the upstream catalog.\nsetup/remove changes integration setup; pause/resume retains credentials.\nsync --preview shows the model/configuration plan, not a byte-level file diff.\nNo client program is force-restarted.",
|
|
281
291
|
config:
|
|
282
292
|
"Only service and terminal preferences are in scope. Browser appearance stays in WebUI.\nReset keeps accounts, keys, model plans and chats and stores a pre-reset backup.\nSaved and effective values can differ; restart requirements remain explicit.",
|
|
@@ -285,7 +295,7 @@ const extras = {
|
|
|
285
295
|
status:
|
|
286
296
|
"Default interactive status is brief; --details retains the complete diagnostic view.\nThe installed package version can differ from the running service.\nA listening gateway does not prove upstream model access.",
|
|
287
297
|
usage:
|
|
288
|
-
"Default usage includes all recorded usage. Filter it with --provider, --model and --days 1..365|all, or --from/--to YYYY-MM-DD.\nDates use --time-zone (UTC by default). Source-qualified models use 'source / model'.\n--scope run reads the running service and supports only --provider.\nGemini usage includes Antigravity Copilot and native Google responses. Missing upstream counts stay unknown; historical missing usage is not reconstructed.\nUsage records are not billed request counts. Cache hit is a token-reuse estimate.",
|
|
298
|
+
"Default usage includes all recorded usage. Filter it with --provider, --model, --purpose and --days 1..365|all, or --from/--to YYYY-MM-DD.\nPurpose: conversation, compaction, diagnostic, compatibility or unknown. Older records without a purpose remain unknown; every purpose stays in default totals.\nDates use --time-zone (UTC by default). Source-qualified models use 'source / model'.\n--scope run reads the running service and supports only --provider.\nGemini usage includes Antigravity Copilot and native Google responses. Missing upstream counts stay unknown; historical missing usage is not reconstructed.\nUsage records are not billed request counts. Cache hit is a token-reuse estimate.",
|
|
289
299
|
doctor:
|
|
290
300
|
"Default checks are read-only. Explicit online/compatibility checks and owned repairs have separate options.",
|
|
291
301
|
update:
|
|
@@ -325,5 +335,5 @@ export function managedCommandHelp(parts) {
|
|
|
325
335
|
);
|
|
326
336
|
}
|
|
327
337
|
export function rootCommandHelp() {
|
|
328
|
-
return `Usage:\n ccdx [start] [--show-request-id] [--no-browser] [--verbose]\n\nCommon:\n status Show service state; --details expands diagnostics\n web Open local management tools\n requests Show retained model requests and failures\n usage Show recorded token usage\n doctor Check local setup; deeper checks are explicit\n\nManage:\n source Accounts, APIs, catalogs and client authorization\n app Client model plans, sync and app-specific features\n config Service and terminal preferences\n\nUpdate:\n update check Check without installing\n update github|npm Install; restart the service normally afterward\n version Show installed package version\n\nHelp:\n ccdx <command> --help\n ccdx help app codex prediction\n\nStart keeps the existing configured-client setup and launch behavior.\nCLI output stays in English. Read-only commands do not start a service.`;
|
|
338
|
+
return `Usage:\n ccdx [start] [--show-request-id] [--no-browser] [--verbose]\n\nCommon:\n status Show service state; --details expands diagnostics\n web Open local management tools\n requests Show retained model requests and failures\n usage Show recorded token usage\n compact Inspect and control context compression\n doctor Check local setup; deeper checks are explicit\n\nManage:\n source Accounts, APIs, catalogs and client authorization\n app Client model plans, sync and app-specific features\n config Service and terminal preferences\n\nUpdate:\n update check Check without installing\n update github|npm Install; restart the service normally afterward\n version Show installed package version\n\nHelp:\n ccdx <command> --help\n ccdx help app codex prediction\n\nStart keeps the existing configured-client setup and launch behavior.\nCLI output stays in English. Read-only commands do not start a service.`;
|
|
329
339
|
}
|