codex-copilot-dx 1.2.27 → 1.2.29

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 CHANGED
@@ -11,7 +11,7 @@ npm install -g codex-copilot-dx@latest
11
11
  ccdx
12
12
  ```
13
13
 
14
- No Node or Git? Download [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.27/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.27/install.ps1) (Windows), then run `sh install.sh` or `./install.ps1` under your current shell policy. The bootstrap reuses compatible Node/npm or installs verified official Node 24.22.0 privately for CCDX. It adds no Git, compiler or system package manager. It keeps registry/proxy/certificate policy, verifies the Release package and installed runtime, and restores the prior CCDX package if installation fails. Dependencies still need your configured registry. See [installation limits and private command paths](docs/REFERENCE.md#install-without-node-or-git).
14
+ No Node or Git? Download [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.29/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.29/install.ps1) (Windows), then run `sh install.sh` or `./install.ps1` under your current shell policy. The bootstrap reuses compatible Node/npm or installs verified official Node 24.22.0 privately for CCDX. It adds no Git, compiler or system package manager. It keeps registry/proxy/certificate policy, verifies the Release package and installed runtime, and restores the prior CCDX package if installation fails. Dependencies still need your configured registry. See [installation limits and private command paths](docs/REFERENCE.md#install-without-node-or-git).
15
15
 
16
16
  CCDX reuses a compatible local credential or starts GitHub Device Flow, listens on `127.0.0.1:2026`, configures Codex, and opens the App. Interactive desktop starts also open the local WebUI once; use `ccdx --no-browser` or disable this in WebUI settings. No client binary patch is needed. On Windows, open the App manually unless native prediction setup is enabled. In restricted Windows PowerShell, use `npm.cmd` to install and `ccdx.cmd` for the first launch, or run `ccdx.cmd doctor --fix`. Startup, updates and explicit repair remove only CCDX's exact npm-generated `.ps1` launchers so later calls can use `ccdx`. The npm package adds no install hook or policy change; custom launchers are preserved. npm's own script is untouched. The configured `dummy` API key is a placeholder, not a credential.
17
17
 
@@ -52,17 +52,17 @@ Requests shows live app/source/model flow above existing summaries and finished
52
52
 
53
53
  ## Add your own API
54
54
 
55
- Run `ccdx web` without GitHub sign-in. In **Model sources → Add API**, enter the HTTPS address/key, read the catalog, select models and declare their real interfaces. Then open **Codex** or **Claude**, choose visible models across sources, set a default and save. Claude App/Code use Messages; Codex uses Responses, all on port 2026. GitHub-only Codex selections retain native OpenAI mode and readable model names. Token counting is separate from message generation. For manual APIs, an observed count-endpoint 404 is remembered for one minute per model/API-header scope; CCDX returns a clear 404 without inventing a token count. Unknown count capabilities share their first admitted request; a 404 prevents distinct waiting inputs from fanning out. A supported endpoint still counts each distinct input separately. Identical small count requests share bounded work. A request stays on its selected deployment; there is no automatic cross-source retry or model replacement. Reopen clients after configuration changes and start a new conversation after source/key changes. Stop management before normal `ccdx` startup for the live terminal.
55
+ Run `ccdx web` without GitHub sign-in. In **Model sources → Add API**, enter the HTTPS address/key, read the catalog, select models and declare their real interfaces. Then open **Codex** or **Claude**, choose visible models across sources, set a default and save. Claude App/Code use Messages; Codex uses Responses, all on port 2026. GitHub-only Codex selections retain native OpenAI mode and readable model names. Token counting is separate from message generation. For manual APIs, an observed count-endpoint 404 is remembered for one minute per model/API-header scope; CCDX returns a clear 404 without inventing a token count. Unknown count capabilities share their first admitted request; a 404 prevents distinct waiting inputs from fanning out. A supported endpoint still counts each distinct input separately. Identical small count requests share bounded work. A request stays on its selected deployment; there is no automatic cross-source retry or model replacement. Reopen clients after configuration changes. Claude App can continue an existing conversation on a different selected, authorized source when complete Messages history is available; unfinished tool turns, unavailable attachments and company-account isolation still apply. Codex and Claude Code retain their existing history rules. Stop management before normal `ccdx` startup for the live terminal.
56
56
 
57
57
  Keys use system credential protection or an explicit environment reference; clients receive separate local credentials. Saving reads model metadata automatically, without inference. Startup and the existing model refresh cycle also refresh enabled APIs when the 30-minute cache expires; failed reads retain saved configuration. Selecting no models pauses access; enable a source and select models to resume. Closed sources can be restored on Model sources; closed apps remain reachable for restoration on their app pages. Pinned streams finish on their original source. The version-two graph preserves old single-source visibility and saves a byte-for-byte v1 backup before migration. User and managed client settings remain protected.
58
58
 
59
- Model lists/details preserve the upstream maker declaration separately from your API source name. Missing maker metadata shows Not provided; model names are never used to guess a maker. Maker evidence is rebuildable display cache and does not change the strict connection schema or routing identity. Model details show upstream capabilities per API, with optional manual overrides collapsed below. Context, input/output limits, reasoning levels, thinking modes, input types, tools and native search are deployment-specific. Structured Anthropic declarations are mapped to Messages; they do not grant the same capabilities to a gateway's other interfaces. Missing and unrecognized metadata are distinguished, without guessing from model names. Manual overrides, including false, take priority. Claude synchronization projects compatible routes, supported host controls and per-model budgets. Unknown or out-of-range windows and unverified client versions are reported as limited; they are not promoted to 1M. Output requests are bounded by declared limits. Compatibility routes do not prove that every model supports every App tool, search or reasoning mode. See the [capability and synchronization limits](docs/REFERENCE.md#model-capabilities-and-claude-synchronization). [1.2.27 changes and verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.27.md) cover Claude App model synchronization that preserves its 1M preference and avoids duplicate context choices, while retaining native GitHub sign-in/model protections.
59
+ Model lists/details preserve the upstream maker declaration separately from your API source name. Missing maker metadata shows Not provided; model names are never used to guess a maker. Maker evidence is rebuildable display cache and does not change the strict connection schema or routing identity. Model details show upstream capabilities per API, with optional manual overrides collapsed below. Context, input/output limits, reasoning levels, thinking modes, input types, tools and native search are deployment-specific. Structured Anthropic declarations are mapped to Messages; they do not grant the same capabilities to a gateway's other interfaces. Missing and unrecognized metadata are distinguished, without guessing from model names. Manual overrides, including false, take priority. Claude synchronization projects compatible routes, supported host controls and per-model budgets. Unknown or out-of-range windows and unverified client versions are reported as limited; they are not promoted to 1M. Output requests are bounded by declared limits. Compatibility routes do not prove that every model supports every App tool, search or reasoning mode. See the [capability and synchronization limits](docs/REFERENCE.md#model-capabilities-and-claude-synchronization). [1.2.29 changes and verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.29.md) cover copyable GitHub verification codes, explicit M365 app grants, protocol-equivalent history continuation and traceable network/cache model reads. Existing native Codex sign-in/model protections and the 1.2.27 context-preference fix remain included.
60
60
 
61
61
  ## Microsoft 365 access
62
62
 
63
63
  Eligible macOS/Windows machines attempt silent Microsoft authorization at startup, without Copilot CLI or a browser login. MDM alone is insufficient: account, tenant, device policy and Loki entitlement must permit access. Optional failure does not block GitHub. Saved bindings stay selected; unresolved company accounts can be chosen under **Model sources → Microsoft 365** or `ccdx m365 account` in the updated running service. Listing is local; changing accounts validates only the selected account, affects M365 in Codex/Claude and requires new conversations. See the reference for identity and history limits. Microsoft 365 uses the fixed `loki.delve.office.com` service origin. Account/origin-bound model discovery is separate from inference; old environment caches are not advertised as current. This does not enable a paused source or change existing application routing.
64
64
 
65
- Claude clients use `http://127.0.0.1:2026/anthropic` (or the configured main port), a private local gateway key and a Claude-only catalog. No second Claude listener is opened. Existing unchanged CCDX-owned 2027 addresses migrate automatically; hand-written or managed addresses are preserved and need explicit migration. The optional prediction CONNECT/PAC bridge remains a separate transport.
65
+ In **Model sources → Microsoft 365 → Allowed apps**, choose consuming apps; discovery alone does not configure them all. Existing grants are retained, and changing access preserves other sources. Claude clients use `http://127.0.0.1:2026/anthropic` (or the configured main port), a private local gateway key and a Claude-only catalog. No second Claude listener is opened. Existing unchanged CCDX-owned 2027 addresses migrate automatically; hand-written or managed addresses are preserved and need explicit migration. The optional prediction CONNECT/PAC bridge remains a separate transport.
66
66
  Existing custom/managed settings are preserved; already-running clients may need a normal restart.
67
67
  Canonical Claude IDs and advertised effort caps refresh only in unchanged CCDX-owned settings. User and managed choices are preserved; supported App versions can update model knowledge through Anthropic's signed catalog. New protocol semantics may require a client or CCDX update. See the [model reference](docs/REFERENCE.md#claude-gateway-and-client-ownership).
68
68
  `ccdx m365 off` restores unchanged owned fields; `remove` also clears owned M365 state. With managed client connections, off pauses affected bindings instead of selecting another source; removal retains shared client-ownership records needed by manual APIs.
@@ -135,12 +135,46 @@ For this same manual App boundary, system-role text is collected into the native
135
135
  top-level system field in order; conversation blocks and their order are retained.
136
136
 
137
137
  `conversation-source-guard.mjs` retains bounded HMAC correlations for observed
138
- managed histories. Known source/key conflicts fail before forwarding. It does
139
- not establish provenance for an unseen history or implement dynamic affinity.
140
- The existing Responses route-plan boundary continues to own opaque-state checks.
138
+ managed histories. Codex and Claude Code retain their existing conflict checks.
139
+ Claude App explicitly supplies the protocol-level `messages-history-transfer.mjs`
140
+ policy after resolving an authorized model/source. The policy has no application,
141
+ provider or model-name rules. It rebuilds only the forwarded Messages prefix,
142
+ removes source-private thinking from that prefix, preserves native completed tool
143
+ pairs and available media, and rejects unfinished tools or unrecoverable source
144
+ handles. New-source thinking after the checkpoint stays unchanged. Changed
145
+ prefixes can be rebuilt only at a completed tool boundary. It adds no automatic
146
+ retry, summary inference, routing fallback or conversation database.
147
+
148
+ Transfer records are bounded to 1024 hashed keys per 512 KiB versioned file;
149
+ they contain owner hashes, prefix hashes and counts, not transcripts.
150
+ `conversation-prefixes.json` adds protocol-equivalent block fingerprints beside
151
+ the unchanged legacy `conversation-transfers.json` shape. Strings and single
152
+ text blocks compare equally; adjacent same-role messages can be combined without
153
+ changing the proved block prefix. Text/code whitespace, arrays and tool argument
154
+ values remain significant. Only protocol cache hints are excluded. The semantic
155
+ receipt is anchored to its legacy owner/count/hash so an older writer invalidates
156
+ stale proof. Both files commit under the existing lock and atomic file-pair
157
+ rollback. Legacy receipts upgrade only after their prefix is proved; unmatched
158
+ old history is never guessed. Old versions can still read the legacy receipt.
159
+ Count/model-validation requests do not rebind. A per-conversation request lease
160
+ pins active source work; the gateway commits a checkpoint immediately before
161
+ delivering usable output/tool/private state and releases every lease on failure
162
+ or completion. Pre-output errors preserve the earlier checkpoint, while partial
163
+ output keeps the actual source's provenance. A matching private request grant
164
+ allows first association with the selected M365 account; known foreign account
165
+ owners are still refused. Native Responses recovery/configuration is unchanged.
141
166
 
142
167
  `dashboard/connections.js` owns settings forms; application source/review and
143
168
  account/catalog views keep their existing scopes and use the same backend graph.
169
+ M365's `source_access` action changes client grants without choosing a source or
170
+ model. Only revoked active routes and necessary shared-key migrations synchronize
171
+ client configuration; unrelated clients and empty sync targets are untouched.
172
+ Unchecked routes are removed from runtime authorization while other deployments
173
+ remain selected. Fresh discovery without owned legacy configuration grants no
174
+ automatic M365 consumers; existing graph/legacy ownership is retained. Explicit
175
+ CLI source selection remains an intentional grant for Codex only. Shared native
176
+ Claude capability settings are preserved when an unaffected consumer is not yet
177
+ checked, until normal reconciliation can verify both consumers.
144
178
  Its binding draft retains selected identities independently from current catalog
145
179
  availability. Missing selections stay visible and cannot be silently dropped on save.
146
180
  Full configuration is on-demand; ordinary status uses compact cached summaries.
@@ -407,6 +441,13 @@ settlement for two seconds; no successful plaintext cache or transcript index ex
407
441
  ## Dashboard reads
408
442
 
409
443
  `account-tools.mjs` is the shared explicit GitHub sign-in/check/sign-out boundary for CLI and WebUI. It reuses bounded device polling and `auth-status.mjs` access checks, isolates candidate credentials until verification, compares the original credential under the existing cross-process auth lock, and atomically commits to the CCDX-owned store. It does not own Microsoft SSO. Public snapshots project fixed stages/codes and omit token material. A cancelled or failed candidate is never persisted; the service keeps one sign-in controller and one connection-check flight, with bounded lifetimes/cooldowns. Explicit cache invalidation aborts a pending token refresh while preserving the runtime's account binding. The CLI notifies a compatible local service after changes; account changes require a restart.
444
+ The verification view starts one deferred ClipboardItem write in the explicit
445
+ sign-in gesture, resolves it only to the short public user code and retains an
446
+ explicit writeText/selectable-text fallback. Fixed-URL native link activation
447
+ retries copying without awaiting a popup-blocking task. Flow/account generations
448
+ ignore cancelled or obsolete completion; unchanged polls do not rewrite or
449
+ reannounce the clipboard feedback. No clipboard read or token projection is added.
450
+
410
451
 
411
452
  `local-tools.mjs` reuses doctor and the existing config writer. It projects redacted local checks and a revision-bound config preview rather than wrapping arbitrary shell commands. The config writer validates the revision again inside its own lock, then preserves unmanaged settings and backs up changed originals. `dashboard-tools.mjs` owns the small strict action schema and bounded request-body transport; `optional-routes.mjs` creates these tools lazily per handler and disposes sign-in work when the listener closes. `dashboard/tools.js` owns the source-specific account view, user-triggered checks/preview and local progress polling; source selection does not change routing. `dashboard/icons.js` supplies fixed local circle SVGs and separate localized text nodes, preserving language changes without replacing the icons. No runtime dependency or per-stream instrumentation is added.
412
453
 
package/docs/REFERENCE.md CHANGED
@@ -1336,7 +1336,7 @@ Unknown support prevents an explicitly requested exception from starting.
1336
1336
  For an older updater that still requires Git, install the Release tarball directly:
1337
1337
 
1338
1338
  ```sh
1339
- npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.27/codex-copilot-dx-1.2.27.tgz
1339
+ npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.29/codex-copilot-dx-1.2.29.tgz
1340
1340
  # Windows PowerShell: use npm.cmd instead of npm.
1341
1341
  ```
1342
1342
 
@@ -1760,7 +1760,7 @@ unchanged.
1760
1760
 
1761
1761
  New explicit-tool sign-ins use `~/.local/share/ccdx/github_token` and fingerprint-bound `.account.json` metadata, with private permissions and the existing atomic paired writer. When present, this owned store takes precedence over `~/.local/share/copilot-api/github_token`; existing startup/discovery compatibility remains supported. `auth logout` requires interactive confirmation or `--yes`, writes an empty owned credential, and does not delete or revoke other apps' legacy credentials. This intentionally blocks inference's legacy fallback. New login or normal startup can perform the existing explicit discovery/sign-in process again. CLI changes notify a compatible running local service; if notification is unavailable, the CLI asks for a service restart. In-flight model requests are not replayed or forcibly stopped. A token cache invalidation preserves its running account binding, so switching accounts still requires a restart.
1762
1762
 
1763
- Model sources uses one source selector for the selected source controls, account and catalog. Disabled sources remain under its collapsed list; there is no second list of enabled source cards. Selecting a tab is browsing only. GitHub offers sign-in, independent connection checks and cancellation; sign-out is under More actions. The browser opens only the fixed GitHub device authorization URL after the user chooses Open GitHub. No token or password entry field is added. Microsoft 365 retains local account discovery/selection and source controls; its corporate SSO is not replaced with a GitHub-style login. Raw codes remain under details and last-good model lists retain their previous timestamp after failures.
1763
+ Model sources uses one source selector for the selected source controls, account and catalog. Disabled sources remain under its collapsed list; there is no second list of enabled source cards. Selecting a tab is browsing only. GitHub offers sign-in, independent connection checks and cancellation; sign-out is under More actions. The browser opens only the fixed GitHub device authorization URL after the user chooses Copy & open GitHub. Its copy icon writes only the displayed short user code. The originating sign-in click prepares one asynchronous clipboard write; browsers that reject it retain an explicit copy action and selectable text. Re-rendering/polling does not repeatedly overwrite the clipboard. Clipboard reads are never requested, failed writes never show Copied, and cancelled/obsolete flow completions cannot update the new flow. Opening the link retries the copy in the click without delaying the native link activation. No token or password entry field is added. Microsoft 365 retains local account discovery/selection and source controls; its corporate SSO is not replaced with a GitHub-style login. Raw codes remain under details and last-good model lists retain their previous timestamp after failures.
1764
1764
 
1765
1765
  `ccdx web` opens an existing compatible dashboard or starts a management-only local listener without sign-in, app configuration, app launch, prediction setup or automatic M365 startup. It does not claim normal startup integrations are active. Stop that management listener with Ctrl+C before running normal `ccdx` for application routing and optional integrations. Opening the dashboard does not initiate a GitHub Device Flow or model inference.
1766
1766
 
@@ -2184,6 +2184,77 @@ without that header remain unchanged. This header is correlation only: model
2184
2184
  access and the company's account/history checks remain authoritative.
2185
2185
 
2186
2186
 
2187
+ ### Claude App cross-source continuation
2188
+
2189
+ In Claude App, choose another model that you have selected and authorized for
2190
+ that app. CCDX can continue the same conversation across Messages sources using
2191
+ the complete history supplied by the client. This is explicit model selection,
2192
+ not automatic failover. Codex and Claude Code retain their existing source rules.
2193
+
2194
+ CCDX preserves the original client conversation. In the forwarded request it
2195
+ keeps visible messages, available image/document content, and completed native
2196
+ tool calls/results; it removes incompatible old-source thinking and records a
2197
+ hashed history checkpoint. Subsequent thinking from the new source is retained.
2198
+ A changed/compacted client prefix is rebuilt only between completed tool turns.
2199
+ No automatic summary, tool execution, history truncation or hidden inference is
2200
+ added. Target capabilities and input/output limits still apply; unsupported
2201
+ upstream behavior is reported without retrying another source.
2202
+
2203
+ Finish a running response/tool operation before changing sources. Incomplete
2204
+ tool pairs, source-owned file/container handles and unrecoverable encrypted
2205
+ history require completing the operation or restoring the original content.
2206
+ Known history belonging to a different company account remains blocked. Model
2207
+ validation and token counting do not move a conversation's source. A failed
2208
+ request before usable output leaves its prior checkpoint; partial output keeps
2209
+ the actual new-source checkpoint and is never automatically replayed.
2210
+
2211
+ `conversation-transfers.json`, beside `connections.json`, stores at most 1024
2212
+ HMAC-keyed entries with source/prefix hashes and message counts, within a 512 KiB
2213
+ read limit. It stores no prompts, files, raw session IDs or credentials. Records
2214
+ survive ordinary service restart; corrupt records are preserved and reported,
2215
+ not replaced with empty defaults. This does not persist Responses history or
2216
+ change Codex login/provider/model-list configuration.
2217
+
2218
+ `conversation-prefixes.json` adds a second bounded receipt with protocol-equivalent
2219
+ block fingerprints. A string and its single text block compare equally, and
2220
+ combining adjacent same-role messages preserves the proved block prefix. This
2221
+ changes only comparison, not the client's messages. Text/code whitespace and
2222
+ tool argument values remain significant. Each semantic receipt is tied to the
2223
+ legacy owner/count/hash; an older writer makes stale semantic proof ineligible.
2224
+ The pair commits atomically. Legacy receipts upgrade only when their prefix is
2225
+ proved, and the original legacy file remains readable by older versions. Each
2226
+ file is limited to 1024 keys and a 512 KiB read. No tool or private state is
2227
+ replayed to work around an unknown prefix or account mismatch. Rejections report
2228
+ whether the source changed or the prefix changed, and whether a tool result is
2229
+ missing/unmatched or a tool turn is active.
2230
+
2231
+ ### Explicit M365 app access and directory read receipts
2232
+
2233
+ Model sources → Microsoft 365 → Allowed apps grants the current source to one,
2234
+ several or no enabled apps. Granting access does not choose models or change the
2235
+ current source. Removing access removes only that source's selected routes,
2236
+ preserving other source selections and an unavailable default until explicitly
2237
+ replaced. The runtime enforces revoked access even if a client retains its old
2238
+ model menu. Shared legacy Claude-key migration reports which retained consumers
2239
+ need reopening. Existing saved grants/owned legacy setups are retained; first-time
2240
+ discovery/sign-in alone does not connect all apps. An explicit CLI M365 source
2241
+ choice authorizes Codex only. Ordinary grants do not synchronize unrelated Codex
2242
+ configuration, authentication or catalogs.
2243
+
2244
+ M365's explicit directory refresh always requests the network, even when a
2245
+ usable local model cache exists. `Cache-Control: no-cache` and `Pragma: no-cache`
2246
+ request HTTP revalidation through the existing transport. They do not bypass
2247
+ enterprise proxies, certificates, account policies or change token refresh.
2248
+ The read summary distinguishes network from CCDX cache, records the data time,
2249
+ raw total, compatible GPT/Claude counts and locally excluded count. Collapsed
2250
+ details include sanitized upstream/client correlation IDs, HTTP status and a
2251
+ bounded upstream Age value when returned. A network response containing five
2252
+ models replaces an older fifteen-model cache; a failed check preserves and
2253
+ labels prior data. Directory access is not inference authorization. There is no
2254
+ automatic empty-directory substitution, fabricated Claude entry, extra polling
2255
+ loop or inference probe. Correlation IDs are receipts, not proof that every
2256
+ intermediate proxy honored revalidation.
2257
+
2187
2258
  ### Upstream maker metadata
2188
2259
 
2189
2260
  Manual API discovery accepts bounded text from publisher, vendor and owned_by.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "1.2.27",
3
+ "version": "1.2.29",
4
4
  "description": "Local gateway for Codex and Claude with Copilot, Microsoft 365 and custom APIs",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
package/src/adapter.mjs CHANGED
@@ -276,7 +276,7 @@ export function createAdapterHandler(options = {}) {
276
276
  const query = new URL(req.url, "http://localhost").search;
277
277
  req.url = pathname.slice("/anthropic".length) + query;
278
278
  try { return await options.providerRuntime.handleClaude(req, res); }
279
- catch (error) { sendJsonError(res, error, error.statusCode || 502); }
279
+ catch (error) { return sendJsonError(res, error, error.statusCode || 502); }
280
280
  finally { req.url = original; }
281
281
  }
282
282
  if (req.method === "POST" && ["/v1/responses", "/v1/responses/compact"].includes(pathname)
@@ -23,6 +23,8 @@ function send(res, code, value) {
23
23
  res.writeHead(code, { "Content-Type": "application/json", "Cache-Control": "no-store" });res.end(JSON.stringify(value));
24
24
  }
25
25
  const apiError = (code, message) => ({ type: "error", error: { type: "api_error", code, message } });
26
+ const hasMessageState = block => Boolean(block && (block.id || block.signature || block.data
27
+ || typeof block.text === "string" && block.text.length || typeof block.thinking === "string" && block.thinking.length));
26
28
  function desktopMessages(body) {
27
29
  const messages = [], instructions = [];
28
30
  const blocks = content => {
@@ -119,7 +121,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
119
121
  const tracker = countTokens ? parent?.streamPerformance : performance.begin("messages", { requestId, application: requestApplication(req.headers, "claude") });
120
122
  if (!resolveRequest) tracker?.setProvider(provider.id);
121
123
  const abort = createRequestAbort(req, res);
122
- let release = () => {}, outcome = "failed", model = null, configuredModel = null, clientModel = null, responseId = null, usage = null, stopReason = null, streamed = false, sawStop = false, failedEvent = false;
124
+ let release = () => {}, conversation, outcome = "failed", model = null, configuredModel = null, clientModel = null, responseId = null, usage = null, stopReason = null, streamed = false, sawStop = false, failedEvent = false;
123
125
  let terminalOrigin = "client_validation", failureStatus = null, countDeadline = null, rejectionReason;
124
126
  if (!countTokens) { stats.total++;stats.active++;stats.last_request_at = new Date().toISOString(); }
125
127
  const context = parent || { requestId };
@@ -152,7 +154,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
152
154
  context.model = configuredModel || model;
153
155
  if (!countTokens) markRequestObservation({ max_output_tokens_requested: body.max_tokens });
154
156
  tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });
155
- validateConversation?.(body, req.headers, selectedProvider);
157
+ conversation = validateConversation?.(body, req.headers, selectedProvider);
156
158
  terminalOrigin = "transport";
157
159
  const upstream = await selectedProvider.client.messages(body, { headers: req.headers, countTokens, signal: abort.signal,
158
160
  onCountObservation(value) {
@@ -179,6 +181,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
179
181
  if (!upstream.ok) context.onHttpError?.({ ...upstreamErrorEvidence(raw),
180
182
  origin: context.countObservation?.cached ? "capability_cache" : "upstream_http", headers: upstream.headers });
181
183
  if (!countTokens && upstream.ok && value?.type === "message" && Array.isArray(value.content)) {
184
+ if (value.content.some(hasMessageState)) conversation?.commit?.({ tool: value.content.some(block => block?.type === "tool_use") });
182
185
  model = value.model || model;responseId = value.id;usage = value.usage;stopReason = value.stop_reason;
183
186
  sawStop = typeof stopReason === "string";outcome = stopReason === "max_tokens" ? "incomplete" : sawStop ? "completed" : "failed";
184
187
  } else if (countTokens && upstream.ok) outcome = "completed";
@@ -191,6 +194,8 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
191
194
  const observer = createMessagesObserver(event => {
192
195
  if (event.type === "error") { failedEvent = true;outcome = "failed";return; }
193
196
  if (sawStop || failedEvent) return;
197
+ if (event.type === "content_block_start" && hasMessageState(event.content_block)
198
+ || event.type === "content_block_delta" && (isMessagesOutputDelta(event.delta) || event.delta?.type === "signature_delta" && event.delta.signature)) conversation?.commit?.({ tool: event.content_block?.type === "tool_use" });
194
199
  if (event.type === "message_start") { responseId = event.message?.id;model = event.message?.model || model;usage = event.message?.usage || {}; }
195
200
  if (event.type === "content_block_delta" && isMessagesOutputDelta(event.delta)) tracker?.firstOutput();
196
201
  if (event.type === "message_delta") { usage = { ...usage, ...event.usage };stopReason = event.delta?.stop_reason || stopReason; }
@@ -223,16 +228,17 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
223
228
  const diagnostic = error.code === "ccdx_api_network_unavailable" ? transportErrorDetails(error) : null;
224
229
  log(outcome === "cancelled" ? "info" : "warn", `Claude request ${requestId}: ${detail.code}${diagnostic ? ` (${diagnostic.code}, ${diagnostic.phase})` : ""}`);
225
230
  tracker?.setErrorOrigin(terminalOrigin);
226
- context.onHttpError?.({ code: detail.code, origin: terminalOrigin, ...(diagnostic ? { transport: diagnostic } : {}) });
231
+ context.onHttpError?.({ code: detail.code, origin: terminalOrigin, ...(rejectionReason ? { reason: rejectionReason } : {}), ...(diagnostic ? { transport: diagnostic } : {}) });
227
232
  if (outcome === "cancelled") return;
228
233
  if (!res.headersSent) {
229
234
  const value = apiError(abort.reason || error.code || "ccdx_gateway_error", message);
235
+ if (rejectionReason) value.error.reason = rejectionReason;
230
236
  if (diagnostic) value.error.diagnostic = diagnostic;
231
237
  send(res, statusCode, value);
232
238
  }
233
239
  else if (!res.destroyed && !res.writableEnded) res.end(`event: error\ndata: ${JSON.stringify(apiError("ccdx_gateway_error", message))}\n\n`);
234
240
  } finally {
235
- release();abort.cleanup();finishProvider();
241
+ conversation?.release?.();release();abort.cleanup();finishProvider();
236
242
  if (!countTokens) {
237
243
  stats.active--;stats[outcome]++;
238
244
  const usageRecord = buildMessagesUsageRecord({ model: configuredModel || model, responseId, usage, mode: streamed ? "stream" : "json",
@@ -13,11 +13,13 @@ import { configureCodexApi } from "./codex-api-config.mjs";
13
13
  import { autoReviewReasoningEfforts } from "./models.mjs";
14
14
  import { createRequestAdmission } from "./request-admission.mjs";
15
15
  import { createConversationSourceGuard } from "./conversation-source-guard.mjs";
16
+ import { createMessagesHistoryTransfer } from "./messages-history-transfer.mjs";
16
17
  import { compileClientModels, sourceModels } from "./client-model-plan.mjs";
17
18
  import { codexClientCatalog, codexSourceCatalog } from "./clients/codex-models.mjs";
18
19
  import { currentRequestContext } from "./request-context.mjs";
19
20
  import { claudeSharedCapabilityPlan, syncClaudeCapabilities, inspectClaudeCapabilitySupport, inspectClaudeCapabilityConfiguration } from "./claude-capability-config.mjs";
20
21
  import { deploymentModelId, resolveModelCapabilities, deploymentRevision } from "./model-capabilities.mjs";
22
+ import { m365Paths } from "./m365-settings.mjs";
21
23
 
22
24
  const validObject = (value, keys) => value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).every(key => keys.includes(key));
23
25
  export function createConnectionRuntime({ legacy, home, env = process.env, platform = process.platform, corePort = 2026,
@@ -25,8 +27,10 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
25
27
  configureCodex = configureCodexApi, inspectDesktop = inspectClaudeDesktopPolicy, clientAccessChanged, preserveClientConfiguration, now = Date.now, log = () => {} } = {}) {
26
28
  const options = { home, env, platform, preserveClientConfiguration }, secrets = secretStore || createApiSecretStore(options), modelDisplay = createApiModelDisplayStore(options);
27
29
  const guardConversation = createConversationSourceGuard(options), acquireClaudeRequest = createRequestAdmission({ maxBytes: 16 * 1024 * 1024, maxQueued: 8 });
30
+ const messagesTransfer = createMessagesHistoryTransfer({ ...options, onTransfer: () => log("info", "Conversation continued on the selected source; original history kept") });
28
31
  const memoryModel = createCodexMemoryModel({ ...options, corePort });
29
32
  let settings = readAccessSettings(options), managed = fs.existsSync(accessSettingsPath(options)), serial = Promise.resolve(), keys, closed = false;
33
+ const legacyClaudeAccess = fs.existsSync(m365Paths(options).ownership);
30
34
  const instances = new Map(), active = new Map(), retired = new Set(), handlers = new Map(), summaries = new WeakMap(), sourceSecrets = new WeakMap(), setup = {}, lastClients = {};
31
35
  const retiredSecrets = new Map(), cleanups = new Set(), plans = new Map(), discoveries = new Map();
32
36
  const catalogRefresh = createApiCatalogRefresh({ config: id => settings.apis.find(api => api.id === id), source: getSource, track,
@@ -47,7 +51,9 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
47
51
  }
48
52
  const identities = () => keys ||= readClientGatewayKeys(options);
49
53
  const enabled = id => id?.startsWith("api_") ? settings.apis.find(api => api.id === id)?.enabled === true : settings.providers[id] === true;
50
- const binding = id => managed ? settings.clients[id] : { ...settings.clients[id], source: id === "codex" ? legacy.selection().codex : legacy.snapshot().m365.enabled ? "m365" : null };
54
+ const binding = id => managed ? settings.clients[id] : { ...settings.clients[id],
55
+ allowed: settings.clients[id].allowed.filter(source => source !== "m365" || legacyClaudeAccess || id === "codex" && legacy.selection().codex === "m365"),
56
+ source: id === "codex" ? legacy.selection().codex : legacyClaudeAccess && legacy.snapshot().m365.enabled ? "m365" : null };
51
57
  // GitHub-only selections retain the existing native loopback access contract.
52
58
  // Any other deployment still requires the private per-client credential.
53
59
  function codexAccessMode() {
@@ -111,7 +117,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
111
117
  function editable() {
112
118
  if (managed) return structuredClone(settings);
113
119
  const next = structuredClone(settings);next.providers.m365 = legacy.snapshot().m365.enabled === true;
114
- for (const id of CLIENT_IDS) next.clients[id].source = binding(id).source;
120
+ for (const id of CLIENT_IDS) next.clients[id] = { ...binding(id) };
115
121
  return next;
116
122
  }
117
123
  function save(next) {
@@ -146,6 +152,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
146
152
  route_id: deploymentModelId(source, model.id), capability: model.capability || resolveModelCapabilities(model, { builtin: true }) }))), sync: sharedSync, support: capabilitySupport } }) })), managed, m365_state: state.m365.state });
147
153
  }
148
154
  async function syncClients(ids = CLIENT_IDS) {
155
+ if (!ids.length) return;
149
156
  for (const id of ids) syncTargets.add(id);
150
157
  syncAgain = true;if (syncFlight) return syncFlight;
151
158
  syncFlight = (async () => { do { syncAgain = false;const targets = new Set(syncTargets);syncTargets.clear();await performClientSync(targets); } while (syncAgain && !closed); })();
@@ -189,6 +196,10 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
189
196
  if (["claude_app", "claude_code"].some(id => setup[id] === "default_unavailable")) {
190
197
  sharedSync = { ...sharedSync, state: "partially_preserved", limitations: [{ code: "default_model_unavailable" }] };return;
191
198
  }
199
+ if (!["claude_app", "claude_code"].some(id => targets.has(id))) return;
200
+ if (["claude_app", "claude_code"].some(id => !targets.has(id) && !setup[id] && binding(id).enabled && plan(id).models.length)) {
201
+ sharedSync = { state: "partially_preserved", limitations: [{ code: "other_client_not_checked" }] };return;
202
+ }
192
203
  const shared = claudeSharedCapabilityPlan({ app: setup.claude_app === "configured" ? plan("claude_app").models : [],
193
204
  code: setup.claude_code === "configured" ? plan("claude_code").models : [], support: capabilitySupport });
194
205
  if (["claude_app", "claude_code"].some(id => setup[id] === "manual_sync")) {
@@ -204,7 +215,13 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
204
215
  }
205
216
  function validateConversation(body, headers, source, client = "codex") {
206
217
  if (!body || typeof body !== "object" || Array.isArray(body)) return;
207
- if (managed && (binding(client).history_isolation || source?.id.startsWith("api_"))) guardConversation(client, source.profileId(client === "codex" ? "responses" : "messages"), body, headers, identities()[client]);
218
+ if (managed && (binding(client).history_isolation || source?.id.startsWith("api_") || client === "claude_app")) {
219
+ const transfer = client === "claude_app" ? {
220
+ profiles: [...new Set(plan(client).models.map(model => model.source_id))].map(id => getSource(id).profileId("messages")),
221
+ prepare: input => messagesTransfer.prepare({ ...input, countTokens: currentRequestContext()?.route === "messages_count_tokens" }),
222
+ } : undefined;
223
+ return guardConversation(client, source.profileId(client === "codex" ? "responses" : "messages"), body, headers, identities()[client], transfer);
224
+ }
208
225
  }
209
226
  async function applyCatalog(id, models, revision, checkedAt, active) {
210
227
  if (!active()) throw accessError("ccdx_connections_conflict", 409);
@@ -224,7 +241,29 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
224
241
  if (closed) throw accessError("ccdx_connections_closed", 503);
225
242
  if (!validObject(input, ["operation", "id", "config", "key", "allowed", "source", "enabled", "replacements", "model", "auto_review_model", "auto_review_effort", "deployments", "default_model", "auto_sync"])) throw accessError("ccdx_connections_action_invalid");
226
243
  const next = editable();let freshRef, previousRef;
227
- if (input.operation === "save_api") {
244
+ if (input.operation === "source_access") {
245
+ if (input.id !== "m365" || !Array.isArray(input.allowed) || new Set(input.allowed).size !== input.allowed.length || input.allowed.some(id => !CLIENT_IDS.includes(id))) throw accessError("ccdx_connections_action_invalid");
246
+ const affected = CLIENT_IDS.filter(id => next.clients[id].allowed.includes(input.id) !== input.allowed.includes(id));
247
+ const sharedClaude = ["claude_app", "claude_code"].filter(id => next.clients[id].enabled && next.clients[id].source === "m365");
248
+ const migrateClaude = !next.claude_private_keys && sharedClaude.length > 0 && affected.some(id => id !== "codex");
249
+ const targets = new Set();
250
+ for (const id of affected) {
251
+ const c = next.clients[id];
252
+ c.allowed = [...c.allowed.filter(source => source !== input.id), ...(input.allowed.includes(id) ? [input.id] : [])];
253
+ if (!input.allowed.includes(id)) {
254
+ if (c.source === input.id || c.deployments?.some(item => item.source === input.id)) targets.add(id);
255
+ if (c.source === input.id) c.source = null;
256
+ if (Array.isArray(c.deployments)) c.deployments = c.deployments.filter(item => item.source !== input.id);
257
+ c.history_isolation = true;
258
+ }
259
+ }
260
+ if (migrateClaude) next.claude_private_keys = true;
261
+ if (migrateClaude) for (const id of ["claude_app", "claude_code"]) if (next.clients[id].source === "m365") targets.add(id);
262
+ save(next);await syncClients([...targets]);
263
+ const retained = migrateClaude ? [...targets].filter(id => id !== "codex" && next.clients[id].enabled && next.clients[id].source === "m365") : [];
264
+ return { ...snapshot(), client_refresh: retained.filter(id => setup[id] === "configured"),
265
+ client_review: retained.filter(id => ["preserved", "partially_preserved", "manual_sync", "configuration_unavailable"].includes(setup[id])) };
266
+ } else if (input.operation === "save_api") {
228
267
  const existing = next.apis.find(api => api.id === input.id);
229
268
  if (!existing && next.apis.length >= 16) throw accessError("ccdx_api_limit");
230
269
  if (!validObject(input.config, ["name", "base_url", "endpoints", "auth_header", "models", "key_env", "model_display"])) throw accessError("ccdx_api_config_invalid");
@@ -347,6 +386,9 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
347
386
  }
348
387
  return {
349
388
  ...legacy,
389
+ managesClaude() { return !managed ? !legacyClaudeAccess : settings.claude_private_keys
390
+ || !["claude_app", "claude_code"].every(id => binding(id).enabled && binding(id).source === "m365" && binding(id).allowed.includes("m365")); },
391
+ syncSourceClients(source) { return syncClients(CLIENT_IDS.filter(id => binding(id).source === source || binding(id).deployments?.some(item => item.source === source))); },
350
392
  source: getSource,
351
393
  connections: snapshot,
352
394
  privateScopes: id => [...new Set(plan(id).models.map(model => model.source_id))].sort().map(source => [source, getSource(source).profileId(id === "codex" ? "responses" : "messages")]),
@@ -446,7 +488,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
446
488
  return { historyNamespace: target.profileId() };
447
489
  },
448
490
  async handleClaude(req, res) {
449
- if (!managed) return legacy.handleClaude(req, res);
491
+ if (!managed) { if (!legacyClaudeAccess) throw accessError("ccdx_client_source_disabled", 503);return legacy.handleClaude(req, res); }
450
492
  if (!settings.claude_private_keys) {
451
493
  if (["claude_app", "claude_code"].every(id => permitted(id, "m365") && binding(id).source === "m365")) return legacy.handleClaude(req, res);
452
494
  throw accessError("ccdx_client_source_disabled", 503);
@@ -516,9 +558,9 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
516
558
  model: input.model, auto_review_model: input.auto_review_model, auto_review_effort: input.auto_review_effort });return this.snapshot(); }
517
559
  if (input.action === "auto-review" && managed && binding("codex").source !== "github") { await this.manageConnections({ operation: "client", id: "codex", ...clientInput, auto_review_model: input.model, auto_review_effort: input.effort });return this.snapshot(); }
518
560
  if (input.action === "auto-review" && managed && legacy.selection().codex !== "github") await legacy.action({ action: "switch", provider: "github" });
519
- if (managed && input.action === "switch" && !permitted("codex", input.provider)) throw accessError("ccdx_client_source_disabled", 503);
561
+ if (managed && input.action === "switch" && !enabled(input.provider)) throw accessError("ccdx_client_source_disabled", 503);
520
562
  const result = await legacy.action(input);
521
- if (managed && input.action === "switch") { const next = editable();if (next.clients.codex.source !== input.provider) next.clients.codex.history_isolation = true;next.clients.codex.source = input.provider;next.clients.codex.deployments = null;next.clients.codex.default_model = null;for (const key of ["model", "auto_review_model", "auto_review_effort"]) delete next.clients.codex[key];if (input.provider === "m365") Object.assign(next.clients.codex, legacy.selection().m365);save(next);await syncClients(); }
563
+ if (managed && input.action === "switch") { const next = editable();if (next.clients.codex.source !== input.provider) next.clients.codex.history_isolation = true;next.clients.codex.allowed = [...new Set([...next.clients.codex.allowed, input.provider])];next.clients.codex.source = input.provider;next.clients.codex.deployments = null;next.clients.codex.default_model = null;for (const key of ["model", "auto_review_model", "auto_review_effort"]) delete next.clients.codex[key];if (input.provider === "m365") Object.assign(next.clients.codex, legacy.selection().m365);save(next);await syncClients(["codex"]); }
522
564
  return result;
523
565
  },
524
566
  async close() { closed = true;await memoryModel.close();await catalogRefresh.close();await serial;await syncFlight;for (const { source } of instances.values()) source.close();for (const source of retired) source.close();active.clear();for (const id of retiredSecrets.keys()) cleanSecrets(id);await Promise.allSettled([...cleanups]);secrets.close();await legacy.close(); },
@@ -9,7 +9,7 @@ import { withFileLockSync } from "./lock.mjs";
9
9
  // Correlation only: retain hashes, never prompts, session IDs or credentials.
10
10
  export function createConversationSourceGuard(options = {}) {
11
11
  const file = path.join(path.dirname(accessSettingsPath(options)), "conversation-sources.json");let cache;
12
- return (client, profile, body, headers = {}, salt) => {
12
+ return (client, profile, body, headers = {}, salt, transfer) => {
13
13
  const hash = value => createHmac("sha256", salt).update(value).digest("hex");
14
14
  const items = Array.isArray(body.messages) ? body.messages : Array.isArray(body.input) ? body.input : [];
15
15
  const hasHistory = Boolean(body.previous_response_id) || items.filter(item => item?.role === "user").length > 1
@@ -25,20 +25,30 @@ export function createConversationSourceGuard(options = {}) {
25
25
  const agent = headers["x-claude-code-agent-id"];
26
26
  const child = identified && ["claude_app", "claude_code"].includes(client) && typeof agent === "string" && /^[\w-]{1,128}$/.test(agent) ? `\0agent\0${agent}` : "";
27
27
  const key = hash(client + "\0" + input + child), owner = hash(profile);
28
- if (cache?.[key] === owner) return;
29
- if (cache?.[key] && (identified || hasHistory)) throw accessError("ccdx_conversation_source_changed", 409);
28
+ const prepare = previousOwner => transfer?.prepare({ key, owner, previousOwner, profile, body,
29
+ knownOwners: transfer.profiles?.map(hash) || [] });
30
+ let prepared;
31
+ if (cache?.[key]) {
32
+ prepared = prepare(cache[key]);
33
+ if (prepared?.handled || cache[key] === owner) return prepared;
34
+ prepared?.release();
35
+ if (identified || hasHistory) throw accessError("ccdx_conversation_source_changed", 409);
36
+ }
30
37
  fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
31
- withFileLockSync(`${file}.lock`, () => {
38
+ try { return withFileLockSync(`${file}.lock`, () => {
32
39
  let owners = {};
33
40
  try { owners = JSON.parse(readBoundedFileSync(file, { encoding: "utf8", maxBytes: 256 * 1024 })); } catch (error) { if (error.code !== "ENOENT") throw accessError("ccdx_conversation_state_invalid", 409); }
34
41
  if (!owners || typeof owners !== "object" || Array.isArray(owners) || Object.keys(owners).length > 1024
35
42
  || Object.entries(owners).some(([key, owner]) => !/^[a-f0-9]{64}$/.test(key) || !/^[a-f0-9]{64}$/.test(owner))) throw accessError("ccdx_conversation_state_invalid", 409);
43
+ prepared = prepare(owners[key]);
44
+ if (prepared?.handled) { cache = owners;return prepared; }
36
45
  if (owners[key] && owners[key] !== owner && (identified || hasHistory)) throw accessError("ccdx_conversation_source_changed", 409);
37
46
  if (owners[key] !== owner) {
38
47
  owners[key] = owner;while (Object.keys(owners).length > 1024) delete owners[Object.keys(owners)[0]];
39
48
  atomicWriteFileSync(file, JSON.stringify(owners) + "\n", { mode: 0o600 });
40
49
  }
41
50
  cache = owners;
42
- });
51
+ return prepared;
52
+ }); } catch (error) { prepared?.release();throw error; }
43
53
  };
44
54
  }
@@ -8,6 +8,28 @@
8
8
  const apiForm = el("connection-api-form"), clientForm = el("connection-client-form");
9
9
  const node = (tag, text, className) => { const item = document.createElement(tag);if (text !== undefined) item.textContent = text;if (className) item.className = className;return item; };
10
10
  const source = id => data.providers.find(item => item.id === id), client = id => data.clients.find(item => item.id === id);
11
+ let accessDraft = null, accessError = null, accessRefresh = [], accessReview = [];
12
+ const accessForm = el("m365-app-access");
13
+ function renderAccess() {
14
+ if (!accessForm) return;accessForm.hidden = selectedProvider !== "m365";
15
+ const saved = data.clients.filter(c => c.allowed.includes("m365")).map(c => c.id), selected = accessDraft || saved;
16
+ const area = el("m365-allowed-apps"), focus = area.contains(document.activeElement) ? document.activeElement.value : null;
17
+ area.replaceChildren(...data.clients.filter(c => c.enabled).map(c => {
18
+ const item = check("m365-app", c.id, selected.includes(c.id), c.name);
19
+ item.firstChild.disabled = busy;item.firstChild.addEventListener("change", () => {
20
+ accessDraft = [...selected.filter(id => !data.clients.find(c => c.id === id)?.enabled), ...[...area.querySelectorAll("input:checked")].map(input => input.value)];
21
+ accessError = null;
22
+ renderAccess();[...area.querySelectorAll("input")].find(input => input.value === c.id)?.focus();
23
+ });return item;
24
+ }));
25
+ const dirty = JSON.stringify([...saved].sort()) !== JSON.stringify([...selected].sort());el("m365-access-save").disabled = busy || !dirty;
26
+ words(el("m365-access-state"), accessError || (dirty ? "cap_unsaved" : accessReview.length ? "source_apps_review" : accessRefresh.length ? "source_apps_reopen" : saved.length ? "cap_saved" : "source_apps_none"),
27
+ { apps: (accessReview.length ? [...new Set([...accessReview, ...accessRefresh])] : accessRefresh).map(id => data.clients.find(c => c.id === id)?.name || id).join(" / ") });
28
+ const affected = data.clients.filter(c => !selected.includes(c.id) && (c.source === "m365" || c.deployments?.some(item => item.source === "m365")));
29
+ el("m365-access-warning").hidden = !affected.length;words(el("m365-access-warning"), "source_apps_pause", { apps: affected.map(c => c.name).join(" / ") });
30
+ if (focus) [...area.querySelectorAll("input")].find(input => input.value === focus)?.focus();
31
+ }
32
+ accessForm?.addEventListener("submit", event => { event.preventDefault();accessError = null;void change({ operation: "source_access", id: "m365", allowed: accessDraft || [] }, result => { accessDraft = null;accessRefresh = result.client_refresh || [];accessReview = result.client_review || [];renderAccess(); }); });
11
33
  const compatible = (provider, id) => provider.protocols.includes(id === "codex" ? "responses" : "messages");
12
34
  const selectableSource = (provider, id) => compatible(provider, id)
13
35
  && (provider.builtin || provider.models?.some(model => model.protocols.includes(id === "codex" ? "responses" : "messages")));
@@ -66,6 +88,7 @@
66
88
  const m365Toggle = el("m365-enabled")?.closest(".setting-row");if (m365Toggle) m365Toggle.hidden = true;
67
89
  for (const link of document.querySelectorAll("[data-source-link]")) { const id = link.dataset.sourceLink;if (["m365", "github"].includes(id)) link.hidden = !source(id)?.enabled; }
68
90
  globalThis.ccdxConnectionNames = Object.fromEntries(data.providers.map(p => [p.id, p.name]));
91
+ renderAccess();
69
92
  }
70
93
  async function load() {
71
94
  if (busy) return;const current = ++generation;
@@ -91,9 +114,10 @@
91
114
  if (input.operation === "client" && input.source && setup === "not_installed") key = "api_client_not_installed";
92
115
  if (input.operation === "client") words(el("connection-client-note"), key);else message(key);
93
116
  }window.dispatchEvent(new CustomEvent("ccdx:connections"));void dashboardRefresh.refresh("auth", { force: true });void dashboardRefresh.refresh("status", { force: true }); }
94
- catch (error) { if (input.operation === "client") words(el("connection-client-note"), error.message);else message(error.message); }
117
+ catch (error) { if (input.operation === "source_access") accessError = error.message;else if (input.operation === "client") words(el("connection-client-note"), error.message);else message(error.message); }
95
118
  finally { busy = false;if (trigger?.tagName === "BUTTON") { trigger.removeAttribute("aria-busy");trigger.disabled = false;if (oldKey) words(trigger, oldKey);else trigger.textContent = oldText; }
96
119
  if (["client", "preview_client"].includes(input.operation)) bindingRows();
120
+ if (input.operation === "source_access") renderAccess();
97
121
  }
98
122
  }
99
123
  const resolved = (model, protocol = model.protocols.includes("messages") ? "messages" : model.protocols[0]) => {
@@ -212,8 +212,10 @@
212
212
  <p class="hint" data-i18n="tools_no_inference">Checks access and models. No chat request is sent.</p>
213
213
  <section id="github-login-flow" class="tool-flow" hidden aria-label="GitHub sign-in">
214
214
  <h3 id="github-flow-state" data-i18n="tools_waiting">Waiting for GitHub</h3>
215
- <p class="hint" data-i18n="tools_device_instructions">Open GitHub, enter this code, and authorize CCDX.</p><code id="github-user-code" class="device-code">—</code>
216
- <a id="github-authorize" class="tool-link" href="https://github.com/login/device" target="_blank" rel="noopener noreferrer" data-i18n="tools_open_github">Open GitHub</a>
215
+ <p class="hint" data-i18n="tools_device_instructions">Open GitHub, enter this code, and authorize CCDX.</p>
216
+ <div class="device-code-row"><code id="github-user-code" class="device-code">—</code><button id="github-copy-code" class="icon-button" type="button" aria-label="Copy code" data-i18n-label="tools_copy_code" disabled><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true"><rect x="8" y="8" width="12" height="12" rx="1"/><path d="M16 8V4H4v12h4"/></svg></button></div>
217
+ <p id="github-copy-state" class="hint" role="status" aria-live="polite"></p>
218
+ <a id="github-authorize" class="tool-link button-link" href="https://github.com/login/device" target="_blank" rel="noopener noreferrer" data-i18n="tools_copy_open_github">Copy &amp; open GitHub</a>
217
219
  <button id="github-cancel" type="button" data-i18n="cancel">Cancel</button>
218
220
  <p class="hint" data-i18n="tools_keep_old_signin">Old sign-in is kept until verification succeeds.</p>
219
221
  </section>
@@ -236,6 +238,7 @@
236
238
  <p class="hint" data-i18n="company_account_scope">Applies to Microsoft 365 in Codex and Claude. Start a new conversation after changing accounts.</p>
237
239
  </div>
238
240
  <p id="m365-account-note" class="hint" role="status" aria-live="polite"></p>
241
+ <form id="m365-app-access" hidden><fieldset><legend data-i18n="source_allowed_apps">Allowed apps</legend><div class="connection-checks" id="m365-allowed-apps"></div></fieldset><p class="hint" data-i18n="source_apps_hint">Choose models on the app page after granting access.</p><p id="m365-access-warning" class="hint" role="status" hidden></p><div class="section-actions"><button id="m365-access-save" type="submit" data-i18n="api_save" disabled>Save</button><span id="m365-access-state" class="hint" role="status" aria-live="polite"></span></div></form>
239
242
  </section>
240
243
  <details class="panel dashboard-section model-catalog" id="upstream-models" open>
241
244
  <summary class="panel-heading"><h2 data-i18n="model_catalog">MODEL LIST</h2><span id="models-state" role="status" aria-live="polite" data-i18n="checking_live">CHECKING</span></summary>
@@ -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,6 +178,19 @@ 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);
183
196
  if (data.provider && data.provider !== selectedProvider) return;
@@ -307,8 +320,10 @@ const dashboardRefresh = globalThis.ccdxRefresh.createController({
307
320
  state: state => {
308
321
  if (state.attemptVariant !== selectedProvider) return;
309
322
  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;
323
+ 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");
324
+ const evidence = state.value?.provider === selectedProvider ? state.value : modelSnapshots.get(selectedProvider);
325
+ element("model-check-details").hidden = !state.error && !evidence?.catalog_read;
326
+ if (!state.error) catalogReadDetails(evidence);
312
327
  if (state.error) {
313
328
  const message = String(state.error.message || state.error).slice(0, 240);
314
329
  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),
@@ -0,0 +1,209 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { createHash } from "node:crypto";
4
+ import { accessSettingsPath } from "./access-settings.mjs";
5
+ import { readBoundedFileSync } from "./bounded-file.mjs";
6
+ import { atomicWriteFilePairSync } from "./atomic-file.mjs";
7
+ import { withFileLockSync } from "./lock.mjs";
8
+
9
+ const grants = new WeakMap(), HASH = /^[a-f0-9]{64}$/, LIMIT = 1024;
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");
13
+ const parts = message => Array.isArray(message?.content) ? message.content : [];
14
+ const thinking = part => ["thinking", "redacted_thinking", "reasoning"].includes(part?.type);
15
+ const history = body => body.messages.some(message => message?.role === "assistant" || parts(message).some(part => part?.type === "tool_result"))
16
+ || body.messages.filter(message => message?.role === "user").length > 1;
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 } } } : {}) }); };
19
+ const invalidState = () => fail("ccdx_history_transfer_state_invalid", "History transfer records could not be read. Existing records and conversation were kept.");
20
+
21
+ // Only a locally prepared request can carry this grant; HTTP fields cannot set it.
22
+ export const messagesHistoryTransferGrant = body => {
23
+ const grant = grants.get(body);return grant?.active ? grant : undefined;
24
+ };
25
+ export function messagesTransferPath(options = {}) {
26
+ return path.join(path.dirname(accessSettingsPath(options)), "conversation-transfers.json");
27
+ }
28
+ function checkedRecords(value, canonical = false) {
29
+ if (!value || value.version !== 1 || !value.records || typeof value.records !== "object" || Array.isArray(value.records)
30
+ || Object.keys(value).some(key => !["version", "records"].includes(key)) || Object.keys(value.records).length > LIMIT) invalidState();
31
+ for (const [key, record] of Object.entries(value.records)) {
32
+ if (!HASH.test(key) || !record || Object.keys(record).some(key => !(canonical ? ["owner", "count", "prefix", "raw_count", "raw_prefix"] : ["owner", "count", "prefix"]).includes(key))
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();
35
+ }
36
+ return value.records;
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
+ }
71
+ function checkBlocks(blocks) {
72
+ for (const part of blocks) {
73
+ if (thinking(part)) continue;
74
+ if (!part || !["text", "image", "document", "tool_use", "tool_result", "tool_reference"].includes(part.type)) {
75
+ fail("ccdx_history_transfer_content_unsupported", "This content cannot be transferred safely. The original conversation was kept.");
76
+ }
77
+ const stack = [part];
78
+ while (stack.length) {
79
+ const value = stack.pop();if (!value || typeof value !== "object") continue;
80
+ if (Array.isArray(value)) { for (const child of value) stack.push(child);continue; }
81
+ if (["file_id", "container_id", "encrypted_content", "previous_response_id"].some(key => Object.hasOwn(value, key))
82
+ || ["compaction", "item_reference"].includes(value.type)) {
83
+ fail("ccdx_history_transfer_rebuild_required", "Restore the original messages or attachment before switching. Source-owned state cannot be transferred.");
84
+ }
85
+ for (const [key, child] of Object.entries(value)) if (key !== "input") stack.push(child);
86
+ }
87
+ if (part.type === "tool_result" && Array.isArray(part.content)) checkBlocks(part.content);
88
+ }
89
+ }
90
+ function checkHistory(body, counting) {
91
+ if (body.previous_response_id || body.conversation || body.container) {
92
+ fail("ccdx_history_transfer_rebuild_required", "Restore complete message history before switching. The original conversation was kept.");
93
+ }
94
+ const pending = new Set();
95
+ for (const message of body.messages) {
96
+ if (!message || !["user", "assistant"].includes(message.role) || !(typeof message.content === "string" || Array.isArray(message.content))) {
97
+ fail("ccdx_history_transfer_invalid", "Message history is incomplete or invalid. The original conversation was kept.");
98
+ }
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");
100
+ checkBlocks(parts(message));
101
+ for (const part of parts(message)) {
102
+ if (part.type === "tool_use") {
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");
104
+ pending.add(part.id);
105
+ }
106
+ if (part.type === "tool_result" && (message.role !== "user" || !pending.delete(part.tool_use_id))) {
107
+ fail("ccdx_history_transfer_tool_incomplete", "A tool result has no matching call. Restore complete history before switching.", "tool_result_unmatched");
108
+ }
109
+ }
110
+ }
111
+ if (!counting && (pending.size || parts(body.messages.at(-1)).some(part => ["tool_use", "tool_result"].includes(part.type)))) {
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");
113
+ }
114
+ }
115
+ function project(body, count) {
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;
120
+ const out = { ...message };delete out.reasoning_content;
121
+ if (Array.isArray(message.content)) {
122
+ out.content = message.content.filter((part, offset) => { if (start + offset >= count || !thinking(part)) return true;removed++;return false; });
123
+ if (!out.content.length) return null;
124
+ }
125
+ return out;
126
+ }).filter(Boolean);
127
+ return removed;
128
+ }
129
+
130
+ // Caller selects eligible clients. This module knows only Messages and source
131
+ // fingerprints; it neither changes routing nor stores conversation contents.
132
+ export function createMessagesHistoryTransfer(options = {}) {
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); }
136
+ catch (error) { if (error.code === "ENOENT") return {};invalidState(); }
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
+ }
143
+ function save(key, record) {
144
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
145
+ withFileLockSync(`${file}.lock`, () => {
146
+ const next = read();delete next[key];next[key] = { ...record.raw, canonical: record.canonical };
147
+ while (Object.keys(next).length > LIMIT) delete next[Object.keys(next)[0]];
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;
152
+ });
153
+ }
154
+ return { prepare({ key, owner, previousOwner, profile, body, countTokens = false, knownOwners = [] }) {
155
+ if (!Array.isArray(body?.messages) || body.input !== undefined) return null;
156
+ records ||= read();const entry = records[key], changed = entry ? entry.owner !== owner : Boolean(previousOwner && previousOwner !== owner);
157
+ const initial = knownOwners.includes(entry?.owner || previousOwner);
158
+ const hasHistory = history(body), noncommitting = countTokens || Boolean(changed || entry) && !hasHistory;
159
+ const items = changed || entry ? canonicalItems(body.messages) : null;
160
+ if (noncommitting) {
161
+ if (changed || entry) {
162
+ checkHistory(body, true);
163
+ const count = entry?.owner === owner ? knownPrefix(entry, body.messages, items)?.count ?? items.length : items.length;
164
+ project(body, count);
165
+ }
166
+ const grant = { profile, noncommitting: true, initial, active: true };grants.set(body, grant);
167
+ const nextCheckpoint = countTokens ? null : checkpoint(owner, body.messages);
168
+ let toolLease, committed = false;
169
+ return { handled: true, commit(state) {
170
+ // A no-history model probe must not pin the conversation. An actual
171
+ // tool call must: its following results continue this very same turn.
172
+ if (countTokens || !state?.tool || committed) return;
173
+ const lease = active.get(key);
174
+ if (lease && lease.owner !== owner) fail("ccdx_history_transfer_busy", "Wait for the current response to finish before switching sources.");
175
+ save(key, nextCheckpoint);committed = true;
176
+ toolLease = lease || { owner, count: 0 };toolLease.count++;active.set(key, toolLease);
177
+ }, release() {
178
+ grant.active = false;if (toolLease && --toolLease.count === 0) active.delete(key);toolLease = null;
179
+ } };
180
+ }
181
+ const lease = active.get(key);
182
+ if (lease && lease.owner !== owner) fail("ccdx_history_transfer_busy", "Wait for the current response to finish before switching sources.");
183
+ let candidate = null, removed = 0, grant;
184
+ if (changed || entry) {
185
+ let count;
186
+ const known = !changed ? knownPrefix(entry, body.messages, items) : null;
187
+ if (known) { count = known.count;candidate = known.migrated || null; }
188
+ else {
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);
194
+ }
195
+ removed = project(body, count);grant = { profile, noncommitting: false, initial, active: true };grants.set(body, grant);
196
+ }
197
+ const current = lease || { owner, count: 0 };current.count++;active.set(key, current);
198
+ let released = false, committed = false;
199
+ return { handled: Boolean(changed || entry), commit() {
200
+ if (committed || released) return;
201
+ if (candidate) save(key, candidate);
202
+ committed = true;
203
+ if (candidate && changed) options.onTransfer?.({ removed_thinking: removed });
204
+ }, release() {
205
+ if (released) return;released = true;if (grant) grant.active = false;
206
+ if (--current.count === 0) active.delete(key);
207
+ } };
208
+ } };
209
+ }
@@ -15,6 +15,7 @@ import { createConnectionRuntime } from "./connection-runtime.mjs";
15
15
  import { accessSettingsPath, readAccessSettings } from "./access-settings.mjs";
16
16
  import { createStreamPerformanceMetrics } from "./stream-performance.mjs";
17
17
  import { M365_API_HOST } from "./providers/m365-endpoint.mjs";
18
+ import { m365CatalogDiagnostic, m365CatalogMessage } from "./providers/m365-catalog-diagnostic.mjs";
18
19
 
19
20
  const unavailable = reason => Object.assign(new Error(`Microsoft 365 is unavailable (${reason}); GitHub routing was not substituted`),
20
21
  { code: reason, statusCode: 503 });
@@ -24,12 +25,8 @@ const unavailable = reason => Object.assign(new Error(`Microsoft 365 is unavaila
24
25
  export function createProviderRuntime(options = {}) {
25
26
  options = { ...options, corePort: options.corePort ?? Number((options.env || process.env).ADAPTER_PORT || 2026) };
26
27
  let connections;
27
- const legacy = createBuiltinProviderRuntime({ ...options, managedClaude: () => {
28
- if (!fs.existsSync(accessSettingsPath(options))) return false;
29
- const graph = readAccessSettings(options);
30
- return graph.claude_private_keys || !["claude_app", "claude_code"].every(id => graph.clients[id].enabled && graph.clients[id].source === "m365" && graph.clients[id].allowed.includes("m365"));
31
- },
32
- onClaudeReady: () => connections?.syncClients() });
28
+ const legacy = createBuiltinProviderRuntime({ ...options, managedClaude: () => connections?.managesClaude() !== false,
29
+ onClaudeReady: () => connections?.syncSourceClients("m365") });
33
30
  connections = createConnectionRuntime({ ...options, legacy });return connections;
34
31
  }
35
32
 
@@ -230,7 +227,11 @@ function createBuiltinProviderRuntime({ githubClient, githubRegistry, githubCred
230
227
  if (changingAccount) { res.writeHead(409, { "Content-Type": "application/json", "Cache-Control": "no-store" });res.end(JSON.stringify({ error: { code: "m365_account_busy", message: m365AccountMessage("m365_account_busy") } }));return; }
231
228
  if (!enabled || !gateway?.handle) {
232
229
  res.writeHead(503, { "Content-Type": "application/json", "Cache-Control": "no-store" });
233
- res.end(JSON.stringify({ type: "error", error: { type: "api_error", code: claudeReason || reason || "m365_claude_unavailable", message: "Claude is unavailable; check the model service settings." } }));return;
230
+ const diagnostic = enabled ? m365CatalogDiagnostic(m365?.snapshot().catalog_diagnostic) : null;
231
+ const code = claudeReason || reason || "m365_claude_unavailable";
232
+ res.end(JSON.stringify({ type: "error", error: { type: "api_error", code,
233
+ message: m365CatalogMessage(diagnostic) || (code === "m365_no_claude_models" ? "The model directory did not include Claude models. Check the directory read details."
234
+ : "Claude is unavailable; check the model service settings."), ...(diagnostic ? { diagnostic } : {}) } }));return;
234
235
  }
235
236
  return gateway.handle(req, res);
236
237
  },
@@ -251,7 +252,7 @@ function createBuiltinProviderRuntime({ githubClient, githubRegistry, githubCred
251
252
  if (closed || !enabled || source !== m365 || changingAccount) throw unavailable("m365_refresh_cancelled");
252
253
  reason = null;
253
254
  const eligible = new Set([...source.models("gpt"), ...source.models("claude")]);
254
- return { source: "catalog", checkedAt: m365.snapshot().models.refreshed_at, upstreamHost: M365_API_HOST,
255
+ return { source: "catalog", checkedAt: m365.snapshot().models.refreshed_at, upstreamHost: M365_API_HOST, catalogRead: source.snapshot().catalog_read,
255
256
  advertised: m365.catalog().length, models: publicModelCatalog(m365.catalog(), {
256
257
  selectable: model => eligible.has(model),
257
258
  clients: model => !eligible.has(model) ? [] : model.publisher?.toLowerCase() === "anthropic" ? ["claude_code", "claude_app"] : ["codex"],
@@ -36,3 +36,15 @@ export function catalogFailure(response, body, { checkedAt, lastSuccessAt } = {}
36
36
  return m365CatalogDiagnostic({ stage: "catalog", cause_code, http_status: code, checked_at: checkedAt,
37
37
  last_success_at: lastSuccessAt, request_id: response.headers.get("request-id") || response.headers.get("x-ms-request-id") });
38
38
  }
39
+
40
+ export function m365CatalogRead(value) {
41
+ if (!value || !["network", "cache"].includes(value.source) || !date(value.checked_at)
42
+ || !["total", "claude", "gpt", "filtered"].every(key => Number.isInteger(value[key]) && value[key] >= 0 && value[key] <= 1000)
43
+ || value.claude + value.gpt + value.filtered !== value.total) return null;
44
+ const identifier = id => typeof id === "string" && /^[a-zA-Z0-9_-]{1,80}$/.test(id) && !/^(?:github_pat_|gh[pousr]_|sk-|eyJ)/.test(id) ? id : null;
45
+ return { source: value.source, checked_at: value.checked_at, total: value.total, claude: value.claude, gpt: value.gpt, filtered: value.filtered,
46
+ request_id: identifier(value.request_id), client_correlation_id: identifier(value.client_correlation_id),
47
+ http_status: value.source === "network" && value.http_status === 200 ? 200 : null,
48
+ local_cache_used: value.source === "cache", http_revalidation_requested: value.source === "network" && value.http_revalidation_requested === true,
49
+ response_age_seconds: Number.isSafeInteger(value.response_age_seconds) && value.response_age_seconds >= 0 && value.response_age_seconds <= 604800 ? value.response_age_seconds : null };
50
+ }
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { m365Paths, readM365Json, writeM365Json, m365AccountKey } from "../m365-settings.mjs";
3
3
  import { withFileLockSync } from "../lock.mjs";
4
4
  import fs from "node:fs";
5
+ import { messagesHistoryTransferGrant } from "../messages-history-transfer.mjs";
5
6
 
6
7
  const changed = () => Object.assign(new Error("This conversation belongs to another company account. Start a new conversation."),
7
8
  { code: "m365_account_changed", statusCode: 409 });
@@ -10,7 +11,7 @@ const hash = value => createHash("sha256").update(value).digest("hex");
10
11
  export function createM365ConversationGuard({ home } = {}) {
11
12
  const { directory, conversations: file } = m365Paths({ home });
12
13
  let cached;
13
- return (account, body, headers = {}) => {
14
+ return (account, body, headers = {}, options = {}) => {
14
15
  const items = Array.isArray(body.messages) ? body.messages : Array.isArray(body.input) ? body.input : [];
15
16
  let session = headers["session_id"] || headers["session-id"] || headers["x-conversation-id"] || headers["x-claude-code-session-id"];
16
17
  if (!session && typeof body.metadata?.user_id === "string") {
@@ -24,6 +25,9 @@ export function createM365ConversationGuard({ home } = {}) {
24
25
  || Array.isArray(item?.content) && item.content.some(part => part?.type === "tool_result"));
25
26
  if (!key) { if (account.history_isolation && hasHistory) throw changed();return; }
26
27
  const owner = m365AccountKey(account);
28
+ const grant = messagesHistoryTransferGrant(body), authorized = Boolean(grant && grant.profile === options.profile);
29
+ const noncommitting = options.countTokens || authorized && grant.noncommitting;
30
+ if (noncommitting && !hasHistory) return;
27
31
  if (cached?.[key] === owner) return;
28
32
  if (cached?.[key] && cached[key] !== owner) throw changed();
29
33
  fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
@@ -32,7 +36,8 @@ export function createM365ConversationGuard({ home } = {}) {
32
36
  if (!saved.owners || typeof saved.owners !== "object" || Array.isArray(saved.owners)
33
37
  || Object.keys(saved.owners).length > 1024 || Object.entries(saved.owners).some(([id, value]) => !/^[a-f0-9]{64}$/.test(id) || !/^[a-f0-9]{64}$/.test(value))) throw changed();
34
38
  const owners = saved.owners;
35
- if (owners[key] && owners[key] !== owner || !owners[key] && account.history_isolation && hasHistory) throw changed();
39
+ if (owners[key] && owners[key] !== owner || !owners[key] && account.history_isolation && hasHistory && !(authorized && grant.initial)) throw changed();
40
+ if (noncommitting) return;
36
41
  if (owners[key]) { cached = owners;return; }
37
42
  owners[key] = owner;
38
43
  while (Object.keys(owners).length > 1024) delete owners[Object.keys(owners)[0]];
@@ -16,7 +16,7 @@ import { resolveClaudeModel } from "../claude-models.mjs";
16
16
  import { modelReasoningEfforts } from "../provider-metadata.mjs";
17
17
  import { limitM365CacheTtl } from "./m365-messages-policy.mjs";
18
18
  import { createM365ConversationGuard } from "./m365-conversation-accounts.mjs";
19
- import { catalogFailure, m365CatalogDiagnostic } from "./m365-catalog-diagnostic.mjs";
19
+ import { catalogFailure, m365CatalogDiagnostic, m365CatalogRead } from "./m365-catalog-diagnostic.mjs";
20
20
  import { m365NetworkDiagnostic } from "./m365-network-diagnostic.mjs";
21
21
 
22
22
  import { M365_API_BASE, M365_API_ORIGIN } from "./m365-endpoint.mjs";
@@ -77,7 +77,7 @@ export function createM365Provider({ home, env = process.env, account: accountOv
77
77
  const guardConversation = createM365ConversationGuard({ home });
78
78
  let catalog = null, account = null, catalogAt = 0, state = "idle", reason = null, flight = null, controller = null, generation = 0;
79
79
  let network = null, networkFlight = null, cacheTtlAdjustments = 0;
80
- let networkDiagnostic = null, catalogDiagnostic = null;
80
+ let networkDiagnostic = null, catalogDiagnostic = null, catalogRead = null, lastCatalogResponse = null;
81
81
  const registry = { models: null, source: "unavailable", cacheState: "none", cacheSavedAtMs: null,
82
82
  refreshInFlight: false, generation: 0, lastError: null, lastErrorAtMs: null };
83
83
  const profile = () => account ? `m365:${M365_API_ORIGIN}:${m365AccountKey(account)}` : "m365:unavailable";
@@ -95,17 +95,23 @@ export function createM365Provider({ home, env = process.env, account: accountOv
95
95
  }
96
96
  return networkFlight;
97
97
  }
98
- function applyCatalog(value, source, savedAt) {
98
+ function readObservation(value, source, savedAt, evidence = {}) {
99
+ const claude = m365Models(value, "claude").length, gpt = m365Models(value, "gpt").length;
100
+ return m365CatalogRead({ ...evidence, source: source === "live" ? "network" : "cache", checked_at: new Date(savedAt).toISOString(),
101
+ total: value.data.length, claude, gpt, filtered: value.data.length - claude - gpt });
102
+ }
103
+ function applyCatalog(value, source, savedAt, evidence) {
99
104
  catalog = m365Catalog(value);catalogAt = savedAt;
100
105
  registry.models = { data: m365Models(catalog, "gpt").map(model => ({ ...model,
101
106
  vendor: "OpenAI", model_picker_enabled: true, policy: { state: "enabled" } })) };
102
107
  registry.source = source;registry.cacheSavedAtMs = savedAt;registry.cacheState = now() - savedAt < SOFT_TTL_MS ? "fresh" : "stale";
108
+ catalogRead = readObservation(catalog, source, savedAt, source === "live" ? lastCatalogResponse : evidence);
103
109
  }
104
110
  try {
105
111
  account = accountOverride || readM365Account({ home });
106
112
  const saved = readM365Json(paths.catalog);
107
113
  if (account && saved?.service_origin === M365_API_ORIGIN && saved.account_key === m365AccountKey(account) && Number.isFinite(saved.saved_at)
108
- && now() - saved.saved_at < HARD_TTL_MS) applyCatalog(saved.models, "cache", saved.saved_at);
114
+ && now() - saved.saved_at < HARD_TTL_MS) applyCatalog(saved.models, "cache", saved.saved_at, m365CatalogRead(saved.catalog_read));
109
115
  } catch { reason = "m365_cache_unavailable"; }
110
116
 
111
117
  async function request(endpoint, body, options = {}) {
@@ -116,6 +122,7 @@ export function createM365Provider({ home, env = process.env, account: accountOv
116
122
  const requestHeaders = m365Headers(credential.token, { ...options,
117
123
  conversationId: body ? m365ConversationId(body, options.headers, m365AccountKey(credential.account)) : undefined,
118
124
  stream: body?.stream === true });
125
+ if (endpoint === "/models") { requestHeaders["Cache-Control"] = "no-cache";requestHeaders.Pragma = "no-cache"; }
119
126
  const serialized = body ? options.bodyText ?? JSON.stringify(body) : undefined;
120
127
  if (serialized !== undefined) requestHeaders["Content-Length"] = String(Buffer.byteLength(serialized));
121
128
  options.onUpstreamStart?.();
@@ -124,6 +131,12 @@ export function createM365Provider({ home, env = process.env, account: accountOv
124
131
  const send = fetchImpl || await transport(options.signal);
125
132
  const response = await send(`${M365_API_BASE}${endpoint}`, { method: body ? "POST" : "GET", headers: requestHeaders,
126
133
  ...(serialized !== undefined ? { body: serialized } : {}), signal: options.signal, redirect: "manual" });
134
+ if (endpoint === "/models") {
135
+ const age = response.headers.get("age");
136
+ lastCatalogResponse = { http_status: response.status, request_id: response.headers.get("request-id") || response.headers.get("x-ms-request-id") || response.headers.get("x-request-id"),
137
+ client_correlation_id: requestHeaders["X-ClientCorrelationId"], http_revalidation_requested: true,
138
+ response_age_seconds: age !== null && /^\d+$/.test(age) ? Number(age) : null };
139
+ }
127
140
  if (response.ok) return response;
128
141
  const raw = await readBoundedResponseText(response, { maxBytes: MAX_UPSTREAM_ERROR_BODY_BYTES, label: "M365 error", signal: options.signal });
129
142
  const safe = raw.split(credential.token).join("[redacted]");
@@ -155,7 +168,8 @@ export function createM365Provider({ home, env = process.env, account: accountOv
155
168
  if (current !== generation || signal.aborted) throw m365Error("m365_refresh_cancelled");
156
169
  const savedAt = now();
157
170
  const nextAccount = { ...credential.account, ...(account?.history_isolation ? { history_isolation: true } : {}) };
158
- if (persist) writeM365Binding(nextAccount, { account_key: m365AccountKey(nextAccount), service_origin: M365_API_ORIGIN, saved_at: savedAt, models: value }, { home, expectedAccount: account });
171
+ if (persist) writeM365Binding(nextAccount, { account_key: m365AccountKey(nextAccount), service_origin: M365_API_ORIGIN, saved_at: savedAt, models: value,
172
+ catalog_read: readObservation(value, "live", savedAt, lastCatalogResponse) }, { home, expectedAccount: account });
159
173
  account = nextAccount;
160
174
  applyCatalog(value, "live", savedAt);catalogDiagnostic = null;state = "ready";reason = null;registry.lastError = null;registry.lastErrorAtMs = null;
161
175
  try { await onCatalog(value); } catch { log("warn", "M365 models are ready; optional client configuration could not be updated"); }
@@ -211,7 +225,7 @@ export function createM365Provider({ home, env = process.env, account: accountOv
211
225
  async messages(body, options = {}) {
212
226
  if (catalog && now() - catalogAt >= SOFT_TTL_MS && !flight) void refresh().catch(() => {});
213
227
  const model = selectedModel(body.model, "claude");
214
- if (account) guardConversation(account, body, options.headers);
228
+ if (account) guardConversation(account, body, options.headers, { profile: profile(), countTokens: options.countTokens === true });
215
229
  const efforts = modelReasoningEfforts(model);
216
230
  if (body.output_config?.effort !== undefined && efforts && !efforts.includes(body.output_config.effort)) {
217
231
  throw protocolError("m365_effort_unavailable", "The selected effort is not advertised by this model. Refresh its model list and select an available effort.");
@@ -253,7 +267,8 @@ export function createM365Provider({ home, env = process.env, account: accountOv
253
267
  },
254
268
  commitSelection(expectedAccount) {
255
269
  if (!catalog || state !== "ready" || !account) throw m365Error("m365_not_ready");
256
- writeM365Binding(account, { account_key: m365AccountKey(account), service_origin: M365_API_ORIGIN, saved_at: catalogAt, models: catalog }, { home, expectedAccount });
270
+ writeM365Binding(account, { account_key: m365AccountKey(account), service_origin: M365_API_ORIGIN, saved_at: catalogAt, models: catalog,
271
+ catalog_read: m365CatalogRead(catalogRead) }, { home, expectedAccount });
257
272
  persist = true;
258
273
  },
259
274
  snapshot: () => ({ ...auth.snapshot(), state, reason: reason || auth.snapshot().reason, account: account ? { login: account.login, tenant: account.tenant, selection_source: account.selection_source || "legacy" } : null,
@@ -261,6 +276,7 @@ export function createM365Provider({ home, env = process.env, account: accountOv
261
276
  network: network?.snapshot() || null,
262
277
  network_diagnostic: networkDiagnostic ? { ...networkDiagnostic } : null,
263
278
  catalog_diagnostic: m365CatalogDiagnostic(catalogDiagnostic),
279
+ catalog_read: m365CatalogRead(catalogRead),
264
280
  cache_ttl_adjustments: cacheTtlAdjustments,
265
281
  models: { total: catalog?.data.length || 0, claude: m365Models(catalog, "claude").length, gpt: m365Models(catalog, "gpt").length,
266
282
  source: registry.source, refreshed_at: catalogAt ? new Date(catalogAt).toISOString() : null }, refresh_in_flight: Boolean(flight) }),
@@ -176,6 +176,13 @@ export function buildHttpFailureDetails({ statusCode, route, requestId, model, c
176
176
  ccdx_model_ambiguous: "This model name matches multiple sources. Select its source-specific entry.",
177
177
  ccdx_model_catalog_unavailable: "The selected model is not currently available in its source catalog.",
178
178
  ccdx_client_source_disabled: "This app or its model source is turned off." };
179
+ for (const prefix of ["source_changed", "prefix_changed"]) {
180
+ reasons[`${prefix}_tool_call_pending`] = "A tool call is still waiting for its result. Finish the current turn before switching.";
181
+ reasons[`${prefix}_tool_result_unmatched`] = "A tool result has no matching call. Restore complete history before switching.";
182
+ reasons[`${prefix}_tool_history_invalid`] = "The tool history is incomplete. Restore complete history before switching.";
183
+ reasons[`${prefix}_active_tool_turn`] = prefix === "prefix_changed" ? "History changed during a tool turn. Finish the current turn before switching."
184
+ : "A tool turn is still active on the previous source. Finish it before switching.";
185
+ }
179
186
  const message = (Object.hasOwn(reasons, reason) ? reasons[reason] : null) || (route === "messages_count_tokens" && statusCode === 404 ? "The source's token-count endpoint returned HTTP 404. Message generation is separate."
180
187
  : code === "ccdx_api_network_unavailable" ? "Connection to the model source failed."
181
188
  : origin === "client_validation" ? "The request was rejected locally before an upstream call."