codex-copilot-dx 0.6.15 → 0.6.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -143,7 +143,8 @@ integrity, isolated Claude profile, and live relay routing without changing file
143
143
  ccdx pms status
144
144
  ```
145
145
 
146
- `ccdx pm-studio status` and `ccdx pm-studio setup` are equivalent long-form aliases.
146
+ `ccdx pm-studio status`, `ccdx pm-studio setup`, and `ccdx pm-studio restore`
147
+ are equivalent long-form aliases.
147
148
 
148
149
  `ccdx pms setup` performs local preflight, structural verification, backup,
149
150
  staging, integrity, signing, and replacement work. It does not access a PM
@@ -183,37 +184,47 @@ require reinstalling PM Studio. Setup prints the verified backup and
183
184
  manifest paths plus the version-matched restore procedure. Never restore a
184
185
  backup over a different PM Studio version or build.
185
186
 
186
- To restore, first quit PM Studio and its updater. Use the exact verified backup
187
- path printed by setup as `BACKUP_APP`, then confirm that both the installed App
188
- and backup still report the same version/build printed by setup:
187
+ To restore the original local bundle, first quit PM Studio and its updater,
188
+ then run:
189
189
 
190
190
  ```bash
191
- BACKUP_APP="<verified-backup-path-from-ccdx-pms-setup>"
192
- /usr/bin/plutil -extract CFBundleShortVersionString raw -o - "/Applications/PM Studio.app/Contents/Info.plist"
193
- /usr/bin/plutil -extract CFBundleVersion raw -o - "/Applications/PM Studio.app/Contents/Info.plist"
194
- /usr/bin/plutil -extract CFBundleShortVersionString raw -o - "$BACKUP_APP/Contents/Info.plist"
195
- /usr/bin/plutil -extract CFBundleVersion raw -o - "$BACKUP_APP/Contents/Info.plist"
191
+ ccdx pms restore
196
192
  ```
197
193
 
198
- Only when all four values match each other and the version/build recorded in the
199
- source-bound manifest, move the patched App aside, restore the complete local
200
- bundle, and verify it before launch:
194
+ The explicit command authorizes the local App replacement and does not show an
195
+ additional confirmation prompt. Restore neither needs the Claude profile nor
196
+ starts the adapter, Device Flow, Codex, or PM Studio. It selects the unique
197
+ source-bound backup itself, verifies the installed patch record and the exact
198
+ clean backup, stages and verifies the complete bundle, confirms that the
199
+ installed App did not change during staging, and then performs an atomic
200
+ replacement. It never restores a missing, ambiguous, drifted, or
201
+ version/build-mismatched record. The original local signature is inspected and
202
+ reported, but is not an admission gate: the exact source-bound content recorded
203
+ when setup created the backup is authoritative. The verified backup and manifest
204
+ remain available after a successful restore. Repeating restore on the same
205
+ recorded clean App is safe and does not replace it again.
206
+
207
+ If automatic restore reports that the replacement state cannot be verified, do
208
+ not launch PM Studio. Keep the recovery path printed by the command and reinstall
209
+ PM Studio. The following manual procedure is only an exceptional recovery path;
210
+ use the exact backup and manifest paths printed by setup or restore, and first
211
+ confirm that the installed App and backup still match the manifest version/build:
201
212
 
202
213
  ```bash
214
+ BACKUP_APP="<exact-verified-backup-path>"
203
215
  RECOVERY_DIR="$(/usr/bin/mktemp -d '/Applications/CCDX-PM-Studio-recovery.XXXXXX')"
204
216
  PATCHED_APP="$RECOVERY_DIR/PM Studio.app"
205
217
  mv "/Applications/PM Studio.app" "$PATCHED_APP"
206
218
  /usr/bin/ditto --rsrc --extattr --acl "$BACKUP_APP" "/Applications/PM Studio.app"
207
- /usr/bin/codesign --verify --deep --strict --verbose=2 "/Applications/PM Studio.app"
208
219
  ccdx pms status
209
220
  ```
210
221
 
211
222
  The App-patch row from `ccdx pms status` must classify the restored bundle as
212
223
  the recorded clean local content rather than integrity drift. If the version
213
- check, copy, or either verification path fails,
224
+ check, copy, or content verification fails,
214
225
  do not launch the restored App. Keep the moved patched bundle at `$PATCHED_APP`
215
226
  and reinstall PM Studio instead of applying a version-mismatched
216
- backup. CCDX never runs these restore commands or `sudo` automatically.
227
+ backup. CCDX never uses `sudo` automatically.
217
228
 
218
229
  To change the model used by Codex Auto-review, run:
219
230
 
package/bin/cli.mjs CHANGED
@@ -143,6 +143,11 @@ if (CLI.command === "pms") {
143
143
  });
144
144
  process.exit(result.ok ? 0 : 1);
145
145
  }
146
+ if (CLI.action === "restore") {
147
+ const { runPmStudioRestore } = await import("../src/pm-studio-setup.mjs");
148
+ await runPmStudioRestore({ commandName: CLI_NAME });
149
+ process.exit(0);
150
+ }
146
151
  const { runPmStudioSetup } = await import("../src/pm-studio-setup.mjs");
147
152
  await runPmStudioSetup({ commandName: CLI_NAME });
148
153
  process.exit(0);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "0.6.15",
3
+ "version": "0.6.18",
4
4
  "description": "Use Codex Desktop, Claude Code, and Claude App with GitHub Copilot",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
package/src/adapter.mjs CHANGED
@@ -155,6 +155,7 @@ export function createAdapterHandler(options = {}) {
155
155
  chatCompletionsFn: codexChatCompletionsFn,
156
156
  getCachedModelEndpointsFn,
157
157
  imagePressure,
158
+ modelRegistry: codexModelRegistry,
158
159
  now: options.now,
159
160
  openAIModelEnv,
160
161
  responsesPayloadOptions: options.responsesPayloadOptions,
@@ -168,6 +169,7 @@ export function createAdapterHandler(options = {}) {
168
169
  acquireRequest,
169
170
  autoReviewModelResolver: options.autoReviewModelResolver,
170
171
  imagePressure,
172
+ modelRegistry: codexModelRegistry,
171
173
  now: options.now,
172
174
  openAIModelEnv,
173
175
  requestBodyTimeoutMs,
@@ -294,6 +296,9 @@ export function createAdapterHandler(options = {}) {
294
296
  res.writeHead(404, { "Content-Type": "application/json" });
295
297
  res.end(JSON.stringify({ error: "Not found" }));
296
298
  };
299
+ const dispatchRequest = typeof options.dispatchRequestForTests === "function"
300
+ ? options.dispatchRequestForTests
301
+ : dispatch;
297
302
 
298
303
  return (req, res) => {
299
304
  const requestId = createRequestId();
@@ -326,10 +331,28 @@ export function createAdapterHandler(options = {}) {
326
331
  const finishRequest = ({ statusCode = 0, aborted = false } = {}) => {
327
332
  if (requestFinished) return;
328
333
  requestFinished = true;
329
- complete({ statusCode, aborted });
330
- streamPerformance?.finish({ failed: aborted || statusCode >= 400 });
334
+ try { complete({ statusCode, aborted }); } catch {}
335
+ try { streamPerformance?.finish({ failed: aborted || statusCode >= 400 }); } catch {}
331
336
  try { finishTerminalActivity(); } catch {}
332
337
  };
338
+ const containUnexpectedError = (error) => {
339
+ try { finishRequest({ statusCode: res.statusCode >= 400 ? res.statusCode : 500 }); } catch {}
340
+ const safeCause = error instanceof Error ? error : new Error("Unexpected adapter failure");
341
+ try { logRequestFailure("Adapter", safeCause); } catch {}
342
+ try {
343
+ const safeError = httpError("Internal adapter error", 500);
344
+ safeError.jsonBody = {
345
+ error: {
346
+ message: safeError.message,
347
+ type: "server_error",
348
+ code: "ccdx_internal_error",
349
+ },
350
+ };
351
+ sendJsonError(res, safeError, 500);
352
+ } catch {
353
+ try { res.destroy?.(); } catch {}
354
+ }
355
+ };
333
356
  if (trackRequest && typeof res.once === "function") {
334
357
  res.once("finish", () => finishRequest({ statusCode: res.statusCode }));
335
358
  res.once("close", () => finishRequest({
@@ -344,17 +367,15 @@ export function createAdapterHandler(options = {}) {
344
367
  pathname,
345
368
  showRequestId: options.showRequestId === true,
346
369
  streamPerformance,
347
- }, () => dispatch(req, res, pathname));
370
+ }, () => dispatchRequest(req, res, pathname));
348
371
  if (result && typeof result.then === "function") {
349
372
  return result.catch((error) => {
350
- finishRequest({ statusCode: res.statusCode >= 400 ? res.statusCode : 500 });
351
- throw error;
373
+ containUnexpectedError(error);
352
374
  });
353
375
  }
354
376
  return result;
355
377
  } catch (error) {
356
- finishRequest({ statusCode: res.statusCode >= 400 ? res.statusCode : 500 });
357
- throw error;
378
+ containUnexpectedError(error);
358
379
  }
359
380
  };
360
381
  }
@@ -7,7 +7,9 @@ import {
7
7
  import {
8
8
  createRequestAbort,
9
9
  logRequestFailure,
10
+ MAX_UPSTREAM_ERROR_BODY_BYTES,
10
11
  readJsonBody,
12
+ readBoundedResponseText,
11
13
  sendJsonError,
12
14
  sendUpstreamError,
13
15
  writeOrDrain,
@@ -21,6 +23,7 @@ import { safeUpstreamResponseHeaders } from "./upstream-headers.mjs";
21
23
  import { recordAnthropicUsage } from "./usage.mjs";
22
24
 
23
25
  const PROMPT_TOO_LONG_MESSAGE = "prompt is too long: your prompt is too long. Please reduce the number of messages or use a model with a larger context window.";
26
+ const DOWNSTREAM_CLOSED = Symbol("downstream-closed");
24
27
 
25
28
  function contextWindowErrorBody(text) {
26
29
  let error;
@@ -112,7 +115,10 @@ export function createAnthropicMessagesHandler(options) {
112
115
  const upstream = await chatCompletionsFn(withChatStreamUsage(chatReq), { signal: abort.signal });
113
116
  releaseRequest();
114
117
  if (!upstream.ok) {
115
- sendAnthropicUpstreamError(res, upstream, await upstream.text());
118
+ sendAnthropicUpstreamError(res, upstream, await readBoundedResponseText(upstream, {
119
+ maxBytes: MAX_UPSTREAM_ERROR_BODY_BYTES,
120
+ label: "Copilot Chat error body",
121
+ }));
116
122
  return;
117
123
  }
118
124
  await requireUpstreamEventStream(upstream);
@@ -132,12 +138,15 @@ export function createAnthropicMessagesHandler(options) {
132
138
  async (event, data) => {
133
139
  if (event === "message_start") messageId = data.message?.id;
134
140
  if (event === "message_delta") usage = data.usage;
135
- await writeOrDrain(res, `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
141
+ if (!await writeOrDrain(res, `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)) {
142
+ throw DOWNSTREAM_CLOSED;
143
+ }
136
144
  },
137
145
  requestedModel,
138
146
  { forceModel: forceRequestedModel },
139
147
  );
140
148
  } catch (error) {
149
+ if (error === DOWNSTREAM_CLOSED) return;
141
150
  logRequestFailure("Messages", error, abort);
142
151
  await endStreamWithError(res, "anthropic", error, abort);
143
152
  return;
@@ -147,7 +156,12 @@ export function createAnthropicMessagesHandler(options) {
147
156
  } else {
148
157
  const upstream = await chatCompletionsFn({ ...chatReq, stream: false }, { signal: abort.signal });
149
158
  releaseRequest();
150
- const data = await upstream.text();
159
+ const data = upstream.ok
160
+ ? await upstream.text()
161
+ : await readBoundedResponseText(upstream, {
162
+ maxBytes: MAX_UPSTREAM_ERROR_BODY_BYTES,
163
+ label: "Copilot Chat error body",
164
+ });
151
165
  if (!upstream.ok) {
152
166
  sendAnthropicUpstreamError(res, upstream, data);
153
167
  return;
package/src/anthropic.mjs CHANGED
@@ -163,6 +163,10 @@ export function anthropicToChat(body, options = {}) {
163
163
 
164
164
  function uid() { return randomUUID().replace(/-/g, ""); }
165
165
 
166
+ function nonNegativeTokenCount(value) {
167
+ return Number.isFinite(value) ? Math.max(0, value) : 0;
168
+ }
169
+
166
170
  function invalidToolArguments(toolName) {
167
171
  const name = String(toolName || "unknown").slice(0, 100);
168
172
  return invalidUpstreamStream(
@@ -198,10 +202,11 @@ export function chatToAnthropic(openaiResp, model, options = {}) {
198
202
  }
199
203
 
200
204
  const u = openaiResp.usage || {};
201
- const cached = u.prompt_tokens_details?.cached_tokens ?? 0;
205
+ const prompt = nonNegativeTokenCount(u.prompt_tokens);
206
+ const cached = Math.min(prompt, nonNegativeTokenCount(u.prompt_tokens_details?.cached_tokens));
202
207
  const usage = {
203
- input_tokens: (u.prompt_tokens ?? 0) - cached,
204
- output_tokens: u.completion_tokens ?? 0,
208
+ input_tokens: prompt - cached,
209
+ output_tokens: nonNegativeTokenCount(u.completion_tokens),
205
210
  };
206
211
  if (cached > 0) usage.cache_read_input_tokens = cached;
207
212
 
@@ -281,7 +286,7 @@ export async function streamAnthropicFromLines(lineIterator, emit, model, option
281
286
  if (upstreamError) throw upstreamError;
282
287
  if (!options.forceModel && parsed.model) actualModel = parsed.model;
283
288
  if (parsed.usage?.completion_tokens != null) {
284
- outputTokens = parsed.usage.completion_tokens;
289
+ outputTokens = nonNegativeTokenCount(parsed.usage.completion_tokens);
285
290
  markOutputTokens(outputTokens);
286
291
  }
287
292
  const choice = parsed.choices?.[0];
@@ -24,9 +24,12 @@ function syncDirectory(directory) {
24
24
  }
25
25
  }
26
26
 
27
- export function atomicWriteFileSync(filePath, data, { mode = 0o600 } = {}) {
27
+ export function atomicWriteFileSync(filePath, data, {
28
+ mode = 0o600,
29
+ preserveMode = true,
30
+ } = {}) {
28
31
  const directory = path.dirname(filePath);
29
- const finalMode = existingMode(filePath, mode);
32
+ const finalMode = preserveMode ? existingMode(filePath, mode) : mode;
30
33
  const tempPath = path.join(directory, `.${path.basename(filePath)}.${process.pid}.${randomUUID()}.tmp`);
31
34
  fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
32
35
 
@@ -50,6 +53,77 @@ export function atomicWriteFileSync(filePath, data, { mode = 0o600 } = {}) {
50
53
  }
51
54
  }
52
55
 
56
+ function fileSnapshot(filePath) {
57
+ try {
58
+ return {
59
+ exists: true,
60
+ data: fs.readFileSync(filePath),
61
+ mode: fs.statSync(filePath).mode & 0o777,
62
+ };
63
+ } catch (error) {
64
+ if (error?.code === "ENOENT") return { exists: false, data: null, mode: 0o600 };
65
+ throw error;
66
+ }
67
+ }
68
+
69
+ function removeFile(filePath, unlinkFile) {
70
+ try {
71
+ unlinkFile(filePath);
72
+ } catch (error) {
73
+ if (error?.code !== "ENOENT") throw error;
74
+ }
75
+ }
76
+
77
+ function writeExactMode(filePath, data, mode, writeFile) {
78
+ writeFile(filePath, data, { mode, preserveMode: false });
79
+ fs.chmodSync(filePath, mode);
80
+ }
81
+
82
+ function restoreFile(filePath, snapshot, { writeFile, unlinkFile }) {
83
+ if (snapshot.exists) {
84
+ writeExactMode(filePath, snapshot.data, snapshot.mode, writeFile);
85
+ return;
86
+ }
87
+ removeFile(filePath, unlinkFile);
88
+ }
89
+
90
+ // Commit a primary file first and its metadata/activation marker last. A null
91
+ // secondary value removes stale metadata as the final transaction step.
92
+ export function atomicWriteFilePairSync(
93
+ primaryPath,
94
+ primaryData,
95
+ secondaryPath,
96
+ secondaryData,
97
+ {
98
+ mode = 0o600,
99
+ writeFile = atomicWriteFileSync,
100
+ unlinkFile = fs.unlinkSync,
101
+ } = {},
102
+ ) {
103
+ const primarySnapshot = fileSnapshot(primaryPath);
104
+ const secondarySnapshot = fileSnapshot(secondaryPath);
105
+
106
+ try {
107
+ writeExactMode(primaryPath, primaryData, mode, writeFile);
108
+ if (secondaryData === null) removeFile(secondaryPath, unlinkFile);
109
+ else writeExactMode(secondaryPath, secondaryData, mode, writeFile);
110
+ } catch (error) {
111
+ let rollbackError;
112
+ try {
113
+ restoreFile(primaryPath, primarySnapshot, { writeFile, unlinkFile });
114
+ } catch (cause) {
115
+ rollbackError = cause;
116
+ }
117
+ try {
118
+ restoreFile(secondaryPath, secondarySnapshot, { writeFile, unlinkFile });
119
+ } catch (cause) {
120
+ rollbackError ||= cause;
121
+ }
122
+ if (rollbackError) error.rollbackError = rollbackError;
123
+ throw error;
124
+ }
125
+ }
126
+
53
127
  export function atomicWriteFileIfChangedSync(filePath, data, options = {}) {
54
128
  try {
55
129
  const current = fs.readFileSync(filePath);
@@ -1,7 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
- import { atomicWriteFileSync } from "./atomic-file.mjs";
4
+ import { atomicWriteFilePairSync, atomicWriteFileSync } from "./atomic-file.mjs";
5
5
  import {
6
6
  githubTokenLockPath,
7
7
  githubTokenMetadataPath,
@@ -131,27 +131,11 @@ export function withAuthProfileLock(profile, fn, {
131
131
  return withFileLock(lockPath, fn, { ...lockOptions(env), ...options });
132
132
  }
133
133
 
134
- function writeSecret(filePath, data, writeFile) {
135
- writeFile(filePath, data, { mode: 0o600 });
136
- fs.chmodSync(filePath, 0o600);
137
- }
138
-
139
- function restoreSnapshot(filePath, snapshot, writeFile) {
140
- if (snapshot.exists) {
141
- writeSecret(filePath, snapshot.data, writeFile);
142
- return;
143
- }
144
- try {
145
- fs.unlinkSync(filePath);
146
- } catch (error) {
147
- if (error?.code !== "ENOENT") throw error;
148
- }
149
- }
150
-
151
134
  export function writeClaudeAuthProfile(token, identity, {
152
135
  home = os.homedir(),
153
136
  now = () => new Date(),
154
137
  writeFile = atomicWriteFileSync,
138
+ unlinkFile = fs.unlinkSync,
155
139
  } = {}) {
156
140
  const cleanToken = String(token || "").trim();
157
141
  const normalizedIdentity = normalizeGithubIdentity(identity);
@@ -163,8 +147,6 @@ export function writeClaudeAuthProfile(token, identity, {
163
147
  fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
164
148
  fs.chmodSync(directory, 0o700);
165
149
 
166
- const previousToken = readOptionalFile(paths.tokenPath);
167
- const previousMetadata = readOptionalFile(paths.metadataPath);
168
150
  const timestamp = now();
169
151
  const updatedAt = timestamp instanceof Date ? timestamp.toISOString() : new Date(timestamp).toISOString();
170
152
  const metadata = `${JSON.stringify({
@@ -174,20 +156,15 @@ export function writeClaudeAuthProfile(token, identity, {
174
156
  updated_at: updatedAt,
175
157
  }, null, 2)}\n`;
176
158
 
177
- try {
178
- writeSecret(paths.tokenPath, cleanToken, writeFile);
179
- // Commit the activation marker last. Readers never observe a configured
180
- // Claude profile unless the token and its fingerprint agree.
181
- writeSecret(paths.metadataPath, metadata, writeFile);
182
- } catch (error) {
183
- try {
184
- restoreSnapshot(paths.tokenPath, previousToken, writeFile);
185
- restoreSnapshot(paths.metadataPath, previousMetadata, writeFile);
186
- } catch (rollbackError) {
187
- error.rollbackError = rollbackError;
188
- }
189
- throw error;
190
- }
159
+ // Commit the activation marker last. Readers never observe a configured
160
+ // Claude profile unless the token and its fingerprint agree.
161
+ atomicWriteFilePairSync(
162
+ paths.tokenPath,
163
+ cleanToken,
164
+ paths.metadataPath,
165
+ metadata,
166
+ { mode: 0o600, writeFile, unlinkFile },
167
+ );
191
168
 
192
169
  return {
193
170
  profile: AUTH_PROFILE_CLAUDE,