codex-copilot-dx 1.2.2 → 1.2.3
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 -2
- package/docs/ARCHITECTURE.md +4 -0
- package/docs/REFERENCE.md +13 -4
- package/package.json +1 -1
- package/src/adapter.mjs +2 -1
- package/src/cli-m365.mjs +27 -2
- package/src/cli-options.mjs +6 -5
- package/src/dashboard/console.js +49 -3
- package/src/dashboard/index.html +8 -0
- package/src/dashboard/language.js +24 -0
- package/src/dashboard-api.mjs +12 -1
- package/src/m365-settings.mjs +23 -1
- package/src/optional-routes.mjs +1 -1
- package/src/provider-management.mjs +3 -2
- package/src/provider-runtime.mjs +60 -5
- package/src/providers/m365-accounts.mjs +66 -0
- package/src/providers/m365-auth-helper.mjs +12 -10
- package/src/providers/m365-auth.mjs +13 -4
- package/src/providers/m365-conversation-accounts.mjs +42 -0
- package/src/providers/m365.mjs +19 -8
- package/src/service-control.mjs +5 -3
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ npm install -g codex-copilot-dx@latest
|
|
|
14
14
|
ccdx
|
|
15
15
|
```
|
|
16
16
|
|
|
17
|
-
No Node or Git? Download [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.
|
|
17
|
+
No Node or Git? Download [install.sh](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.3/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.3/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).
|
|
18
18
|
|
|
19
19
|
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.
|
|
20
20
|
|
|
@@ -44,6 +44,7 @@ The **Requests by source** section and `ccdx status` separate request outcomes b
|
|
|
44
44
|
| `ccdx usage` | Recorded tokens and upstream prompt-cache hit rate |
|
|
45
45
|
| `ccdx usage --provider ID` | Filter current or historical source-specific usage |
|
|
46
46
|
| `ccdx m365 status` / `models` | M365 authorization, Claude gateway and Claude models |
|
|
47
|
+
| `ccdx m365 accounts` / `account` | List local company accounts or select one; `account --id ID` supports scripts |
|
|
47
48
|
| `ccdx m365 switch` | Choose the Codex source; default remains GitHub |
|
|
48
49
|
| `ccdx m365 on` / `off` / `remove` | Enable discovery, restore owned client settings, or remove owned M365 state |
|
|
49
50
|
| `ccdx auto-review-model` | Select model, then reasoning effort; `0` follows client |
|
|
@@ -60,7 +61,7 @@ The **Requests by source** section and `ccdx status` separate request outcomes b
|
|
|
60
61
|
## Microsoft 365 access
|
|
61
62
|
|
|
62
63
|
Eligible macOS/Windows machines attempt silent Microsoft authorization at startup, without Copilot CLI or a browser login. MDM alone is insufficient: account, tenant,
|
|
63
|
-
device policy and Loki entitlement must permit access. Optional failure does not block GitHub.
|
|
64
|
+
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.
|
|
64
65
|
|
|
65
66
|
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
67
|
Existing custom/managed settings are preserved; already-running clients may need a normal restart.
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -61,6 +61,10 @@ fields that still match its own values. Foreign gateways and managed desktop
|
|
|
61
61
|
policies are not overwritten. Removing M365 does not remove shared management,
|
|
62
62
|
GitHub auth, prediction, image configuration or historical usage.
|
|
63
63
|
|
|
64
|
+
Company-account discovery and selection are separate from token acquisition. `providers/m365-accounts.mjs` normalizes/deduplicates broker identities, excludes consumer accounts and applies saved binding → unique exact system UPN → single-company-account selection. A bounded Windows system `whoami.exe /upn` lookup runs only for unbound multiple-account discovery; failure never guesses an identity. The short-lived native helper's `accounts` operation performs no token acquisition. `provider-runtime.mjs` owns explicit account changes: admission is paused for M365, a separate candidate validates one account/catalog, then the locked binding writer commits before provider/gateway replacement. GitHub is unaffected; failed candidates are discarded. CLI and the same-origin dashboard use this composition boundary rather than invoking authentication themselves.
|
|
65
|
+
|
|
66
|
+
`providers/m365-conversation-accounts.mjs` bounds account ownership metadata to 1024 hashed conversation keys, writes only on first association, and refuses cross-account or unknown old history after account changes. Response-history transfer between M365 account namespaces is disabled. Binding metadata retains selection provenance and history isolation across restarts; it contains no token. Catalogs remain account-fingerprinted. These controls do not establish Windows enrollment, model entitlement or successful inference, and no account is tried merely because another was refused.
|
|
67
|
+
|
|
64
68
|
### Existing service composition
|
|
65
69
|
|
|
66
70
|
The CLI composes the service. Client integration owns its `configure`, `start`,
|
package/docs/REFERENCE.md
CHANGED
|
@@ -13,6 +13,9 @@ or PM Studio patch. The core Codex provider remains GitHub until explicitly chan
|
|
|
13
13
|
```bash
|
|
14
14
|
ccdx m365 status
|
|
15
15
|
ccdx m365 models
|
|
16
|
+
ccdx m365 accounts
|
|
17
|
+
ccdx m365 account
|
|
18
|
+
ccdx m365 account --id aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
|
|
16
19
|
ccdx m365 switch
|
|
17
20
|
ccdx m365 switch m365 --model gpt-6-sol --auto-review-model gpt-6-sol
|
|
18
21
|
ccdx m365 switch github
|
|
@@ -37,9 +40,11 @@ short-lived Node helper. It discovers OS broker accounts and calls silent token
|
|
|
37
40
|
acquisition only. It neither launches a login UI nor reads Copilot CLI tokens.
|
|
38
41
|
macOS requires MDM enrollment and a working Microsoft Enterprise SSO broker;
|
|
39
42
|
Windows uses its Microsoft account broker. Tenant policy, device compliance,
|
|
40
|
-
account authorization and Loki entitlement still decide access.
|
|
41
|
-
|
|
42
|
-
|
|
43
|
+
account authorization and Loki entitlement still decide access. Saved bindings remain selected, including bindings created before account selection was added. Without a binding, Windows runs its system `whoami.exe /upn` once when multiple candidates exist (2.5-second limit) and accepts only a unique exact case-insensitive match with a discovered company account. It does not use the device enrollment identity, environment username, email suffix or list order. Local sign-ins, unsupported UPN lookup and shared UPNs fall back to a single company account or explicit selection. The Node broker has no explicit current-OS-account flag; a UPN match is not a SID/object-ID or device-compliance check. Entra/hybrid enterprise environments still need their own validation.
|
|
44
|
+
|
|
45
|
+
Duplicate stable account/tenant records are merged only when their identity metadata agrees. Conflicts and multiple remaining accounts require user action. Personal Microsoft consumer-tenant accounts are excluded. Windows local sign-in with an Office company account works only when the broker can discover that account; Office's sign-in UI does not prove broker visibility or model entitlement.
|
|
46
|
+
|
|
47
|
+
Use **Model sources → Microsoft 365 → Company account** or `ccdx m365 account` to choose. `ccdx m365 accounts` performs local discovery only; its opaque IDs can be passed as `ccdx m365 account --id ID`. These commands require the updated running service. Selection rediscovers accounts, rejects stale IDs, authorizes only the selected account and fetches its catalog once before committing. Failure retains the previous binding/catalog. Active M365 requests or startup work prevent selection; new M365 requests are refused during validation, while GitHub remains independent. Account changes apply to both M365 GPT and Claude; the selected Codex provider and saved model choices are not silently changed. Models missing from the new catalog require an explicit model choice. No interactive Microsoft sign-in UI is opened automatically. Interaction requirements, policy refusal or a missing native package leave M365 unavailable. None of these invalidate GitHub credentials.
|
|
43
48
|
The GitHub-selected Codex path retains its existing first-run GitHub login flow.
|
|
44
49
|
|
|
45
50
|
The optional package download is approximately 14.6 MB, contains prebuilt binaries
|
|
@@ -90,6 +95,10 @@ optional image MCP/skill/API remains separately configured and off by default.
|
|
|
90
95
|
|
|
91
96
|
### Claude gateway and client ownership
|
|
92
97
|
|
|
98
|
+
Company-account history is isolated. `conversations.json` stores at most 1024 hashes of conversation identifiers (or the first user item when no native identifier exists) and their account fingerprints; no messages, raw session IDs or tokens are stored there. Each new conversation writes its ownership once; known conversations use memory. After changing accounts, known foreign conversations are refused before forwarding. Unknown requests containing old history are also refused, including after restart; use a new conversation. Clients without stable conversation IDs can collide when their first user item is identical, so supply a unique native session ID. Evicted/unrecognized history fails closed after a switch. The history-isolation marker is saved with the binding and survives token renewal. Removing the M365 profile clears this ownership file, but never removes system sign-in or usage history.
|
|
99
|
+
|
|
100
|
+
Account selection stages the new authorization/catalog before replacing the old provider. Catalog and binding writes use the existing locked atomic writer with restoration on failure; this is not a crash/power-loss transaction. Client configuration remains a separate readiness state: its failure does not claim that account authorization failed or overwrite custom/managed fields. Previously saved model preferences are not substituted when the new account lacks those models.
|
|
101
|
+
|
|
93
102
|
Since 1.1.0, Claude mounts under the main HTTP listener at
|
|
94
103
|
`http://127.0.0.1:<ADAPTER_PORT>/anthropic` (default main port 2026).
|
|
95
104
|
It exposes `GET /anthropic/v1/models`, `POST /anthropic/v1/messages` and
|
|
@@ -985,7 +994,7 @@ Unknown support prevents an explicitly requested exception from starting.
|
|
|
985
994
|
For an older updater that still requires Git, install the Release tarball directly:
|
|
986
995
|
|
|
987
996
|
```sh
|
|
988
|
-
npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.
|
|
997
|
+
npm install -g https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.3/codex-copilot-dx-1.2.3.tgz
|
|
989
998
|
# Windows PowerShell: use npm.cmd instead of npm.
|
|
990
999
|
```
|
|
991
1000
|
|
package/package.json
CHANGED
package/src/adapter.mjs
CHANGED
|
@@ -169,7 +169,8 @@ export function createAdapterHandler(options = {}) {
|
|
|
169
169
|
const httpErrors = createHttpFailureDiagnostics();
|
|
170
170
|
const optionalRoutes = createOptionalRoutes({ ...options, dashboardOptions: { ...options.dashboardOptions,
|
|
171
171
|
...(options.providerRuntime ? { providerCatalogFn: input => options.providerRuntime.dashboardCatalog(input),
|
|
172
|
-
providerStateFn: () => options.providerRuntime.dashboardProviders()
|
|
172
|
+
providerStateFn: () => options.providerRuntime.dashboardProviders(),
|
|
173
|
+
providerAccountsFn: () => options.providerRuntime.action({ action: "accounts" }) } : {}) } });
|
|
173
174
|
let statusSnapshot;
|
|
174
175
|
const managementHandler = createManagementHandler({
|
|
175
176
|
nativePredictionPac: options.nativePredictionPac, fixPrediction: options.fixPrediction, requestBodyTimeoutMs,
|
package/src/cli-m365.mjs
CHANGED
|
@@ -9,6 +9,7 @@ import { terminalCell } from "./terminal-text.mjs";
|
|
|
9
9
|
import { readBoundedResponseText } from "./upstream-body.mjs";
|
|
10
10
|
import { parseAdapterAddressOptions } from "./cli-options.mjs";
|
|
11
11
|
import { autoReviewReasoningEfforts } from "./models.mjs";
|
|
12
|
+
import { m365AccountMessage } from "./providers/m365-accounts.mjs";
|
|
12
13
|
|
|
13
14
|
export async function fetchActiveProviderModels({ control = providerControl, ...options } = {}) {
|
|
14
15
|
if (readProviderSettings(options).codex !== "m365") {
|
|
@@ -35,6 +36,8 @@ export function formatM365Status(state) {
|
|
|
35
36
|
return [
|
|
36
37
|
`Microsoft 365: ${terminalCell(m.state || "not running")}${m.reason ? ` (${terminalCell(m.reason)})` : ""}`,
|
|
37
38
|
...(m.account?.login ? [`Account: ${terminalCell(m.account.login)}`] : []),
|
|
39
|
+
...(m.account?.tenant ? [`Tenant: ${terminalCell(m.account.tenant)} / ${terminalCell(m.account.selection_source || "legacy")}`] : []),
|
|
40
|
+
...(m.reason ? [m365AccountMessage(m.reason)] : []),
|
|
38
41
|
`Models: ${models.claude || 0} Claude / ${models.gpt || 0} GPT (${models.source || "unavailable"})`,
|
|
39
42
|
`Claude gateway: ${claude.gateway || "not running"}${claude.base_url ? ` / ${claude.base_url}` : ""}`,
|
|
40
43
|
...(claude.reason ? [`Claude detail: ${terminalCell(claude.reason)}`] : []),
|
|
@@ -62,14 +65,36 @@ export async function runProviderAutoReviewCommand(options = {}) {
|
|
|
62
65
|
});
|
|
63
66
|
}
|
|
64
67
|
|
|
65
|
-
export async function runM365Command({ action = "status", provider, model, autoReviewModel, host, port, home,
|
|
68
|
+
export async function runM365Command({ action = "status", provider, model, autoReviewModel, accountId, host, port, home,
|
|
66
69
|
env = process.env, input = process.stdin, output = process.stdout, prompt, control = providerControl } = {}) {
|
|
67
70
|
const options = { home, env };
|
|
68
71
|
let readline;
|
|
69
72
|
const ask = prompt || (question => { if (!input.isTTY || !output.isTTY) throw new Error("Choose the source and models with command arguments.");
|
|
70
73
|
readline ||= createInterface({ input, output });return readline.question(question); });
|
|
71
|
-
const request = value => control({ host, port, action: value });
|
|
74
|
+
const request = value => control({ host, port, action: value, ...(value?.action === "account" ? { timeoutMs: 65000 } : {}) });
|
|
72
75
|
try {
|
|
76
|
+
if (action === "accounts" || action === "account") {
|
|
77
|
+
const result = await request({ action: "accounts" });
|
|
78
|
+
const accounts = result.accounts || [];
|
|
79
|
+
if (!accounts.length) throw new Error("No company account found. Connect your work account in Windows or macOS, then check again.");
|
|
80
|
+
if (action === "accounts") {
|
|
81
|
+
output.write(accounts.map(value => `${terminalCell(value.login)} / ${terminalCell(value.tenant)}${value.selected ? " [selected]" : value.current_windows ? " [Windows sign-in]" : ""}\n ID: ${value.id}`).join("\n") + "\n");
|
|
82
|
+
return result;
|
|
83
|
+
}
|
|
84
|
+
if (!accountId) {
|
|
85
|
+
if (!prompt && (!input.isTTY || !output.isTTY)) throw new Error("Use ccdx m365 account --id ID from ccdx m365 accounts.");
|
|
86
|
+
output.write(accounts.map((value, index) => ` ${index + 1}. ${terminalCell(value.login)} / ${terminalCell(value.tenant)}${value.selected ? " [selected]" : value.current_windows ? " [Windows sign-in]" : ""}`).join("\n") + "\n");
|
|
87
|
+
const answer = String(await ask("Choose an account, or q to cancel: ")).trim();
|
|
88
|
+
if (answer === "q") return { cancelled: true };
|
|
89
|
+
const index = Number(answer) - 1;
|
|
90
|
+
if (!Number.isInteger(index) || !accounts[index]) throw new Error("Choose a listed account");
|
|
91
|
+
accountId = accounts[index].id;
|
|
92
|
+
}
|
|
93
|
+
if (!accounts.some(value => value.id === accountId)) throw new Error("Account list changed. Check again and select a listed account.");
|
|
94
|
+
output.write("Applies to Microsoft 365 in Codex and Claude. Use a new conversation after changing accounts.\n");
|
|
95
|
+
const state = await request({ action: "account", account_id: accountId });
|
|
96
|
+
output.write(formatM365Status(state) + "\n");return state;
|
|
97
|
+
}
|
|
73
98
|
if (action === "status") {
|
|
74
99
|
try { const state = await request();output.write(formatM365Status(state) + "\n");return state; }
|
|
75
100
|
catch (error) {
|
package/src/cli-options.mjs
CHANGED
|
@@ -159,12 +159,13 @@ export function parseCliArgs(args = []) {
|
|
|
159
159
|
if (command === "start") return parseStartOptions(rest);
|
|
160
160
|
if (command === "m365") {
|
|
161
161
|
const [action = "status", ...args] = rest;
|
|
162
|
-
if (!["status", "models", "switch", "on", "off", "remove"].includes(action)) throw new Error("
|
|
162
|
+
if (!["status", "models", "switch", "on", "off", "remove", "accounts", "account"].includes(action)) throw new Error("Choose status, models, accounts, account, switch, on, off or remove");
|
|
163
163
|
let provider, remaining = args;
|
|
164
164
|
if (action === "switch" && args[0] && !args[0].startsWith("--")) { provider = args[0];remaining = args.slice(1); }
|
|
165
165
|
if (provider && !["github", "m365"].includes(provider)) throw new Error("Choose github or m365");
|
|
166
|
-
const values = parseOptions(remaining, new Map(action === "switch" ? [["--model", "value"], ["--auto-review-model", "value"]] : []));
|
|
167
|
-
|
|
166
|
+
const values = parseOptions(remaining, new Map(action === "switch" ? [["--model", "value"], ["--auto-review-model", "value"]] : action === "account" ? [["--id", "value"]] : []));
|
|
167
|
+
if (values["--id"] && !/^[a-f0-9]{64}$/.test(values["--id"])) throw new Error("Use an account ID from ccdx m365 accounts");
|
|
168
|
+
return baseCommand("m365", { action, provider, model: values["--model"], autoReviewModel: values["--auto-review-model"], ...(values["--id"] ? { accountId: values["--id"] } : {}) });
|
|
168
169
|
}
|
|
169
170
|
if (command === "status" || command === "--status") {
|
|
170
171
|
if (rest.length) unexpectedArgs(rest);
|
|
@@ -396,7 +397,7 @@ function topicHelp(name, topic) {
|
|
|
396
397
|
"image-status": `Usage:\n ${name} image-status\n\n- Shows provider configuration and locally advertised generation/editing tools without generating an image or exposing its API key.`,
|
|
397
398
|
"auto-review-model": `Usage:\n ${name} auto-review-model\n\n- Select a Responses model, then an advertised reasoning effort.\n- Enter keeps the default/current choice; q cancels both steps without saving.\n- Effort 0 follows the client (low when omitted).\n- Settings apply only to Auto-review on the next request; no client patch or restart is required for adapters running 0.9.13 or newer.`,
|
|
398
399
|
"suggestion": `The CCDX prediction panel has been retired. Run ${name} suggestion off to safely remove unchanged CCDX registrations. This cleanup does not change native predictions; see ${name} prediction --help for that separate opt-in feature.`,
|
|
399
|
-
m365: `Usage:\n ${name} m365 [status|models|on|off|remove]\n ${name} m365 switch [github|m365] [--model ID] [--auto-review-model ID]\n\n- M365 is discovered silently at startup on supported managed environments.\n- Claude uses /anthropic on the same local port.\n- Codex stays on GitHub unless you explicitly switch.\n- M365 switching requires a running compatible adapter and available GPT/Auto-review choices; it never substitutes unavailable models.\n- Select an available model in Codex after switching an existing thread.\n- Off restores only owned Claude settings and selects GitHub.\n- Remove also clears the CCDX M365 profile, retaining a disabled preference and historical usage.\n- System Microsoft sign-in, GitHub credentials, predictions and images are preserved.`,
|
|
400
|
+
m365: `Usage:\n ${name} m365 [status|models|accounts|account|on|off|remove]\n ${name} m365 account [--id ID]\n ${name} m365 switch [github|m365] [--model ID] [--auto-review-model ID]\n\n- M365 is discovered silently at startup on supported managed environments.\n- accounts lists local company accounts without requesting tokens.\n- account chooses a company account; --id supports scripts. A running updated service is required.\n- Saved bindings stay selected. Otherwise an exact Windows sign-in match, then a single company account, is used.\n- Changing accounts applies to M365 in Codex and Claude; start a new conversation.\n- Claude uses /anthropic on the same local port.\n- Codex stays on GitHub unless you explicitly switch.\n- M365 switching requires a running compatible adapter and available GPT/Auto-review choices; it never substitutes unavailable models.\n- Select an available model in Codex after switching an existing thread.\n- Off restores only owned Claude settings and selects GitHub.\n- Remove also clears the CCDX M365 profile, retaining a disabled preference and historical usage.\n- System Microsoft sign-in, GitHub credentials, predictions and images are preserved.`,
|
|
400
401
|
prediction: `Usage:\n ${name} prediction [status|on|off|fix]\n\n- Optional native next-message predictions; off by default. macOS and Windows.\n- Windows requires the registered official MSIX App, an initialized profile, Windows PowerShell and .NET Framework 4.7.2+; Git/OpenSSL is not required for prediction setup.\n- Quit Codex before on/off, then restart ccdx.\n- On adds private App-profile certificate trust and an App-only route for chatgpt.com and ab.chatgpt.com.\n- HTTPS on those hosts is decrypted locally; only prediction configuration is changed.\n- No client program files, OS trust, account permissions, MCP or Hooks are changed.\n- Static HTTP/HTTPS/SOCKS5 proxies and bypass rules are preserved.\n- Windows supports company PAC/WPAD; macOS dynamic PAC/WPAD remains unsupported.\n- Static IPv4/IPv6 CIDRs match URL IP literals without DNS.\n- The bridge port persists across restarts/updates; a busy saved port disables only predictions.\n- Launch/reuse checks the App's actual route; an older random or missing route may require one full App quit.\n- Official prediction configuration is preserved; the conversation's model is used.\n- App updates require another compatibility check.\n- Status distinguishes saved preference and observed config traffic from unverified candidate visibility.\n- Fix asks a compatible running CCDX adapter to repair the enabled bridge once on its saved port.\n- It never enables predictions, renews certificates or force-restarts Codex.\n- Healthy unchanged bridges are retained.\n- Fix rechecks system proxy settings.\n- Changed routes may need a normal App relaunch to reload cached PAC; failed rechecks preserve the previous bridge with a nonzero exit.\n- Process environment variables and Node trust are not hot-reloaded; changed trust inputs need a CCDX service restart.\n- Startup, status and doctor share sanitized environment diagnostics.\n- Missing App routes require a normal full quit and ccdx launch; partial repair exits 1.\n- An older adapter must first be upgraded and restarted once to gain this repair endpoint.`,
|
|
401
402
|
update: `Usage:\n ${name} update [npm|github] [--allow-remote]\n\n- Updates the global package from the configured npm registry or the latest stable GitHub release.\n- With no source, an interactive terminal prompts for one.\n- Windows uses system cmd.exe to run npm.cmd without changing PowerShell policy; use the .cmd entrypoint if scripts are blocked.\n- GitHub verifies a Release tarball; Git is not required. Dependencies use the configured npm registry.\n- By default npm's remote-download policy is preserved.\n- If npm reports EALLOWREMOTE for a trusted mirror tarball, --allow-remote explicitly permits URL dependencies for this one installation's entire dependency tree; it is not a hostname allowlist.\n- No .npmrc, registry or persistent policy is changed, and failed installations are not retried automatically.\n- Use this only if company policy permits it.\n- Restart the running adapter after installation.`,
|
|
402
403
|
version: `Usage:\n ${name} --version`,
|
|
@@ -424,7 +425,7 @@ export function cliHelp(commandName = "ccdx", topic = "") {
|
|
|
424
425
|
${name} image-status
|
|
425
426
|
${name} auto-review-model
|
|
426
427
|
${name} prediction [status|on|off|fix]
|
|
427
|
-
${name} m365 [status|models|switch|on|off|remove]
|
|
428
|
+
${name} m365 [status|models|accounts|account|switch|on|off|remove]
|
|
428
429
|
${name} update [npm|github] [--allow-remote]
|
|
429
430
|
${name} --version
|
|
430
431
|
${name} --help
|
package/src/dashboard/console.js
CHANGED
|
@@ -5,6 +5,38 @@
|
|
|
5
5
|
let current = "overview", settings = null, settingsPending = false, stopped = false, timer = null, ticks = 0;
|
|
6
6
|
let sourceDirty = false, reviewDirty = false, sourceModels = [], modelsPreference = null, sourceGeneration = 0, modelsSource = null;
|
|
7
7
|
let settingsReadAt = null;
|
|
8
|
+
let accountsPending = false;
|
|
9
|
+
const accountReasons = new Set(["m365_account_ambiguous", "m365_account_unavailable", "m365_account_conflict", "m365_interaction_required", "m365_llm_permission_unavailable", "m365_account_busy", "m365_account_selection_stale"]);
|
|
10
|
+
function syncAccountControls() {
|
|
11
|
+
el("m365-accounts-refresh").disabled = accountsPending || settingsPending;
|
|
12
|
+
el("m365-account-choice").disabled = accountsPending || settingsPending;
|
|
13
|
+
el("m365-account-apply").disabled = accountsPending || settingsPending || !el("m365-account-choice").value || !settings?.providers?.m365?.enabled;
|
|
14
|
+
}
|
|
15
|
+
async function loadAccounts() {
|
|
16
|
+
if (accountsPending || settingsPending) return;
|
|
17
|
+
accountsPending = true;syncAccountControls();label(el("m365-account-note"), "checking");
|
|
18
|
+
try {
|
|
19
|
+
const response = await fetch("/_ccdx/ui/m365/accounts", { headers: { "X-CCDX-Dashboard": "1" }, cache: "no-store", signal: AbortSignal.timeout(30000) });
|
|
20
|
+
const data = await response.json();if (!response.ok || !Array.isArray(data.accounts)) throw Object.assign(new Error("Account discovery failed"), { code: data.code });
|
|
21
|
+
const previous = el("m365-account-choice").value;
|
|
22
|
+
const placeholder = document.createElement("option");placeholder.value = "";label(placeholder, "choose_company_account");
|
|
23
|
+
el("m365-account-choice").replaceChildren(placeholder, ...data.accounts.map(account => {
|
|
24
|
+
const option = document.createElement("option");option.value = account.id;
|
|
25
|
+
option.textContent = `${account.login} / ${account.tenant}`;return option;
|
|
26
|
+
}));
|
|
27
|
+
const selected = data.accounts.find(account => account.id === previous) || data.accounts.find(account => account.selected) || data.accounts.find(account => account.current_windows);
|
|
28
|
+
el("m365-account-choice").value = selected?.id || "";
|
|
29
|
+
el("m365-account-form").hidden = !data.accounts.length;
|
|
30
|
+
label(el("m365-account-note"), data.accounts.length ? "company_account_choose" : "company_account_empty");
|
|
31
|
+
} catch (error) { el("m365-account-form").hidden = true;label(el("m365-account-note"), accountReasons.has(error.code) ? error.code : "company_account_check_failed"); }
|
|
32
|
+
finally { accountsPending = false;syncAccountControls(); }
|
|
33
|
+
}
|
|
34
|
+
el("m365-accounts-refresh").addEventListener("click", () => void loadAccounts());
|
|
35
|
+
el("m365-account-choice").addEventListener("change", syncAccountControls);
|
|
36
|
+
el("m365-account-apply").addEventListener("click", () => {
|
|
37
|
+
if (settings?.providers?.m365?.account && !window.confirm(globalThis.ccdxLanguage.format("company_account_confirm"))) return;
|
|
38
|
+
void change({ action: "provider", operation: "account", account_id: el("m365-account-choice").value }, el("m365-account-apply"));
|
|
39
|
+
});
|
|
8
40
|
function navigate() {
|
|
9
41
|
const route = location.hash.slice(1), next = Object.hasOwn(titles, route) ? route : "overview";
|
|
10
42
|
current = next;
|
|
@@ -22,8 +54,8 @@
|
|
|
22
54
|
async function api(body) {
|
|
23
55
|
const response = await fetch("/_ccdx/ui/settings", { method: body ? "POST" : "GET", cache: "no-store",
|
|
24
56
|
headers: { "X-CCDX-Dashboard": "1", ...(body ? { "Content-Type": "application/json" } : {}) },
|
|
25
|
-
...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(15000) });
|
|
26
|
-
const data = await response.json();if (!response.ok) throw new Error(data.error || `HTTP ${response.status}`);return data;
|
|
57
|
+
...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(body?.operation === "account" ? 65000 : 15000) });
|
|
58
|
+
const data = await response.json();if (!response.ok) throw Object.assign(new Error(data.error || `HTTP ${response.status}`), { code: data.code });return data;
|
|
27
59
|
}
|
|
28
60
|
const states = { immediate: "effective_now", terminal_unavailable: "terminal_animation_unavailable_in_this_output_mode", next_start: "next_ccdx_start", next_call: "applies_to_new_calls", needs_setup: "setup_required",
|
|
29
61
|
next_config_request: "next_configuration_request_cached_suggestions_may_remain", needs_app_relaunch: "reopen_the_client_to_finish", needs_service_restart: "restart_ccdx_to_finish" };
|
|
@@ -82,6 +114,11 @@
|
|
|
82
114
|
label(el("settings-note"), "settings_read_from_the_running_service");
|
|
83
115
|
el("page-settings-note").textContent = "";
|
|
84
116
|
const state = data.providers;
|
|
117
|
+
const account = state?.m365?.account;
|
|
118
|
+
if (account) label(el("m365-account-current"), "company_account_current", { login: account.login, tenant: account.tenant || "—", source: { key: `account_source_${account.selection_source || "legacy"}` } });
|
|
119
|
+
else label(el("m365-account-current"), "company_account_none");
|
|
120
|
+
if (accountReasons.has(state?.m365?.reason)) label(el("m365-account-note"), state.m365.reason);
|
|
121
|
+
syncAccountControls();
|
|
85
122
|
syncSources();
|
|
86
123
|
if (current === "codex" && state && (modelsSource !== el("source-provider").value || !sourceDirty && !reviewDirty && modelsPreference !== JSON.stringify(state[el("source-provider").value]?.preference))) void loadSourceModels();
|
|
87
124
|
el("m365-control-note").replaceChildren();
|
|
@@ -102,6 +139,7 @@
|
|
|
102
139
|
if (settingsPending) return;
|
|
103
140
|
settingsPending = true;
|
|
104
141
|
el("terminal-color-theme").disabled = true;
|
|
142
|
+
syncAccountControls();
|
|
105
143
|
try { applySettings(await api());settingsReadAt = new Date().toLocaleTimeString(); }
|
|
106
144
|
catch (error) {
|
|
107
145
|
for (const id of ["settings-note", "page-settings-note"]) {
|
|
@@ -109,11 +147,12 @@
|
|
|
109
147
|
el(id).title = error.message;
|
|
110
148
|
}
|
|
111
149
|
}
|
|
112
|
-
finally { settingsPending = false;el("terminal-color-theme").disabled = !settings;el("apply-source").disabled = !sourceReady();syncReviewButton(); }
|
|
150
|
+
finally { settingsPending = false;el("terminal-color-theme").disabled = !settings;el("apply-source").disabled = !sourceReady();syncReviewButton();syncAccountControls(); }
|
|
113
151
|
}
|
|
114
152
|
async function change(body, button) {
|
|
115
153
|
if (settingsPending) return;
|
|
116
154
|
settingsPending = true;
|
|
155
|
+
syncAccountControls();
|
|
117
156
|
const controls = [...document.querySelectorAll("[role=switch], #save-history, #clean-history, #fix-prediction, #apply-source, #save-review, #source-provider, #source-model, #source-review, #source-review-effort, #terminal-color-theme, #m365-on, #m365-off")];
|
|
118
157
|
controls.forEach(input => { input.disabled = true; });
|
|
119
158
|
label(el("settings-note"), "applying");
|
|
@@ -125,15 +164,22 @@
|
|
|
125
164
|
if (body.action === "provider" && body.operation === "off") { sourceDirty = false;reviewDirty = false; }
|
|
126
165
|
el("review-control-note").textContent = "";
|
|
127
166
|
applySettings(data);
|
|
167
|
+
if (body.operation === "account") {
|
|
168
|
+
modelsPreference = null;modelsSource = null;
|
|
169
|
+
dashboardRefresh.invalidate("models", { clear: true });
|
|
170
|
+
label(el("m365-account-note"), "company_account_checked");
|
|
171
|
+
}
|
|
128
172
|
if (body.action !== "color_theme") { await dashboardRefresh.refresh("status", { force: true });await dashboardRefresh.refresh("auth", { force: true }); }
|
|
129
173
|
}
|
|
130
174
|
catch (error) {
|
|
131
175
|
if (settings) applySettings(settings);
|
|
176
|
+
if (body.operation === "account") { label(el("m365-account-note"), "company_account_not_saved", { reason: { key: accountReasons.has(error.code) ? error.code : error.message } });return; }
|
|
132
177
|
if (body.action === "color_theme") { label(el("terminal-color-note"), "not_saved_error", { error: error.message });return; }
|
|
133
178
|
el("settings-note").textContent = error.message;el("source-control-note").textContent = error.message;el("m365-control-note").textContent = error.message;el("review-control-note").textContent = error.message;el("effect-history").textContent = error.message;
|
|
134
179
|
if (body.key) el(`effect-${body.key}`).textContent = error.message;
|
|
135
180
|
} finally {
|
|
136
181
|
settingsPending = false;controls.forEach(input => { input.disabled = false; });
|
|
182
|
+
syncAccountControls();
|
|
137
183
|
if (settings) for (const [key, value] of Object.entries(settings.effective)) if (value.locked) el(`setting-${key}`).disabled = true;
|
|
138
184
|
if (settings?.history.source === "environment") el("save-history").disabled = true;
|
|
139
185
|
el("apply-source").disabled = !sourceReady();el("source-model").disabled = !selectedSource()?.selection.models_required;syncReviewButton();
|
package/src/dashboard/index.html
CHANGED
|
@@ -142,6 +142,14 @@
|
|
|
142
142
|
<p class="hint" data-i18n="m365_source_access">Provides models for Codex and Claude on supported devices.</p>
|
|
143
143
|
<div class="section-actions"><button id="m365-on" type="button" data-i18n="enable_service">Enable source</button><button id="m365-off" type="button" data-i18n="disable_service">Disable source</button></div>
|
|
144
144
|
<div id="m365-control-note" class="hint" role="status"></div>
|
|
145
|
+
<h3 data-i18n="company_account">Company account</h3>
|
|
146
|
+
<p id="m365-account-current" class="hint" role="status"></p>
|
|
147
|
+
<div class="section-actions"><button id="m365-accounts-refresh" type="button" data-i18n="check_accounts">Check accounts</button></div>
|
|
148
|
+
<div id="m365-account-form" hidden>
|
|
149
|
+
<div class="section-actions"><label><span data-i18n="choose_company_account">Choose a company account</span><select id="m365-account-choice"></select></label><button id="m365-account-apply" type="button" disabled data-i18n="use_this_account">Use this account</button></div>
|
|
150
|
+
<p class="hint" data-i18n="company_account_scope">Applies to Microsoft 365 in Codex and Claude. Start a new conversation after changing accounts.</p>
|
|
151
|
+
</div>
|
|
152
|
+
<p id="m365-account-note" class="hint" role="status" aria-live="polite"></p>
|
|
145
153
|
</section>
|
|
146
154
|
</div>
|
|
147
155
|
<div data-view="usage" hidden>
|
|
@@ -1,5 +1,29 @@
|
|
|
1
1
|
(() => {
|
|
2
2
|
const translations = {
|
|
3
|
+
"company_account": ["Company account", "公司账号"],
|
|
4
|
+
"check_accounts": ["Check accounts", "检查账号"],
|
|
5
|
+
"choose_company_account": ["Choose a company account", "选择公司账号"],
|
|
6
|
+
"use_this_account": ["Use this account", "使用此账号"],
|
|
7
|
+
"company_account_scope": ["Applies to Microsoft 365 in Codex and Claude. Start a new conversation after changing accounts.", "影响 Codex 和 Claude 的 M365 服务。\n更换账号后请新建对话。"],
|
|
8
|
+
"company_account_current": ["{login} · Tenant {tenant} · {source}", "{login}\n租户:{tenant} · {source}"],
|
|
9
|
+
"account_source_windows": ["Windows sign-in", "Windows 登录账号"],
|
|
10
|
+
"account_source_single": ["Only company account", "唯一公司账号"],
|
|
11
|
+
"account_source_manual": ["Your choice", "手动选择"],
|
|
12
|
+
"account_source_legacy": ["Saved account", "已保存账号"],
|
|
13
|
+
"company_account_none": ["No company account connected.", "尚未连接公司账号。"],
|
|
14
|
+
"company_account_choose": ["Choose an account. Browsing does not change your connection.", "请选择账号。查看列表不会切换。"],
|
|
15
|
+
"company_account_empty": ["No company account found. Connect your work account in Windows or macOS, then check again.", "未找到公司账号。\n请先连接工作账号,再检查。"],
|
|
16
|
+
"company_account_confirm": ["Change the Microsoft 365 account for Codex and Claude? Existing conversations will not move to the new account. Start a new conversation.", "更换 Codex 和 Claude 的 M365 账号?旧对话不会转移,请新建对话。"],
|
|
17
|
+
"company_account_checked": ["Account connected. Model list checked; inference access is not tested.", "账号已连接,模型列表已检查。\n尚未测试实际请求。"],
|
|
18
|
+
"m365_account_ambiguous": ["Choose a company account below.", "请在下方选择公司账号。"],
|
|
19
|
+
"m365_account_unavailable": ["Company account unavailable. Check your work sign-in, then check again.", "公司账号不可用。\n请检查工作账号登录。"],
|
|
20
|
+
"m365_account_conflict": ["Account records conflict. Check your work sign-in.", "账号记录冲突,请检查工作登录。"],
|
|
21
|
+
"m365_interaction_required": ["Complete your company sign-in, then check again.", "请先完成公司登录,再检查。"],
|
|
22
|
+
"m365_llm_permission_unavailable": ["This account does not have model access.", "此账号没有模型访问权限。"],
|
|
23
|
+
"m365_account_busy": ["Finish Microsoft 365 requests before changing accounts.", "请在 M365 请求结束后更换。"],
|
|
24
|
+
"m365_account_selection_stale": ["Account list changed. Check again and select an account.", "账号列表已变化,请重新检查。"],
|
|
25
|
+
"company_account_check_failed": ["Could not read accounts. Check company sign-in and the native authentication component.", "未能读取账号。\n请检查公司登录和认证组件。"],
|
|
26
|
+
"company_account_not_saved": ["Account not changed. Previous connection kept. {reason}", "账号未更换,保留原连接。\n{reason}"],
|
|
3
27
|
"source_catalog_unavailable": ["Model list unavailable: {code}", "模型列表不可用:{code}"],
|
|
4
28
|
"terminal_color_preview": ["Terminal color preview", "终端配色预览"],
|
|
5
29
|
"source_retry_time": ["Can retry after {time}.", "可在 {time} 后重试。"],
|
package/src/dashboard-api.mjs
CHANGED
|
@@ -142,6 +142,7 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
142
142
|
authStatusFn = () => authStatus({ home }),
|
|
143
143
|
providerCatalogFn,
|
|
144
144
|
providerStateFn,
|
|
145
|
+
providerAccountsFn,
|
|
145
146
|
serviceControl,
|
|
146
147
|
applyAnimation,
|
|
147
148
|
} = {}) {
|
|
@@ -162,6 +163,15 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
162
163
|
return;
|
|
163
164
|
}
|
|
164
165
|
|
|
166
|
+
if (pathname === "/_ccdx/ui/m365/accounts" && req.method === "GET") {
|
|
167
|
+
if (!providerAccountsFn) { sendJson(res, 503, { error: "Account selection requires the updated running service" });return; }
|
|
168
|
+
try {
|
|
169
|
+
const result = await providerAccountsFn();
|
|
170
|
+
sendJson(res, 200, { accounts: result.accounts.map(value => ({ id: value.id, login: safeText(value.login, 320), tenant: safeText(value.tenant, 128), selected: value.selected === true, current_windows: value.current_windows === true })) });
|
|
171
|
+
} catch (error) { sendJson(res, error.statusCode || 503, { error: "Could not read company accounts", code: /^m365_[a-z_]+$/.test(error.code || "") ? error.code : "m365_accounts_unavailable" }); }
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
|
|
165
175
|
if (pathname === "/_ccdx/ui/settings") {
|
|
166
176
|
if (!serviceControl) { sendJson(res, 503, { error: "Settings require the running service; restart the updated CCDX" });return; }
|
|
167
177
|
if (req.method === "GET") {
|
|
@@ -177,7 +187,8 @@ export async function handleDashboardApi(req, res, pathname, {
|
|
|
177
187
|
abort.clearTimeout();const data = await serviceControl.action(input);
|
|
178
188
|
if (!res.destroyed && !res.writableEnded) sendJson(res, 200, data);
|
|
179
189
|
} catch (error) {
|
|
180
|
-
sendJson(res, error.statusCode || (error.code?.startsWith("ccdx_cache_") ? 409 : 400), { error: safeText(error.message, 300)
|
|
190
|
+
sendJson(res, error.statusCode || (error.code?.startsWith("ccdx_cache_") ? 409 : 400), { error: safeText(error.message, 300),
|
|
191
|
+
...(/^m365_[a-z_]+$/.test(error.code || "") ? { code: error.code } : {}) });
|
|
181
192
|
} finally { abort.cleanup(); }
|
|
182
193
|
return;
|
|
183
194
|
}
|
package/src/m365-settings.mjs
CHANGED
|
@@ -10,7 +10,7 @@ export function m365Paths({ home = os.homedir() } = {}) {
|
|
|
10
10
|
const directory = path.join(home, ".local", "share", "codex-copilot-dx", "profiles", "m365");
|
|
11
11
|
return { directory, settings: path.join(directory, "settings.json"), account: path.join(directory, "account.json"),
|
|
12
12
|
catalog: path.join(directory, "models.json"), gateway: path.join(directory, "gateway.json"),
|
|
13
|
-
ownership: path.join(directory, "client-config.json") };
|
|
13
|
+
ownership: path.join(directory, "client-config.json"), conversations: path.join(directory, "conversations.json") };
|
|
14
14
|
}
|
|
15
15
|
|
|
16
16
|
export function readM365Json(file, fallback = null) {
|
|
@@ -71,6 +71,28 @@ export function readM365Account(options = {}) {
|
|
|
71
71
|
return account;
|
|
72
72
|
}
|
|
73
73
|
|
|
74
|
+
export function writeM365Binding(account, catalog, { expectedAccount, ...options } = {}) {
|
|
75
|
+
const paths = m365Paths(options);m365AccountKey(account);
|
|
76
|
+
fs.mkdirSync(paths.directory, { recursive: true, mode: 0o700 });
|
|
77
|
+
return withFileLockSync(path.join(paths.directory, "binding.lock"), () => {
|
|
78
|
+
const previous = readM365Account(options), oldCatalog = readM365Json(paths.catalog);
|
|
79
|
+
if (expectedAccount !== undefined && (previous ? m365AccountKey(previous) : null) !== (expectedAccount ? m365AccountKey(expectedAccount) : null)) {
|
|
80
|
+
throw Object.assign(new Error("The company account changed. Refresh the account list."), { code: "m365_account_selection_stale", statusCode: 409 });
|
|
81
|
+
}
|
|
82
|
+
try {
|
|
83
|
+
writeM365Json(paths.catalog, catalog);
|
|
84
|
+
writeM365Json(paths.account, account);
|
|
85
|
+
} catch (error) {
|
|
86
|
+
try {
|
|
87
|
+
if (oldCatalog) writeM365Json(paths.catalog, oldCatalog);else fs.rmSync(paths.catalog, { force: true });
|
|
88
|
+
if (previous) writeM365Json(paths.account, previous);else fs.rmSync(paths.account, { force: true });
|
|
89
|
+
}
|
|
90
|
+
catch { throw Object.assign(new Error("Company account save failed; its model cache could not be restored. Existing account binding was preserved."), { code: "m365_account_save_failed", cause: error }); }
|
|
91
|
+
throw error;
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
|
|
74
96
|
export function ensureM365GatewayKey(options = {}) {
|
|
75
97
|
const file = m365Paths(options).gateway;
|
|
76
98
|
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
package/src/optional-routes.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/status.js", "/usage.js", "/ui.js", "/console.js"]);
|
|
2
|
-
export const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth", "/_ccdx/ui/providers", "/_ccdx/ui/settings"]);
|
|
2
|
+
export const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth", "/_ccdx/ui/providers", "/_ccdx/ui/settings", "/_ccdx/ui/m365/accounts"]);
|
|
3
3
|
|
|
4
4
|
export function isOptionalRoute(method, pathname) {
|
|
5
5
|
return DASHBOARD_API_PATHS.has(pathname) || pathname === "/mcp/image"
|
|
@@ -15,9 +15,10 @@ export async function handleProviderManagement(req, res, runtime) {
|
|
|
15
15
|
const abort = createRequestAbort(req, res);abort.setTimeout(2000, "request_body_timeout");
|
|
16
16
|
try {
|
|
17
17
|
const input = await readJsonBody(req, { maxBodyBytes: 4096, maxDecodedBodyBytes: 4096, signal: abort.signal });
|
|
18
|
-
const allowed = new Set(["action", "provider", "model", "auto_review_model", "family", "effort"]);
|
|
18
|
+
const allowed = new Set(["action", "provider", "model", "auto_review_model", "family", "effort", "account_id"]);
|
|
19
19
|
if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some(key => !allowed.has(key))
|
|
20
|
-
|| !["models", "switch", "on", "off", "remove", "auto-review"].includes(input.action)) throw httpError("Invalid provider action", 400);
|
|
20
|
+
|| !["models", "switch", "on", "off", "remove", "auto-review", "accounts", "account"].includes(input.action)) throw httpError("Invalid provider action", 400);
|
|
21
|
+
if (input.action === "account" && (typeof input.account_id !== "string" || !/^[a-f0-9]{64}$/.test(input.account_id))) throw httpError("Select an available company account", 400);
|
|
21
22
|
if (input.effort !== undefined && input.effort !== null && (typeof input.effort !== "string" || input.effort.length > 16)) throw httpError("Invalid reasoning effort", 400);
|
|
22
23
|
for (const key of ["provider", "model", "auto_review_model", "family"]) if (input[key] !== undefined && (typeof input[key] !== "string" || input[key].length > 128)) throw httpError("Invalid provider selection", 400);
|
|
23
24
|
abort.clearTimeout();
|
package/src/provider-runtime.mjs
CHANGED
|
@@ -4,7 +4,9 @@ import { autoReviewReasoningEfforts, DEFAULT_CODEX_AUTO_REVIEW_MODEL, responsesM
|
|
|
4
4
|
import { publicModelCatalog } from "./provider-metadata.mjs";
|
|
5
5
|
import { createGithubProvider } from "./providers/github.mjs";
|
|
6
6
|
import { readProviderSettings, writeProviderSettings } from "./provider-settings.mjs";
|
|
7
|
-
import { readM365Settings, updateM365Settings, m365Paths, ensureM365GatewayKey } from "./m365-settings.mjs";
|
|
7
|
+
import { readM365Settings, updateM365Settings, m365Paths, ensureM365GatewayKey, readM365Account, m365AccountKey } from "./m365-settings.mjs";
|
|
8
|
+
import { requestM365Accounts } from "./providers/m365-auth.mjs";
|
|
9
|
+
import { publicM365Accounts, accountChoiceId, m365AccountMessage } from "./providers/m365-accounts.mjs";
|
|
8
10
|
import { providerRegistry } from "./provider-registry.mjs";
|
|
9
11
|
import { createClaudeClientLifecycle } from "./claude-client-lifecycle.mjs";
|
|
10
12
|
|
|
@@ -14,12 +16,14 @@ const unavailable = reason => Object.assign(new Error(`Microsoft 365 is unavaila
|
|
|
14
16
|
// Composition owns source selection. Providers never modify Codex, prediction,
|
|
15
17
|
// image configuration or each other's credentials.
|
|
16
18
|
export function createProviderRuntime({ githubClient, githubRegistry, githubCredentialFingerprint = "", home, env = process.env, platform = process.platform,
|
|
17
|
-
corePort = Number(env.ADAPTER_PORT || 2026), log = () => {}, createM365, startGateway, configureClients, restoreClients
|
|
19
|
+
corePort = Number(env.ADAPTER_PORT || 2026), log = () => {}, createM365, startGateway, configureClients, restoreClients,
|
|
20
|
+
discoverM365 = requestM365Accounts } = {}) {
|
|
18
21
|
const options = { home, env, platform }, github = { ...createGithubProvider({ client: githubClient,
|
|
19
22
|
profileId: () => { const value = typeof githubCredentialFingerprint === "function" ? githubCredentialFingerprint() : githubCredentialFingerprint;
|
|
20
23
|
return value ? `codex:${value}` : "codex"; } }), registry: githubRegistry };
|
|
21
24
|
let selection = readProviderSettings(options), m365 = null, gateway = null, pending = null, closed = false, serial = null;
|
|
22
25
|
let reason = null, claudeReason = null, lastClients = {};
|
|
26
|
+
let changingAccount = false;
|
|
23
27
|
const clientLifecycle = createClaudeClientLifecycle({ options, configureClients, restoreClients });
|
|
24
28
|
const sources = new Map([[github.id, github]]);
|
|
25
29
|
const dashboardProfiles = new Map();
|
|
@@ -76,7 +80,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
76
80
|
return m365;
|
|
77
81
|
})().catch(error => {
|
|
78
82
|
reason = /^m365_[a-z0-9_]+$/.test(error.code || "") ? error.code : error.code === "EADDRINUSE" ? "m365_gateway_port_busy" : "m365_unavailable";
|
|
79
|
-
log("info",
|
|
83
|
+
log("info", m365AccountMessage(reason));return null;
|
|
80
84
|
}).finally(() => { if (pending === operation) pending = null; });
|
|
81
85
|
pending = operation;return operation;
|
|
82
86
|
}
|
|
@@ -86,6 +90,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
86
90
|
m365: { ...(m365?.snapshot() || {}), enabled, state: !enabled ? "disabled" : pending ? "checking"
|
|
87
91
|
: !["darwin", "win32"].includes(platform) ? "unsupported" : m365?.snapshot().state || (reason ? "unavailable" : "idle"),
|
|
88
92
|
reason: reason || m365?.snapshot().reason || null,
|
|
93
|
+
account_change_in_flight: changingAccount,
|
|
89
94
|
preference: selection.m365 || null,
|
|
90
95
|
active_requests: activeM365Requests,
|
|
91
96
|
claude: { gateway: gateway ? "running" : "unavailable", reason: claudeReason, port: gateway ? corePort : null,
|
|
@@ -93,6 +98,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
93
98
|
observed_clients: { ...lastClients }, requests: gateway?.snapshot?.() || null } } });
|
|
94
99
|
|
|
95
100
|
function current() {
|
|
101
|
+
if (selection.codex === "m365" && changingAccount) throw Object.assign(new Error(m365AccountMessage("m365_account_busy")), { code: "m365_account_busy", statusCode: 409 });
|
|
96
102
|
const source = sources.get(selection.codex);
|
|
97
103
|
if (!source || selection.codex === "m365" && (!enabled || source.snapshot().state === "disabled")) throw unavailable(reason || "m365_not_ready");
|
|
98
104
|
return source;
|
|
@@ -101,6 +107,47 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
101
107
|
const next = (serial || Promise.resolve()).then(task);
|
|
102
108
|
serial = next.catch(() => {});return next;
|
|
103
109
|
};
|
|
110
|
+
async function discoverAccounts() {
|
|
111
|
+
if (!["darwin", "win32"].includes(platform)) throw unavailable("m365_platform_unsupported");
|
|
112
|
+
const result = await discoverM365({ env });
|
|
113
|
+
return { ...result, binding: readM365Account(options) };
|
|
114
|
+
}
|
|
115
|
+
async function selectAccount(id) {
|
|
116
|
+
if (typeof id !== "string" || !/^[a-f0-9]{64}$/.test(id)) throw Object.assign(new Error("Use an account ID from ccdx m365 accounts"), { statusCode: 400 });
|
|
117
|
+
if (!enabled) throw unavailable("m365_disabled");
|
|
118
|
+
if (activeM365Requests > 0 || gateway?.snapshot?.().active > 0 || pending) {
|
|
119
|
+
throw Object.assign(new Error(m365AccountMessage("m365_account_busy")), { code: "m365_account_busy", statusCode: 409 });
|
|
120
|
+
}
|
|
121
|
+
changingAccount = true;
|
|
122
|
+
let candidate, opened;
|
|
123
|
+
try {
|
|
124
|
+
const discovered = await discoverAccounts();
|
|
125
|
+
const chosen = discovered.accounts.find(value => accountChoiceId(value) === id);
|
|
126
|
+
if (!chosen) throw Object.assign(new Error("Account list changed. Check again and select an available account."), { code: "m365_account_selection_stale", statusCode: 409 });
|
|
127
|
+
const switched = discovered.binding && m365AccountKey(discovered.binding) !== m365AccountKey(chosen);
|
|
128
|
+
const factory = createM365 || (await import("./providers/m365.mjs")).createM365Provider;
|
|
129
|
+
candidate = factory({ home, env, log, persist: false,
|
|
130
|
+
account: { ...chosen, selection_source: "manual", ...(switched || discovered.binding?.history_isolation ? { history_isolation: true } : {}) },
|
|
131
|
+
onCatalog() { if (candidate === m365 && !closed) setImmediate(() => { if (candidate === m365 && !closed) void syncClaudeClients(); }); } });
|
|
132
|
+
await candidate.refresh();
|
|
133
|
+
if (closed) throw unavailable("m365_runtime_closed");
|
|
134
|
+
if (candidate.models("claude").length) {
|
|
135
|
+
const start = startGateway || (await import("./claude-gateway.mjs")).createClaudeGateway;
|
|
136
|
+
opened = await start({ provider: candidate, apiKey: ensureM365GatewayKey(options), port: corePort, env, log,
|
|
137
|
+
onRequest({ client }) { lastClients[client] = new Date().toISOString(); } });
|
|
138
|
+
}
|
|
139
|
+
candidate.commitSelection(discovered.binding);
|
|
140
|
+
const previous = m365, previousGateway = gateway;
|
|
141
|
+
m365 = candidate;gateway = opened || null;sources.set("m365", m365);reason = null;
|
|
142
|
+
candidate = null;opened = null;
|
|
143
|
+
try { await previousGateway?.close();previous?.close(); }
|
|
144
|
+
catch { log("warn", "Previous Microsoft 365 connection cleanup failed; the selected account is active"); }
|
|
145
|
+
claudeReason = gateway ? null : "m365_no_claude_models";
|
|
146
|
+
await syncClaudeClients();
|
|
147
|
+
changingAccount = false;
|
|
148
|
+
return snapshot();
|
|
149
|
+
} finally { await opened?.close();candidate?.close();changingAccount = false; }
|
|
150
|
+
}
|
|
104
151
|
async function switchSource(provider, preference) {
|
|
105
152
|
if (!providerRegistry.get(provider)?.codex) throw new Error("Choose a listed Codex source");
|
|
106
153
|
if (provider === "m365") {
|
|
@@ -134,7 +181,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
134
181
|
if (remove) {
|
|
135
182
|
if (result.remaining) throw Object.assign(new Error("User-modified Claude settings were preserved; M365 profile cleanup is incomplete"), { code: "m365_cleanup_preserved" });
|
|
136
183
|
const paths = m365Paths(options);
|
|
137
|
-
for (const file of [paths.account, paths.catalog, paths.gateway, paths.ownership]) {
|
|
184
|
+
for (const file of [paths.account, paths.catalog, paths.gateway, paths.ownership, paths.conversations]) {
|
|
138
185
|
try { if (!fs.lstatSync(file).isFile()) throw Error();fs.unlinkSync(file); }
|
|
139
186
|
catch (error) { if (error.code !== "ENOENT") throw new Error("M365 cleanup preserved an unexpected file"); }
|
|
140
187
|
}
|
|
@@ -144,6 +191,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
144
191
|
return {
|
|
145
192
|
github, current, snapshot, start: startM365, refresh: () => startM365(true),
|
|
146
193
|
handleClaude(req, res) {
|
|
194
|
+
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; }
|
|
147
195
|
if (!enabled || !gateway?.handle) {
|
|
148
196
|
res.writeHead(503, { "Content-Type": "application/json", "Cache-Control": "no-store" });
|
|
149
197
|
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;
|
|
@@ -161,6 +209,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
161
209
|
{ id: "m365", name: "Microsoft 365", generation: m365 ? dashboardGeneration(m365) : 0, enabled, state: ms.state, reason: ms.reason,
|
|
162
210
|
auth: { state: ms.token_cached ? "authorized" : !enabled ? "disabled" : ms.reason ? "unavailable" : "unknown",
|
|
163
211
|
account: ms.account?.login || "", token_cached: ms.token_cached === true,
|
|
212
|
+
tenant: ms.account?.tenant || "", selection_source: ms.account?.selection_source || null,
|
|
164
213
|
expires_in_ms: ms.token_expires_in_ms ?? null, checked_at: ms.token_checked_at || null },
|
|
165
214
|
models: { count: ms.models?.total ?? null, source: ms.models?.source || "unavailable", checked_at: ms.models?.refreshed_at || null },
|
|
166
215
|
clients: [{ id: "codex", name: "Codex App", selected: selection.codex === "m365", state: selection.codex === "m365" ? ms.state : "standby" },
|
|
@@ -195,7 +244,8 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
195
244
|
// Internal bounded correlation only; IDs are never exposed or persisted.
|
|
196
245
|
const key = typeof raw === "string" && raw.length <= 512 ? raw : null;
|
|
197
246
|
const previous = key && sessions.get(key)?.namespace || priorNamespace, order = ++requestOrder;
|
|
198
|
-
return { historyNamespace: namespace, historyTransferNamespace: previous && previous !== namespace
|
|
247
|
+
return { historyNamespace: namespace, historyTransferNamespace: previous && previous !== namespace
|
|
248
|
+
&& !(previous.startsWith("m365:") && namespace.startsWith("m365:")) ? previous : undefined,
|
|
199
249
|
onHistoryStored() {
|
|
200
250
|
if (!key) return;
|
|
201
251
|
const record = sessions.get(key);
|
|
@@ -208,6 +258,11 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
208
258
|
async action(input) {
|
|
209
259
|
return serialize(async () => {
|
|
210
260
|
if (closed) throw unavailable("m365_runtime_closed");
|
|
261
|
+
if (input.action === "accounts") {
|
|
262
|
+
const result = await discoverAccounts();
|
|
263
|
+
return { accounts: publicM365Accounts(result.accounts, result), state: snapshot() };
|
|
264
|
+
}
|
|
265
|
+
if (input.action === "account") return selectAccount(input.account_id);
|
|
211
266
|
if (input.action === "models") { await startM365();return { state: snapshot(), models: m365?.models(input.family === "claude" ? "claude" : "gpt") || [] }; }
|
|
212
267
|
if (input.action === "auto-review") {
|
|
213
268
|
if (input.provider && input.provider !== selection.codex) throw new Error("Save the source before changing review settings");
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { execFile } from "node:child_process";
|
|
3
|
+
import { promisify } from "node:util";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
|
|
6
|
+
const fail = code => Object.assign(new Error(code), { code });
|
|
7
|
+
const clean = (value, limit) => typeof value === "string" && value.length > 0 && value.length <= limit && !/[\u0000-\u0020\u007f]/.test(value);
|
|
8
|
+
export const accountChoiceId = account => createHash("sha256").update(`${account.tenant}\0${account.id}`).digest("hex");
|
|
9
|
+
|
|
10
|
+
export function normalizeBrokerAccounts(values) {
|
|
11
|
+
if (!Array.isArray(values) || values.length > 128) throw fail("m365_accounts_invalid");
|
|
12
|
+
const accounts = new Map();
|
|
13
|
+
for (const value of values) {
|
|
14
|
+
if (!clean(value?.homeAccountId, 512) || !clean(value.realm, 128) || !clean(value.username, 320) || !clean(value.accountId, 512)) continue;
|
|
15
|
+
// Personal Microsoft accounts cannot authorize this organization-only service.
|
|
16
|
+
if (value.realm.toLowerCase() === "9188040d-6c67-4c5b-b112-36a304b66dad") continue;
|
|
17
|
+
const account = { id: value.homeAccountId, tenant: value.realm, login: value.username };
|
|
18
|
+
const key = accountChoiceId(account), prior = accounts.get(key);
|
|
19
|
+
if (prior && (prior.login.toLowerCase() !== account.login.toLowerCase()
|
|
20
|
+
|| prior.native.environment !== value.environment || prior.native.localAccountId !== value.localAccountId)) throw fail("m365_account_conflict");
|
|
21
|
+
if (!prior) accounts.set(key, { ...account, native: value });
|
|
22
|
+
}
|
|
23
|
+
return [...accounts.values()];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export async function windowsAccountHint({ platform = process.platform, env = process.env, signal, execFileImpl = promisify(execFile) } = {}) {
|
|
27
|
+
if (platform !== "win32") return null;
|
|
28
|
+
try {
|
|
29
|
+
const { stdout } = await execFileImpl(path.win32.join(env.SystemRoot || env.WINDIR || "C:\\Windows", "System32", "whoami.exe"), ["/upn"],
|
|
30
|
+
{ env, signal, timeout: 2500, maxBuffer: 8192, windowsHide: true, encoding: "utf8" });
|
|
31
|
+
const upn = stdout.trim();
|
|
32
|
+
return clean(upn, 320) && /^[^@\s]+@[^@\s]+$/.test(upn) ? upn : null;
|
|
33
|
+
} catch { return null; }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function chooseM365Account(accounts, { binding, windowsLogin } = {}) {
|
|
37
|
+
if (binding) {
|
|
38
|
+
const matches = accounts.filter(value => value.id === binding.id && value.tenant === binding.tenant);
|
|
39
|
+
if (matches.length !== 1) throw fail("m365_account_unavailable");
|
|
40
|
+
return { ...matches[0], selection_source: ["manual", "windows", "single"].includes(binding.selection_source) ? binding.selection_source : "legacy" };
|
|
41
|
+
}
|
|
42
|
+
if (!accounts.length) throw fail("m365_account_unavailable");
|
|
43
|
+
const current = windowsLogin && accounts.filter(value => value.login.toLowerCase() === windowsLogin.toLowerCase());
|
|
44
|
+
if (current?.length === 1) return { ...current[0], selection_source: "windows" };
|
|
45
|
+
if (accounts.length === 1) return { ...accounts[0], selection_source: "single" };
|
|
46
|
+
throw fail("m365_account_ambiguous");
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function publicM365Accounts(accounts, { binding, windowsLogin } = {}) {
|
|
50
|
+
const matches = windowsLogin ? accounts.filter(value => value.login.toLowerCase() === windowsLogin.toLowerCase()) : [];
|
|
51
|
+
return accounts.map(account => ({ id: accountChoiceId(account), login: account.login, tenant: account.tenant,
|
|
52
|
+
selected: Boolean(binding && binding.id === account.id && binding.tenant === account.tenant),
|
|
53
|
+
current_windows: matches.length === 1 && matches[0] === account }));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function m365AccountMessage(code) {
|
|
57
|
+
return ({ m365_account_ambiguous: "Choose a company account in Model sources or run ccdx m365 account.",
|
|
58
|
+
m365_account_unavailable: "Company account unavailable. Connect it in Windows or macOS, then check again.",
|
|
59
|
+
m365_account_conflict: "Account records conflict. Check your company sign-in, then check again.",
|
|
60
|
+
m365_interaction_required: "Complete your company sign-in, then check again.",
|
|
61
|
+
m365_llm_permission_unavailable: "This account does not have model access.",
|
|
62
|
+
m365_account_busy: "Finish active Microsoft 365 requests before changing accounts.",
|
|
63
|
+
m365_account_changed: "This conversation belongs to another company account. Start a new conversation.",
|
|
64
|
+
m365_catalog_http_403: "Model access was denied. Check company permissions and network policy.",
|
|
65
|
+
m365_catalog_http_401: "Company authorization was rejected. Check your sign-in and company policy." })[code] || "Microsoft 365 is unavailable. Check company sign-in, network and permissions.";
|
|
66
|
+
}
|
|
@@ -6,6 +6,7 @@ import { promisify } from "node:util";
|
|
|
6
6
|
import { randomUUID } from "node:crypto";
|
|
7
7
|
import { fileURLToPath } from "node:url";
|
|
8
8
|
import path from "node:path";
|
|
9
|
+
import { normalizeBrokerAccounts, chooseM365Account, windowsAccountHint } from "./m365-accounts.mjs";
|
|
9
10
|
|
|
10
11
|
export const M365_CLIENT_ID = "aebc6443-996d-45c2-90f0-388ff96faa56";
|
|
11
12
|
export const M365_RESOURCE = "42c8f7bd-c7a8-4ba9-bc1c-91edfb716247";
|
|
@@ -19,9 +20,9 @@ export function brokerFailure(error) {
|
|
|
19
20
|
return { code, aadsts: [...new Set(String(error?.errorContext || "").match(/AADSTS\d+/g) || [])].slice(0, 3) };
|
|
20
21
|
}
|
|
21
22
|
|
|
22
|
-
export async function acquireSilentM365Token({ account = null } = {}, {
|
|
23
|
+
export async function acquireSilentM365Token({ account = null, action = "token" } = {}, {
|
|
23
24
|
platform = process.platform, loadBroker = () => createRequire(import.meta.url)("@azure/msal-node-runtime").msalNodeRuntime,
|
|
24
|
-
execFileImpl = promisify(execFile),
|
|
25
|
+
execFileImpl = promisify(execFile), env = process.env,
|
|
25
26
|
} = {}) {
|
|
26
27
|
if (!["darwin", "win32"].includes(platform)) throw fail("m365_platform_unsupported");
|
|
27
28
|
if (platform === "darwin") {
|
|
@@ -39,18 +40,19 @@ export async function acquireSilentM365Token({ account = null } = {}, {
|
|
|
39
40
|
catch (error) { reject(error); }
|
|
40
41
|
});
|
|
41
42
|
const discovered = await invoke("DiscoverAccountsAsync", M365_CLIENT_ID, randomUUID());
|
|
42
|
-
const accounts = (discovered.accounts || [])
|
|
43
|
-
const
|
|
44
|
-
|
|
45
|
-
if (
|
|
46
|
-
const selected =
|
|
43
|
+
const accounts = normalizeBrokerAccounts(discovered.accounts || []);
|
|
44
|
+
const windowsLogin = (!account || action === "accounts") && accounts.length > 1
|
|
45
|
+
? await windowsAccountHint({ platform, env, execFileImpl }) : null;
|
|
46
|
+
if (action === "accounts") return { accounts: accounts.map(({ native, ...value }) => value), windowsLogin };
|
|
47
|
+
const selected = chooseM365Account(accounts, { binding: account, windowsLogin }), parameters = new broker.AuthParameters();
|
|
47
48
|
parameters.CreateAuthParameters(M365_CLIENT_ID, AUTHORITY);
|
|
48
49
|
parameters.SetRedirectUri(platform === "darwin" ? "msauth.com.msauth.unsignedapp://auth" : `ms-appx-web://Microsoft.AAD.BrokerPlugin/${M365_CLIENT_ID}`);
|
|
49
50
|
parameters.SetRequestedScopes(`${M365_RESOURCE}/.default`);
|
|
50
|
-
const result = await invoke("AcquireTokenSilentlyAsync", parameters, randomUUID(), selected);
|
|
51
|
+
const result = await invoke("AcquireTokenSilentlyAsync", parameters, randomUUID(), selected.native);
|
|
51
52
|
if (!result.accessToken || !String(result.grantedScopes || "").split(" ").includes(`${M365_RESOURCE}/LLM.Read`)) throw fail("m365_llm_permission_unavailable");
|
|
53
|
+
if (result.account && (result.account.homeAccountId !== selected.id || result.account.realm !== selected.tenant)) throw fail("m365_account_changed");
|
|
52
54
|
return { token: result.accessToken, expiresAt: Number(result.expiresOn) * 1000,
|
|
53
|
-
account: { id: selected.
|
|
55
|
+
account: { id: selected.id, tenant: selected.tenant, login: selected.login, selection_source: selected.selection_source } };
|
|
54
56
|
}
|
|
55
57
|
|
|
56
58
|
async function main() {
|
|
@@ -63,7 +65,7 @@ async function main() {
|
|
|
63
65
|
if (Buffer.byteLength(input) > 4096) throw fail("m365_auth_request_invalid");
|
|
64
66
|
}
|
|
65
67
|
const request = JSON.parse(input);
|
|
66
|
-
if (request.action
|
|
68
|
+
if (!["token", "accounts"].includes(request.action)) throw fail("m365_auth_request_invalid");
|
|
67
69
|
const result = await acquireSilentM365Token(request);
|
|
68
70
|
process.stdout.write(JSON.stringify(result), () => process.exit(0));
|
|
69
71
|
} catch (error) { process.stdout.write(JSON.stringify({ error: brokerFailure(error) }), () => process.exit(1)); }
|
|
@@ -12,7 +12,7 @@ export function m365HelperEnvironment(env = process.env) {
|
|
|
12
12
|
return Object.fromEntries(Object.entries(env).filter(([key]) => keys.has(key.toUpperCase())));
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
-
|
|
15
|
+
function requestM365Helper({ action = "token", account, signal, env = process.env, spawnImpl = spawn, timeoutMs = 28000 } = {}) {
|
|
16
16
|
if (signal?.aborted) return Promise.reject(abortError(signal));
|
|
17
17
|
return new Promise((resolve, reject) => {
|
|
18
18
|
let child, timer, finished = false, bytes = 0;
|
|
@@ -46,6 +46,12 @@ export function requestM365Token({ account, signal, env = process.env, spawnImpl
|
|
|
46
46
|
finish(m365Error(/^m365_[a-z_]+$/.test(result.error?.code || "") ? result.error.code : "m365_auth_failed"));return;
|
|
47
47
|
}
|
|
48
48
|
try {
|
|
49
|
+
if (action === "accounts") {
|
|
50
|
+
if (!Array.isArray(result.accounts) || result.accounts.length > 128) throw Error();
|
|
51
|
+
for (const value of result.accounts) m365AccountKey(value);
|
|
52
|
+
if (result.windowsLogin !== null && (typeof result.windowsLogin !== "string" || result.windowsLogin.length > 320 || /[\r\n\0]/.test(result.windowsLogin))) throw Error();
|
|
53
|
+
finish(null, result);return;
|
|
54
|
+
}
|
|
49
55
|
m365AccountKey(result.account);
|
|
50
56
|
if (typeof result.token !== "string" || !result.token || /\s/.test(result.token)
|
|
51
57
|
|| !Number.isFinite(result.expiresAt) || result.expiresAt <= Date.now()) throw Error();
|
|
@@ -53,11 +59,14 @@ export function requestM365Token({ account, signal, env = process.env, spawnImpl
|
|
|
53
59
|
} catch { finish(m365Error("m365_auth_response_invalid"));return; }
|
|
54
60
|
finish(null, result);
|
|
55
61
|
});
|
|
56
|
-
child.stdin.end(JSON.stringify({ action
|
|
62
|
+
child.stdin.end(JSON.stringify({ action, account: account || null }));
|
|
57
63
|
});
|
|
58
64
|
}
|
|
59
65
|
|
|
60
|
-
export
|
|
66
|
+
export const requestM365Token = options => requestM365Helper({ ...options, action: "token" });
|
|
67
|
+
export const requestM365Accounts = options => requestM365Helper({ ...options, action: "accounts" });
|
|
68
|
+
|
|
69
|
+
export function createM365Auth({ home, env = process.env, account, acquire = requestM365Token, now = Date.now } = {}) {
|
|
61
70
|
let cached = null, flight = null, generation = 0, lastError = null, retryAt = 0, checkedAt = null;
|
|
62
71
|
const snapshot = () => ({ token_cached: Boolean(cached && cached.expiresAt > now()),
|
|
63
72
|
token_expires_in_ms: cached ? Math.max(0, cached.expiresAt - now()) : null,
|
|
@@ -71,7 +80,7 @@ export function createM365Auth({ home, env = process.env, acquire = requestM365T
|
|
|
71
80
|
if (!flight) {
|
|
72
81
|
const controller = new AbortController(), current = generation;
|
|
73
82
|
const entry = { controller, waiters: 0, settled: false, promise: null };
|
|
74
|
-
entry.promise = Promise.resolve().then(() => acquire({ account: cached?.account || readM365Account({ home }), env, signal: controller.signal }))
|
|
83
|
+
entry.promise = Promise.resolve().then(() => acquire({ account: cached?.account || account || readM365Account({ home }), env, signal: controller.signal }))
|
|
75
84
|
.then(result => {
|
|
76
85
|
if (current !== generation || controller.signal.aborted) throw abortError(controller.signal);
|
|
77
86
|
m365AccountKey(result.account);
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { m365Paths, readM365Json, writeM365Json, m365AccountKey } from "../m365-settings.mjs";
|
|
3
|
+
import { withFileLockSync } from "../lock.mjs";
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
|
|
6
|
+
const changed = () => Object.assign(new Error("This conversation belongs to another company account. Start a new conversation."),
|
|
7
|
+
{ code: "m365_account_changed", statusCode: 409 });
|
|
8
|
+
const hash = value => createHash("sha256").update(value).digest("hex");
|
|
9
|
+
|
|
10
|
+
export function createM365ConversationGuard({ home } = {}) {
|
|
11
|
+
const { directory, conversations: file } = m365Paths({ home });
|
|
12
|
+
let cached;
|
|
13
|
+
return (account, body, headers = {}) => {
|
|
14
|
+
const items = Array.isArray(body.messages) ? body.messages : Array.isArray(body.input) ? body.input : [];
|
|
15
|
+
let session = headers["session_id"] || headers["session-id"] || headers["x-conversation-id"] || headers["x-claude-code-session-id"];
|
|
16
|
+
if (!session && typeof body.metadata?.user_id === "string") {
|
|
17
|
+
try { session = JSON.parse(body.metadata.user_id)?.session_id; } catch { session = /(?:^|_)session_([\w-]{8,128})$/.exec(body.metadata.user_id)?.[1]; }
|
|
18
|
+
}
|
|
19
|
+
const first = items.find(item => item?.role === "user");
|
|
20
|
+
const key = typeof session === "string" && session.length > 0 && session.length <= 512 && !/[\u0000-\u001f\u007f]/.test(session)
|
|
21
|
+
? hash(`session\0${session}`) : first ? hash(`first\0${JSON.stringify(first)}`) : typeof body.input === "string" ? hash(`first\0${body.input}`) : null;
|
|
22
|
+
const hasHistory = Boolean(body.previous_response_id) || items.filter(item => item?.role === "user").length > 1
|
|
23
|
+
|| items.some(item => item?.role === "assistant" || item?.role === "tool" || /(?:call|output|reasoning|compaction)/.test(item?.type || "")
|
|
24
|
+
|| Array.isArray(item?.content) && item.content.some(part => part?.type === "tool_result"));
|
|
25
|
+
if (!key) { if (account.history_isolation && hasHistory) throw changed();return; }
|
|
26
|
+
const owner = m365AccountKey(account);
|
|
27
|
+
if (cached?.[key] === owner) return;
|
|
28
|
+
if (cached?.[key] && cached[key] !== owner) throw changed();
|
|
29
|
+
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
30
|
+
withFileLockSync(`${file}.lock`, () => {
|
|
31
|
+
const saved = readM365Json(file, { owners: {} });
|
|
32
|
+
if (!saved.owners || typeof saved.owners !== "object" || Array.isArray(saved.owners)
|
|
33
|
+
|| 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
|
+
const owners = saved.owners;
|
|
35
|
+
if (owners[key] && owners[key] !== owner || !owners[key] && account.history_isolation && hasHistory) throw changed();
|
|
36
|
+
if (owners[key]) { cached = owners;return; }
|
|
37
|
+
owners[key] = owner;
|
|
38
|
+
while (Object.keys(owners).length > 1024) delete owners[Object.keys(owners)[0]];
|
|
39
|
+
writeM365Json(file, { owners });cached = owners;
|
|
40
|
+
});
|
|
41
|
+
};
|
|
42
|
+
}
|
package/src/providers/m365.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
2
|
import { createM365Auth, m365Error } from "./m365-auth.mjs";
|
|
3
|
-
import { m365Paths, m365AccountKey, readM365Account, readM365Json,
|
|
3
|
+
import { m365Paths, m365AccountKey, readM365Account, readM365Json, writeM365Binding } from "../m365-settings.mjs";
|
|
4
4
|
import { MAX_UPSTREAM_ERROR_BODY_BYTES, MAX_UPSTREAM_MODEL_CATALOG_BYTES, readBoundedResponseText } from "../http-transport.mjs";
|
|
5
5
|
import { prepareResponsesPayload, summarizeReqBody } from "../image-optimization.mjs";
|
|
6
6
|
import { enforceResponsesPayloadByteBudget } from "../responses-byte-budget.mjs";
|
|
@@ -15,6 +15,7 @@ import { removeNativeImageTools } from "../responses-image-tools.mjs";
|
|
|
15
15
|
import { resolveClaudeModel } from "../claude-models.mjs";
|
|
16
16
|
import { modelReasoningEfforts } from "../provider-metadata.mjs";
|
|
17
17
|
import { limitM365CacheTtl } from "./m365-messages-policy.mjs";
|
|
18
|
+
import { createM365ConversationGuard } from "./m365-conversation-accounts.mjs";
|
|
18
19
|
|
|
19
20
|
export const M365_API_BASE = "https://df.loki.delve.office.com/api/v1/llmapi";
|
|
20
21
|
const SOFT_TTL_MS = 2 * 60 * 60 * 1000;
|
|
@@ -66,9 +67,11 @@ export function m365Models(catalog, family) {
|
|
|
66
67
|
&& model.supported_endpoints.some(endpoint => endpoint === "/responses" || endpoint === "/v1/responses"));
|
|
67
68
|
}
|
|
68
69
|
|
|
69
|
-
export function createM365Provider({ home, env = process.env,
|
|
70
|
+
export function createM365Provider({ home, env = process.env, account: accountOverride, persist = true,
|
|
71
|
+
auth = createM365Auth({ home, env, account: accountOverride }), fetchImpl,
|
|
70
72
|
createNetwork, now = Date.now, log = (kind, message) => console.log(status(kind, message)), onCatalog = () => {} } = {}) {
|
|
71
73
|
const paths = m365Paths({ home });
|
|
74
|
+
const guardConversation = createM365ConversationGuard({ home });
|
|
72
75
|
let catalog = null, account = null, catalogAt = 0, state = "idle", reason = null, flight = null, controller = null, generation = 0;
|
|
73
76
|
let network = null, networkFlight = null, cacheTtlAdjustments = 0;
|
|
74
77
|
const registry = { models: null, source: "unavailable", cacheState: "none", cacheSavedAtMs: null,
|
|
@@ -95,7 +98,7 @@ export function createM365Provider({ home, env = process.env, auth = createM365A
|
|
|
95
98
|
registry.source = source;registry.cacheSavedAtMs = savedAt;registry.cacheState = now() - savedAt < SOFT_TTL_MS ? "fresh" : "stale";
|
|
96
99
|
}
|
|
97
100
|
try {
|
|
98
|
-
account = readM365Account({ home });
|
|
101
|
+
account = accountOverride || readM365Account({ home });
|
|
99
102
|
const saved = readM365Json(paths.catalog);
|
|
100
103
|
if (account && saved?.account_key === m365AccountKey(account) && Number.isFinite(saved.saved_at)
|
|
101
104
|
&& now() - saved.saved_at < HARD_TTL_MS) applyCatalog(saved.models, "cache", saved.saved_at);
|
|
@@ -143,10 +146,11 @@ export function createM365Provider({ home, env = process.env, auth = createM365A
|
|
|
143
146
|
if (!response.ok) throw m365Error(`m365_catalog_http_${response.status}`);
|
|
144
147
|
let value;try { value = m365Catalog(JSON.parse(raw)); } catch { throw m365Error("m365_catalog_invalid"); }
|
|
145
148
|
if (current !== generation || signal.aborted) throw m365Error("m365_refresh_cancelled");
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
149
|
+
const savedAt = now();
|
|
150
|
+
const nextAccount = { ...credential.account, ...(account?.history_isolation ? { history_isolation: true } : {}) };
|
|
151
|
+
if (persist) writeM365Binding(nextAccount, { account_key: m365AccountKey(nextAccount), saved_at: savedAt, models: value }, { home, expectedAccount: account });
|
|
152
|
+
account = nextAccount;
|
|
153
|
+
applyCatalog(value, "live", savedAt);state = "ready";reason = null;registry.lastError = null;registry.lastErrorAtMs = null;
|
|
150
154
|
try { await onCatalog(value); } catch { log("warn", "M365 models are ready; optional client configuration could not be updated"); }
|
|
151
155
|
return value;
|
|
152
156
|
})().catch(error => {
|
|
@@ -180,6 +184,7 @@ export function createM365Provider({ home, env = process.env, auth = createM365A
|
|
|
180
184
|
cacheModelEndpoints() {},
|
|
181
185
|
async responses(body, options = {}) {
|
|
182
186
|
const model = selectedModel(body.model, "gpt");
|
|
187
|
+
if (account) guardConversation(account, body, currentRequestContext()?.clientHeaders || options.headers);
|
|
183
188
|
const prepared = await prepareResponsesPayload(body, { ...options.payloadOptions, assertActive: options.assertActive,
|
|
184
189
|
currentInputStart: options.currentInputStart || 0, signal: options.signal,
|
|
185
190
|
profiles: options.payloadPrepared ? [] : options.payloadOptions?.profiles,
|
|
@@ -197,6 +202,7 @@ export function createM365Provider({ home, env = process.env, auth = createM365A
|
|
|
197
202
|
async messages(body, options = {}) {
|
|
198
203
|
if (catalog && now() - catalogAt >= SOFT_TTL_MS && !flight) void refresh().catch(() => {});
|
|
199
204
|
const model = selectedModel(body.model, "claude");
|
|
205
|
+
if (account) guardConversation(account, body, options.headers);
|
|
200
206
|
const efforts = modelReasoningEfforts(model);
|
|
201
207
|
if (body.output_config?.effort !== undefined && efforts && !efforts.includes(body.output_config.effort)) {
|
|
202
208
|
throw protocolError("m365_effort_unavailable", "The selected effort is not advertised by this model. Refresh its model list and select an available effort.");
|
|
@@ -236,7 +242,12 @@ export function createM365Provider({ home, env = process.env, auth = createM365A
|
|
|
236
242
|
return { resp, reqContext: context, errorText, usedRetryPolicies: new Set() };
|
|
237
243
|
},
|
|
238
244
|
},
|
|
239
|
-
|
|
245
|
+
commitSelection(expectedAccount) {
|
|
246
|
+
if (!catalog || state !== "ready" || !account) throw m365Error("m365_not_ready");
|
|
247
|
+
writeM365Binding(account, { account_key: m365AccountKey(account), saved_at: catalogAt, models: catalog }, { home, expectedAccount });
|
|
248
|
+
persist = true;
|
|
249
|
+
},
|
|
250
|
+
snapshot: () => ({ ...auth.snapshot(), state, reason: reason || auth.snapshot().reason, account: account ? { login: account.login, tenant: account.tenant, selection_source: account.selection_source || "legacy" } : null,
|
|
240
251
|
network: network?.snapshot() || null,
|
|
241
252
|
cache_ttl_adjustments: cacheTtlAdjustments,
|
|
242
253
|
models: { total: catalog?.data.length || 0, claude: m365Models(catalog, "claude").length, gpt: m365Models(catalog, "gpt").length,
|
package/src/service-control.mjs
CHANGED
|
@@ -29,7 +29,7 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
29
29
|
if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("Invalid setting action");
|
|
30
30
|
const allowed = { preference: ["action", "key", "value"], animation: ["action", "theme"], color_theme: ["action", "theme"],
|
|
31
31
|
history_limit: ["action", "mib"], history_clean: ["action"], prediction_fix: ["action"],
|
|
32
|
-
provider: ["action", "operation", "provider", "model", "auto_review_model", "auto_review_effort"] }[input.action];
|
|
32
|
+
provider: ["action", "operation", "provider", "model", "auto_review_model", "auto_review_effort", "account_id"] }[input.action];
|
|
33
33
|
if (!allowed || Object.keys(input).some(key => !allowed.includes(key))) throw new Error("Unknown setting action or field");
|
|
34
34
|
if (input.action === "preference") {
|
|
35
35
|
writeServicePreference(input.key, input.value, options);
|
|
@@ -51,9 +51,11 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
51
51
|
try { writeResponseHistoryLimitMib(input.mib, options); } catch (error) { setHistoryCacheLimit(before);throw error; }
|
|
52
52
|
} else if (input.action === "history_clean") cleanRuntimeCaches({ history: true });
|
|
53
53
|
else {
|
|
54
|
-
if (!providerRuntime || !["on", "off", "switch", "auto-review"].includes(input.operation)) throw new Error("Invalid provider operation");
|
|
54
|
+
if (!providerRuntime || !["on", "off", "switch", "auto-review", "account"].includes(input.operation)) throw new Error("Invalid provider operation");
|
|
55
|
+
if (input.operation === "account" && (typeof input.account_id !== "string" || !/^[a-f0-9]{64}$/.test(input.account_id))) throw new Error("Select an available company account");
|
|
55
56
|
if (input.operation === "on" && env.CCDX_M365 === "0") throw new Error("Microsoft 365 is disabled by CCDX_M365=0");
|
|
56
|
-
await providerRuntime.action({ action: input.operation, provider: input.provider, model: input.model, auto_review_model: input.auto_review_model, auto_review_effort: input.auto_review_effort, effort: input.auto_review_effort
|
|
57
|
+
await providerRuntime.action({ action: input.operation, provider: input.provider, model: input.model, auto_review_model: input.auto_review_model, auto_review_effort: input.auto_review_effort, effort: input.auto_review_effort,
|
|
58
|
+
...(input.operation === "account" ? { account_id: input.account_id } : {}) });
|
|
57
59
|
}
|
|
58
60
|
return snapshot();
|
|
59
61
|
}
|