codex-copilot-dx 1.2.28 → 1.2.30

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.
@@ -1,5 +1,27 @@
1
1
  (() => {
2
2
  const translations = {
3
+ "tools_copy_code": ["Copy code", "复制验证码"],
4
+ "tools_copy_open_github": ["Copy & open GitHub", "复制并打开验证页"],
5
+ "tools_code_copied": ["Copied. Ready to paste.", "已复制,可直接粘贴。"],
6
+ "tools_code_copy_needed": ["Click copy before pasting.", "点击复制图标后再粘贴。"],
7
+ "tools_code_copy_failed": ["Select the code and copy it manually.", "请选择验证码,手动复制。"],
8
+ "source_allowed_apps": ["Allowed apps", "允许使用的应用"],
9
+ "source_apps_hint": ["Choose models on the app page after granting access.", "授权后,在应用页选择模型。"],
10
+ "source_apps_none": ["Signed in. No app has access.", "仅保留登录,暂无应用使用。"],
11
+ "source_apps_pause": ["Saving stops {apps} from using this source.", "保存后,{apps} 将停止使用此来源。"],
12
+ "source_apps_reopen": ["Saved. Reopen {apps} to apply access.", "已保存,重新打开 {apps} 后生效。"],
13
+ "source_apps_review": ["Saved. Review {apps} sync results on the app page.", "已保存,请在应用页复核 {apps} 同步结果。"],
14
+ "catalog_read_network": ["Online read", "在线读取"],
15
+ "catalog_read_cache": ["Local cache", "本地缓存"],
16
+ "catalog_read_summary": ["{origin} · {total} models · GPT {gpt} / Claude {claude} · {time}", "{origin} · {total} 个模型 · GPT {gpt} / Claude {claude} · {time}"],
17
+ "catalog_local_cache": ["CCDX model cache", "本机模型缓存"],
18
+ "catalog_cache_used": ["Used", "已使用"],
19
+ "catalog_cache_unused": ["Not used", "未使用"],
20
+ "catalog_http_cache": ["HTTP cache", "HTTP 缓存"],
21
+ "catalog_revalidation_requested": ["Revalidation requested", "已请求重新校验"],
22
+ "catalog_filtered": ["Excluded locally", "本地过滤数"],
23
+ "catalog_response_age": ["Last response age (seconds)", "上次响应缓存年龄(秒)"],
24
+ "catalog_correlation": ["Client correlation ID", "客户端关联 ID"],
3
25
  "preferences_heading": ["SAVE & RESTORE", "保存与恢复"],
4
26
  "preferences_auto": ["Save changes automatically", "自动保存设置"],
5
27
  "preferences_auto_hint": ["Valid changes on this page save automatically.", "本页改动有效后自动保存。"],
@@ -3,6 +3,42 @@
3
3
  const label = (node, key, values) => language.set(node, key, values);
4
4
  const text = (id, key, values) => label(el(id), key, values);
5
5
  let account = null, pending = false, pollTimer = null, stopped = false, repairPreview = null;
6
+ let codeCopy = null, copyGeneration = 0, accountGeneration = 0, copyState = "tools_code_copy_needed";
7
+ const userCode = () => account?.operation?.state === "authorizing" && /^[A-Z0-9]{4}-[A-Z0-9]{4}$/i.test(account.operation.user_code || "") ? account.operation.user_code : null;
8
+ function showCopyState() {
9
+ el("github-copy-code").disabled = pending || !userCode();
10
+ const node = el("github-copy-state");
11
+ if (userCode()) { if (node.dataset.i18n !== copyState || node.textContent !== language.format(copyState)) text("github-copy-state", copyState); }
12
+ else { node.removeAttribute("data-i18n");node.textContent = ""; }
13
+ }
14
+ function finishCodeCopy() { copyGeneration++;codeCopy?.reject(Error("Sign-in ended"));codeCopy = null;copyState = "tools_code_copy_needed"; }
15
+ function copied(promise, generation, code, automatic = false) {
16
+ return Promise.resolve(promise).then(() => {
17
+ if (generation === copyGeneration && code === userCode()) { copyState = "tools_code_copied";showCopyState(); }return true;
18
+ }, () => {
19
+ if (generation === copyGeneration) { copyState = automatic ? "tools_code_copy_needed" : "tools_code_copy_failed";showCopyState(); }return false;
20
+ });
21
+ }
22
+ function copyCode(automatic = false) {
23
+ const code = userCode(), generation = copyGeneration;if (!code) return Promise.resolve(false);
24
+ try { return copied(navigator.clipboard.writeText(code), generation, code, automatic); }
25
+ catch { copyState = automatic ? "tools_code_copy_needed" : "tools_code_copy_failed";showCopyState();return Promise.resolve(false); }
26
+ }
27
+ function prepareCodeCopy() {
28
+ finishCodeCopy();const generation = copyGeneration;
29
+ let resolve, reject;const value = new Promise((yes, no) => { resolve = yes;reject = no; });value.catch(() => {});
30
+ codeCopy = { resolve, reject, prepared: false, code: null };
31
+ // Start the clipboard operation inside the original click. The code can
32
+ // arrive later through polling without losing Safari's user activation.
33
+ if (navigator.clipboard?.write && typeof ClipboardItem === "function") try {
34
+ const payload = value.then(code => new Blob([code], { type: "text/plain" }));payload.catch(() => {});
35
+ const item = new ClipboardItem({ "text/plain": payload });
36
+ const write = navigator.clipboard.write([item]);codeCopy.prepared = true;
37
+ void Promise.resolve(write).then(() => { if (generation === copyGeneration && codeCopy?.code && codeCopy.code === userCode()) { copyState = "tools_code_copied";showCopyState(); } }, () => {
38
+ if (generation === copyGeneration) { copyState = "tools_code_copy_needed";showCopyState(); }
39
+ });
40
+ } catch { /* The explicit copy button remains available. */ }
41
+ }
6
42
  const activeFlow = () => ["starting", "authorizing", "verifying"].includes(account?.operation?.state);
7
43
  async function api(path, body) {
8
44
  const response = await fetch(`/_ccdx/ui/${path}`, { method: body ? "POST" : "GET", cache: "no-store",
@@ -54,6 +90,8 @@
54
90
  el("github-user-code").textContent = op?.user_code || "—";
55
91
  el("github-authorize").hidden = op?.state !== "authorizing";
56
92
  el("github-authorize").href = op?.verification_uri === "https://github.com/login/device" ? op.verification_uri : "https://github.com/login/device";
93
+ if (userCode() && codeCopy && !codeCopy.code) { codeCopy.code = userCode();codeCopy.resolve(codeCopy.code);if (!codeCopy.prepared) void copyCode(true); }
94
+ if (!activeFlow() && codeCopy) finishCodeCopy();showCopyState();
57
95
  el("github-cancel").disabled = pending;
58
96
  el("github-check-code").textContent = online?.reason || "—";
59
97
  el("github-check-http").textContent = online?.http_status || "—";
@@ -67,10 +105,10 @@
67
105
  }
68
106
  function schedulePoll() {
69
107
  clearTimeout(pollTimer);pollTimer = null;
70
- if (stopped || !activeFlow() || document.visibilityState !== "visible") return;
108
+ if (stopped || pending || !activeFlow() || document.visibilityState !== "visible") return;
71
109
  pollTimer = setTimeout(async () => {
72
110
  try {
73
- const before = account.operation.state, data = await api("account");renderAccount(data);
111
+ const generation = accountGeneration, before = account.operation.state, data = await api("account");if (generation !== accountGeneration || pending) return;renderAccount(data);
74
112
  if (before !== data.operation?.state && data.operation?.state === "complete") {
75
113
  dashboardRefresh.invalidate("auth");dashboardRefresh.invalidate("models", { clear: true });
76
114
  void dashboardRefresh.refreshVisible({ force: true });
@@ -80,18 +118,24 @@
80
118
  }
81
119
  async function accountAction(action) {
82
120
  if (pending) return;
121
+ accountGeneration++;clearTimeout(pollTimer);
83
122
  pending = true;if (account) renderAccount(account);text("github-account-note", "checking");
123
+ if (action.action === "start") prepareCodeCopy();
124
+ else if (action.action === "cancel" || action.action === "logout") finishCodeCopy();
84
125
  let failureCode = null;
85
126
  try { renderAccount(await api("account", action)); }
86
- catch (error) { failureCode = error.code; }
127
+ catch (error) { failureCode = error.code;if (action.action === "start") finishCodeCopy(); }
87
128
  finally { pending = false;if (account) renderAccount(account);if (failureCode) text("github-account-note", failureCode); }
88
129
  }
89
130
  el("github-signin").addEventListener("click", () => void accountAction({ action: "start", reauth: account?.saved === true }));
90
131
  el("github-force-reauth").addEventListener("click", () => void accountAction({ action: "start", reauth: true }));
91
132
  el("github-check").addEventListener("click", () => void accountAction({ action: "check" }));
92
133
  el("github-cancel").addEventListener("click", () => { if (account?.operation) void accountAction({ action: "cancel", id: account.operation.id }); });
134
+ el("github-copy-code").addEventListener("click", () => void copyCode());
135
+ el("github-authorize").addEventListener("click", event => { if (pending || !userCode()) { event.preventDefault();return; }void copyCode(); });
136
+ window.addEventListener("pagehide", finishCodeCopy);
93
137
  el("github-logout").addEventListener("click", () => { if (window.confirm(language.format("tools_logout_confirm"))) void accountAction({ action: "logout", confirmed: true }); });
94
- async function loadAccount() { try { renderAccount(await api("account")); } catch { text("github-account-note", "tools_read_failed"); } }
138
+ async function loadAccount() { const generation = accountGeneration;try { const data = await api("account");if (generation === accountGeneration && !pending) renderAccount(data); } catch { if (generation === accountGeneration) text("github-account-note", "tools_read_failed"); } }
95
139
  function renderChecks(data) {
96
140
  const body = el("checks-body");body.replaceChildren();
97
141
  const groups = new Map();
@@ -19,6 +19,14 @@ button:hover, .button-link:hover { background: var(--button-hover); }
19
19
  button:focus-visible, .button-link:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
20
20
  .button-link { display:inline-flex;align-items:center;justify-content:center;text-decoration:none; }
21
21
  .account-entry { text-transform:none; }
22
+ .device-code-row { display:flex;align-items:center;gap:10px; }
23
+ .device-code-row .device-code { margin:10px 0; }
24
+ #github-copy-state:empty { display:none; }
25
+ #m365-app-access { margin-top:22px; }
26
+ #m365-app-access fieldset { border:0;padding:0;margin:0; }
27
+ #m365-app-access legend { margin-bottom:10px;padding:0; }
28
+ #m365-access-warning { color:var(--incomplete); }
29
+ #m365-access-state { margin:0; }
22
30
  button:disabled { opacity: .55; cursor: default; }
23
31
  button[aria-busy="true"] { cursor: progress; }
24
32
  .icon-button { display: inline-flex; flex:none; align-items: center; justify-content: center; width: 32px; height: 32px; padding: 6px; border: 0; background: transparent; }
@@ -178,8 +178,22 @@ async function readModelCatalog(provider) {
178
178
  }
179
179
  async function loadModels() { return refreshCatalog({ force: true }); }
180
180
 
181
+ function catalogReadDetails(data) {
182
+ const read = data?.catalog_read;if (!read) return;
183
+ text("models-note", "catalog_read_summary", { origin: phrase(read.source === "network" ? "catalog_read_network" : "catalog_read_cache"),
184
+ total: number(read.total), claude: number(read.claude), gpt: number(read.gpt), time: time(read.checked_at) });
185
+ const fields = element("model-check-fields");fields.replaceChildren();element("model-check-details").hidden = false;
186
+ for (const [key, value] of [["source", data.upstream_host], ["source_check_time", time(read.checked_at)], ["http_status", read.http_status],
187
+ ["catalog_local_cache", phrase(read.local_cache_used ? "catalog_cache_used" : "catalog_cache_unused")],
188
+ ["catalog_http_cache", read.http_revalidation_requested ? phrase("catalog_revalidation_requested") : null], ["catalog_filtered", read.filtered],
189
+ ["catalog_response_age", read.response_age_seconds], ["upstream_request_id", read.request_id], ["catalog_correlation", read.client_correlation_id]]) {
190
+ if (value === null || value === undefined || value === "") continue;
191
+ const term = document.createElement("dt"), detail = document.createElement("dd");localize(term, key);detail.textContent = String(value);fields.append(term, detail);
192
+ }
193
+ }
181
194
  function applyModels(data, { changed }) {
182
195
  modelSnapshots.set(data.provider || selectedProvider, data);
196
+ if (changed) void globalThis.ccdxConnections?.load?.();
183
197
  if (data.provider && data.provider !== selectedProvider) return;
184
198
  if (changed) {
185
199
  const body = element("live-models-body");
@@ -307,8 +321,10 @@ const dashboardRefresh = globalThis.ccdxRefresh.createController({
307
321
  state: state => {
308
322
  if (state.attemptVariant !== selectedProvider) return;
309
323
  element("refresh-models").disabled = Boolean(state.pending);
310
- text("models-state", state.pending ? "checking_live" : state.error ? "live_lookup_failed" : state.value?.source === "configured" ? "api_configured_models" : state.value?.source === "catalog" ? "catalog_snapshot" : "live_snapshot");
311
- element("model-check-details").hidden = !state.error;
324
+ text("models-state", state.pending ? "checking_live" : state.error ? "live_lookup_failed" : state.value?.catalog_read ? state.value.catalog_read.source === "network" ? "catalog_read_network" : "catalog_read_cache" : state.value?.source === "configured" ? "api_configured_models" : state.value?.source === "catalog" ? "catalog_snapshot" : "live_snapshot");
325
+ const evidence = state.value?.provider === selectedProvider ? state.value : modelSnapshots.get(selectedProvider);
326
+ element("model-check-details").hidden = !state.error && !evidence?.catalog_read;
327
+ if (!state.error) catalogReadDetails(evidence);
312
328
  if (state.error) {
313
329
  const message = String(state.error.message || state.error).slice(0, 240);
314
330
  const httpError = /^Live model lookup failed \(HTTP (\d{3})\)\. Run ccdx models for details\.$/.exec(message);
@@ -1,6 +1,6 @@
1
1
  import os from "node:os";
2
2
  import { isProviderId } from "./provider-metadata.mjs";
3
- import { m365CatalogDiagnostic } from "./providers/m365-catalog-diagnostic.mjs";
3
+ import { m365CatalogDiagnostic, m365CatalogRead } from "./providers/m365-catalog-diagnostic.mjs";
4
4
  import { m365NetworkDiagnostic } from "./providers/m365-network-diagnostic.mjs";
5
5
  import { fetchLiveCopilotModels } from "./live-models.mjs";
6
6
  import { authStatus } from "./auth-status.mjs";
@@ -309,6 +309,7 @@ export async function handleDashboardApi(req, res, pathname, {
309
309
  checked_at: ["catalog", "configured"].includes(catalog.source) ? catalog.checkedAt : new Date().toISOString(),
310
310
  upstream_host: safeText(catalog?.upstreamHost || "GitHub Copilot", 120),
311
311
  advertised: finite(catalog?.advertised),
312
+ ...(m365CatalogRead(catalog?.catalogRead) ? { catalog_read: m365CatalogRead(catalog.catalogRead) } : {}),
312
313
  selectable: models.filter(model => model.selectable !== false).length,
313
314
  models: models.slice(0, 500).map((model) => ({
314
315
  id: safeText(model.id, 160),
@@ -3,16 +3,19 @@ import path from "node:path";
3
3
  import { createHash } from "node:crypto";
4
4
  import { accessSettingsPath } from "./access-settings.mjs";
5
5
  import { readBoundedFileSync } from "./bounded-file.mjs";
6
- import { atomicWriteFileSync } from "./atomic-file.mjs";
6
+ import { atomicWriteFilePairSync } from "./atomic-file.mjs";
7
7
  import { withFileLockSync } from "./lock.mjs";
8
8
 
9
9
  const grants = new WeakMap(), HASH = /^[a-f0-9]{64}$/, LIMIT = 1024;
10
10
  const digest = value => createHash("sha256").update(JSON.stringify(value, (key, entry) => key === "cache_control" ? undefined : entry)).digest("hex");
11
+ const semanticDigest = value => createHash("sha256").update(JSON.stringify(value, (_key, entry) => entry && typeof entry === "object" && !Array.isArray(entry)
12
+ ? Object.fromEntries(Object.keys(entry).sort().map(key => [key, entry[key]])) : entry)).digest("hex");
11
13
  const parts = message => Array.isArray(message?.content) ? message.content : [];
12
14
  const thinking = part => ["thinking", "redacted_thinking", "reasoning"].includes(part?.type);
13
15
  const history = body => body.messages.some(message => message?.role === "assistant" || parts(message).some(part => part?.type === "tool_result"))
14
16
  || body.messages.filter(message => message?.role === "user").length > 1;
15
- const fail = (code, message) => { throw Object.assign(new Error(message), { code, statusCode: 409 }); };
17
+ const fail = (code, message, reason) => { throw Object.assign(new Error(message), { code, statusCode: 409,
18
+ ...(reason ? { jsonBody: { type: "error", error: { type: "invalid_request_error", code, message, reason } } } : {}) }); };
16
19
  const invalidState = () => fail("ccdx_history_transfer_state_invalid", "History transfer records could not be read. Existing records and conversation were kept.");
17
20
 
18
21
  // Only a locally prepared request can carry this grant; HTTP fields cannot set it.
@@ -22,15 +25,49 @@ export const messagesHistoryTransferGrant = body => {
22
25
  export function messagesTransferPath(options = {}) {
23
26
  return path.join(path.dirname(accessSettingsPath(options)), "conversation-transfers.json");
24
27
  }
25
- function checkedRecords(value) {
28
+ function checkedRecords(value, canonical = false) {
26
29
  if (!value || value.version !== 1 || !value.records || typeof value.records !== "object" || Array.isArray(value.records)
27
30
  || Object.keys(value).some(key => !["version", "records"].includes(key)) || Object.keys(value.records).length > LIMIT) invalidState();
28
31
  for (const [key, record] of Object.entries(value.records)) {
29
- if (!HASH.test(key) || !record || Object.keys(record).some(key => !["owner", "count", "prefix"].includes(key))
32
+ if (!HASH.test(key) || !record || Object.keys(record).some(key => !(canonical ? ["owner", "count", "prefix", "raw_count", "raw_prefix"] : ["owner", "count", "prefix"]).includes(key))
30
33
  || !HASH.test(record.owner) || !HASH.test(record.prefix) || !Number.isSafeInteger(record.count) || record.count < 1 || record.count > 1_000_000) invalidState();
34
+ if (canonical && (!HASH.test(record.raw_prefix) || !Number.isSafeInteger(record.raw_count) || record.raw_count < 1 || record.raw_count > 1_000_000)) invalidState();
31
35
  }
32
36
  return value.records;
33
37
  }
38
+ function canonicalBlock(block) {
39
+ if (!block || typeof block !== "object") return block;
40
+ const { cache_control, ...value } = block;
41
+ if (block.type === "tool_result" && Array.isArray(block.content)) value.content = block.content.map(canonicalBlock);
42
+ return value;
43
+ }
44
+ function canonicalItems(messages) {
45
+ const out = [];
46
+ for (const message of messages) {
47
+ if (!message || typeof message !== "object" || !["user", "assistant"].includes(message.role)) fail("ccdx_history_transfer_invalid", "Message history is incomplete or invalid.");
48
+ const { content, cache_control, ...fields } = message;
49
+ const blocks = typeof content === "string" ? [{ type: "text", text: content }] : content;
50
+ if (!Array.isArray(blocks)) fail("ccdx_history_transfer_invalid", "Message history is incomplete or invalid.");
51
+ for (const block of blocks.length ? blocks : [null]) out.push({ ...fields, block: canonicalBlock(block) });
52
+ }
53
+ return out;
54
+ }
55
+ function checkpoint(owner, messages) {
56
+ const items = canonicalItems(messages), raw = { owner, count: messages.length, prefix: digest(messages) };
57
+ return { raw, canonical: { owner, count: items.length, prefix: semanticDigest(items), raw_count: raw.count, raw_prefix: raw.prefix } };
58
+ }
59
+ function knownPrefix(entry, messages, items) {
60
+ if (entry.canonical) return items.length >= entry.canonical.count
61
+ && semanticDigest(items.slice(0, entry.canonical.count)) === entry.canonical.prefix ? { count: entry.canonical.count } : null;
62
+ if (messages.length < entry.count) return null;
63
+ const prefix = messages.slice(0, entry.count);
64
+ const forms = [prefix,
65
+ prefix.map(message => typeof message.content === "string" ? { ...message, content: [{ type: "text", text: message.content }] } : message),
66
+ prefix.map(message => Array.isArray(message.content) && message.content.length === 1 && message.content[0]?.type === "text"
67
+ && Object.keys(message.content[0]).every(key => ["type", "text"].includes(key)) ? { ...message, content: message.content[0].text } : message)];
68
+ if (!forms.some(form => digest(form) === entry.prefix)) return null;
69
+ const migrated = checkpoint(entry.owner, prefix);return { count: migrated.canonical.count, migrated };
70
+ }
34
71
  function checkBlocks(blocks) {
35
72
  for (const part of blocks) {
36
73
  if (thinking(part)) continue;
@@ -59,29 +96,30 @@ function checkHistory(body, counting) {
59
96
  if (!message || !["user", "assistant"].includes(message.role) || !(typeof message.content === "string" || Array.isArray(message.content))) {
60
97
  fail("ccdx_history_transfer_invalid", "Message history is incomplete or invalid. The original conversation was kept.");
61
98
  }
62
- if (message.role === "assistant" && pending.size) fail("ccdx_history_transfer_tool_incomplete", "Finish the current tool operation before switching. No tool was repeated.");
99
+ if (message.role === "assistant" && pending.size) fail("ccdx_history_transfer_tool_incomplete", "Finish the current tool operation before switching. No tool was repeated.", "tool_call_pending");
63
100
  checkBlocks(parts(message));
64
101
  for (const part of parts(message)) {
65
102
  if (part.type === "tool_use") {
66
- if (message.role !== "assistant" || typeof part.id !== "string" || pending.has(part.id)) fail("ccdx_history_transfer_tool_incomplete", "Tool history is incomplete. Finish the current operation before switching.");
103
+ if (message.role !== "assistant" || typeof part.id !== "string" || pending.has(part.id)) fail("ccdx_history_transfer_tool_incomplete", "Tool history is incomplete. Finish the current operation before switching.", "tool_history_invalid");
67
104
  pending.add(part.id);
68
105
  }
69
106
  if (part.type === "tool_result" && (message.role !== "user" || !pending.delete(part.tool_use_id))) {
70
- fail("ccdx_history_transfer_tool_incomplete", "A tool result has no matching call. Restore complete history before switching.");
107
+ fail("ccdx_history_transfer_tool_incomplete", "A tool result has no matching call. Restore complete history before switching.", "tool_result_unmatched");
71
108
  }
72
109
  }
73
110
  }
74
111
  if (!counting && (pending.size || parts(body.messages.at(-1)).some(part => ["tool_use", "tool_result"].includes(part.type)))) {
75
- fail("ccdx_history_transfer_tool_incomplete", "Finish the current tool operation before switching. No tool was repeated.");
112
+ fail("ccdx_history_transfer_tool_incomplete", "Finish the current tool operation before switching. No tool was repeated.", pending.size ? "tool_call_pending" : "active_tool_turn");
76
113
  }
77
114
  }
78
115
  function project(body, count) {
79
- let removed = 0;
80
- body.messages = body.messages.map((message, index) => {
81
- if (index >= count || message.role !== "assistant") return message;
116
+ let removed = 0, index = 0;
117
+ body.messages = body.messages.map(message => {
118
+ const start = index;index += Array.isArray(message.content) ? Math.max(1, message.content.length) : 1;
119
+ if (start >= count || message.role !== "assistant") return message;
82
120
  const out = { ...message };delete out.reasoning_content;
83
121
  if (Array.isArray(message.content)) {
84
- out.content = message.content.filter(part => { if (!thinking(part)) return true;removed++;return false; });
122
+ out.content = message.content.filter((part, offset) => { if (start + offset >= count || !thinking(part)) return true;removed++;return false; });
85
123
  if (!out.content.length) return null;
86
124
  }
87
125
  return out;
@@ -92,17 +130,25 @@ function project(body, count) {
92
130
  // Caller selects eligible clients. This module knows only Messages and source
93
131
  // fingerprints; it neither changes routing nor stores conversation contents.
94
132
  export function createMessagesHistoryTransfer(options = {}) {
95
- const file = messagesTransferPath(options), active = new Map();let records;
96
- function read() {
97
- try { return checkedRecords(JSON.parse(readBoundedFileSync(file, { encoding: "utf8", maxBytes: 512 * 1024 }))); }
133
+ const file = messagesTransferPath(options), canonicalFile = path.join(path.dirname(file), "conversation-prefixes.json"), active = new Map();let records;
134
+ function readFile(target, canonical = false) {
135
+ try { return checkedRecords(JSON.parse(readBoundedFileSync(target, { encoding: "utf8", maxBytes: 512 * 1024 })), canonical); }
98
136
  catch (error) { if (error.code === "ENOENT") return {};invalidState(); }
99
137
  }
138
+ function read() {
139
+ const raw = readFile(file), canonical = readFile(canonicalFile, true);
140
+ return Object.fromEntries(Object.entries(raw).map(([key, record]) => [key, { ...record,
141
+ ...(canonical[key]?.owner === record.owner && canonical[key].raw_count === record.count && canonical[key].raw_prefix === record.prefix ? { canonical: canonical[key] } : {}) }]));
142
+ }
100
143
  function save(key, record) {
101
144
  fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
102
145
  withFileLockSync(`${file}.lock`, () => {
103
- const next = read();delete next[key];next[key] = record;
146
+ const next = read();delete next[key];next[key] = { ...record.raw, canonical: record.canonical };
104
147
  while (Object.keys(next).length > LIMIT) delete next[Object.keys(next)[0]];
105
- atomicWriteFileSync(file, JSON.stringify({ version: 1, records: next }) + "\n", { mode: 0o600 });records = next;
148
+ const raw = Object.fromEntries(Object.entries(next).map(([key, { canonical, ...value }]) => [key, value]));
149
+ const canonical = Object.fromEntries(Object.entries(next).filter(([, value]) => value.canonical).map(([key, value]) => [key, value.canonical]));
150
+ checkedRecords({ version: 1, records: raw });checkedRecords({ version: 1, records: canonical }, true);
151
+ atomicWriteFilePairSync(file, JSON.stringify({ version: 1, records: raw }) + "\n", canonicalFile, JSON.stringify({ version: 1, records: canonical }) + "\n");records = next;
106
152
  });
107
153
  }
108
154
  return { prepare({ key, owner, previousOwner, profile, body, countTokens = false, knownOwners = [] }) {
@@ -110,15 +156,15 @@ export function createMessagesHistoryTransfer(options = {}) {
110
156
  records ||= read();const entry = records[key], changed = entry ? entry.owner !== owner : Boolean(previousOwner && previousOwner !== owner);
111
157
  const initial = knownOwners.includes(entry?.owner || previousOwner);
112
158
  const hasHistory = history(body), noncommitting = countTokens || Boolean(changed || entry) && !hasHistory;
159
+ const items = changed || entry ? canonicalItems(body.messages) : null;
113
160
  if (noncommitting) {
114
161
  if (changed || entry) {
115
162
  checkHistory(body, true);
116
- const count = entry?.owner === owner && body.messages.length >= entry.count && digest(body.messages.slice(0, entry.count)) === entry.prefix
117
- ? entry.count : body.messages.length;
163
+ const count = entry?.owner === owner ? knownPrefix(entry, body.messages, items)?.count ?? items.length : items.length;
118
164
  project(body, count);
119
165
  }
120
166
  const grant = { profile, noncommitting: true, initial, active: true };grants.set(body, grant);
121
- const checkpoint = countTokens ? null : { owner, count: body.messages.length, prefix: digest(body.messages) };
167
+ const nextCheckpoint = countTokens ? null : checkpoint(owner, body.messages);
122
168
  let toolLease, committed = false;
123
169
  return { handled: true, commit(state) {
124
170
  // A no-history model probe must not pin the conversation. An actual
@@ -126,7 +172,7 @@ export function createMessagesHistoryTransfer(options = {}) {
126
172
  if (countTokens || !state?.tool || committed) return;
127
173
  const lease = active.get(key);
128
174
  if (lease && lease.owner !== owner) fail("ccdx_history_transfer_busy", "Wait for the current response to finish before switching sources.");
129
- save(key, checkpoint);committed = true;
175
+ save(key, nextCheckpoint);committed = true;
130
176
  toolLease = lease || { owner, count: 0 };toolLease.count++;active.set(key, toolLease);
131
177
  }, release() {
132
178
  grant.active = false;if (toolLease && --toolLease.count === 0) active.delete(key);toolLease = null;
@@ -137,9 +183,14 @@ export function createMessagesHistoryTransfer(options = {}) {
137
183
  let candidate = null, removed = 0, grant;
138
184
  if (changed || entry) {
139
185
  let count;
140
- if (!changed && body.messages.length >= entry.count && digest(body.messages.slice(0, entry.count)) === entry.prefix) count = entry.count;
186
+ const known = !changed ? knownPrefix(entry, body.messages, items) : null;
187
+ if (known) { count = known.count;candidate = known.migrated || null; }
141
188
  else {
142
- checkHistory(body, false);count = body.messages.length;candidate = { owner, count, prefix: digest(body.messages) };
189
+ try { checkHistory(body, false); } catch (error) {
190
+ if (error.jsonBody?.error?.reason) error.jsonBody.error.reason = `${changed ? "source_changed" : "prefix_changed"}_${error.jsonBody.error.reason}`;
191
+ throw error;
192
+ }
193
+ count = items.length;candidate = checkpoint(owner, body.messages);
143
194
  }
144
195
  removed = project(body, count);grant = { profile, noncommitting: false, initial, active: true };grants.set(body, grant);
145
196
  }
@@ -4,7 +4,7 @@ import path from 'node:path';
4
4
  import { execFile } from 'node:child_process';
5
5
  import { promisify } from 'node:util';
6
6
  import { inspectPackageUpdateEnvironment } from './package-update.mjs';
7
- import { downloadRelease, createNpmReleaseFetch, protectInstallation, stableVersion, writePrivateLaunchers, privateUnixLauncher } from './release-install.mjs';
7
+ import { downloadRelease, createNpmReleaseFetch, protectInstallation, stableVersion, writePrivateLaunchers, privateUnixLauncher, remoteDownloadDenied } from './release-install.mjs';
8
8
  import { inspectWindowsCommand } from './windows-command.mjs';
9
9
  import { isVersionGreater } from './version.mjs';
10
10
  import { readBoundedResponseText } from './upstream-body.mjs';
@@ -64,15 +64,22 @@ export async function prepareNightlyRelease(release, { environment, root=nightly
64
64
  const target=path.join(directory,...(process.platform==='win32'?[]:['lib']),'node_modules/codex-copilot-dx');
65
65
  const brokerRequired=fs.existsSync(path.join(environment.target,'node_modules/@azure/msal-node-runtime'));
66
66
  try {
67
- const artifact=await downloadRelease(version,{directory,fetchImpl,signal});
67
+ let artifact=await downloadRelease(version,{directory,fetchImpl,signal});
68
68
  const args=['install','--global','--ignore-scripts','--no-audit','--no-fund'];
69
- await execute(process.execPath,[environment.npmCli,...args,'--prefix',directory,artifact.file],{env,signal,timeout:300000,maxBuffer:128*1024,windowsHide:true});
69
+ const installArgs=()=>[...args,...(artifact.complete?['--offline']:[])];
70
+ try { await execute(process.execPath,[environment.npmCli,...installArgs(),'--prefix',directory,artifact.file],{env,signal,timeout:300000,maxBuffer:128*1024,windowsHide:true}); }
71
+ catch(error) {
72
+ if(!remoteDownloadDenied(error)||signal?.aborted)throw error;
73
+ artifact=await downloadRelease(version,{directory,fetchImpl,signal,complete:true});
74
+ fs.rmSync(target,{recursive:true,force:true});
75
+ await execute(process.execPath,[environment.npmCli,...installArgs(),'--prefix',directory,artifact.file],{env,signal,timeout:300000,maxBuffer:128*1024,windowsHide:true});
76
+ }
70
77
  await verify(target,version,{signal,brokerRequired});
71
78
  return { version, target, directory,
72
79
  async install() {
73
80
  signal?.throwIfAborted();const transaction=protectInstallation(environment);
74
81
  try {
75
- await execute(process.execPath,[environment.npmCli,...args,'--prefix',environment.prefix,artifact.file],{env,signal,timeout:300000,maxBuffer:128*1024,windowsHide:true});
82
+ await execute(process.execPath,[environment.npmCli,...installArgs(),'--prefix',environment.prefix,artifact.file],{env,signal,timeout:300000,maxBuffer:128*1024,windowsHide:true});
76
83
  await verify(environment.target,version,{signal,brokerRequired});
77
84
  const normalize=value=>process.platform==='win32'?path.resolve(value).toLowerCase():path.resolve(value);
78
85
  if(env.CCDX_PRIVATE_INSTALL_PREFIX&&normalize(env.CCDX_PRIVATE_INSTALL_PREFIX)===normalize(environment.prefix))await writePrivateLaunchers(environment);
@@ -1,7 +1,7 @@
1
1
  import { spawn, execFileSync } from "node:child_process";
2
2
  import fs from "node:fs";
3
3
  import os from "node:os";
4
- import { downloadRelease, protectInstallation, verifyPackageRuntime, writePrivateLaunchers, createNpmReleaseFetch } from "./release-install.mjs";
4
+ import { downloadRelease, protectInstallation, verifyPackageRuntime, writePrivateLaunchers, createNpmReleaseFetch, remoteDownloadDenied } from "./release-install.mjs";
5
5
  import path from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { createInterface } from "node:readline/promises";
@@ -77,16 +77,20 @@ export function inspectNpmDownloadPolicy({ env = process.env, platform = process
77
77
  return result;
78
78
  }
79
79
 
80
- export function globalUpdateCommand(source, { platform = process.platform, releaseTag, releaseFile, allowRemote = false } = {}) {
80
+ export function globalUpdateCommand(source, { platform = process.platform, releaseTag, releaseFile, allowRemote = false, complete = false } = {}) {
81
81
  if (typeof allowRemote !== "boolean") throw new Error("Remote download permission must be a boolean");
82
+ if (typeof complete !== "boolean") throw new Error("Complete-package selection must be a boolean");
82
83
  const normalized = normalizeUpdateSource(source);
83
84
  if (!normalized) throw new Error(`Choose npm or github. Received: ${source}`);
84
85
  const args = ["install", "--global"];
85
86
  if (allowRemote) args.push("--allow-remote=all");
87
+ if (complete) args.push("--offline", "--ignore-scripts", "--no-audit", "--no-fund");
86
88
  if (normalized === "github") {
87
89
  if (!githubReleaseVersion(releaseTag)) throw new Error("A valid stable GitHub release tag is required");
88
90
  const version = githubReleaseVersion(releaseTag), name = `codex-copilot-dx-${version}.tgz`;
89
- if (releaseFile !== undefined && releaseFile !== `./${name}`) throw new Error("Invalid verified release filename");
91
+ const runtimeNames = ["darwin-x64", "darwin-arm64", "win32-x64", "win32-arm64", "linux-x64-glibc", "linux-arm64-glibc", "linux-x64-musl", "linux-arm64-musl"]
92
+ .map(target => `./codex-copilot-dx-${version}-${target}.tgz`);
93
+ if (releaseFile !== undefined && releaseFile !== `./${name}` && !(complete && runtimeNames.includes(releaseFile))) throw new Error("Invalid verified release filename");
90
94
  args.push(releaseFile || `${UPDATE_SPECS.github}/v${version}/${name}`);
91
95
  } else {
92
96
  args.push(UPDATE_SPECS[normalized]);
@@ -100,17 +104,29 @@ export function globalUpdateCommand(source, { platform = process.platform, relea
100
104
 
101
105
  function waitForExit(child) {
102
106
  return new Promise((resolve, reject) => {
103
- let settled = false;
107
+ let settled = false, exited = false, ended = !child.stderr, failure, tail = "", denied = false;
104
108
  const finish = (handler, value) => {
105
109
  if (settled) return;
106
110
  settled = true;
107
111
  handler(value);
108
112
  };
113
+ const complete = () => { if (exited && ended) {
114
+ if (failure) { if (denied) failure.npmCode = "EALLOWREMOTE";finish(reject, failure); }
115
+ else finish(resolve);
116
+ } };
117
+ child.stderr?.on("data", bytes => {
118
+ process.stderr.write(bytes);const text = tail + bytes.toString();
119
+ if (/npm (?:error|ERR!) code EALLOWREMOTE\b/.test(text)) denied = true;
120
+ tail = text.slice(-64);
121
+ });
122
+ const end = () => { ended = true;complete(); };
123
+ child.stderr?.once("end", end);child.stderr?.once("close", end);child.stderr?.once("error", end);
109
124
  child.once("error", (error) => finish(reject, error));
110
125
  child.once("exit", (code, signal) => {
111
- if (signal) finish(reject, new Error(`npm update was interrupted by ${signal}`));
112
- else if (code !== 0) finish(reject, Object.assign(new Error(`npm update exited with status ${code}`), { npmExitCode: code }));
113
- else finish(resolve);
126
+ exited = true;
127
+ if (signal) failure = new Error(`npm update was interrupted by ${signal}`);
128
+ else if (code !== 0) failure = Object.assign(new Error(`npm update exited with status ${code}`), { npmExitCode: code });
129
+ complete();
114
130
  });
115
131
  });
116
132
  }
@@ -203,7 +219,6 @@ export async function runPackageUpdateCommand({
203
219
  output.write("Release package verified; Git is not required. Dependencies use the configured npm registry.\n");
204
220
  }
205
221
  try {
206
- const update = globalUpdateCommand(selectedSource, { platform, releaseTag: release?.tagName, releaseFile: artifact ? `./${artifact.name}` : undefined, allowRemote: permitRemote });
207
222
  const sourceLabel = selectedSource === "npm" ? "npm registry" : `GitHub release ${release.tagName}`;
208
223
  output.write(`Updating ${PACKAGE_NAME} from ${sourceLabel}...\n`);
209
224
  if (policy.allowRemote) output.write(`npm ${terminalCell(policy.version)}: saved allow-remote=${policy.allowRemote}${policy.registryOrigin ? `; registry ${terminalCell(policy.registryOrigin)}` : ""}.\n`);
@@ -214,30 +229,46 @@ export async function runPackageUpdateCommand({
214
229
  }
215
230
  // The verified tarball basename is fixed and safe for cmd.exe. Its directory
216
231
  // is passed as cwd, never interpolated into the Windows command string.
217
- const launch = npmLaunch(update.args, { platform, env });
218
232
  const brokerRequired = Boolean(environment?.target && fs.existsSync(path.join(environment.target, "node_modules", "@azure", "msal-node-runtime")));
233
+ const install = async item => {
234
+ const update = globalUpdateCommand(selectedSource, { platform, releaseTag: release?.tagName,
235
+ releaseFile: item ? `./${item.name}` : undefined, allowRemote: permitRemote && !item?.complete, complete: item?.complete === true });
236
+ const launch = npmLaunch(update.args, { platform, env });
219
237
  const transaction = protectInstallationFn({ ...environment, platform });
220
- let installedVersion;
238
+ let version;
221
239
  try {
222
240
  const child = spawnImpl(launch.command, launch.args, {
223
241
  env,
224
242
  ...(directory ? { cwd: directory } : {}),
225
243
  shell: false,
226
- stdio: "inherit",
244
+ stdio: ["inherit", "inherit", "pipe"],
227
245
  ...launch.options,
228
246
  });
229
247
  try { await waitForExit(child); }
230
248
  catch (error) {
231
249
  if (Number.isInteger(error.npmExitCode) && !allowRemote && ["none", "root"].includes(policy.allowRemote)) {
232
- error.message += `. npm allow-remote=${policy.allowRemote} was preserved. If npm reported EALLOWREMOTE, its registry/mirror tarball URL was refused; only if you trust this update and policy permits it, retry explicitly with ${terminalCell(commandName)} update ${selectedSource} --allow-remote. This grants URL downloads to this installation's dependency tree, not just one hostname. No automatic retry or config change was made.`;
250
+ error.message += `. npm allow-remote=${policy.allowRemote} was preserved. If npm reported EALLOWREMOTE, its registry/mirror tarball URL was refused; only if you trust this update and policy permits it, retry explicitly with ${terminalCell(commandName)} update ${selectedSource} --allow-remote. This grants URL downloads to this installation's dependency tree, not just one hostname. No permission or config change was made.`;
233
251
  }
234
252
  throw error;
235
253
  }
236
- installedVersion = verifyInstalledFn(environment?.target, { expectedVersion: release?.version });
237
- if (environment?.target && installedVersion) verifyRuntimeFn(environment.target, installedVersion, { brokerRequired });
254
+ version = verifyInstalledFn(environment?.target, { expectedVersion: release?.version });
255
+ if (environment?.target && version) verifyRuntimeFn(environment.target, version, { brokerRequired });
238
256
  if (env.CCDX_PRIVATE_INSTALL_PREFIX && environment?.prefix && (platform === "win32" ? path.win32.resolve(env.CCDX_PRIVATE_INSTALL_PREFIX).toLowerCase() === path.win32.resolve(environment.prefix).toLowerCase() : path.resolve(env.CCDX_PRIVATE_INSTALL_PREFIX) === path.resolve(environment.prefix))) await writePrivateLaunchers(environment);
239
257
  transaction.commit();
258
+ return version;
240
259
  } catch (error) { transaction.rollback();throw error; }
260
+ };
261
+ let installedVersion;
262
+ try { installedVersion = await install(artifact); }
263
+ catch (error) {
264
+ if (selectedSource !== "github" || allowRemote || !remoteDownloadDenied(error)) throw error;
265
+ output.write("npm refused a remote dependency. Previous installation restored; checking the same version's complete platform package.\n");
266
+ try { artifact = await downloadReleaseFn(release.tagName, { fetchImpl, directory, complete: true, platform }); }
267
+ catch (fallbackError) { error.message += ` Complete platform package unavailable: ${fallbackError.message}`;throw error; }
268
+ if (!artifact.complete) throw new Error("The fallback is not a verified complete platform package; no second installation was started");
269
+ output.write("Complete platform package verified; installing offline with the saved npm policy.\n");
270
+ installedVersion = await install(artifact);
271
+ }
241
272
  if (installedVersion) {
242
273
  output.write(`Updated ${PACKAGE_NAME}: installed v${terminalCell(installedVersion)} at ${terminalCell(environment.target)}.\n`);
243
274
  if (platform === "win32") {
@@ -148,9 +148,11 @@ export function createProfileModelRuntime({
148
148
  }
149
149
 
150
150
  async function performRefresh(generation) {
151
+ const fingerprint = credentialFingerprint();
151
152
  try {
152
153
  const models = await requestCatalog();
153
154
  if (refreshGeneration !== generation) return codexRegistry.models;
155
+ if (fingerprint !== credentialFingerprint()) throw new Error("GitHub account changed during model refresh; the previous catalog was preserved");
154
156
  checkCatalog(models);
155
157
  applyCatalog(models, "live");
156
158
  persist(models, generation);
@@ -173,8 +175,12 @@ export function createProfileModelRuntime({
173
175
  }
174
176
  }
175
177
 
176
- function refreshCodex() {
177
- if (refreshFlight) return refreshFlight;
178
+ function refreshCodex({ strict = false } = {}) {
179
+ const result = flight => strict ? flight.then(models => {
180
+ if (codexRegistry.lastError || !isValidModelList(models)) throw new Error(codexRegistry.lastError || "GitHub model catalog is unavailable");
181
+ return models;
182
+ }) : flight;
183
+ if (refreshFlight) return result(refreshFlight);
178
184
  const generation = refreshGeneration + 1;
179
185
  refreshGeneration = generation;
180
186
  codexRegistry.generation = generation;
@@ -184,7 +190,7 @@ export function createProfileModelRuntime({
184
190
  if (refreshGeneration === generation) codexRegistry.refreshInFlight = false;
185
191
  });
186
192
  refreshFlight = flight;
187
- return flight;
193
+ return result(flight);
188
194
  }
189
195
 
190
196
  async function initialize() {