codex-copilot-dx 1.2.27 → 1.2.28
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 +19 -3
- package/docs/REFERENCE.md +32 -1
- package/package.json +1 -1
- package/src/claude-gateway.mjs +8 -3
- package/src/connection-runtime.mjs +9 -1
- package/src/conversation-source-guard.mjs +15 -5
- package/src/messages-history-transfer.mjs +158 -0
- package/src/providers/m365-conversation-accounts.mjs +7 -2
- package/src/providers/m365.mjs +1 -1
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.28/install.sh) (macOS/Linux) or [install.ps1](https://github.com/DaleXiao/codex-copilot-dx/releases/download/v1.2.28/install.ps1) (Windows), then run `sh install.sh` or `./install.ps1` under your current shell policy. The bootstrap reuses compatible Node/npm or installs verified official Node 24.22.0 privately for CCDX. It adds no Git, compiler or system package manager. It keeps registry/proxy/certificate policy, verifies the Release package and installed runtime, and restores the prior CCDX package if installation fails. Dependencies still need your configured registry. See [installation limits and private command paths](docs/REFERENCE.md#install-without-node-or-git).
|
|
15
15
|
|
|
16
16
|
CCDX reuses a compatible local credential or starts GitHub Device Flow, listens on `127.0.0.1:2026`, configures Codex, and opens the App. Interactive desktop starts also open the local WebUI once; use `ccdx --no-browser` or disable this in WebUI settings. No client binary patch is needed. On Windows, open the App manually unless native prediction setup is enabled. In restricted Windows PowerShell, use `npm.cmd` to install and `ccdx.cmd` for the first launch, or run `ccdx.cmd doctor --fix`. Startup, updates and explicit repair remove only CCDX's exact npm-generated `.ps1` launchers so later calls can use `ccdx`. The npm package adds no install hook or policy change; custom launchers are preserved. npm's own script is untouched. The configured `dummy` API key is a placeholder, not a credential.
|
|
17
17
|
|
|
@@ -52,11 +52,11 @@ Requests shows live app/source/model flow above existing summaries and finished
|
|
|
52
52
|
|
|
53
53
|
## Add your own API
|
|
54
54
|
|
|
55
|
-
Run `ccdx web` without GitHub sign-in. In **Model sources → Add API**, enter the HTTPS address/key, read the catalog, select models and declare their real interfaces. Then open **Codex** or **Claude**, choose visible models across sources, set a default and save. Claude App/Code use Messages; Codex uses Responses, all on port 2026. GitHub-only Codex selections retain native OpenAI mode and readable model names. Token counting is separate from message generation. For manual APIs, an observed count-endpoint 404 is remembered for one minute per model/API-header scope; CCDX returns a clear 404 without inventing a token count. Unknown count capabilities share their first admitted request; a 404 prevents distinct waiting inputs from fanning out. A supported endpoint still counts each distinct input separately. Identical small count requests share bounded work. A request stays on its selected deployment; there is no automatic cross-source retry or model replacement. Reopen clients after configuration changes
|
|
55
|
+
Run `ccdx web` without GitHub sign-in. In **Model sources → Add API**, enter the HTTPS address/key, read the catalog, select models and declare their real interfaces. Then open **Codex** or **Claude**, choose visible models across sources, set a default and save. Claude App/Code use Messages; Codex uses Responses, all on port 2026. GitHub-only Codex selections retain native OpenAI mode and readable model names. Token counting is separate from message generation. For manual APIs, an observed count-endpoint 404 is remembered for one minute per model/API-header scope; CCDX returns a clear 404 without inventing a token count. Unknown count capabilities share their first admitted request; a 404 prevents distinct waiting inputs from fanning out. A supported endpoint still counts each distinct input separately. Identical small count requests share bounded work. A request stays on its selected deployment; there is no automatic cross-source retry or model replacement. Reopen clients after configuration changes. Claude App can continue an existing conversation on a different selected, authorized source when complete Messages history is available; unfinished tool turns, unavailable attachments and company-account isolation still apply. Codex and Claude Code retain their existing history rules. Stop management before normal `ccdx` startup for the live terminal.
|
|
56
56
|
|
|
57
57
|
Keys use system credential protection or an explicit environment reference; clients receive separate local credentials. Saving reads model metadata automatically, without inference. Startup and the existing model refresh cycle also refresh enabled APIs when the 30-minute cache expires; failed reads retain saved configuration. Selecting no models pauses access; enable a source and select models to resume. Closed sources can be restored on Model sources; closed apps remain reachable for restoration on their app pages. Pinned streams finish on their original source. The version-two graph preserves old single-source visibility and saves a byte-for-byte v1 backup before migration. User and managed client settings remain protected.
|
|
58
58
|
|
|
59
|
-
Model lists/details preserve the upstream maker declaration separately from your API source name. Missing maker metadata shows Not provided; model names are never used to guess a maker. Maker evidence is rebuildable display cache and does not change the strict connection schema or routing identity. Model details show upstream capabilities per API, with optional manual overrides collapsed below. Context, input/output limits, reasoning levels, thinking modes, input types, tools and native search are deployment-specific. Structured Anthropic declarations are mapped to Messages; they do not grant the same capabilities to a gateway's other interfaces. Missing and unrecognized metadata are distinguished, without guessing from model names. Manual overrides, including false, take priority. Claude synchronization projects compatible routes, supported host controls and per-model budgets. Unknown or out-of-range windows and unverified client versions are reported as limited; they are not promoted to 1M. Output requests are bounded by declared limits. Compatibility routes do not prove that every model supports every App tool, search or reasoning mode. See the [capability and synchronization limits](docs/REFERENCE.md#model-capabilities-and-claude-synchronization). [1.2.
|
|
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.28 changes and verification](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/RELEASE_1.2.28.md) cover Claude App cross-source conversation continuation, with persistent hashed history checkpoints, native tool pairs and unchanged Codex sign-in/model configuration. The 1.2.27 context-preference fix remains included.
|
|
60
60
|
|
|
61
61
|
## Microsoft 365 access
|
|
62
62
|
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -135,9 +135,25 @@ For this same manual App boundary, system-role text is collected into the native
|
|
|
135
135
|
top-level system field in order; conversation blocks and their order are retained.
|
|
136
136
|
|
|
137
137
|
`conversation-source-guard.mjs` retains bounded HMAC correlations for observed
|
|
138
|
-
managed histories.
|
|
139
|
-
|
|
140
|
-
|
|
138
|
+
managed histories. Codex and Claude Code retain their existing conflict checks.
|
|
139
|
+
Claude App explicitly supplies the protocol-level `messages-history-transfer.mjs`
|
|
140
|
+
policy after resolving an authorized model/source. The policy has no application,
|
|
141
|
+
provider or model-name rules. It rebuilds only the forwarded Messages prefix,
|
|
142
|
+
removes source-private thinking from that prefix, preserves native completed tool
|
|
143
|
+
pairs and available media, and rejects unfinished tools or unrecoverable source
|
|
144
|
+
handles. New-source thinking after the checkpoint stays unchanged. Changed
|
|
145
|
+
prefixes can be rebuilt only at a completed tool boundary. It adds no automatic
|
|
146
|
+
retry, summary inference, routing fallback or conversation database.
|
|
147
|
+
|
|
148
|
+
Transfer records are bounded to 1024 hashed keys in a 512 KiB versioned file;
|
|
149
|
+
they contain owner hashes, prefix hashes and message counts, not transcripts.
|
|
150
|
+
Count/model-validation requests do not rebind. A per-conversation request lease
|
|
151
|
+
pins active source work; the gateway commits a checkpoint immediately before
|
|
152
|
+
delivering usable output/tool/private state and releases every lease on failure
|
|
153
|
+
or completion. Pre-output errors preserve the earlier checkpoint, while partial
|
|
154
|
+
output keeps the actual source's provenance. A matching private request grant
|
|
155
|
+
allows first association with the selected M365 account; known foreign account
|
|
156
|
+
owners are still refused. Native Responses recovery/configuration is unchanged.
|
|
141
157
|
|
|
142
158
|
`dashboard/connections.js` owns settings forms; application source/review and
|
|
143
159
|
account/catalog views keep their existing scopes and use the same backend graph.
|
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.28/codex-copilot-dx-1.2.28.tgz
|
|
1340
1340
|
# Windows PowerShell: use npm.cmd instead of npm.
|
|
1341
1341
|
```
|
|
1342
1342
|
|
|
@@ -2184,6 +2184,37 @@ without that header remain unchanged. This header is correlation only: model
|
|
|
2184
2184
|
access and the company's account/history checks remain authoritative.
|
|
2185
2185
|
|
|
2186
2186
|
|
|
2187
|
+
### Claude App cross-source continuation
|
|
2188
|
+
|
|
2189
|
+
In Claude App, choose another model that you have selected and authorized for
|
|
2190
|
+
that app. CCDX can continue the same conversation across Messages sources using
|
|
2191
|
+
the complete history supplied by the client. This is explicit model selection,
|
|
2192
|
+
not automatic failover. Codex and Claude Code retain their existing source rules.
|
|
2193
|
+
|
|
2194
|
+
CCDX preserves the original client conversation. In the forwarded request it
|
|
2195
|
+
keeps visible messages, available image/document content, and completed native
|
|
2196
|
+
tool calls/results; it removes incompatible old-source thinking and records a
|
|
2197
|
+
hashed history checkpoint. Subsequent thinking from the new source is retained.
|
|
2198
|
+
A changed/compacted client prefix is rebuilt only between completed tool turns.
|
|
2199
|
+
No automatic summary, tool execution, history truncation or hidden inference is
|
|
2200
|
+
added. Target capabilities and input/output limits still apply; unsupported
|
|
2201
|
+
upstream behavior is reported without retrying another source.
|
|
2202
|
+
|
|
2203
|
+
Finish a running response/tool operation before changing sources. Incomplete
|
|
2204
|
+
tool pairs, source-owned file/container handles and unrecoverable encrypted
|
|
2205
|
+
history require completing the operation or restoring the original content.
|
|
2206
|
+
Known history belonging to a different company account remains blocked. Model
|
|
2207
|
+
validation and token counting do not move a conversation's source. A failed
|
|
2208
|
+
request before usable output leaves its prior checkpoint; partial output keeps
|
|
2209
|
+
the actual new-source checkpoint and is never automatically replayed.
|
|
2210
|
+
|
|
2211
|
+
`conversation-transfers.json`, beside `connections.json`, stores at most 1024
|
|
2212
|
+
HMAC-keyed entries with source/prefix hashes and message counts, within a 512 KiB
|
|
2213
|
+
read limit. It stores no prompts, files, raw session IDs or credentials. Records
|
|
2214
|
+
survive ordinary service restart; corrupt records are preserved and reported,
|
|
2215
|
+
not replaced with empty defaults. This does not persist Responses history or
|
|
2216
|
+
change Codex login/provider/model-list configuration.
|
|
2217
|
+
|
|
2187
2218
|
### Upstream maker metadata
|
|
2188
2219
|
|
|
2189
2220
|
Manual API discovery accepts bounded text from publisher, vendor and owned_by.
|
package/package.json
CHANGED
package/src/claude-gateway.mjs
CHANGED
|
@@ -23,6 +23,8 @@ function send(res, code, value) {
|
|
|
23
23
|
res.writeHead(code, { "Content-Type": "application/json", "Cache-Control": "no-store" });res.end(JSON.stringify(value));
|
|
24
24
|
}
|
|
25
25
|
const apiError = (code, message) => ({ type: "error", error: { type: "api_error", code, message } });
|
|
26
|
+
const hasMessageState = block => Boolean(block && (block.id || block.signature || block.data
|
|
27
|
+
|| typeof block.text === "string" && block.text.length || typeof block.thinking === "string" && block.thinking.length));
|
|
26
28
|
function desktopMessages(body) {
|
|
27
29
|
const messages = [], instructions = [];
|
|
28
30
|
const blocks = content => {
|
|
@@ -119,7 +121,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
119
121
|
const tracker = countTokens ? parent?.streamPerformance : performance.begin("messages", { requestId, application: requestApplication(req.headers, "claude") });
|
|
120
122
|
if (!resolveRequest) tracker?.setProvider(provider.id);
|
|
121
123
|
const abort = createRequestAbort(req, res);
|
|
122
|
-
let release = () => {}, outcome = "failed", model = null, configuredModel = null, clientModel = null, responseId = null, usage = null, stopReason = null, streamed = false, sawStop = false, failedEvent = false;
|
|
124
|
+
let release = () => {}, conversation, outcome = "failed", model = null, configuredModel = null, clientModel = null, responseId = null, usage = null, stopReason = null, streamed = false, sawStop = false, failedEvent = false;
|
|
123
125
|
let terminalOrigin = "client_validation", failureStatus = null, countDeadline = null, rejectionReason;
|
|
124
126
|
if (!countTokens) { stats.total++;stats.active++;stats.last_request_at = new Date().toISOString(); }
|
|
125
127
|
const context = parent || { requestId };
|
|
@@ -152,7 +154,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
152
154
|
context.model = configuredModel || model;
|
|
153
155
|
if (!countTokens) markRequestObservation({ max_output_tokens_requested: body.max_tokens });
|
|
154
156
|
tracker?.setModel(configuredModel || model, { configured: Boolean(configuredModel) });
|
|
155
|
-
validateConversation?.(body, req.headers, selectedProvider);
|
|
157
|
+
conversation = validateConversation?.(body, req.headers, selectedProvider);
|
|
156
158
|
terminalOrigin = "transport";
|
|
157
159
|
const upstream = await selectedProvider.client.messages(body, { headers: req.headers, countTokens, signal: abort.signal,
|
|
158
160
|
onCountObservation(value) {
|
|
@@ -179,6 +181,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
179
181
|
if (!upstream.ok) context.onHttpError?.({ ...upstreamErrorEvidence(raw),
|
|
180
182
|
origin: context.countObservation?.cached ? "capability_cache" : "upstream_http", headers: upstream.headers });
|
|
181
183
|
if (!countTokens && upstream.ok && value?.type === "message" && Array.isArray(value.content)) {
|
|
184
|
+
if (value.content.some(hasMessageState)) conversation?.commit?.({ tool: value.content.some(block => block?.type === "tool_use") });
|
|
182
185
|
model = value.model || model;responseId = value.id;usage = value.usage;stopReason = value.stop_reason;
|
|
183
186
|
sawStop = typeof stopReason === "string";outcome = stopReason === "max_tokens" ? "incomplete" : sawStop ? "completed" : "failed";
|
|
184
187
|
} else if (countTokens && upstream.ok) outcome = "completed";
|
|
@@ -191,6 +194,8 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
191
194
|
const observer = createMessagesObserver(event => {
|
|
192
195
|
if (event.type === "error") { failedEvent = true;outcome = "failed";return; }
|
|
193
196
|
if (sawStop || failedEvent) return;
|
|
197
|
+
if (event.type === "content_block_start" && hasMessageState(event.content_block)
|
|
198
|
+
|| event.type === "content_block_delta" && (isMessagesOutputDelta(event.delta) || event.delta?.type === "signature_delta" && event.delta.signature)) conversation?.commit?.({ tool: event.content_block?.type === "tool_use" });
|
|
194
199
|
if (event.type === "message_start") { responseId = event.message?.id;model = event.message?.model || model;usage = event.message?.usage || {}; }
|
|
195
200
|
if (event.type === "content_block_delta" && isMessagesOutputDelta(event.delta)) tracker?.firstOutput();
|
|
196
201
|
if (event.type === "message_delta") { usage = { ...usage, ...event.usage };stopReason = event.delta?.stop_reason || stopReason; }
|
|
@@ -232,7 +237,7 @@ export function createClaudeGatewayHandler({ provider, apiKey, desktopAliases =
|
|
|
232
237
|
}
|
|
233
238
|
else if (!res.destroyed && !res.writableEnded) res.end(`event: error\ndata: ${JSON.stringify(apiError("ccdx_gateway_error", message))}\n\n`);
|
|
234
239
|
} finally {
|
|
235
|
-
release();abort.cleanup();finishProvider();
|
|
240
|
+
conversation?.release?.();release();abort.cleanup();finishProvider();
|
|
236
241
|
if (!countTokens) {
|
|
237
242
|
stats.active--;stats[outcome]++;
|
|
238
243
|
const usageRecord = buildMessagesUsageRecord({ model: configuredModel || model, responseId, usage, mode: streamed ? "stream" : "json",
|
|
@@ -13,6 +13,7 @@ import { configureCodexApi } from "./codex-api-config.mjs";
|
|
|
13
13
|
import { autoReviewReasoningEfforts } from "./models.mjs";
|
|
14
14
|
import { createRequestAdmission } from "./request-admission.mjs";
|
|
15
15
|
import { createConversationSourceGuard } from "./conversation-source-guard.mjs";
|
|
16
|
+
import { createMessagesHistoryTransfer } from "./messages-history-transfer.mjs";
|
|
16
17
|
import { compileClientModels, sourceModels } from "./client-model-plan.mjs";
|
|
17
18
|
import { codexClientCatalog, codexSourceCatalog } from "./clients/codex-models.mjs";
|
|
18
19
|
import { currentRequestContext } from "./request-context.mjs";
|
|
@@ -25,6 +26,7 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
25
26
|
configureCodex = configureCodexApi, inspectDesktop = inspectClaudeDesktopPolicy, clientAccessChanged, preserveClientConfiguration, now = Date.now, log = () => {} } = {}) {
|
|
26
27
|
const options = { home, env, platform, preserveClientConfiguration }, secrets = secretStore || createApiSecretStore(options), modelDisplay = createApiModelDisplayStore(options);
|
|
27
28
|
const guardConversation = createConversationSourceGuard(options), acquireClaudeRequest = createRequestAdmission({ maxBytes: 16 * 1024 * 1024, maxQueued: 8 });
|
|
29
|
+
const messagesTransfer = createMessagesHistoryTransfer({ ...options, onTransfer: () => log("info", "Conversation continued on the selected source; original history kept") });
|
|
28
30
|
const memoryModel = createCodexMemoryModel({ ...options, corePort });
|
|
29
31
|
let settings = readAccessSettings(options), managed = fs.existsSync(accessSettingsPath(options)), serial = Promise.resolve(), keys, closed = false;
|
|
30
32
|
const instances = new Map(), active = new Map(), retired = new Set(), handlers = new Map(), summaries = new WeakMap(), sourceSecrets = new WeakMap(), setup = {}, lastClients = {};
|
|
@@ -204,7 +206,13 @@ export function createConnectionRuntime({ legacy, home, env = process.env, platf
|
|
|
204
206
|
}
|
|
205
207
|
function validateConversation(body, headers, source, client = "codex") {
|
|
206
208
|
if (!body || typeof body !== "object" || Array.isArray(body)) return;
|
|
207
|
-
if (managed && (binding(client).history_isolation || source?.id.startsWith("api_")
|
|
209
|
+
if (managed && (binding(client).history_isolation || source?.id.startsWith("api_") || client === "claude_app")) {
|
|
210
|
+
const transfer = client === "claude_app" ? {
|
|
211
|
+
profiles: [...new Set(plan(client).models.map(model => model.source_id))].map(id => getSource(id).profileId("messages")),
|
|
212
|
+
prepare: input => messagesTransfer.prepare({ ...input, countTokens: currentRequestContext()?.route === "messages_count_tokens" }),
|
|
213
|
+
} : undefined;
|
|
214
|
+
return guardConversation(client, source.profileId(client === "codex" ? "responses" : "messages"), body, headers, identities()[client], transfer);
|
|
215
|
+
}
|
|
208
216
|
}
|
|
209
217
|
async function applyCatalog(id, models, revision, checkedAt, active) {
|
|
210
218
|
if (!active()) throw accessError("ccdx_connections_conflict", 409);
|
|
@@ -9,7 +9,7 @@ import { withFileLockSync } from "./lock.mjs";
|
|
|
9
9
|
// Correlation only: retain hashes, never prompts, session IDs or credentials.
|
|
10
10
|
export function createConversationSourceGuard(options = {}) {
|
|
11
11
|
const file = path.join(path.dirname(accessSettingsPath(options)), "conversation-sources.json");let cache;
|
|
12
|
-
return (client, profile, body, headers = {}, salt) => {
|
|
12
|
+
return (client, profile, body, headers = {}, salt, transfer) => {
|
|
13
13
|
const hash = value => createHmac("sha256", salt).update(value).digest("hex");
|
|
14
14
|
const items = Array.isArray(body.messages) ? body.messages : Array.isArray(body.input) ? body.input : [];
|
|
15
15
|
const hasHistory = Boolean(body.previous_response_id) || items.filter(item => item?.role === "user").length > 1
|
|
@@ -25,20 +25,30 @@ export function createConversationSourceGuard(options = {}) {
|
|
|
25
25
|
const agent = headers["x-claude-code-agent-id"];
|
|
26
26
|
const child = identified && ["claude_app", "claude_code"].includes(client) && typeof agent === "string" && /^[\w-]{1,128}$/.test(agent) ? `\0agent\0${agent}` : "";
|
|
27
27
|
const key = hash(client + "\0" + input + child), owner = hash(profile);
|
|
28
|
-
|
|
29
|
-
|
|
28
|
+
const prepare = previousOwner => transfer?.prepare({ key, owner, previousOwner, profile, body,
|
|
29
|
+
knownOwners: transfer.profiles?.map(hash) || [] });
|
|
30
|
+
let prepared;
|
|
31
|
+
if (cache?.[key]) {
|
|
32
|
+
prepared = prepare(cache[key]);
|
|
33
|
+
if (prepared?.handled || cache[key] === owner) return prepared;
|
|
34
|
+
prepared?.release();
|
|
35
|
+
if (identified || hasHistory) throw accessError("ccdx_conversation_source_changed", 409);
|
|
36
|
+
}
|
|
30
37
|
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
31
|
-
withFileLockSync(`${file}.lock`, () => {
|
|
38
|
+
try { return withFileLockSync(`${file}.lock`, () => {
|
|
32
39
|
let owners = {};
|
|
33
40
|
try { owners = JSON.parse(readBoundedFileSync(file, { encoding: "utf8", maxBytes: 256 * 1024 })); } catch (error) { if (error.code !== "ENOENT") throw accessError("ccdx_conversation_state_invalid", 409); }
|
|
34
41
|
if (!owners || typeof owners !== "object" || Array.isArray(owners) || Object.keys(owners).length > 1024
|
|
35
42
|
|| Object.entries(owners).some(([key, owner]) => !/^[a-f0-9]{64}$/.test(key) || !/^[a-f0-9]{64}$/.test(owner))) throw accessError("ccdx_conversation_state_invalid", 409);
|
|
43
|
+
prepared = prepare(owners[key]);
|
|
44
|
+
if (prepared?.handled) { cache = owners;return prepared; }
|
|
36
45
|
if (owners[key] && owners[key] !== owner && (identified || hasHistory)) throw accessError("ccdx_conversation_source_changed", 409);
|
|
37
46
|
if (owners[key] !== owner) {
|
|
38
47
|
owners[key] = owner;while (Object.keys(owners).length > 1024) delete owners[Object.keys(owners)[0]];
|
|
39
48
|
atomicWriteFileSync(file, JSON.stringify(owners) + "\n", { mode: 0o600 });
|
|
40
49
|
}
|
|
41
50
|
cache = owners;
|
|
42
|
-
|
|
51
|
+
return prepared;
|
|
52
|
+
}); } catch (error) { prepared?.release();throw error; }
|
|
43
53
|
};
|
|
44
54
|
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { accessSettingsPath } from "./access-settings.mjs";
|
|
5
|
+
import { readBoundedFileSync } from "./bounded-file.mjs";
|
|
6
|
+
import { atomicWriteFileSync } from "./atomic-file.mjs";
|
|
7
|
+
import { withFileLockSync } from "./lock.mjs";
|
|
8
|
+
|
|
9
|
+
const grants = new WeakMap(), HASH = /^[a-f0-9]{64}$/, LIMIT = 1024;
|
|
10
|
+
const digest = value => createHash("sha256").update(JSON.stringify(value, (key, entry) => key === "cache_control" ? undefined : entry)).digest("hex");
|
|
11
|
+
const parts = message => Array.isArray(message?.content) ? message.content : [];
|
|
12
|
+
const thinking = part => ["thinking", "redacted_thinking", "reasoning"].includes(part?.type);
|
|
13
|
+
const history = body => body.messages.some(message => message?.role === "assistant" || parts(message).some(part => part?.type === "tool_result"))
|
|
14
|
+
|| body.messages.filter(message => message?.role === "user").length > 1;
|
|
15
|
+
const fail = (code, message) => { throw Object.assign(new Error(message), { code, statusCode: 409 }); };
|
|
16
|
+
const invalidState = () => fail("ccdx_history_transfer_state_invalid", "History transfer records could not be read. Existing records and conversation were kept.");
|
|
17
|
+
|
|
18
|
+
// Only a locally prepared request can carry this grant; HTTP fields cannot set it.
|
|
19
|
+
export const messagesHistoryTransferGrant = body => {
|
|
20
|
+
const grant = grants.get(body);return grant?.active ? grant : undefined;
|
|
21
|
+
};
|
|
22
|
+
export function messagesTransferPath(options = {}) {
|
|
23
|
+
return path.join(path.dirname(accessSettingsPath(options)), "conversation-transfers.json");
|
|
24
|
+
}
|
|
25
|
+
function checkedRecords(value) {
|
|
26
|
+
if (!value || value.version !== 1 || !value.records || typeof value.records !== "object" || Array.isArray(value.records)
|
|
27
|
+
|| Object.keys(value).some(key => !["version", "records"].includes(key)) || Object.keys(value.records).length > LIMIT) invalidState();
|
|
28
|
+
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))
|
|
30
|
+
|| !HASH.test(record.owner) || !HASH.test(record.prefix) || !Number.isSafeInteger(record.count) || record.count < 1 || record.count > 1_000_000) invalidState();
|
|
31
|
+
}
|
|
32
|
+
return value.records;
|
|
33
|
+
}
|
|
34
|
+
function checkBlocks(blocks) {
|
|
35
|
+
for (const part of blocks) {
|
|
36
|
+
if (thinking(part)) continue;
|
|
37
|
+
if (!part || !["text", "image", "document", "tool_use", "tool_result", "tool_reference"].includes(part.type)) {
|
|
38
|
+
fail("ccdx_history_transfer_content_unsupported", "This content cannot be transferred safely. The original conversation was kept.");
|
|
39
|
+
}
|
|
40
|
+
const stack = [part];
|
|
41
|
+
while (stack.length) {
|
|
42
|
+
const value = stack.pop();if (!value || typeof value !== "object") continue;
|
|
43
|
+
if (Array.isArray(value)) { for (const child of value) stack.push(child);continue; }
|
|
44
|
+
if (["file_id", "container_id", "encrypted_content", "previous_response_id"].some(key => Object.hasOwn(value, key))
|
|
45
|
+
|| ["compaction", "item_reference"].includes(value.type)) {
|
|
46
|
+
fail("ccdx_history_transfer_rebuild_required", "Restore the original messages or attachment before switching. Source-owned state cannot be transferred.");
|
|
47
|
+
}
|
|
48
|
+
for (const [key, child] of Object.entries(value)) if (key !== "input") stack.push(child);
|
|
49
|
+
}
|
|
50
|
+
if (part.type === "tool_result" && Array.isArray(part.content)) checkBlocks(part.content);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
function checkHistory(body, counting) {
|
|
54
|
+
if (body.previous_response_id || body.conversation || body.container) {
|
|
55
|
+
fail("ccdx_history_transfer_rebuild_required", "Restore complete message history before switching. The original conversation was kept.");
|
|
56
|
+
}
|
|
57
|
+
const pending = new Set();
|
|
58
|
+
for (const message of body.messages) {
|
|
59
|
+
if (!message || !["user", "assistant"].includes(message.role) || !(typeof message.content === "string" || Array.isArray(message.content))) {
|
|
60
|
+
fail("ccdx_history_transfer_invalid", "Message history is incomplete or invalid. The original conversation was kept.");
|
|
61
|
+
}
|
|
62
|
+
if (message.role === "assistant" && pending.size) fail("ccdx_history_transfer_tool_incomplete", "Finish the current tool operation before switching. No tool was repeated.");
|
|
63
|
+
checkBlocks(parts(message));
|
|
64
|
+
for (const part of parts(message)) {
|
|
65
|
+
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.");
|
|
67
|
+
pending.add(part.id);
|
|
68
|
+
}
|
|
69
|
+
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.");
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
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.");
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
function project(body, count) {
|
|
79
|
+
let removed = 0;
|
|
80
|
+
body.messages = body.messages.map((message, index) => {
|
|
81
|
+
if (index >= count || message.role !== "assistant") return message;
|
|
82
|
+
const out = { ...message };delete out.reasoning_content;
|
|
83
|
+
if (Array.isArray(message.content)) {
|
|
84
|
+
out.content = message.content.filter(part => { if (!thinking(part)) return true;removed++;return false; });
|
|
85
|
+
if (!out.content.length) return null;
|
|
86
|
+
}
|
|
87
|
+
return out;
|
|
88
|
+
}).filter(Boolean);
|
|
89
|
+
return removed;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Caller selects eligible clients. This module knows only Messages and source
|
|
93
|
+
// fingerprints; it neither changes routing nor stores conversation contents.
|
|
94
|
+
export function createMessagesHistoryTransfer(options = {}) {
|
|
95
|
+
const file = messagesTransferPath(options), active = new Map();let records;
|
|
96
|
+
function read() {
|
|
97
|
+
try { return checkedRecords(JSON.parse(readBoundedFileSync(file, { encoding: "utf8", maxBytes: 512 * 1024 }))); }
|
|
98
|
+
catch (error) { if (error.code === "ENOENT") return {};invalidState(); }
|
|
99
|
+
}
|
|
100
|
+
function save(key, record) {
|
|
101
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
102
|
+
withFileLockSync(`${file}.lock`, () => {
|
|
103
|
+
const next = read();delete next[key];next[key] = record;
|
|
104
|
+
while (Object.keys(next).length > LIMIT) delete next[Object.keys(next)[0]];
|
|
105
|
+
atomicWriteFileSync(file, JSON.stringify({ version: 1, records: next }) + "\n", { mode: 0o600 });records = next;
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
return { prepare({ key, owner, previousOwner, profile, body, countTokens = false, knownOwners = [] }) {
|
|
109
|
+
if (!Array.isArray(body?.messages) || body.input !== undefined) return null;
|
|
110
|
+
records ||= read();const entry = records[key], changed = entry ? entry.owner !== owner : Boolean(previousOwner && previousOwner !== owner);
|
|
111
|
+
const initial = knownOwners.includes(entry?.owner || previousOwner);
|
|
112
|
+
const hasHistory = history(body), noncommitting = countTokens || Boolean(changed || entry) && !hasHistory;
|
|
113
|
+
if (noncommitting) {
|
|
114
|
+
if (changed || entry) {
|
|
115
|
+
checkHistory(body, true);
|
|
116
|
+
const count = entry?.owner === owner && body.messages.length >= entry.count && digest(body.messages.slice(0, entry.count)) === entry.prefix
|
|
117
|
+
? entry.count : body.messages.length;
|
|
118
|
+
project(body, count);
|
|
119
|
+
}
|
|
120
|
+
const grant = { profile, noncommitting: true, initial, active: true };grants.set(body, grant);
|
|
121
|
+
const checkpoint = countTokens ? null : { owner, count: body.messages.length, prefix: digest(body.messages) };
|
|
122
|
+
let toolLease, committed = false;
|
|
123
|
+
return { handled: true, commit(state) {
|
|
124
|
+
// A no-history model probe must not pin the conversation. An actual
|
|
125
|
+
// tool call must: its following results continue this very same turn.
|
|
126
|
+
if (countTokens || !state?.tool || committed) return;
|
|
127
|
+
const lease = active.get(key);
|
|
128
|
+
if (lease && lease.owner !== owner) fail("ccdx_history_transfer_busy", "Wait for the current response to finish before switching sources.");
|
|
129
|
+
save(key, checkpoint);committed = true;
|
|
130
|
+
toolLease = lease || { owner, count: 0 };toolLease.count++;active.set(key, toolLease);
|
|
131
|
+
}, release() {
|
|
132
|
+
grant.active = false;if (toolLease && --toolLease.count === 0) active.delete(key);toolLease = null;
|
|
133
|
+
} };
|
|
134
|
+
}
|
|
135
|
+
const lease = active.get(key);
|
|
136
|
+
if (lease && lease.owner !== owner) fail("ccdx_history_transfer_busy", "Wait for the current response to finish before switching sources.");
|
|
137
|
+
let candidate = null, removed = 0, grant;
|
|
138
|
+
if (changed || entry) {
|
|
139
|
+
let count;
|
|
140
|
+
if (!changed && body.messages.length >= entry.count && digest(body.messages.slice(0, entry.count)) === entry.prefix) count = entry.count;
|
|
141
|
+
else {
|
|
142
|
+
checkHistory(body, false);count = body.messages.length;candidate = { owner, count, prefix: digest(body.messages) };
|
|
143
|
+
}
|
|
144
|
+
removed = project(body, count);grant = { profile, noncommitting: false, initial, active: true };grants.set(body, grant);
|
|
145
|
+
}
|
|
146
|
+
const current = lease || { owner, count: 0 };current.count++;active.set(key, current);
|
|
147
|
+
let released = false, committed = false;
|
|
148
|
+
return { handled: Boolean(changed || entry), commit() {
|
|
149
|
+
if (committed || released) return;
|
|
150
|
+
if (candidate) save(key, candidate);
|
|
151
|
+
committed = true;
|
|
152
|
+
if (candidate && changed) options.onTransfer?.({ removed_thinking: removed });
|
|
153
|
+
}, release() {
|
|
154
|
+
if (released) return;released = true;if (grant) grant.active = false;
|
|
155
|
+
if (--current.count === 0) active.delete(key);
|
|
156
|
+
} };
|
|
157
|
+
} };
|
|
158
|
+
}
|
|
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import { m365Paths, readM365Json, writeM365Json, m365AccountKey } from "../m365-settings.mjs";
|
|
3
3
|
import { withFileLockSync } from "../lock.mjs";
|
|
4
4
|
import fs from "node:fs";
|
|
5
|
+
import { messagesHistoryTransferGrant } from "../messages-history-transfer.mjs";
|
|
5
6
|
|
|
6
7
|
const changed = () => Object.assign(new Error("This conversation belongs to another company account. Start a new conversation."),
|
|
7
8
|
{ code: "m365_account_changed", statusCode: 409 });
|
|
@@ -10,7 +11,7 @@ const hash = value => createHash("sha256").update(value).digest("hex");
|
|
|
10
11
|
export function createM365ConversationGuard({ home } = {}) {
|
|
11
12
|
const { directory, conversations: file } = m365Paths({ home });
|
|
12
13
|
let cached;
|
|
13
|
-
return (account, body, headers = {}) => {
|
|
14
|
+
return (account, body, headers = {}, options = {}) => {
|
|
14
15
|
const items = Array.isArray(body.messages) ? body.messages : Array.isArray(body.input) ? body.input : [];
|
|
15
16
|
let session = headers["session_id"] || headers["session-id"] || headers["x-conversation-id"] || headers["x-claude-code-session-id"];
|
|
16
17
|
if (!session && typeof body.metadata?.user_id === "string") {
|
|
@@ -24,6 +25,9 @@ export function createM365ConversationGuard({ home } = {}) {
|
|
|
24
25
|
|| Array.isArray(item?.content) && item.content.some(part => part?.type === "tool_result"));
|
|
25
26
|
if (!key) { if (account.history_isolation && hasHistory) throw changed();return; }
|
|
26
27
|
const owner = m365AccountKey(account);
|
|
28
|
+
const grant = messagesHistoryTransferGrant(body), authorized = Boolean(grant && grant.profile === options.profile);
|
|
29
|
+
const noncommitting = options.countTokens || authorized && grant.noncommitting;
|
|
30
|
+
if (noncommitting && !hasHistory) return;
|
|
27
31
|
if (cached?.[key] === owner) return;
|
|
28
32
|
if (cached?.[key] && cached[key] !== owner) throw changed();
|
|
29
33
|
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
@@ -32,7 +36,8 @@ export function createM365ConversationGuard({ home } = {}) {
|
|
|
32
36
|
if (!saved.owners || typeof saved.owners !== "object" || Array.isArray(saved.owners)
|
|
33
37
|
|| Object.keys(saved.owners).length > 1024 || Object.entries(saved.owners).some(([id, value]) => !/^[a-f0-9]{64}$/.test(id) || !/^[a-f0-9]{64}$/.test(value))) throw changed();
|
|
34
38
|
const owners = saved.owners;
|
|
35
|
-
if (owners[key] && owners[key] !== owner || !owners[key] && account.history_isolation && hasHistory) throw changed();
|
|
39
|
+
if (owners[key] && owners[key] !== owner || !owners[key] && account.history_isolation && hasHistory && !(authorized && grant.initial)) throw changed();
|
|
40
|
+
if (noncommitting) return;
|
|
36
41
|
if (owners[key]) { cached = owners;return; }
|
|
37
42
|
owners[key] = owner;
|
|
38
43
|
while (Object.keys(owners).length > 1024) delete owners[Object.keys(owners)[0]];
|
package/src/providers/m365.mjs
CHANGED
|
@@ -211,7 +211,7 @@ export function createM365Provider({ home, env = process.env, account: accountOv
|
|
|
211
211
|
async messages(body, options = {}) {
|
|
212
212
|
if (catalog && now() - catalogAt >= SOFT_TTL_MS && !flight) void refresh().catch(() => {});
|
|
213
213
|
const model = selectedModel(body.model, "claude");
|
|
214
|
-
if (account) guardConversation(account, body, options.headers);
|
|
214
|
+
if (account) guardConversation(account, body, options.headers, { profile: profile(), countTokens: options.countTokens === true });
|
|
215
215
|
const efforts = modelReasoningEfforts(model);
|
|
216
216
|
if (body.output_config?.effort !== undefined && efforts && !efforts.includes(body.output_config.effort)) {
|
|
217
217
|
throw protocolError("m365_effort_unavailable", "The selected effort is not advertised by this model. Refresh its model list and select an available effort.");
|