codex-copilot-dx 1.2.28 → 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 +3 -3
- package/docs/ARCHITECTURE.md +27 -2
- package/docs/REFERENCE.md +42 -2
- package/package.json +1 -1
- package/src/adapter.mjs +1 -1
- package/src/claude-gateway.mjs +2 -1
- package/src/connection-runtime.mjs +40 -6
- package/src/dashboard/connections.js +25 -1
- package/src/dashboard/index.html +5 -2
- package/src/dashboard/language.js +22 -0
- package/src/dashboard/tools.js +48 -4
- package/src/dashboard/ui.css +8 -0
- package/src/dashboard/ui.js +17 -2
- package/src/dashboard-api.mjs +2 -1
- package/src/messages-history-transfer.mjs +74 -23
- package/src/provider-runtime.mjs +9 -8
- package/src/providers/m365-catalog-diagnostic.mjs +12 -0
- package/src/providers/m365.mjs +22 -6
- package/src/response-failures.mjs +7 -0
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.
|
|
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
|
|
|
@@ -56,13 +56,13 @@ Run `ccdx web` without GitHub sign-in. In **Model sources → Add API**, enter t
|
|
|
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.
|
|
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.
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -145,8 +145,17 @@ handles. New-source thinking after the checkpoint stays unchanged. Changed
|
|
|
145
145
|
prefixes can be rebuilt only at a completed tool boundary. It adds no automatic
|
|
146
146
|
retry, summary inference, routing fallback or conversation database.
|
|
147
147
|
|
|
148
|
-
Transfer records are bounded to 1024 hashed keys
|
|
149
|
-
they contain owner hashes, prefix hashes and
|
|
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.
|
|
150
159
|
Count/model-validation requests do not rebind. A per-conversation request lease
|
|
151
160
|
pins active source work; the gateway commits a checkpoint immediately before
|
|
152
161
|
delivering usable output/tool/private state and releases every lease on failure
|
|
@@ -157,6 +166,15 @@ owners are still refused. Native Responses recovery/configuration is unchanged.
|
|
|
157
166
|
|
|
158
167
|
`dashboard/connections.js` owns settings forms; application source/review and
|
|
159
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.
|
|
160
178
|
Its binding draft retains selected identities independently from current catalog
|
|
161
179
|
availability. Missing selections stay visible and cannot be silently dropped on save.
|
|
162
180
|
Full configuration is on-demand; ordinary status uses compact cached summaries.
|
|
@@ -423,6 +441,13 @@ settlement for two seconds; no successful plaintext cache or transcript index ex
|
|
|
423
441
|
## Dashboard reads
|
|
424
442
|
|
|
425
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
|
+
|
|
426
451
|
|
|
427
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.
|
|
428
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.
|
|
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
|
|
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
|
|
|
@@ -2215,6 +2215,46 @@ survive ordinary service restart; corrupt records are preserved and reported,
|
|
|
2215
2215
|
not replaced with empty defaults. This does not persist Responses history or
|
|
2216
2216
|
change Codex login/provider/model-list configuration.
|
|
2217
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
|
+
|
|
2218
2258
|
### Upstream maker metadata
|
|
2219
2259
|
|
|
2220
2260
|
Manual API discovery accepts bounded text from publisher, vendor and owned_by.
|
package/package.json
CHANGED
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)
|
package/src/claude-gateway.mjs
CHANGED
|
@@ -228,10 +228,11 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
228
228
|
const diagnostic = error.code === "ccdx_api_network_unavailable" ? transportErrorDetails(error) : null;
|
|
229
229
|
log(outcome === "cancelled" ? "info" : "warn", `Claude request ${requestId}: ${detail.code}${diagnostic ? ` (${diagnostic.code}, ${diagnostic.phase})` : ""}`);
|
|
230
230
|
tracker?.setErrorOrigin(terminalOrigin);
|
|
231
|
-
context.onHttpError?.({ code: detail.code, origin: terminalOrigin, ...(diagnostic ? { transport: diagnostic } : {}) });
|
|
231
|
+
context.onHttpError?.({ code: detail.code, origin: terminalOrigin, ...(rejectionReason ? { reason: rejectionReason } : {}), ...(diagnostic ? { transport: diagnostic } : {}) });
|
|
232
232
|
if (outcome === "cancelled") return;
|
|
233
233
|
if (!res.headersSent) {
|
|
234
234
|
const value = apiError(abort.reason || error.code || "ccdx_gateway_error", message);
|
|
235
|
+
if (rejectionReason) value.error.reason = rejectionReason;
|
|
235
236
|
if (diagnostic) value.error.diagnostic = diagnostic;
|
|
236
237
|
send(res, statusCode, value);
|
|
237
238
|
}
|
|
@@ -19,6 +19,7 @@ import { codexClientCatalog, codexSourceCatalog } from "./clients/codex-models.m
|
|
|
19
19
|
import { currentRequestContext } from "./request-context.mjs";
|
|
20
20
|
import { claudeSharedCapabilityPlan, syncClaudeCapabilities, inspectClaudeCapabilitySupport, inspectClaudeCapabilityConfiguration } from "./claude-capability-config.mjs";
|
|
21
21
|
import { deploymentModelId, resolveModelCapabilities, deploymentRevision } from "./model-capabilities.mjs";
|
|
22
|
+
import { m365Paths } from "./m365-settings.mjs";
|
|
22
23
|
|
|
23
24
|
const validObject = (value, keys) => value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).every(key => keys.includes(key));
|
|
24
25
|
export function createConnectionRuntime({ legacy, home, env = process.env, platform = process.platform, corePort = 2026,
|
|
@@ -29,6 +30,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
29
30
|
const messagesTransfer = createMessagesHistoryTransfer({ ...options, onTransfer: () => log("info", "Conversation continued on the selected source; original history kept") });
|
|
30
31
|
const memoryModel = createCodexMemoryModel({ ...options, corePort });
|
|
31
32
|
let settings = readAccessSettings(options), managed = fs.existsSync(accessSettingsPath(options)), serial = Promise.resolve(), keys, closed = false;
|
|
33
|
+
const legacyClaudeAccess = fs.existsSync(m365Paths(options).ownership);
|
|
32
34
|
const instances = new Map(), active = new Map(), retired = new Set(), handlers = new Map(), summaries = new WeakMap(), sourceSecrets = new WeakMap(), setup = {}, lastClients = {};
|
|
33
35
|
const retiredSecrets = new Map(), cleanups = new Set(), plans = new Map(), discoveries = new Map();
|
|
34
36
|
const catalogRefresh = createApiCatalogRefresh({ config: id => settings.apis.find(api => api.id === id), source: getSource, track,
|
|
@@ -49,7 +51,9 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
49
51
|
}
|
|
50
52
|
const identities = () => keys ||= readClientGatewayKeys(options);
|
|
51
53
|
const enabled = id => id?.startsWith("api_") ? settings.apis.find(api => api.id === id)?.enabled === true : settings.providers[id] === true;
|
|
52
|
-
const binding = id => managed ? settings.clients[id] : { ...settings.clients[id],
|
|
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 };
|
|
53
57
|
// GitHub-only selections retain the existing native loopback access contract.
|
|
54
58
|
// Any other deployment still requires the private per-client credential.
|
|
55
59
|
function codexAccessMode() {
|
|
@@ -113,7 +117,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
113
117
|
function editable() {
|
|
114
118
|
if (managed) return structuredClone(settings);
|
|
115
119
|
const next = structuredClone(settings);next.providers.m365 = legacy.snapshot().m365.enabled === true;
|
|
116
|
-
for (const id of CLIENT_IDS) next.clients[id]
|
|
120
|
+
for (const id of CLIENT_IDS) next.clients[id] = { ...binding(id) };
|
|
117
121
|
return next;
|
|
118
122
|
}
|
|
119
123
|
function save(next) {
|
|
@@ -148,6 +152,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
148
152
|
route_id: deploymentModelId(source, model.id), capability: model.capability || resolveModelCapabilities(model, { builtin: true }) }))), sync: sharedSync, support: capabilitySupport } }) })), managed, m365_state: state.m365.state });
|
|
149
153
|
}
|
|
150
154
|
async function syncClients(ids = CLIENT_IDS) {
|
|
155
|
+
if (!ids.length) return;
|
|
151
156
|
for (const id of ids) syncTargets.add(id);
|
|
152
157
|
syncAgain = true;if (syncFlight) return syncFlight;
|
|
153
158
|
syncFlight = (async () => { do { syncAgain = false;const targets = new Set(syncTargets);syncTargets.clear();await performClientSync(targets); } while (syncAgain && !closed); })();
|
|
@@ -191,6 +196,10 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
191
196
|
if (["claude_app", "claude_code"].some(id => setup[id] === "default_unavailable")) {
|
|
192
197
|
sharedSync = { ...sharedSync, state: "partially_preserved", limitations: [{ code: "default_model_unavailable" }] };return;
|
|
193
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
|
+
}
|
|
194
203
|
const shared = claudeSharedCapabilityPlan({ app: setup.claude_app === "configured" ? plan("claude_app").models : [],
|
|
195
204
|
code: setup.claude_code === "configured" ? plan("claude_code").models : [], support: capabilitySupport });
|
|
196
205
|
if (["claude_app", "claude_code"].some(id => setup[id] === "manual_sync")) {
|
|
@@ -232,7 +241,29 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
232
241
|
if (closed) throw accessError("ccdx_connections_closed", 503);
|
|
233
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");
|
|
234
243
|
const next = editable();let freshRef, previousRef;
|
|
235
|
-
if (input.operation === "
|
|
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") {
|
|
236
267
|
const existing = next.apis.find(api => api.id === input.id);
|
|
237
268
|
if (!existing && next.apis.length >= 16) throw accessError("ccdx_api_limit");
|
|
238
269
|
if (!validObject(input.config, ["name", "base_url", "endpoints", "auth_header", "models", "key_env", "model_display"])) throw accessError("ccdx_api_config_invalid");
|
|
@@ -355,6 +386,9 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
355
386
|
}
|
|
356
387
|
return {
|
|
357
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))); },
|
|
358
392
|
source: getSource,
|
|
359
393
|
connections: snapshot,
|
|
360
394
|
privateScopes: id => [...new Set(plan(id).models.map(model => model.source_id))].sort().map(source => [source, getSource(source).profileId(id === "codex" ? "responses" : "messages")]),
|
|
@@ -454,7 +488,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
454
488
|
return { historyNamespace: target.profileId() };
|
|
455
489
|
},
|
|
456
490
|
async handleClaude(req, res) {
|
|
457
|
-
if (!managed) return legacy.handleClaude(req, res);
|
|
491
|
+
if (!managed) { if (!legacyClaudeAccess) throw accessError("ccdx_client_source_disabled", 503);return legacy.handleClaude(req, res); }
|
|
458
492
|
if (!settings.claude_private_keys) {
|
|
459
493
|
if (["claude_app", "claude_code"].every(id => permitted(id, "m365") && binding(id).source === "m365")) return legacy.handleClaude(req, res);
|
|
460
494
|
throw accessError("ccdx_client_source_disabled", 503);
|
|
@@ -524,9 +558,9 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
524
558
|
model: input.model, auto_review_model: input.auto_review_model, auto_review_effort: input.auto_review_effort });return this.snapshot(); }
|
|
525
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(); }
|
|
526
560
|
if (input.action === "auto-review" && managed && legacy.selection().codex !== "github") await legacy.action({ action: "switch", provider: "github" });
|
|
527
|
-
if (managed && input.action === "switch" && !
|
|
561
|
+
if (managed && input.action === "switch" && !enabled(input.provider)) throw accessError("ccdx_client_source_disabled", 503);
|
|
528
562
|
const result = await legacy.action(input);
|
|
529
|
-
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"]); }
|
|
530
564
|
return result;
|
|
531
565
|
},
|
|
532
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(); },
|
|
@@ -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]) => {
|
package/src/dashboard/index.html
CHANGED
|
@@ -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
|
|
216
|
-
<
|
|
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 & 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.", "本页改动有效后自动保存。"],
|
package/src/dashboard/tools.js
CHANGED
|
@@ -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 {
|
|
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();
|
package/src/dashboard/ui.css
CHANGED
|
@@ -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; }
|
package/src/dashboard/ui.js
CHANGED
|
@@ -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
|
-
|
|
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);
|
package/src/dashboard-api.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import os from "node:os";
|
|
2
2
|
import { isProviderId } from "./provider-metadata.mjs";
|
|
3
|
-
import { m365CatalogDiagnostic } from "./providers/m365-catalog-diagnostic.mjs";
|
|
3
|
+
import { m365CatalogDiagnostic, m365CatalogRead } from "./providers/m365-catalog-diagnostic.mjs";
|
|
4
4
|
import { m365NetworkDiagnostic } from "./providers/m365-network-diagnostic.mjs";
|
|
5
5
|
import { fetchLiveCopilotModels } from "./live-models.mjs";
|
|
6
6
|
import { authStatus } from "./auth-status.mjs";
|
|
@@ -309,6 +309,7 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
309
309
|
checked_at: ["catalog", "configured"].includes(catalog.source) ? catalog.checkedAt : new Date().toISOString(),
|
|
310
310
|
upstream_host: safeText(catalog?.upstreamHost || "GitHub Copilot", 120),
|
|
311
311
|
advertised: finite(catalog?.advertised),
|
|
312
|
+
...(m365CatalogRead(catalog?.catalogRead) ? { catalog_read: m365CatalogRead(catalog.catalogRead) } : {}),
|
|
312
313
|
selectable: models.filter(model => model.selectable !== false).length,
|
|
313
314
|
models: models.slice(0, 500).map((model) => ({
|
|
314
315
|
id: safeText(model.id, 160),
|
|
@@ -3,16 +3,19 @@ import path from "node:path";
|
|
|
3
3
|
import { createHash } from "node:crypto";
|
|
4
4
|
import { accessSettingsPath } from "./access-settings.mjs";
|
|
5
5
|
import { readBoundedFileSync } from "./bounded-file.mjs";
|
|
6
|
-
import {
|
|
6
|
+
import { atomicWriteFilePairSync } from "./atomic-file.mjs";
|
|
7
7
|
import { withFileLockSync } from "./lock.mjs";
|
|
8
8
|
|
|
9
9
|
const grants = new WeakMap(), HASH = /^[a-f0-9]{64}$/, LIMIT = 1024;
|
|
10
10
|
const digest = value => createHash("sha256").update(JSON.stringify(value, (key, entry) => key === "cache_control" ? undefined : entry)).digest("hex");
|
|
11
|
+
const semanticDigest = value => createHash("sha256").update(JSON.stringify(value, (_key, entry) => entry && typeof entry === "object" && !Array.isArray(entry)
|
|
12
|
+
? Object.fromEntries(Object.keys(entry).sort().map(key => [key, entry[key]])) : entry)).digest("hex");
|
|
11
13
|
const parts = message => Array.isArray(message?.content) ? message.content : [];
|
|
12
14
|
const thinking = part => ["thinking", "redacted_thinking", "reasoning"].includes(part?.type);
|
|
13
15
|
const history = body => body.messages.some(message => message?.role === "assistant" || parts(message).some(part => part?.type === "tool_result"))
|
|
14
16
|
|| body.messages.filter(message => message?.role === "user").length > 1;
|
|
15
|
-
const fail = (code, message) => { throw Object.assign(new Error(message), { code, statusCode: 409
|
|
17
|
+
const fail = (code, message, reason) => { throw Object.assign(new Error(message), { code, statusCode: 409,
|
|
18
|
+
...(reason ? { jsonBody: { type: "error", error: { type: "invalid_request_error", code, message, reason } } } : {}) }); };
|
|
16
19
|
const invalidState = () => fail("ccdx_history_transfer_state_invalid", "History transfer records could not be read. Existing records and conversation were kept.");
|
|
17
20
|
|
|
18
21
|
// Only a locally prepared request can carry this grant; HTTP fields cannot set it.
|
|
@@ -22,15 +25,49 @@ export const messagesHistoryTransferGrant = body => {
|
|
|
22
25
|
export function messagesTransferPath(options = {}) {
|
|
23
26
|
return path.join(path.dirname(accessSettingsPath(options)), "conversation-transfers.json");
|
|
24
27
|
}
|
|
25
|
-
function checkedRecords(value) {
|
|
28
|
+
function checkedRecords(value, canonical = false) {
|
|
26
29
|
if (!value || value.version !== 1 || !value.records || typeof value.records !== "object" || Array.isArray(value.records)
|
|
27
30
|
|| Object.keys(value).some(key => !["version", "records"].includes(key)) || Object.keys(value.records).length > LIMIT) invalidState();
|
|
28
31
|
for (const [key, record] of Object.entries(value.records)) {
|
|
29
|
-
if (!HASH.test(key) || !record || Object.keys(record).some(key => !["owner", "count", "prefix"].includes(key))
|
|
32
|
+
if (!HASH.test(key) || !record || Object.keys(record).some(key => !(canonical ? ["owner", "count", "prefix", "raw_count", "raw_prefix"] : ["owner", "count", "prefix"]).includes(key))
|
|
30
33
|
|| !HASH.test(record.owner) || !HASH.test(record.prefix) || !Number.isSafeInteger(record.count) || record.count < 1 || record.count > 1_000_000) invalidState();
|
|
34
|
+
if (canonical && (!HASH.test(record.raw_prefix) || !Number.isSafeInteger(record.raw_count) || record.raw_count < 1 || record.raw_count > 1_000_000)) invalidState();
|
|
31
35
|
}
|
|
32
36
|
return value.records;
|
|
33
37
|
}
|
|
38
|
+
function canonicalBlock(block) {
|
|
39
|
+
if (!block || typeof block !== "object") return block;
|
|
40
|
+
const { cache_control, ...value } = block;
|
|
41
|
+
if (block.type === "tool_result" && Array.isArray(block.content)) value.content = block.content.map(canonicalBlock);
|
|
42
|
+
return value;
|
|
43
|
+
}
|
|
44
|
+
function canonicalItems(messages) {
|
|
45
|
+
const out = [];
|
|
46
|
+
for (const message of messages) {
|
|
47
|
+
if (!message || typeof message !== "object" || !["user", "assistant"].includes(message.role)) fail("ccdx_history_transfer_invalid", "Message history is incomplete or invalid.");
|
|
48
|
+
const { content, cache_control, ...fields } = message;
|
|
49
|
+
const blocks = typeof content === "string" ? [{ type: "text", text: content }] : content;
|
|
50
|
+
if (!Array.isArray(blocks)) fail("ccdx_history_transfer_invalid", "Message history is incomplete or invalid.");
|
|
51
|
+
for (const block of blocks.length ? blocks : [null]) out.push({ ...fields, block: canonicalBlock(block) });
|
|
52
|
+
}
|
|
53
|
+
return out;
|
|
54
|
+
}
|
|
55
|
+
function checkpoint(owner, messages) {
|
|
56
|
+
const items = canonicalItems(messages), raw = { owner, count: messages.length, prefix: digest(messages) };
|
|
57
|
+
return { raw, canonical: { owner, count: items.length, prefix: semanticDigest(items), raw_count: raw.count, raw_prefix: raw.prefix } };
|
|
58
|
+
}
|
|
59
|
+
function knownPrefix(entry, messages, items) {
|
|
60
|
+
if (entry.canonical) return items.length >= entry.canonical.count
|
|
61
|
+
&& semanticDigest(items.slice(0, entry.canonical.count)) === entry.canonical.prefix ? { count: entry.canonical.count } : null;
|
|
62
|
+
if (messages.length < entry.count) return null;
|
|
63
|
+
const prefix = messages.slice(0, entry.count);
|
|
64
|
+
const forms = [prefix,
|
|
65
|
+
prefix.map(message => typeof message.content === "string" ? { ...message, content: [{ type: "text", text: message.content }] } : message),
|
|
66
|
+
prefix.map(message => Array.isArray(message.content) && message.content.length === 1 && message.content[0]?.type === "text"
|
|
67
|
+
&& Object.keys(message.content[0]).every(key => ["type", "text"].includes(key)) ? { ...message, content: message.content[0].text } : message)];
|
|
68
|
+
if (!forms.some(form => digest(form) === entry.prefix)) return null;
|
|
69
|
+
const migrated = checkpoint(entry.owner, prefix);return { count: migrated.canonical.count, migrated };
|
|
70
|
+
}
|
|
34
71
|
function checkBlocks(blocks) {
|
|
35
72
|
for (const part of blocks) {
|
|
36
73
|
if (thinking(part)) continue;
|
|
@@ -59,29 +96,30 @@ function checkHistory(body, counting) {
|
|
|
59
96
|
if (!message || !["user", "assistant"].includes(message.role) || !(typeof message.content === "string" || Array.isArray(message.content))) {
|
|
60
97
|
fail("ccdx_history_transfer_invalid", "Message history is incomplete or invalid. The original conversation was kept.");
|
|
61
98
|
}
|
|
62
|
-
if (message.role === "assistant" && pending.size) fail("ccdx_history_transfer_tool_incomplete", "Finish the current tool operation before switching. No tool was repeated.");
|
|
99
|
+
if (message.role === "assistant" && pending.size) fail("ccdx_history_transfer_tool_incomplete", "Finish the current tool operation before switching. No tool was repeated.", "tool_call_pending");
|
|
63
100
|
checkBlocks(parts(message));
|
|
64
101
|
for (const part of parts(message)) {
|
|
65
102
|
if (part.type === "tool_use") {
|
|
66
|
-
if (message.role !== "assistant" || typeof part.id !== "string" || pending.has(part.id)) fail("ccdx_history_transfer_tool_incomplete", "Tool history is incomplete. Finish the current operation before switching.");
|
|
103
|
+
if (message.role !== "assistant" || typeof part.id !== "string" || pending.has(part.id)) fail("ccdx_history_transfer_tool_incomplete", "Tool history is incomplete. Finish the current operation before switching.", "tool_history_invalid");
|
|
67
104
|
pending.add(part.id);
|
|
68
105
|
}
|
|
69
106
|
if (part.type === "tool_result" && (message.role !== "user" || !pending.delete(part.tool_use_id))) {
|
|
70
|
-
fail("ccdx_history_transfer_tool_incomplete", "A tool result has no matching call. Restore complete history before switching.");
|
|
107
|
+
fail("ccdx_history_transfer_tool_incomplete", "A tool result has no matching call. Restore complete history before switching.", "tool_result_unmatched");
|
|
71
108
|
}
|
|
72
109
|
}
|
|
73
110
|
}
|
|
74
111
|
if (!counting && (pending.size || parts(body.messages.at(-1)).some(part => ["tool_use", "tool_result"].includes(part.type)))) {
|
|
75
|
-
fail("ccdx_history_transfer_tool_incomplete", "Finish the current tool operation before switching. No tool was repeated.");
|
|
112
|
+
fail("ccdx_history_transfer_tool_incomplete", "Finish the current tool operation before switching. No tool was repeated.", pending.size ? "tool_call_pending" : "active_tool_turn");
|
|
76
113
|
}
|
|
77
114
|
}
|
|
78
115
|
function project(body, count) {
|
|
79
|
-
let removed = 0;
|
|
80
|
-
body.messages = body.messages.map(
|
|
81
|
-
|
|
116
|
+
let removed = 0, index = 0;
|
|
117
|
+
body.messages = body.messages.map(message => {
|
|
118
|
+
const start = index;index += Array.isArray(message.content) ? Math.max(1, message.content.length) : 1;
|
|
119
|
+
if (start >= count || message.role !== "assistant") return message;
|
|
82
120
|
const out = { ...message };delete out.reasoning_content;
|
|
83
121
|
if (Array.isArray(message.content)) {
|
|
84
|
-
out.content = message.content.filter(part => { if (!thinking(part)) return true;removed++;return false; });
|
|
122
|
+
out.content = message.content.filter((part, offset) => { if (start + offset >= count || !thinking(part)) return true;removed++;return false; });
|
|
85
123
|
if (!out.content.length) return null;
|
|
86
124
|
}
|
|
87
125
|
return out;
|
|
@@ -92,17 +130,25 @@ function project(body, count) {
|
|
|
92
130
|
// Caller selects eligible clients. This module knows only Messages and source
|
|
93
131
|
// fingerprints; it neither changes routing nor stores conversation contents.
|
|
94
132
|
export function createMessagesHistoryTransfer(options = {}) {
|
|
95
|
-
const file = messagesTransferPath(options), active = new Map();let records;
|
|
96
|
-
function
|
|
97
|
-
try { return checkedRecords(JSON.parse(readBoundedFileSync(
|
|
133
|
+
const file = messagesTransferPath(options), canonicalFile = path.join(path.dirname(file), "conversation-prefixes.json"), active = new Map();let records;
|
|
134
|
+
function readFile(target, canonical = false) {
|
|
135
|
+
try { return checkedRecords(JSON.parse(readBoundedFileSync(target, { encoding: "utf8", maxBytes: 512 * 1024 })), canonical); }
|
|
98
136
|
catch (error) { if (error.code === "ENOENT") return {};invalidState(); }
|
|
99
137
|
}
|
|
138
|
+
function read() {
|
|
139
|
+
const raw = readFile(file), canonical = readFile(canonicalFile, true);
|
|
140
|
+
return Object.fromEntries(Object.entries(raw).map(([key, record]) => [key, { ...record,
|
|
141
|
+
...(canonical[key]?.owner === record.owner && canonical[key].raw_count === record.count && canonical[key].raw_prefix === record.prefix ? { canonical: canonical[key] } : {}) }]));
|
|
142
|
+
}
|
|
100
143
|
function save(key, record) {
|
|
101
144
|
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
102
145
|
withFileLockSync(`${file}.lock`, () => {
|
|
103
|
-
const next = read();delete next[key];next[key] = record;
|
|
146
|
+
const next = read();delete next[key];next[key] = { ...record.raw, canonical: record.canonical };
|
|
104
147
|
while (Object.keys(next).length > LIMIT) delete next[Object.keys(next)[0]];
|
|
105
|
-
|
|
148
|
+
const raw = Object.fromEntries(Object.entries(next).map(([key, { canonical, ...value }]) => [key, value]));
|
|
149
|
+
const canonical = Object.fromEntries(Object.entries(next).filter(([, value]) => value.canonical).map(([key, value]) => [key, value.canonical]));
|
|
150
|
+
checkedRecords({ version: 1, records: raw });checkedRecords({ version: 1, records: canonical }, true);
|
|
151
|
+
atomicWriteFilePairSync(file, JSON.stringify({ version: 1, records: raw }) + "\n", canonicalFile, JSON.stringify({ version: 1, records: canonical }) + "\n");records = next;
|
|
106
152
|
});
|
|
107
153
|
}
|
|
108
154
|
return { prepare({ key, owner, previousOwner, profile, body, countTokens = false, knownOwners = [] }) {
|
|
@@ -110,15 +156,15 @@ export function createMessagesHistoryTransfer(options = {}) {
|
|
|
110
156
|
records ||= read();const entry = records[key], changed = entry ? entry.owner !== owner : Boolean(previousOwner && previousOwner !== owner);
|
|
111
157
|
const initial = knownOwners.includes(entry?.owner || previousOwner);
|
|
112
158
|
const hasHistory = history(body), noncommitting = countTokens || Boolean(changed || entry) && !hasHistory;
|
|
159
|
+
const items = changed || entry ? canonicalItems(body.messages) : null;
|
|
113
160
|
if (noncommitting) {
|
|
114
161
|
if (changed || entry) {
|
|
115
162
|
checkHistory(body, true);
|
|
116
|
-
const count = entry?.owner === owner
|
|
117
|
-
? entry.count : body.messages.length;
|
|
163
|
+
const count = entry?.owner === owner ? knownPrefix(entry, body.messages, items)?.count ?? items.length : items.length;
|
|
118
164
|
project(body, count);
|
|
119
165
|
}
|
|
120
166
|
const grant = { profile, noncommitting: true, initial, active: true };grants.set(body, grant);
|
|
121
|
-
const
|
|
167
|
+
const nextCheckpoint = countTokens ? null : checkpoint(owner, body.messages);
|
|
122
168
|
let toolLease, committed = false;
|
|
123
169
|
return { handled: true, commit(state) {
|
|
124
170
|
// A no-history model probe must not pin the conversation. An actual
|
|
@@ -126,7 +172,7 @@ export function createMessagesHistoryTransfer(options = {}) {
|
|
|
126
172
|
if (countTokens || !state?.tool || committed) return;
|
|
127
173
|
const lease = active.get(key);
|
|
128
174
|
if (lease && lease.owner !== owner) fail("ccdx_history_transfer_busy", "Wait for the current response to finish before switching sources.");
|
|
129
|
-
save(key,
|
|
175
|
+
save(key, nextCheckpoint);committed = true;
|
|
130
176
|
toolLease = lease || { owner, count: 0 };toolLease.count++;active.set(key, toolLease);
|
|
131
177
|
}, release() {
|
|
132
178
|
grant.active = false;if (toolLease && --toolLease.count === 0) active.delete(key);toolLease = null;
|
|
@@ -137,9 +183,14 @@ export function createMessagesHistoryTransfer(options = {}) {
|
|
|
137
183
|
let candidate = null, removed = 0, grant;
|
|
138
184
|
if (changed || entry) {
|
|
139
185
|
let count;
|
|
140
|
-
|
|
186
|
+
const known = !changed ? knownPrefix(entry, body.messages, items) : null;
|
|
187
|
+
if (known) { count = known.count;candidate = known.migrated || null; }
|
|
141
188
|
else {
|
|
142
|
-
checkHistory(body, false);
|
|
189
|
+
try { checkHistory(body, false); } catch (error) {
|
|
190
|
+
if (error.jsonBody?.error?.reason) error.jsonBody.error.reason = `${changed ? "source_changed" : "prefix_changed"}_${error.jsonBody.error.reason}`;
|
|
191
|
+
throw error;
|
|
192
|
+
}
|
|
193
|
+
count = items.length;candidate = checkpoint(owner, body.messages);
|
|
143
194
|
}
|
|
144
195
|
removed = project(body, count);grant = { profile, noncommitting: false, initial, active: true };grants.set(body, grant);
|
|
145
196
|
}
|
package/src/provider-runtime.mjs
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
+
}
|
package/src/providers/m365.mjs
CHANGED
|
@@ -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
|
|
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
|
|
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"); }
|
|
@@ -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
|
|
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."
|