ccdeck 3.53.3 → 3.81.0
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 +63 -7
- package/THIRD_PARTY_NOTICES.md +31 -1
- package/bin/cli/tui.js +433 -11
- package/dist/web/assets/{BrowserWatchModal-CJ0CW4Go.js → BrowserWatchModal-DKvBSlGT.js} +1 -1
- package/dist/web/assets/{IntegrationModal-DlJzBN8b.js → IntegrationModal-D3NLczRe.js} +1 -1
- package/dist/web/assets/{RadioPanel-CHl3s3OH.js → RadioPanel-dCIMGTd9.js} +1 -1
- package/dist/web/assets/{TrafficRadar-Cw3i0Hux.js → TrafficRadar-CMbwnKe7.js} +1 -1
- package/dist/web/assets/{UsageHistoryModal-CiB5-CTH.js → UsageHistoryModal-DkGBQaM4.js} +1 -1
- package/dist/web/assets/{app-xTrs4aEH.css → app-BIrh5Q0W.css} +1 -1
- package/dist/web/assets/{app-2vj7uk2U.js → app-l0spNrc0.js} +93 -93
- package/dist/web/assets/{index-D1YZbdq3.js → index-inV7HzhI.js} +1 -1
- package/dist/web/index.html +3 -3
- package/node_modules/ws/LICENSE +20 -0
- package/node_modules/ws/README.md +540 -0
- package/node_modules/ws/browser.js +8 -0
- package/node_modules/ws/index.js +22 -0
- package/node_modules/ws/lib/buffer-util.js +142 -0
- package/node_modules/ws/lib/constants.js +19 -0
- package/node_modules/ws/lib/event-target.js +292 -0
- package/node_modules/ws/lib/extension.js +203 -0
- package/node_modules/ws/lib/limiter.js +55 -0
- package/node_modules/ws/lib/permessage-deflate.js +530 -0
- package/node_modules/ws/lib/receiver.js +743 -0
- package/node_modules/ws/lib/sender.js +610 -0
- package/node_modules/ws/lib/stream.js +161 -0
- package/node_modules/ws/lib/subprotocol.js +62 -0
- package/node_modules/ws/lib/validation.js +152 -0
- package/node_modules/ws/lib/websocket-server.js +562 -0
- package/node_modules/ws/lib/websocket.js +1426 -0
- package/node_modules/ws/package.json +74 -0
- package/node_modules/ws/wrapper.mjs +21 -0
- package/package.json +5 -3
- package/release-notes.json +71 -0
- package/src/server/account-engine.mjs +87 -0
- package/src/server/account-notify.mjs +81 -16
- package/src/server/account-routes.mjs +49 -3
- package/src/server/account-watch.mjs +21 -0
- package/src/server/codex-auto.mjs +163 -54
- package/src/server/codex-engine-adapter.mjs +272 -0
- package/src/server/codex-engine-bridge.mjs +47 -0
- package/src/server/codex-engine-config.mjs +42 -0
- package/src/server/codex-engine-rpc.mjs +88 -0
- package/src/server/codex-handoff.mjs +20 -0
- package/src/server/codex-interactive-engine.mjs +335 -0
- package/src/server/codex-lan-identity.mjs +61 -0
- package/src/server/codex-live-checkpoint.mjs +55 -0
- package/src/server/codex-live-credentials.mjs +214 -0
- package/src/server/codex-live-engine.mjs +577 -0
- package/src/server/codex-live-handoff.mjs +300 -0
- package/src/server/codex-live-lease.mjs +64 -0
- package/src/server/codex-live-rpc.mjs +158 -0
- package/src/server/codex-profiles.mjs +34 -4
- package/src/server/codex-projects.mjs +308 -0
- package/src/server/codex-quota.mjs +36 -2
- package/src/server/codex-selection.mjs +78 -9
- package/src/server/codex-share.mjs +238 -0
- package/src/server/codex-terminal-runner.mjs +38 -1
- package/src/server/codex-terminal.mjs +15 -3
- package/src/server/codex-usage.mjs +69 -0
- package/src/server/codex-watch.mjs +3 -1
- package/src/server/codex-windows-private.mjs +96 -0
- package/src/server/codex-windows-private.ps1 +140 -0
- package/src/server/codex-windows-proxy.mjs +53 -0
- package/src/server/index.mjs +12 -4
- package/src/server/lan-codex-store.mjs +170 -0
- package/src/server/lan-codex.mjs +103 -0
- package/src/server/lan-deck.mjs +5 -0
- package/src/server/lan-engine.mjs +34 -6
- package/src/server/lan-manifest.mjs +16 -2
- package/src/server/lan-serve.mjs +16 -6
- package/src/server/login-service.mjs +2 -0
- package/src/server/pinned-build.mjs +5 -0
- package/src/server/request-gates.mjs +3 -0
- package/src/server/tui-codex.mjs +229 -0
- package/src/server/tui-lan.mjs +684 -0
- package/src/server/tui-machine.mjs +492 -0
- package/src/server/tui-network.mjs +730 -0
- package/src/server/tui-view.mjs +735 -60
|
@@ -1,7 +1,14 @@
|
|
|
1
1
|
// Auto-switch for Codex accounts: when the account new sessions start on is
|
|
2
2
|
// nearly full, move the default to another account that still has room.
|
|
3
|
-
//
|
|
4
|
-
//
|
|
3
|
+
// This loop moves only the registry's default, through selectCodexProfile.
|
|
4
|
+
// Managed exec continuation is a separate adapter of the shared account engine.
|
|
5
|
+
//
|
|
6
|
+
// A HOME ACCOUNT, as Claude's has (account-choice.mjs), by the same rules: it
|
|
7
|
+
// is the first place a full account goes; Auto-switch takes the default back
|
|
8
|
+
// there once it has room again, but only from an account Auto-switch moved to
|
|
9
|
+
// and only after the move has settled — never from one somebody picked by hand;
|
|
10
|
+
// and setting a home while elsewhere moves there on the next tick. Home is a
|
|
11
|
+
// profile, kept by its id, since a Codex account here is a folder.
|
|
5
12
|
import { readFile, mkdir, unlink } from 'node:fs/promises';
|
|
6
13
|
import { randomUUID } from 'node:crypto';
|
|
7
14
|
import { dirname, join, resolve } from 'node:path';
|
|
@@ -9,6 +16,7 @@ import { deckDataDir } from './deck-home.mjs';
|
|
|
9
16
|
import { createTemp, renameWithRetry } from './atomic-write.mjs';
|
|
10
17
|
import { readCodexSelection, selectCodexProfile } from './codex-selection.mjs';
|
|
11
18
|
import { discoverCodexProfiles, readCodexProfileQuota } from './codex-profiles.mjs';
|
|
19
|
+
import { chooseEngineAccount } from './account-engine.mjs';
|
|
12
20
|
|
|
13
21
|
// The same whole-percent range the page offers (CUSTOM_MIN / CUSTOM_MAX in
|
|
14
22
|
// src/web/auto-switch-threshold.ts). A server module must not import from the
|
|
@@ -18,7 +26,13 @@ const THRESHOLD_MAX = 99;
|
|
|
18
26
|
const DEFAULT_THRESHOLD = '90';
|
|
19
27
|
const COOLDOWN_MS = 5 * 60_000;
|
|
20
28
|
const TICK_MS = 60_000;
|
|
21
|
-
|
|
29
|
+
/** How far under the threshold home must sit to be landed on, so a full
|
|
30
|
+
* account is not left for one that fills again at once (ROOM_MARGIN_PCT). */
|
|
31
|
+
const ROOM_MARGIN_PCT = 5;
|
|
32
|
+
/** How long after a move the way back home waits (SETTLE_MS). */
|
|
33
|
+
const SETTLE_MS = 30 * 60_000;
|
|
34
|
+
/** A reading older than this is not landed on, as chooseEngineAccount. */
|
|
35
|
+
const FRESH_FOR_MS = 15 * 60_000;
|
|
22
36
|
const idPattern = /^[a-f0-9]{20}$/;
|
|
23
37
|
|
|
24
38
|
const storeDir = o => resolve(o.store ?? deckDataDir());
|
|
@@ -38,6 +52,8 @@ function validThreshold(v) {
|
|
|
38
52
|
return n >= THRESHOLD_MIN && n <= THRESHOLD_MAX;
|
|
39
53
|
}
|
|
40
54
|
|
|
55
|
+
const idOrNull = v => (typeof v === 'string' && idPattern.test(v) ? v : null);
|
|
56
|
+
|
|
41
57
|
async function load(o) {
|
|
42
58
|
let raw = {};
|
|
43
59
|
try { raw = JSON.parse(await readFile(filePath(o), 'utf8')) ?? {}; } catch { /* missing or corrupt: defaults */ }
|
|
@@ -46,6 +62,16 @@ async function load(o) {
|
|
|
46
62
|
threshold: validThreshold(raw.threshold) ? raw.threshold : DEFAULT_THRESHOLD,
|
|
47
63
|
next: raw.next === 'weekly' ? 'weekly' : 'room',
|
|
48
64
|
heldOut: Array.isArray(raw.heldOut) ? [...new Set(raw.heldOut.filter(id => typeof id === 'string' && idPattern.test(id)))] : [],
|
|
65
|
+
home: idOrNull(raw.home),
|
|
66
|
+
// A home was just set, so the next tick may take the default there.
|
|
67
|
+
goHome: raw.goHome === true && idOrNull(raw.home) != null,
|
|
68
|
+
// The default in use was picked by hand, so the optional way home leaves
|
|
69
|
+
// it alone until it fills or a home is set.
|
|
70
|
+
manual: raw.manual === true,
|
|
71
|
+
// The default the last tick saw, which is how a pick by hand is told from
|
|
72
|
+
// one of Auto-switch's own.
|
|
73
|
+
lastActive: idOrNull(raw.lastActive),
|
|
74
|
+
movedAt: Number.isFinite(raw.movedAt) ? raw.movedAt : 0,
|
|
49
75
|
};
|
|
50
76
|
}
|
|
51
77
|
|
|
@@ -66,7 +92,10 @@ const statusOf = (o, s) => ({
|
|
|
66
92
|
external: false,
|
|
67
93
|
lastTick: mem(o).lastTick,
|
|
68
94
|
settings: { 'autoswitch.threshold': { value: s.threshold, isDefault: s.threshold === DEFAULT_THRESHOLD } },
|
|
95
|
+
// `home` is Claude's shape (an email and an organization); a Codex home is a
|
|
96
|
+
// profile, so it travels as `homeId` and `home` stays empty.
|
|
69
97
|
choice: { next: s.next, home: null },
|
|
98
|
+
homeId: s.home,
|
|
70
99
|
heldOut: s.heldOut,
|
|
71
100
|
});
|
|
72
101
|
|
|
@@ -83,6 +112,18 @@ export function applyCodexAuto(body, options = {}) {
|
|
|
83
112
|
return run;
|
|
84
113
|
}
|
|
85
114
|
|
|
115
|
+
/** What a tick learned, written over the file as it is when the write runs —
|
|
116
|
+
* in the same queue as the panel's writes, so neither undoes the other. */
|
|
117
|
+
function update(options, change) {
|
|
118
|
+
const run = writes.then(async () => {
|
|
119
|
+
const state = await load(options);
|
|
120
|
+
const next = change(state);
|
|
121
|
+
if (next && JSON.stringify(next) !== JSON.stringify(state)) await save(options, next);
|
|
122
|
+
});
|
|
123
|
+
writes = run.catch(() => {});
|
|
124
|
+
return run;
|
|
125
|
+
}
|
|
126
|
+
|
|
86
127
|
async function apply(body, options) {
|
|
87
128
|
const bad = { ok: false, reason: 'bad_request' };
|
|
88
129
|
if (!body || typeof body !== 'object') return bad;
|
|
@@ -105,6 +146,14 @@ async function apply(body, options) {
|
|
|
105
146
|
state.heldOut = state.heldOut.filter(id => id !== body.id);
|
|
106
147
|
if (!body.enabled) state.heldOut.push(body.id);
|
|
107
148
|
break;
|
|
149
|
+
case 'home':
|
|
150
|
+
// One home; null removes it. Set with Auto-switch on or off, as Claude's:
|
|
151
|
+
// a tick reads it only while the switch is on.
|
|
152
|
+
if (body.id !== null && idOrNull(body.id) == null) return bad;
|
|
153
|
+
state.home = body.id;
|
|
154
|
+
state.goHome = body.id !== null;
|
|
155
|
+
state.manual = false;
|
|
156
|
+
break;
|
|
108
157
|
default:
|
|
109
158
|
return bad;
|
|
110
159
|
}
|
|
@@ -117,66 +166,126 @@ const liveWindows = (quota, nowSec) =>
|
|
|
117
166
|
(quota?.windows ?? []).filter(w => Number.isFinite(w.usedPercent) && (w.resetAt == null || w.resetAt > nowSec));
|
|
118
167
|
const loadOf = live => (live.length ? Math.max(...live.map(w => w.usedPercent)) : null);
|
|
119
168
|
|
|
120
|
-
// When the weekly window resets, if it does within 4 days; otherwise null.
|
|
121
|
-
function weeklyReset(live, nowSec) {
|
|
122
|
-
const w = live.find(x => x.seconds >= 6 * DAY && x.resetAt != null && x.resetAt - nowSec <= 4 * DAY);
|
|
123
|
-
return w ? w.resetAt : null;
|
|
124
|
-
}
|
|
125
|
-
|
|
126
169
|
const hasLogin = row => (row.signedIn === undefined ? row.signedInFilePresent === true : row.signedIn === true);
|
|
127
170
|
|
|
171
|
+
/** Two profiles that are one ChatGPT account share one quota, so being on
|
|
172
|
+
* either is being on it. */
|
|
173
|
+
const sameLogin = (a, b) => a.id === b.id || a.sameAccountAs === b.id || b.sameAccountAs === a.id
|
|
174
|
+
|| (a.sameAccountAs != null && a.sameAccountAs === b.sameAccountAs);
|
|
175
|
+
|
|
176
|
+
/** What the notifications call a profile: its own name, else who it is signed
|
|
177
|
+
* in as, else the row's label. */
|
|
178
|
+
const nameOf = row => row.managedLabel || row.account || row.label || null;
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* One round of the loop. `options.onTick`, when given, is told what the round
|
|
182
|
+
* did (account-watch.mjs `noteCodexAutoTick`, which says the swap notice):
|
|
183
|
+
* `{ enabled: false }` while the loop is off; else `threshold` and `switched`,
|
|
184
|
+
* `reason: 'cooldown'` while the last move settles, and for a move `from`,
|
|
185
|
+
* `to`, `used` and `trigger`. A round that failed tells nothing.
|
|
186
|
+
*/
|
|
128
187
|
export async function codexAutoTick(options = {}) {
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
const nowSec = Math.floor(now() / 1000);
|
|
136
|
-
const threshold = Number(state.threshold);
|
|
137
|
-
const readSelection = options.readSelection ?? readCodexSelection;
|
|
138
|
-
const discover = options.discover ?? discoverCodexProfiles;
|
|
139
|
-
const readQuota = options.readQuota ?? readCodexProfileQuota;
|
|
140
|
-
const select = options.select ?? selectCodexProfile;
|
|
141
|
-
|
|
142
|
-
const selection = await readSelection(options);
|
|
143
|
-
const rows = await discover({ ...options, selection, enableNative: true });
|
|
144
|
-
const home = rows.find(r => r.id === selection.profileId);
|
|
145
|
-
if (!home) return;
|
|
146
|
-
const readOpts = { ...options, selection, enableNative: true };
|
|
147
|
-
const homeQuota = await readQuota(home.id, readOpts);
|
|
148
|
-
// Only a reading taken now says how full an account is: the last good one
|
|
149
|
-
// kept for a failed read is an old number, and acting on it moves sessions
|
|
150
|
-
// for a window that may have reset, or onto an account that has since filled.
|
|
151
|
-
const homeLoad = homeQuota?.ok && !homeQuota.stale ? loadOf(liveWindows(homeQuota, nowSec)) : null;
|
|
152
|
-
if (homeLoad === null || homeLoad < threshold) return;
|
|
188
|
+
let outcome = null;
|
|
189
|
+
try { outcome = await tickOnce(options); } catch { /* a failed round is retried on the next tick */ }
|
|
190
|
+
if (outcome) {
|
|
191
|
+
try { options.onTick?.(outcome); } catch { /* never the loop's problem */ }
|
|
192
|
+
}
|
|
193
|
+
}
|
|
153
194
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
195
|
+
async function tickOnce(options) {
|
|
196
|
+
const state = await load(options);
|
|
197
|
+
if (!state.enabled) return { enabled: false };
|
|
198
|
+
const m = mem(options);
|
|
199
|
+
const now = options.now ?? Date.now;
|
|
200
|
+
const threshold = Number(state.threshold);
|
|
201
|
+
const stayed = { enabled: true, threshold, switched: false };
|
|
202
|
+
if (now() - m.lastSwitchAt < COOLDOWN_MS) return { ...stayed, reason: 'cooldown' };
|
|
203
|
+
const nowSec = Math.floor(now() / 1000);
|
|
204
|
+
const readSelection = options.readSelection ?? readCodexSelection;
|
|
205
|
+
const discover = options.discover ?? discoverCodexProfiles;
|
|
206
|
+
const readQuota = options.readQuota ?? readCodexProfileQuota;
|
|
207
|
+
const select = options.select ?? selectCodexProfile;
|
|
208
|
+
|
|
209
|
+
const selection = await readSelection(options);
|
|
210
|
+
const rows = await discover({ ...options, selection, enableNative: true });
|
|
211
|
+
const current = rows.find(r => r.id === selection.profileId);
|
|
212
|
+
if (!current) return stayed;
|
|
213
|
+
const homeRow = state.home ? rows.find(r => r.id === state.home) ?? null : null;
|
|
214
|
+
const onHome = homeRow != null && sameLogin(homeRow, current);
|
|
215
|
+
|
|
216
|
+
// WHO PICKED THE DEFAULT IN USE. One the last tick did not see is a pick
|
|
217
|
+
// by hand — the panel's Switch, or Codex itself — and stays picked until it
|
|
218
|
+
// fills or a home is set. Written over the file as it is now only when the
|
|
219
|
+
// person has not changed home since it was read, or this would undo them.
|
|
220
|
+
const manual = state.manual || (state.lastActive != null && state.lastActive !== current.id);
|
|
221
|
+
const goHome = state.goHome && !onHome;
|
|
222
|
+
if (manual !== state.manual || goHome !== state.goHome || state.lastActive !== current.id) {
|
|
223
|
+
await update(options, s => (s.home === state.home && s.goHome === state.goHome && s.manual === state.manual
|
|
224
|
+
? { ...s, manual, goHome, lastActive: current.id }
|
|
225
|
+
: { ...s, lastActive: current.id }));
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const readOpts = { ...options, selection, enableNative: true };
|
|
229
|
+
const currentQuota = await readQuota(current.id, readOpts);
|
|
230
|
+
// Only a reading taken now says how full an account is: the last good one
|
|
231
|
+
// kept for a failed read is an old number, and acting on it moves sessions
|
|
232
|
+
// for a window that may have reset, or onto an account that has since filled.
|
|
233
|
+
const currentLoad = currentQuota?.ok && !currentQuota.stale ? loadOf(liveWindows(currentQuota, nowSec)) : null;
|
|
234
|
+
if (currentLoad === null) return stayed;
|
|
235
|
+
|
|
236
|
+
// Home has room: in rotation, signed in, read recently, and comfortably
|
|
237
|
+
// under the threshold on every window that has not reset.
|
|
238
|
+
const homeHasRoom = async () => {
|
|
239
|
+
if (!homeRow || onHome || homeRow.available === false || !hasLogin(homeRow) || state.heldOut.includes(homeRow.id)) return false;
|
|
240
|
+
const q = await readQuota(homeRow.id, readOpts);
|
|
241
|
+
if (!q?.ok || q.stale || (Number.isFinite(q.fetchedAt) && now() - q.fetchedAt > FRESH_FOR_MS)) return false;
|
|
242
|
+
const load = loadOf(liveWindows(q, nowSec));
|
|
243
|
+
return load !== null && load < threshold - ROOM_MARGIN_PCT;
|
|
244
|
+
};
|
|
245
|
+
/** Move the default to `row`; what the round did, for the notifications. */
|
|
246
|
+
const move = async (row, trigger) => {
|
|
171
247
|
try {
|
|
172
|
-
await select({ id:
|
|
248
|
+
await select({ id: row.id, expectedRevision: selection.revision, operationId: randomUUID() }, options);
|
|
173
249
|
} catch (e) {
|
|
174
|
-
if (e?.code === 'selection_conflict') return; // somebody else moved it; look again next tick
|
|
250
|
+
if (e?.code === 'selection_conflict') return stayed; // somebody else moved it; look again next tick
|
|
175
251
|
throw e;
|
|
176
252
|
}
|
|
177
253
|
m.lastSwitchAt = now();
|
|
178
|
-
m.lastTick = { at: now(), event: 'switched', to:
|
|
179
|
-
|
|
254
|
+
m.lastTick = { at: now(), event: 'switched', to: row.id, trigger };
|
|
255
|
+
await update(options, s => ({ ...s, manual: false, lastActive: row.id, movedAt: now(), goHome: s.goHome && row.id !== s.home }));
|
|
256
|
+
return {
|
|
257
|
+
...stayed, switched: true, trigger, used: currentLoad,
|
|
258
|
+
from: { id: current.id, name: nameOf(current) }, to: { id: row.id, name: nameOf(row) },
|
|
259
|
+
};
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
if (currentLoad >= threshold) {
|
|
263
|
+
// HAS TO LEAVE: home first, then the account the engine picks.
|
|
264
|
+
if (await homeHasRoom()) return move(homeRow, 'home');
|
|
265
|
+
// A row that is the same ChatGPT account shares the quota that just ran out.
|
|
266
|
+
const roster = rows.filter(r => r.id !== current.id && r.available && hasLogin(r)
|
|
267
|
+
&& !state.heldOut.includes(r.id) && r.sameAccountAs !== current.id);
|
|
268
|
+
const quotas = new Map();
|
|
269
|
+
for (const row of roster) { // one at a time: each read may spawn a process
|
|
270
|
+
quotas.set(row.id, await readQuota(row.id, readOpts));
|
|
271
|
+
}
|
|
272
|
+
const pick = chooseEngineAccount(roster, quotas, { threshold, next: state.next, nowSec });
|
|
273
|
+
const target = pick ? roster.find(r => r.id === pick.id) : null;
|
|
274
|
+
if (!target) {
|
|
275
|
+
m.lastTick = { at: now(), event: 'nowhere', reason: 'no_account_with_room' };
|
|
276
|
+
return stayed;
|
|
277
|
+
}
|
|
278
|
+
return move(target, 'proactive');
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// BELOW THE THRESHOLD the one move made is the way home, and it is
|
|
282
|
+
// optional: never from home itself, never from a pick by hand, and only
|
|
283
|
+
// once the last move has settled — unless a home was just set, when the
|
|
284
|
+
// person asked to be taken there.
|
|
285
|
+
if (!homeRow || onHome) return stayed;
|
|
286
|
+
const settled = now() - Math.max(m.lastSwitchAt, state.movedAt) >= SETTLE_MS;
|
|
287
|
+
if ((goHome || (!manual && settled)) && await homeHasRoom()) return move(homeRow, 'home');
|
|
288
|
+
return stayed;
|
|
180
289
|
}
|
|
181
290
|
|
|
182
291
|
let stopLoop = null;
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import { renameWithRetry } from './atomic-write.mjs';
|
|
2
|
+
// Codex adapter for supervised exec sessions. Authentication remains in each
|
|
3
|
+
// Codex home; a handoff transfers only the exact, closed conversation rollout.
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
7
|
+
import { chmod, link, lstat, mkdir, open, readdir, realpath, readFile, unlink } from 'node:fs/promises';
|
|
8
|
+
import { constants } from 'node:fs';
|
|
9
|
+
import { dirname, join, relative } from 'node:path';
|
|
10
|
+
import { spawnSpec } from './exec-spec.mjs';
|
|
11
|
+
import { configHash, isTrustOnlyConfig, isCustomCodexConfig } from './codex-engine-config.mjs';
|
|
12
|
+
import { codexHandoffPath } from './codex-handoff.mjs';
|
|
13
|
+
import { killTree } from './exec-children.mjs';
|
|
14
|
+
import { readCodexSelection } from './codex-selection.mjs';
|
|
15
|
+
import { discoverCodexProfiles, readCodexProfileQuota } from './codex-profiles.mjs';
|
|
16
|
+
import { readCodexAuto } from './codex-auto.mjs';
|
|
17
|
+
|
|
18
|
+
const UUID = /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i;
|
|
19
|
+
const CONTINUE = 'Continue the previous task from where it stopped. Check the existing work before repeating any action.';
|
|
20
|
+
const MAX_LINE = 1024 * 1024;
|
|
21
|
+
|
|
22
|
+
// Only a conservative, understood argv shape may be reconstructed on resume.
|
|
23
|
+
// Unknown options still reach Codex unchanged, but cannot authorize a handoff.
|
|
24
|
+
const values = new Set(['-c', '--config', '--enable', '--disable', '-m', '--model', '-s', '--sandbox', '-a', '--ask-for-approval', '-C', '--cd', '--add-dir', '--output-schema', '-o', '--output-last-message', '--color']);
|
|
25
|
+
const switches = new Set(['--json', '--strict-config', '--skip-git-repo-check', '--ignore-user-config', '--ignore-rules', '--approve-for-me', '--dangerously-bypass-approvals-and-sandbox', '--dangerously-bypass-hook-trust', '--search']);
|
|
26
|
+
export function codexEngineInvocation(args) {
|
|
27
|
+
const kept = [];
|
|
28
|
+
let exec = false, resume = false, threadId = null, prompt = false;
|
|
29
|
+
for (let i = 0; i < args.length; i++) {
|
|
30
|
+
const a = args[i];
|
|
31
|
+
if (prompt) return null; // extra positional arguments/attachments need their own contract
|
|
32
|
+
if (a === 'exec' && !exec) { exec = true; kept.push(a); continue; }
|
|
33
|
+
if (a === 'resume' && exec && !resume) { resume = true; continue; }
|
|
34
|
+
if (a === '--') {
|
|
35
|
+
if (!exec || i !== args.length - 2) return null;
|
|
36
|
+
prompt = true; i++; continue;
|
|
37
|
+
}
|
|
38
|
+
const key = a.split('=')[0];
|
|
39
|
+
if (values.has(key)) {
|
|
40
|
+
kept.push(a);
|
|
41
|
+
if (a === key) { if (i + 1 >= args.length) return null; kept.push(args[++i]); }
|
|
42
|
+
// Do not route a non-OpenAI provider or remote/configured proxy implicitly.
|
|
43
|
+
if ((key === '-c' || key === '--config') && /^(?:model_provider|model_providers\.|chatgpt_base_url|openai_base_url)/.test(kept[kept.length - 1].replace(/^--config=/, ''))) return null;
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
if (switches.has(a)) { kept.push(a); continue; }
|
|
47
|
+
if (a.startsWith('-') && a !== '-') return null;
|
|
48
|
+
if (!exec) return null;
|
|
49
|
+
if (resume && !threadId) { if (!UUID.test(a)) return null; threadId = a; }
|
|
50
|
+
else prompt = true;
|
|
51
|
+
}
|
|
52
|
+
if (!exec || !kept.includes('--json')) return null;
|
|
53
|
+
return { threadId, resumeArgs: id => [...kept, 'resume', id, '--', CONTINUE] };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function runCodexEngineAttempt(executable, args, home, { signal, stdout = process.stdout, stderr = process.stderr, spawnChild = spawn, resumed = false, env = process.env } = {}) {
|
|
57
|
+
if (signal?.aborted) return Promise.resolve({ code: 130, reason: 'cancelled' });
|
|
58
|
+
return new Promise((resolveRun, reject) => {
|
|
59
|
+
const spec = spawnSpec(executable, args);
|
|
60
|
+
const child = spawnChild(spec.file, spec.args, { ...spec.opts, stdio: [resumed ? 'ignore' : 'inherit', 'pipe', 'pipe'], env: { ...env, CODEX_HOME: home } });
|
|
61
|
+
let pending = '', threadId = null, failed = null, completed = false, uncertain = false;
|
|
62
|
+
const decoder = new StringDecoder('utf8');
|
|
63
|
+
function line(text) {
|
|
64
|
+
if (!text.trim()) return;
|
|
65
|
+
let event;
|
|
66
|
+
try { event = JSON.parse(text); } catch { uncertain = true; return; }
|
|
67
|
+
if (event.type === 'thread.started') {
|
|
68
|
+
if (!UUID.test(event.thread_id ?? '') || threadId && threadId !== event.thread_id) uncertain = true;
|
|
69
|
+
else threadId = event.thread_id;
|
|
70
|
+
}
|
|
71
|
+
if (event.type === 'turn.completed') completed = true;
|
|
72
|
+
if (event.type === 'turn.failed') failed = event.error;
|
|
73
|
+
}
|
|
74
|
+
const pump = (source, target, inspect = false) => {
|
|
75
|
+
source.on('data', chunk => {
|
|
76
|
+
if (!target.write(chunk)) { source.pause(); target.once('drain', () => source.resume()); }
|
|
77
|
+
if (!inspect) return;
|
|
78
|
+
pending += decoder.write(chunk);
|
|
79
|
+
let end;
|
|
80
|
+
while ((end = pending.indexOf('\n')) >= 0) { line(pending.slice(0, end)); pending = pending.slice(end + 1); }
|
|
81
|
+
if (pending.length > MAX_LINE) { pending = ''; uncertain = true; }
|
|
82
|
+
});
|
|
83
|
+
};
|
|
84
|
+
pump(child.stdout, stdout, true);
|
|
85
|
+
pump(child.stderr, stderr);
|
|
86
|
+
let escalation;
|
|
87
|
+
const stop = () => {
|
|
88
|
+
killTree(child, 'SIGTERM');
|
|
89
|
+
escalation ??= setTimeout(() => killTree(child, 'SIGKILL'), 2000);
|
|
90
|
+
escalation.unref?.();
|
|
91
|
+
};
|
|
92
|
+
signal?.addEventListener('abort', stop, { once: true });
|
|
93
|
+
child.once('error', error => { clearTimeout(escalation); signal?.removeEventListener('abort', stop); reject(error); });
|
|
94
|
+
child.once('close', (code, killedBy) => {
|
|
95
|
+
clearTimeout(escalation);
|
|
96
|
+
signal?.removeEventListener('abort', stop);
|
|
97
|
+
pending += decoder.end();
|
|
98
|
+
if (pending) line(pending);
|
|
99
|
+
const message = typeof failed?.message === 'string' ? failed.message : '';
|
|
100
|
+
const quota = /(?:usage limit|quota (?:exceeded|exhausted)|exceeded your current quota|insufficient_quota|usage_limit_reached)/i.test(message);
|
|
101
|
+
resolveRun({ code: code ?? (killedBy === 'SIGINT' ? 130 : 143), threadId,
|
|
102
|
+
reason: signal?.aborted || killedBy ? 'cancelled' : uncertain ? 'protocol_error' : completed ? 'completed' : failed && quota ? 'usage_limit' : 'failed' });
|
|
103
|
+
});
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export async function transferCodexThread(sourceHome, targetHome, threadId, { moveSource = false, onSourceMoved } = {}) {
|
|
108
|
+
if (!UUID.test(threadId)) throw new Error('Invalid Codex conversation id.');
|
|
109
|
+
const root = join(sourceHome, 'sessions');
|
|
110
|
+
let found = null, visited = 0;
|
|
111
|
+
// Bounded and layout-specific; never walk arbitrary/symlinked directories.
|
|
112
|
+
async function walk(dir, depth) {
|
|
113
|
+
if (++visited > 4096) throw new Error('Codex conversation scan exceeded its limit.');
|
|
114
|
+
let entries;
|
|
115
|
+
try { entries = await readdir(dir, { withFileTypes: true }); } catch (e) { if (e.code === 'ENOENT') return; throw e; }
|
|
116
|
+
for (const entry of entries) {
|
|
117
|
+
const path = join(dir, entry.name);
|
|
118
|
+
if (depth < 3 && entry.isDirectory() && /^\d{2,4}$/.test(entry.name)) await walk(path, depth + 1);
|
|
119
|
+
else if (depth === 3 && entry.isFile() && entry.name.endsWith(`-${threadId}.jsonl`)) {
|
|
120
|
+
if (found) throw new Error('Codex conversation has more than one rollout.');
|
|
121
|
+
found = path;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if ((await lstat(root)).isSymbolicLink()) throw new Error('Codex conversation folder must not be a symbolic link.');
|
|
126
|
+
await walk(root, 0);
|
|
127
|
+
if (!found) throw new Error('Codex conversation could not be found; nothing was resumed.');
|
|
128
|
+
const handle = await open(found, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
129
|
+
let snapshot, content;
|
|
130
|
+
try {
|
|
131
|
+
snapshot = await handle.stat();
|
|
132
|
+
if (snapshot.size > 64 * 1024 * 1024) throw new Error('Codex conversation is too large to transfer automatically.');
|
|
133
|
+
const header = Buffer.alloc(64 * 1024);
|
|
134
|
+
const { bytesRead } = await handle.read(header, 0, header.length, 0);
|
|
135
|
+
const first = header.subarray(0, bytesRead).toString('utf8').split('\n')[0];
|
|
136
|
+
const meta = JSON.parse(first);
|
|
137
|
+
if (meta.type !== 'session_meta' || meta.payload?.id !== threadId) throw new Error('Codex conversation identity did not match.');
|
|
138
|
+
content = Buffer.alloc(snapshot.size);
|
|
139
|
+
for (let offset = 0; offset < content.length;) {
|
|
140
|
+
const { bytesRead } = await handle.read(content, offset, content.length - offset, offset);
|
|
141
|
+
if (!bytesRead) throw new Error('Codex conversation was truncated while being transferred.');
|
|
142
|
+
offset += bytesRead;
|
|
143
|
+
}
|
|
144
|
+
} finally { await handle.close(); }
|
|
145
|
+
const targetRoot = join(targetHome, 'sessions');
|
|
146
|
+
await mkdir(targetRoot, { recursive: true, mode: 0o700 });
|
|
147
|
+
if ((await lstat(targetRoot)).isSymbolicLink()) throw new Error('Target conversation folder must not be a symbolic link.');
|
|
148
|
+
const destination = join(targetRoot, relative(root, found));
|
|
149
|
+
let parent = targetRoot;
|
|
150
|
+
for (const part of relative(targetRoot, dirname(destination)).split(/[\\/]/)) {
|
|
151
|
+
parent = join(parent, part);
|
|
152
|
+
await mkdir(parent, { mode: 0o700 }).catch(e => { if (e.code !== 'EEXIST') throw e; });
|
|
153
|
+
if (!(await lstat(parent)).isDirectory()) throw new Error('Target conversation path is unavailable.');
|
|
154
|
+
}
|
|
155
|
+
if (content.length !== snapshot.size || content.at(-1) !== 10) throw new Error('Codex conversation has an incomplete final record.');
|
|
156
|
+
// Publish the complete private file atomically and exclusively. The sidecar
|
|
157
|
+
// exists before publication, so a live deck never replays the copied prefix.
|
|
158
|
+
try { await lstat(destination); throw new Error('Target conversation already exists.'); }
|
|
159
|
+
catch (e) { if (e.code !== 'ENOENT') throw e; }
|
|
160
|
+
const marker = codexHandoffPath(destination);
|
|
161
|
+
const receipt = await open(marker, 'wx', 0o600);
|
|
162
|
+
try { await receipt.writeFile(JSON.stringify({ version: 1, threadId, copiedBytes: content.length })); }
|
|
163
|
+
catch (e) { await unlink(marker).catch(() => {}); throw e; }
|
|
164
|
+
finally { await receipt.close(); }
|
|
165
|
+
const staged = `${destination}.${randomUUID()}.tmp`;
|
|
166
|
+
let published = false;
|
|
167
|
+
try {
|
|
168
|
+
const output = await open(staged, 'wx', 0o600);
|
|
169
|
+
try { await output.writeFile(content); await output.sync(); }
|
|
170
|
+
finally { await output.close(); }
|
|
171
|
+
const after = await lstat(found);
|
|
172
|
+
if (after.size !== snapshot.size || after.mtimeMs !== snapshot.mtimeMs || after.ino !== snapshot.ino) throw new Error('Codex conversation changed while being transferred.');
|
|
173
|
+
await link(staged, destination);
|
|
174
|
+
published = true;
|
|
175
|
+
} finally {
|
|
176
|
+
await unlink(staged).catch(() => {});
|
|
177
|
+
if (!published) await unlink(marker).catch(() => {});
|
|
178
|
+
}
|
|
179
|
+
if (moveSource) {
|
|
180
|
+
const backup = `${found}.ccdeck-moved-${randomUUID()}`;
|
|
181
|
+
try {
|
|
182
|
+
await renameWithRetry(found, backup);
|
|
183
|
+
await chmod(backup, 0o600);
|
|
184
|
+
// A returning rollout publishes a fresh prefix receipt. Keep the old
|
|
185
|
+
// one beside its backup rather than blocking a later round trip.
|
|
186
|
+
await renameWithRetry(codexHandoffPath(found), codexHandoffPath(backup)).catch(e => { if (e.code !== 'ENOENT') throw e; });
|
|
187
|
+
}
|
|
188
|
+
catch (error) {
|
|
189
|
+
await renameWithRetry(backup, found).catch(() => {});
|
|
190
|
+
await unlink(destination).catch(() => {}); await unlink(marker).catch(() => {}); throw error;
|
|
191
|
+
}
|
|
192
|
+
let restored = false;
|
|
193
|
+
onSourceMoved?.(async () => {
|
|
194
|
+
if (restored) return;
|
|
195
|
+
const saved = await lstat(backup);
|
|
196
|
+
if (!saved.isFile() || saved.ino !== snapshot.ino || saved.size !== snapshot.size
|
|
197
|
+
|| saved.mtimeMs !== snapshot.mtimeMs) throw new Error('Codex source backup changed; restore manually.');
|
|
198
|
+
// Exclusive hard links restore the exact stopped rollout without ever
|
|
199
|
+
// overwriting work created in the source home after preparation.
|
|
200
|
+
try { await link(codexHandoffPath(backup), codexHandoffPath(found)); }
|
|
201
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
202
|
+
await link(backup, found);
|
|
203
|
+
restored = true;
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
return destination;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export function createCodexEngineAdapter(file, executable, args, home, options = {}) {
|
|
210
|
+
const invocation = codexEngineInvocation(args);
|
|
211
|
+
if (!invocation) return null;
|
|
212
|
+
const settingsOptions = { store: dirname(file), ...options };
|
|
213
|
+
let selection;
|
|
214
|
+
const leases = new Map();
|
|
215
|
+
return {
|
|
216
|
+
async close() {
|
|
217
|
+
for (const lease of leases.values()) {
|
|
218
|
+
try {
|
|
219
|
+
const owner = JSON.parse(await readFile(lease.path, 'utf8'));
|
|
220
|
+
if (owner.pid === process.pid && owner.nonce === lease.nonce) await unlink(lease.path);
|
|
221
|
+
} catch { /* never remove a replacement lease */ }
|
|
222
|
+
}
|
|
223
|
+
leases.clear();
|
|
224
|
+
},
|
|
225
|
+
invocation,
|
|
226
|
+
async settings() {
|
|
227
|
+
const s = await readCodexAuto(settingsOptions);
|
|
228
|
+
const config = await readFile(join(home, 'config.toml'), 'utf8').catch(e => { if (e.code === 'ENOENT') return ''; throw e; });
|
|
229
|
+
// A custom provider/profile can use a different authentication lifecycle.
|
|
230
|
+
// Its process remains untouched instead of rotating ChatGPT accounts.
|
|
231
|
+
const custom = isCustomCodexConfig(config);
|
|
232
|
+
return { enabled: s.enabled && !custom, custom, threshold: Number(s.settings['autoswitch.threshold'].value), next: s.choice.next, heldOut: s.heldOut };
|
|
233
|
+
},
|
|
234
|
+
async accounts() {
|
|
235
|
+
selection = await readCodexSelection(settingsOptions);
|
|
236
|
+
return discoverCodexProfiles({ ...settingsOptions, selection, enableNative: true });
|
|
237
|
+
},
|
|
238
|
+
quota(id) { return readCodexProfileQuota(id, { ...settingsOptions, selection, enableNative: true }); },
|
|
239
|
+
run(current, context) { return runCodexEngineAttempt(executable, current.args, current.home, { ...options, ...context, resumed: current.resumed }); },
|
|
240
|
+
async prepare({ from, id, threadId, sessionConfig }) {
|
|
241
|
+
// Per-account configuration can select a different provider, MCP servers,
|
|
242
|
+
// or permissions. Never transfer work into a different configuration.
|
|
243
|
+
const config = async home => readFile(join(home, 'config.toml'), 'utf8').catch(e => { if (e.code === 'ENOENT') return ''; throw e; });
|
|
244
|
+
const latest = await readCodexSelection(settingsOptions);
|
|
245
|
+
const target = latest.profiles.find(p => p.id === id && p.available);
|
|
246
|
+
const source = latest.profiles.find(p => p.id === from.id && p.available);
|
|
247
|
+
if (!target || !source || await realpath(source.home) !== await realpath(from.home)) throw new Error('Codex accounts changed before continuation.');
|
|
248
|
+
// One owner for this conversation across every target account. A stale
|
|
249
|
+
// lease after a crash is refused rather than guessing about a live run.
|
|
250
|
+
if (!leases.has(threadId)) {
|
|
251
|
+
const locks = join(dirname(file), 'codex-engine-locks');
|
|
252
|
+
await mkdir(locks, { recursive: true, mode: 0o700 });
|
|
253
|
+
if (!(await lstat(locks)).isDirectory()) throw new Error('Codex continuation lock folder is unavailable.');
|
|
254
|
+
const lock = join(locks, `${threadId}.lock`);
|
|
255
|
+
const handle = await open(lock, 'wx', 0o600);
|
|
256
|
+
const nonce = randomUUID();
|
|
257
|
+
try { await handle.writeFile(JSON.stringify({ pid: process.pid, nonce })); }
|
|
258
|
+
catch (e) { await unlink(lock).catch(() => {}); throw e; }
|
|
259
|
+
finally { await handle.close(); }
|
|
260
|
+
leases.set(threadId, { path: lock, nonce });
|
|
261
|
+
}
|
|
262
|
+
const sourceConfig = await config(from.home), targetConfig = await config(target.home);
|
|
263
|
+
if (sourceConfig !== targetConfig && (!sessionConfig || sessionConfig.sourceHash !== configHash(sourceConfig)
|
|
264
|
+
|| !isTrustOnlyConfig(targetConfig) && configHash(targetConfig) !== sessionConfig.originHash)) throw new Error('Codex account configurations differ; resume manually.');
|
|
265
|
+
let restoreSource;
|
|
266
|
+
await transferCodexThread(from.home, target.home, threadId, { moveSource: options.moveConversation === true,
|
|
267
|
+
onSourceMoved: restore => { restoreSource = restore; } });
|
|
268
|
+
return { id, home: target.home, args: invocation.resumeArgs(threadId), resumed: true, threadId,
|
|
269
|
+
...(restoreSource ? { restoreSource } : {}) };
|
|
270
|
+
},
|
|
271
|
+
};
|
|
272
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// One authenticated local TUI connection. No browser origins, no shared port,
|
|
2
|
+
// no credentials in the URL, no public listener. ws handles RFC6455 framing.
|
|
3
|
+
import { createServer } from 'node:http';
|
|
4
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
5
|
+
import { WebSocketServer, WebSocket } from 'ws';
|
|
6
|
+
|
|
7
|
+
export async function createCodexEngineBridge({ onMessage, onDisconnect = () => {} }) {
|
|
8
|
+
const token = randomBytes(32).toString('hex');
|
|
9
|
+
const expected = Buffer.from(`Bearer ${token}`);
|
|
10
|
+
const server = createServer((_req, res) => { res.writeHead(404); res.end(); });
|
|
11
|
+
const wss = new WebSocketServer({ noServer: true, maxPayload: 64 * 1024 * 1024, perMessageDeflate: false });
|
|
12
|
+
let client = null, accepted = false;
|
|
13
|
+
server.on('upgrade', (req, socket, head) => {
|
|
14
|
+
const actual = Buffer.from(String(req.headers.authorization ?? ''));
|
|
15
|
+
if (accepted || req.headers.origin || req.url !== '/' || actual.length !== expected.length || !timingSafeEqual(actual, expected)) {
|
|
16
|
+
socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n'); return;
|
|
17
|
+
}
|
|
18
|
+
accepted = true;
|
|
19
|
+
wss.handleUpgrade(req, socket, head, ws => {
|
|
20
|
+
client = ws;
|
|
21
|
+
ws.on('error', () => {});
|
|
22
|
+
ws.on('close', () => { client = null; onDisconnect(); });
|
|
23
|
+
ws.on('message', (data, binary) => {
|
|
24
|
+
if (binary) { ws.close(1003); return; }
|
|
25
|
+
let message;
|
|
26
|
+
try { message = JSON.parse(data.toString()); } catch { ws.close(1007); return; }
|
|
27
|
+
if (!message || typeof message !== 'object' || Array.isArray(message)) { ws.close(1007); return; }
|
|
28
|
+
Promise.resolve().then(() => onMessage(message)).catch(() => ws.close(1011));
|
|
29
|
+
});
|
|
30
|
+
});
|
|
31
|
+
});
|
|
32
|
+
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
|
|
33
|
+
return {
|
|
34
|
+
url: `ws://127.0.0.1:${server.address().port}/`, token,
|
|
35
|
+
send(message) {
|
|
36
|
+
if (client?.readyState !== WebSocket.OPEN) return;
|
|
37
|
+
if (client.bufferedAmount > 64 * 1024 * 1024) { client.close(1009); return; }
|
|
38
|
+
client.send(JSON.stringify(message));
|
|
39
|
+
},
|
|
40
|
+
async close() {
|
|
41
|
+
client?.terminate();
|
|
42
|
+
await new Promise(resolve => wss.close(resolve));
|
|
43
|
+
server.closeAllConnections?.();
|
|
44
|
+
await new Promise(resolve => server.close(resolve));
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// Preserve the live session's configuration through native RPC, without
|
|
2
|
+
// rewriting either account's config or putting settings/secrets in process argv.
|
|
3
|
+
import { readFile } from 'node:fs/promises';
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
export const configHash = text => createHash('sha256').update(text).digest('hex');
|
|
7
|
+
export const configText = home => readFile(join(home, 'config.toml'), 'utf8').catch(e => { if (e.code === 'ENOENT') return ''; throw e; });
|
|
8
|
+
export const isCustomCodexConfig = text => /^\s*(?:model_provider|["']model_provider["'])\s*=\s*["'](?!openai["'])/m.test(text)
|
|
9
|
+
|| /^\s*(?:profile|["']profile["'])\s*=/m.test(text);
|
|
10
|
+
export function isTrustOnlyConfig(text) {
|
|
11
|
+
let project = false;
|
|
12
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
13
|
+
const line = raw.trim();
|
|
14
|
+
if (!line || line.startsWith('#')) continue;
|
|
15
|
+
if (line.startsWith('[')) {
|
|
16
|
+
if (!/^\[projects\..+\]\s*(?:#.*)?$/.test(line)) return false;
|
|
17
|
+
project = true;
|
|
18
|
+
} else if (!project || !/^trust_level\s*=\s*["'](?:trusted|untrusted)["']\s*(?:#.*)?$/.test(line)) return false;
|
|
19
|
+
}
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
function merge(a, b) {
|
|
23
|
+
for (const [key, value] of Object.entries(b ?? {})) {
|
|
24
|
+
if (['__proto__', 'prototype', 'constructor'].includes(key)) throw new Error('Invalid config key.');
|
|
25
|
+
a[key] = value && typeof value === 'object' && !Array.isArray(value)
|
|
26
|
+
? merge(a[key] && typeof a[key] === 'object' && !Array.isArray(a[key]) ? a[key] : {}, value) : value;
|
|
27
|
+
}
|
|
28
|
+
return a;
|
|
29
|
+
}
|
|
30
|
+
export async function captureSessionConfig(rpc, home, cwd) {
|
|
31
|
+
const before = await configText(home);
|
|
32
|
+
const result = await rpc.request('config/read', { includeLayers: true, ...(cwd ? { cwd } : {}) });
|
|
33
|
+
if (!Array.isArray(result?.layers)) return null;
|
|
34
|
+
const overrides = {};
|
|
35
|
+
// Native ConfigReadResponse lists highest priority first.
|
|
36
|
+
for (const layer of [...result.layers].reverse()) if (!layer.disabledReason && layer.config && typeof layer.config === 'object') merge(overrides, layer.config);
|
|
37
|
+
// Only raw TOML layers round-trip as overrides. The effective config/read
|
|
38
|
+
// view contains display values (for example empty policy arrays as strings)
|
|
39
|
+
// that native thread/resume cannot parse back into configuration.
|
|
40
|
+
if (await configText(home) !== before) throw new Error('Codex configuration changed during handoff.');
|
|
41
|
+
return { overrides, sourceHash: configHash(before), originHash: configHash(before) };
|
|
42
|
+
}
|