ccdeck 3.53.3 → 3.80.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 +55 -3
- package/THIRD_PARTY_NOTICES.md +31 -1
- package/dist/web/assets/{BrowserWatchModal-CJ0CW4Go.js → BrowserWatchModal-Bfvo_8H6.js} +1 -1
- package/dist/web/assets/{IntegrationModal-DlJzBN8b.js → IntegrationModal-GS5jIQ_J.js} +1 -1
- package/dist/web/assets/{RadioPanel-CHl3s3OH.js → RadioPanel-Bxd2ElWb.js} +1 -1
- package/dist/web/assets/{TrafficRadar-Cw3i0Hux.js → TrafficRadar-FgHBI2Oh.js} +1 -1
- package/dist/web/assets/{UsageHistoryModal-CiB5-CTH.js → UsageHistoryModal-APwKtE2J.js} +1 -1
- package/dist/web/assets/{app-2vj7uk2U.js → app-BzHVsgB2.js} +69 -69
- package/dist/web/assets/{index-D1YZbdq3.js → index-7whwMaPX.js} +1 -1
- package/dist/web/index.html +2 -2
- 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 +37 -0
- package/src/server/account-engine.mjs +87 -0
- package/src/server/account-routes.mjs +31 -3
- package/src/server/codex-auto.mjs +7 -18
- 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-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 +155 -0
- package/src/server/codex-quota.mjs +36 -2
- package/src/server/codex-selection.mjs +62 -8
- package/src/server/codex-share.mjs +193 -0
- package/src/server/codex-terminal-runner.mjs +38 -1
- package/src/server/codex-terminal.mjs +15 -3
- 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 +7 -1
- package/src/server/login-service.mjs +2 -0
- package/src/server/pinned-build.mjs +2 -0
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
// Quiesce model responses before native auth invalidates their network permits.
|
|
2
|
+
// Never answer approvals, widen permissions, or resume a naturally finished turn.
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { liveError } from './codex-live-rpc.mjs';
|
|
5
|
+
|
|
6
|
+
const passive = new Set(['userMessage', 'hookPrompt', 'agentMessage', 'functionCallOutput', 'plan', 'reasoning']);
|
|
7
|
+
const terminal = new Set(['completed', 'failed', 'declined']);
|
|
8
|
+
const tool = item => !passive.has(item.type);
|
|
9
|
+
const completed = item => item.status !== 'inProgress' && (terminal.has(item.status)
|
|
10
|
+
|| Number.isFinite(item.completedAtMs) && item.completedAtMs > 0);
|
|
11
|
+
const v2Child = thread => thread.canAcceptDirectInput === false && !!thread.parentThreadId
|
|
12
|
+
&& thread.source?.subAgent?.thread_spawn?.parent_thread_id === thread.parentThreadId
|
|
13
|
+
&& typeof thread.source.subAgent.thread_spawn.agent_path === 'string'
|
|
14
|
+
&& thread.source.subAgent.thread_spawn.agent_path.startsWith('/root/');
|
|
15
|
+
function ancestors(thread, known) {
|
|
16
|
+
const seen = new Set([thread.id]), parents = [];
|
|
17
|
+
for (let id = thread.parentThreadId; id; id = known.get(id)?.parentThreadId) {
|
|
18
|
+
if (seen.has(id) || !known.has(id)) throw liveError('native_activity_unknown');
|
|
19
|
+
seen.add(id); parents.push(id);
|
|
20
|
+
}
|
|
21
|
+
return parents;
|
|
22
|
+
}
|
|
23
|
+
// Waiting for a known descendant has no side effect. Spawn/input/close and
|
|
24
|
+
// every real tool must finish before we pause any member of the family.
|
|
25
|
+
const childWait = (item, thread, known) => item.type === 'collabAgentToolCall'
|
|
26
|
+
&& item.tool === 'wait' && item.status === 'inProgress' && item.senderThreadId === thread.id
|
|
27
|
+
&& Array.isArray(item.receiverThreadIds) && (item.receiverThreadIds.length > 0
|
|
28
|
+
? item.receiverThreadIds.every(id => known.has(id) && ancestors(known.get(id), known).includes(thread.id))
|
|
29
|
+
: [...known.values()].some(t => v2Child(t) && ancestors(t, known).includes(thread.id)));
|
|
30
|
+
const safe = (turn, thread, known) => turn?.itemsView === 'full' && Array.isArray(turn?.items)
|
|
31
|
+
&& (turn.items.some(i => i.type === 'userMessage') || v2Child(thread))
|
|
32
|
+
&& turn.items.every(i => passive.has(i.type) || completed(i) || childWait(i, thread, known));
|
|
33
|
+
const inputIds = turn => turn.items.filter(i => i.type === 'userMessage').map(i => i.id);
|
|
34
|
+
const sameInputs = (a, b) => JSON.stringify(inputIds(a)) === JSON.stringify(inputIds(b));
|
|
35
|
+
const retained = new WeakMap();
|
|
36
|
+
|
|
37
|
+
/** Keep this connection's observations attached until a cooperative handoff
|
|
38
|
+
* finishes. Native idle unloading otherwise loses direct-input capabilities
|
|
39
|
+
* between a completed checkpoint and its continuation. Never starts a turn.
|
|
40
|
+
*/
|
|
41
|
+
export async function retainCodexLiveHandoff(rpc, entries) {
|
|
42
|
+
const counts = retained.get(rpc) ?? new Map(); retained.set(rpc, counts);
|
|
43
|
+
const held = [];
|
|
44
|
+
let released = false;
|
|
45
|
+
const release = async () => {
|
|
46
|
+
if (released) return;
|
|
47
|
+
released = true;
|
|
48
|
+
for (const id of held.reverse()) {
|
|
49
|
+
const count = (counts.get(id) ?? 1) - 1;
|
|
50
|
+
if (count) counts.set(id, count);
|
|
51
|
+
else { counts.delete(id); await rpc.request('thread/unsubscribe', { threadId: id }).catch(() => {}); }
|
|
52
|
+
}
|
|
53
|
+
if (!counts.size) retained.delete(rpc);
|
|
54
|
+
};
|
|
55
|
+
try {
|
|
56
|
+
for (const entry of entries) {
|
|
57
|
+
const valid = t => t?.id === entry.threadId && (t.parentThreadId ?? null) === (entry.parentThreadId ?? null)
|
|
58
|
+
&& ['active', 'idle'].includes(t.status?.type);
|
|
59
|
+
if (!valid((await rpc.request('thread/read', { threadId: entry.threadId, includeTurns: false }))?.thread)) throw liveError('native_activity_changed');
|
|
60
|
+
held.push(entry.threadId); counts.set(entry.threadId, (counts.get(entry.threadId) ?? 0) + 1);
|
|
61
|
+
const t = (await rpc.request('thread/resume', { threadId: entry.threadId, excludeTurns: true }))?.thread;
|
|
62
|
+
if (!valid(t)) throw liveError('native_activity_changed');
|
|
63
|
+
}
|
|
64
|
+
return release;
|
|
65
|
+
} catch (error) { await release(); throw error; }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function latest(rpc, threadId) {
|
|
69
|
+
const page = await rpc.request('thread/turns/list', { threadId, limit: 1, sortDirection: 'desc', itemsView: 'full' });
|
|
70
|
+
if (!Array.isArray(page?.data)) throw liveError('native_activity_unknown');
|
|
71
|
+
return page.data[0] ?? null;
|
|
72
|
+
}
|
|
73
|
+
async function liveLatest(rpc, thread) {
|
|
74
|
+
if (thread.historyMode !== 'paginated') return latest(rpc, thread.id);
|
|
75
|
+
// Stored paginated history omits tool-start events. Native resume composes a
|
|
76
|
+
// live snapshot in its listener before subscribing this connection. Request
|
|
77
|
+
// one full turn, apply no settings, ignore replayed requests, then detach.
|
|
78
|
+
try {
|
|
79
|
+
const result = await rpc.request('thread/resume', { threadId: thread.id, excludeTurns: true,
|
|
80
|
+
initialTurnsPage: { limit: 1, sortDirection: 'desc', itemsView: 'full' } });
|
|
81
|
+
const page = result?.initialTurnsPage;
|
|
82
|
+
if (!Array.isArray(page?.data)) throw liveError('native_activity_unknown');
|
|
83
|
+
return page.data[0] ?? null;
|
|
84
|
+
} finally {
|
|
85
|
+
if (!retained.get(rpc)?.has(thread.id)) await rpc.request('thread/unsubscribe', { threadId: thread.id }).catch(() => {});
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
export const readCodexLiveTurn = (rpc, thread) => thread.status?.type === 'active' ? liveLatest(rpc, thread) : latest(rpc, thread.id);
|
|
89
|
+
async function snapshot(rpc) {
|
|
90
|
+
const page = await rpc.request('thread/loaded/list', { limit: 65 });
|
|
91
|
+
if (!Array.isArray(page?.data) || page.data.length > 64 || page.nextCursor) throw liveError('native_activity_unknown');
|
|
92
|
+
const threads = [], known = new Map();
|
|
93
|
+
for (const id of page.data) {
|
|
94
|
+
if (typeof id !== 'string') throw liveError('native_activity_unknown');
|
|
95
|
+
const result = await rpc.request('thread/read', { threadId: id, includeTurns: false });
|
|
96
|
+
const t = result?.thread;
|
|
97
|
+
if (!t || t.id !== id || !['idle', 'systemError', 'active', 'notLoaded'].includes(t.status?.type)) throw liveError('native_activity_unknown');
|
|
98
|
+
known.set(id, t);
|
|
99
|
+
// Ephemeral native jobs have no stored turn-history API. Never interrupt
|
|
100
|
+
// them or attempt to reconstruct their history; wait until twice idle.
|
|
101
|
+
if (t.ephemeral === true) {
|
|
102
|
+
if (t.status.type === 'idle') {
|
|
103
|
+
const again = (await rpc.request('thread/read', { threadId: id, includeTurns: false }))?.thread;
|
|
104
|
+
if (again?.id !== id) throw liveError('native_activity_unknown');
|
|
105
|
+
if (again.ephemeral === true && again.status?.type === 'idle') continue;
|
|
106
|
+
}
|
|
107
|
+
threads.push({ id, active: false, turn: null }); continue;
|
|
108
|
+
}
|
|
109
|
+
let turn;
|
|
110
|
+
try { turn = t.status.type === 'active' ? await liveLatest(rpc, t) : await latest(rpc, id); }
|
|
111
|
+
catch (error) {
|
|
112
|
+
// A newly opened blank native conversation has no stored turn page yet.
|
|
113
|
+
// Only this exact native error and a second idle observation establish
|
|
114
|
+
// that it has no work to hand off. Other rejected reads still fail closed.
|
|
115
|
+
if (t.status.type !== 'idle' || error.code !== 'native_thread_not_materialized') throw error;
|
|
116
|
+
const again = (await rpc.request('thread/read', { threadId: id, includeTurns: false }))?.thread;
|
|
117
|
+
if (again?.id !== id) throw liveError('native_activity_unknown');
|
|
118
|
+
if (again.status?.type === 'idle') continue;
|
|
119
|
+
threads.push({ id, active: false, turn: null });
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
if (t.status.type === 'active' || turn?.status === 'inProgress' || turn?.items?.some(i => i.status === 'inProgress')) threads.push({ id,
|
|
123
|
+
active: t.status.type === 'active',
|
|
124
|
+
thread: t, flags: t.status.activeFlags, turn });
|
|
125
|
+
}
|
|
126
|
+
return { threads, known };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** A waiting result sends no interrupt and no authentication mutation. */
|
|
130
|
+
export async function prepareCodexLiveHandoff(rpc, options = {}) {
|
|
131
|
+
const isCurrent = options.isCurrent ?? (() => true);
|
|
132
|
+
const paused = [];
|
|
133
|
+
const { threads: initial, known } = await snapshot(rpc);
|
|
134
|
+
const routes = new Map();
|
|
135
|
+
for (const t of initial) {
|
|
136
|
+
if (!t.thread || !v2Child(t.thread)) continue;
|
|
137
|
+
const owner = ancestors(t.thread, known).map(id => initial.find(p => p.id === id))
|
|
138
|
+
.find(p => p?.thread.canAcceptDirectInput === true);
|
|
139
|
+
if (owner && (owner.turn?.rootTurnId ?? owner.turn?.id) === (t.turn?.rootTurnId ?? t.turn?.id)) routes.set(t.id, owner.id);
|
|
140
|
+
}
|
|
141
|
+
for (const t of known.values()) {
|
|
142
|
+
if (!v2Child(t)) continue;
|
|
143
|
+
const owner = ancestors(t, known).find(id => initial.some(p => p.id === id && p.thread?.canAcceptDirectInput === true));
|
|
144
|
+
// Even an idle V2 child identifies a parent whose current internal send or
|
|
145
|
+
// followup may be absent from the item feed. Wait for inspectable active
|
|
146
|
+
// child work (then checkpoint it), or for the parent to finish naturally.
|
|
147
|
+
if (owner && ![...routes.values()].includes(owner)) return { waiting: true, paused };
|
|
148
|
+
}
|
|
149
|
+
const cooperative = new Set([...routes.keys(), ...routes.values()]);
|
|
150
|
+
if (initial.some(t => !t.active || t.thread?.canAcceptDirectInput === false && !routes.has(t.id)
|
|
151
|
+
|| t.thread?.parentThreadId && t.thread.canAcceptDirectInput !== true && !routes.has(t.id)
|
|
152
|
+
|| !Array.isArray(t.flags) || t.flags.length || t.turn?.status !== 'inProgress'
|
|
153
|
+
|| (cooperative.has(t.id) ? t.turn.itemsView !== 'full' || !Array.isArray(t.turn.items)
|
|
154
|
+
|| !routes.has(t.id) && !t.turn.items.some(i => i.type === 'userMessage') : !safe(t.turn, t.thread, known)))) {
|
|
155
|
+
return { waiting: true, paused };
|
|
156
|
+
}
|
|
157
|
+
// Stop parents first so a child's interruption cannot complete a live wait
|
|
158
|
+
// and let its parent launch more work. Resume in the opposite order below.
|
|
159
|
+
initial.sort((a, b) => ancestors(a.thread, known).length - ancestors(b.thread, known).length);
|
|
160
|
+
if (routes.size) {
|
|
161
|
+
// V2's send/followup handlers do not expose every tool-start item. Never
|
|
162
|
+
// interrupt that family based on an empty snapshot: ask its owner to drain
|
|
163
|
+
// tools and collect terminal checkpoints through normal agent messaging.
|
|
164
|
+
const owners = new Set(routes.values()), markers = new Map([...owners].map(id => [id, randomUUID()]));
|
|
165
|
+
return { waiting: true, paused, checkpoint: initial.filter(t => routes.has(t.id) || owners.has(t.id)).map(t => ({
|
|
166
|
+
threadId: t.id, turnId: t.turn.id, rootTurnId: t.turn.rootTurnId ?? t.turn.id, inputIds: inputIds(t.turn), messageId: randomUUID(),
|
|
167
|
+
checkpointId: markers.get(routes.get(t.id) ?? t.id),
|
|
168
|
+
...(t.thread.parentThreadId ? { parentThreadId: t.thread.parentThreadId } : {}),
|
|
169
|
+
...(routes.has(t.id) ? { resumeViaThreadId: routes.get(t.id) } : {}),
|
|
170
|
+
})) };
|
|
171
|
+
}
|
|
172
|
+
try {
|
|
173
|
+
for (const observed of initial) {
|
|
174
|
+
if (!isCurrent()) throw liveError('native_switch_superseded');
|
|
175
|
+
const now = (await rpc.request('thread/read', { threadId: observed.id, includeTurns: false }))?.thread;
|
|
176
|
+
if (now?.status?.type !== 'active') continue;
|
|
177
|
+
const turn = await liveLatest(rpc, now);
|
|
178
|
+
if (turn?.id !== observed.turn.id || now.status.activeFlags?.length || now.canAcceptDirectInput === false && !routes.has(observed.id)
|
|
179
|
+
|| (now.parentThreadId ?? null) !== (observed.thread.parentThreadId ?? null)
|
|
180
|
+
|| now.parentThreadId && now.canAcceptDirectInput !== true && !routes.has(observed.id)
|
|
181
|
+
|| routes.has(observed.id) && !v2Child(now)
|
|
182
|
+
|| !safe(turn, now, known) || !sameInputs(observed.turn, turn)) throw liveError('native_activity_changed');
|
|
183
|
+
const entry = { threadId: observed.id, turnId: turn.id, rootTurnId: turn.rootTurnId ?? turn.id, messageId: randomUUID(), inputIds: inputIds(turn),
|
|
184
|
+
...(now.parentThreadId ? { parentThreadId: now.parentThreadId } : {}),
|
|
185
|
+
...(routes.has(observed.id) ? { resumeViaThreadId: routes.get(observed.id) } : {}) };
|
|
186
|
+
await options.beforeInterrupt?.(entry);
|
|
187
|
+
// Native acknowledges terminal completion; verify whether it interrupted
|
|
188
|
+
// or finished naturally. Never use an empty ID or change configuration.
|
|
189
|
+
await rpc.request('turn/interrupt', { threadId: observed.id, turnId: turn.id });
|
|
190
|
+
const after = await latest(rpc, observed.id);
|
|
191
|
+
if (after?.id === turn.id && after.status === 'completed') { await options.afterInterrupt?.(entry, 'skipped'); continue; }
|
|
192
|
+
if (after?.id !== turn.id || after.status !== 'interrupted') throw liveError('native_interrupt_unconfirmed');
|
|
193
|
+
if (!sameInputs(turn, after)) throw liveError('native_activity_changed');
|
|
194
|
+
const previous = new Set(turn.items.map(i => i.id));
|
|
195
|
+
if (after.items.some(i => tool(i) && !previous.has(i.id) && !completed(i))) throw liveError('native_tool_interrupted');
|
|
196
|
+
paused.push(entry);
|
|
197
|
+
await options.afterInterrupt?.(entry, 'paused');
|
|
198
|
+
}
|
|
199
|
+
await assertCodexLiveQuiet(rpc);
|
|
200
|
+
return { waiting: false, paused };
|
|
201
|
+
} catch (error) {
|
|
202
|
+
// Preserve exact interrupted IDs for recovery, never include thread text.
|
|
203
|
+
error.handoff = { waiting: false, paused };
|
|
204
|
+
throw error;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export async function assertCodexLiveQuiet(rpc) {
|
|
209
|
+
if ((await snapshot(rpc)).threads.length) throw liveError('native_activity_changed');
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Mark a send durably before submitting. An uncertain send is never replayed. */
|
|
213
|
+
export async function continueCodexLiveHandoff(rpc, handoff, options = {}) {
|
|
214
|
+
let resumed = 0;
|
|
215
|
+
const delegated = [], owners = new Set();
|
|
216
|
+
for (const entry of [...handoff?.paused ?? []].reverse()) {
|
|
217
|
+
if (entry.sent) continue;
|
|
218
|
+
if (options.isCurrent && !options.isCurrent()) throw liveError('native_switch_superseded');
|
|
219
|
+
const t = (await rpc.request('thread/read', { threadId: entry.threadId, includeTurns: false }))?.thread;
|
|
220
|
+
// A closed/unloaded child has no direct-input capability. Leave it alone
|
|
221
|
+
// before inspecting history, and allow the remaining family to continue.
|
|
222
|
+
if (t?.status?.type !== 'idle') {
|
|
223
|
+
if (entry.resumeViaThreadId && t?.status?.type === 'notLoaded') throw liveError('native_continue_unconfirmed');
|
|
224
|
+
await options.onSkip?.(entry); continue;
|
|
225
|
+
}
|
|
226
|
+
if (entry.resumeViaThreadId ? !v2Child(t) || t.parentThreadId !== entry.parentThreadId
|
|
227
|
+
: t?.canAcceptDirectInput === false || entry.parentThreadId
|
|
228
|
+
&& (t?.canAcceptDirectInput !== true || t.parentThreadId !== entry.parentThreadId)) throw liveError('native_activity_changed');
|
|
229
|
+
const turn = await latest(rpc, entry.threadId);
|
|
230
|
+
// New input, natural completion, archival or a different turn wins over us.
|
|
231
|
+
const checkpoint = entry.checkpointReady && turn?.status === 'completed'
|
|
232
|
+
&& turn.items?.some(i => i.type === 'agentMessage' && i.text?.includes('CCDECK_CHECKPOINT_' + entry.checkpointId));
|
|
233
|
+
if (turn?.id !== entry.turnId || (!checkpoint && turn.status !== 'interrupted')
|
|
234
|
+
|| JSON.stringify(inputIds(turn)) !== JSON.stringify(entry.inputIds)) {
|
|
235
|
+
await options.onSkip?.(entry); continue;
|
|
236
|
+
}
|
|
237
|
+
if (entry.resumeViaThreadId) {
|
|
238
|
+
await options.onDelegate?.(entry);
|
|
239
|
+
entry.sent = true; delegated.push(entry); continue;
|
|
240
|
+
}
|
|
241
|
+
await options.beforeSend?.(entry);
|
|
242
|
+
// Journal/authentication callbacks may wait on disk or native RPC. A user
|
|
243
|
+
// can close the conversation or submit new work during that wait.
|
|
244
|
+
if (options.isCurrent && !options.isCurrent()) throw liveError('native_switch_superseded');
|
|
245
|
+
const current = (await rpc.request('thread/read', { threadId: entry.threadId, includeTurns: false }))?.thread;
|
|
246
|
+
if (current?.status?.type !== 'idle') { await options.onSkip?.(entry); continue; }
|
|
247
|
+
if (current.id !== entry.threadId || current.canAcceptDirectInput === false
|
|
248
|
+
|| (current.parentThreadId ?? null) !== (t.parentThreadId ?? null)) throw liveError('native_activity_changed');
|
|
249
|
+
const finalTurn = await latest(rpc, entry.threadId);
|
|
250
|
+
const finalCheckpoint = entry.checkpointReady && finalTurn?.status === 'completed'
|
|
251
|
+
&& finalTurn.items?.some(i => i.type === 'agentMessage' && i.text?.includes('CCDECK_CHECKPOINT_' + entry.checkpointId));
|
|
252
|
+
if (finalTurn?.id !== entry.turnId || (!finalCheckpoint && finalTurn.status !== 'interrupted')
|
|
253
|
+
|| JSON.stringify(inputIds(finalTurn)) !== JSON.stringify(entry.inputIds)) {
|
|
254
|
+
await options.onSkip?.(entry); continue;
|
|
255
|
+
}
|
|
256
|
+
if (options.isCurrent && !options.isCurrent()) throw liveError('native_switch_superseded');
|
|
257
|
+
entry.sent = true;
|
|
258
|
+
const children = delegated.filter(e => e.resumeViaThreadId === entry.threadId);
|
|
259
|
+
const continuation = 'Continue the interrupted task, honoring the latest user instructions already in this conversation. Do not repeat completed tools or actions. If the user cancelled or asked to stop, remain stopped.';
|
|
260
|
+
const resumeTask = entry.checkpointReady ? 'The ccdeck account change is complete. Resume the original assignment from the checkpoint; the temporary checkpoint request is finished. ' + continuation : continuation;
|
|
261
|
+
const text = children.length ? resumeTask + '\n\nThe account handoff paused these existing subagents (deepest first): '
|
|
262
|
+
+ JSON.stringify(children.map(e => e.threadId)) + '. Before continuing your own work, inspect their current status with list_agents. '
|
|
263
|
+
+ (entry.checkpointReady ? 'These listed agents ended temporary checkpoints; their original assignments are unfinished. Their native status may be completed: that checkpoint still needs continuation. For each that has not already resumed or been closed, '
|
|
264
|
+
: 'For each listed agent that is still interrupted, ')
|
|
265
|
+
+ 'use the native followup_task tool exactly once, targeting that SAME existing agent ID, '
|
|
266
|
+
+ 'with this message: ' + JSON.stringify(resumeTask) + '. Resume in the listed order. Keep their existing assignments, history and parent relationships. '
|
|
267
|
+
+ 'Do not spawn replacements, reopen closed agents, repeat completed work, or send followups to agents already running. '
|
|
268
|
+
+ (entry.checkpointReady ? 'A completed temporary checkpoint is not a finished original assignment. ' : 'Do not restart completed agents. ')
|
|
269
|
+
+ 'Then continue the original task and wait for the same agents as needed.' : resumeTask;
|
|
270
|
+
const result = await rpc.request('turn/start', { threadId: entry.threadId,
|
|
271
|
+
rootTurnId: entry.rootTurnId, clientUserMessageId: entry.messageId,
|
|
272
|
+
input: [{ type: 'text', text }] });
|
|
273
|
+
if (!result?.turn?.id) throw liveError('native_continue_unconfirmed');
|
|
274
|
+
resumed++;
|
|
275
|
+
await options.afterSend?.(entry, result.turn.id);
|
|
276
|
+
owners.add(entry.threadId);
|
|
277
|
+
}
|
|
278
|
+
if (delegated.some(e => !owners.has(e.resumeViaThreadId))) throw liveError('native_continue_unconfirmed');
|
|
279
|
+
return { resumed, ...(delegated.length ? { delegated } : {}) };
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** Observe the parent's native followups; never submit or retry child input. */
|
|
283
|
+
export async function confirmCodexLiveChildren(rpc, entries, options = {}) {
|
|
284
|
+
const pending = [];
|
|
285
|
+
for (const entry of entries) {
|
|
286
|
+
const t = (await rpc.request('thread/read', { threadId: entry.threadId, includeTurns: false }))?.thread;
|
|
287
|
+
if (!t || t.parentThreadId !== entry.parentThreadId) throw liveError('native_activity_changed');
|
|
288
|
+
// Eviction and closure both appear unloaded here. Only the owning parent
|
|
289
|
+
// can distinguish them; do not claim that an unobserved child resumed.
|
|
290
|
+
if (t.status?.type === 'notLoaded') { pending.push(entry); continue; }
|
|
291
|
+
const turn = t.status?.type === 'active' ? await liveLatest(rpc, t) : await latest(rpc, entry.threadId);
|
|
292
|
+
if (turn?.id === entry.turnId && (turn.status === 'interrupted' || entry.checkpointReady && turn.status === 'completed'
|
|
293
|
+
&& turn.items?.some(i => i.type === 'agentMessage' && i.text?.includes('CCDECK_CHECKPOINT_' + entry.checkpointId)))) { pending.push(entry); continue; }
|
|
294
|
+
if (turn?.id !== entry.turnId && turn.rootTurnId === entry.rootTurnId && ['inProgress', 'completed'].includes(turn.status)) {
|
|
295
|
+
await options.onConfirmed?.(entry, turn.id); continue;
|
|
296
|
+
}
|
|
297
|
+
throw liveError('native_activity_changed');
|
|
298
|
+
}
|
|
299
|
+
return { pending };
|
|
300
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// One host controls a daemon's externally managed authentication. The recovery
|
|
2
|
+
// mutex follows the same immutable-lock pattern as the account registry.
|
|
3
|
+
import { createServer } from 'node:net';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
6
|
+
import { link, lstat, mkdir, open, readFile, unlink } from 'node:fs/promises';
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
import { liveError } from './codex-live-rpc.mjs';
|
|
9
|
+
import { ensureWindowsPrivateDirectory, holdWindowsPrivatePath } from './codex-windows-private.mjs';
|
|
10
|
+
const alive = pid => { try { process.kill(pid, 0); return true; } catch (e) { return e.code !== 'ESRCH'; } };
|
|
11
|
+
async function record(file, options) {
|
|
12
|
+
let guard;
|
|
13
|
+
try {
|
|
14
|
+
const windows = (options.platform ?? process.platform) === 'win32';
|
|
15
|
+
if (windows) guard = await holdWindowsPrivatePath(file, { ...options.windowsPrivate, kind: 'file' });
|
|
16
|
+
const info = await lstat(file);
|
|
17
|
+
if (!info.isFile() || !windows && info.uid !== process.getuid?.() || info.size > 4096) return null;
|
|
18
|
+
const value = JSON.parse(await readFile(file, 'utf8'));
|
|
19
|
+
const after = await lstat(file);
|
|
20
|
+
if (guard && !guard.valid() || info.ino !== after.ino || info.dev !== after.dev || info.ctimeMs !== after.ctimeMs || info.size !== after.size) return null;
|
|
21
|
+
return Number.isInteger(value.pid) && value.pid > 0 && typeof value.nonce === 'string' ? { ...value, ino: info.ino, dev: info.dev } : null;
|
|
22
|
+
} catch { return null; }
|
|
23
|
+
finally { await guard?.release(); }
|
|
24
|
+
}
|
|
25
|
+
const same = (a, b) => a && b && a.pid === b.pid && a.nonce === b.nonce && a.ino === b.ino && a.dev === b.dev;
|
|
26
|
+
export async function acquireCodexLiveLease(home, options = {}) {
|
|
27
|
+
const key = createHash('sha256').update(home).digest('hex');
|
|
28
|
+
const windows = (options.platform ?? process.platform) === 'win32';
|
|
29
|
+
let dir = options.leaseDirectory ?? join(tmpdir(), `ccdeck-native-auth-${process.getuid?.() ?? 'user'}`), guard;
|
|
30
|
+
if (windows) {
|
|
31
|
+
try {
|
|
32
|
+
dir = await ensureWindowsPrivateDirectory(dir, options.windowsPrivate);
|
|
33
|
+
guard = await holdWindowsPrivatePath(dir, options.windowsPrivate);
|
|
34
|
+
} catch { throw liveError('untrusted_control_directory'); }
|
|
35
|
+
} else {
|
|
36
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
37
|
+
const info = await lstat(dir);
|
|
38
|
+
if (!info.isDirectory() || info.uid !== process.getuid?.() || info.mode & 0o077) throw liveError('untrusted_control_directory');
|
|
39
|
+
}
|
|
40
|
+
const file = join(dir, `${key}.lock`), nonce = randomUUID(), staged = `${file}.${nonce}.tmp`;
|
|
41
|
+
try {
|
|
42
|
+
const handle = await open(staged, 'wx', 0o600);
|
|
43
|
+
try { await handle.writeFile(JSON.stringify({ pid: process.pid, nonce })); await handle.sync(); }
|
|
44
|
+
finally { await handle.close(); }
|
|
45
|
+
try { await link(staged, file); }
|
|
46
|
+
catch (e) {
|
|
47
|
+
if (e.code !== 'EEXIST') throw liveError('native_control_unavailable');
|
|
48
|
+
const observed = await record(file, options);
|
|
49
|
+
if (observed && !alive(observed.pid)) {
|
|
50
|
+
const mutex = createServer(s => s.destroy());
|
|
51
|
+
const locked = await new Promise(resolve => { mutex.once('error', () => resolve(false)); mutex.listen({ host: '127.0.0.1', port: 49152 + parseInt(key.slice(0, 4), 16) % 16384, exclusive: true }, () => resolve(true)); });
|
|
52
|
+
if (locked) {
|
|
53
|
+
try { const current = await record(file, options); if (same(observed, current) && !alive(current.pid)) await unlink(file); }
|
|
54
|
+
finally { await new Promise(resolve => mutex.close(resolve)); }
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
try { await link(staged, file); } catch { throw liveError('native_control_busy'); }
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
async valid() { const r = await record(file, options); return r?.pid === process.pid && r.nonce === nonce; },
|
|
61
|
+
async release() { const r = await record(file, options); if (r?.pid === process.pid && r.nonce === nonce) await unlink(file).catch(() => {}); },
|
|
62
|
+
};
|
|
63
|
+
} finally { await unlink(staged).catch(() => {}); await guard?.release(); }
|
|
64
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
// A control connection to the user's existing daemon. Closing it never stops
|
|
2
|
+
// that daemon or takes ownership of its conversations.
|
|
3
|
+
import { execFile } from 'node:child_process';
|
|
4
|
+
import { promisify } from 'node:util';
|
|
5
|
+
import { lstat, realpath } from 'node:fs/promises';
|
|
6
|
+
import { dirname, isAbsolute, join, resolve, win32 } from 'node:path';
|
|
7
|
+
import { randomUUID } from 'node:crypto';
|
|
8
|
+
import WebSocket from 'ws';
|
|
9
|
+
import { pathLookup, spawnSpec } from './exec-spec.mjs';
|
|
10
|
+
import { inspectWindowsPrivateSocket, holdWindowsPrivatePath } from './codex-windows-private.mjs';
|
|
11
|
+
import { createCodexWindowsProxy } from './codex-windows-proxy.mjs';
|
|
12
|
+
|
|
13
|
+
export const liveError = code => Object.assign(new Error(code), { code });
|
|
14
|
+
const runFile = promisify(execFile);
|
|
15
|
+
const unmaterializedHistory = /^thread [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12} is not materialized yet; thread\/turns\/list is unavailable before first user message$/i;
|
|
16
|
+
function rejection(method, error) {
|
|
17
|
+
if (method === 'thread/turns/list' && error?.code === -32600 && unmaterializedHistory.test(error.message ?? '')) return liveError('native_thread_not_materialized');
|
|
18
|
+
return liveError(error?.code === -32601 ? 'unsupported_protocol' : 'native_request_rejected');
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function inspectPosixSocket(socketPath, uid = process.getuid?.()) {
|
|
22
|
+
try {
|
|
23
|
+
// Work with the resolved endpoint, never a newly substituted path alias.
|
|
24
|
+
if (uid == null || await realpath(socketPath) !== socketPath) throw liveError('untrusted_native_socket');
|
|
25
|
+
const info = await lstat(socketPath);
|
|
26
|
+
if (!info.isSocket() || info.uid !== uid) throw liveError('untrusted_native_socket');
|
|
27
|
+
const ancestors = [];
|
|
28
|
+
for (let path = dirname(socketPath);; path = dirname(path)) {
|
|
29
|
+
const directory = await lstat(path);
|
|
30
|
+
if (!directory.isDirectory() || directory.uid !== uid && directory.uid !== 0) throw liveError('untrusted_native_socket');
|
|
31
|
+
ancestors.push(directory);
|
|
32
|
+
if (dirname(path) === path) break;
|
|
33
|
+
}
|
|
34
|
+
let privateTraversal = false;
|
|
35
|
+
for (const directory of ancestors.reverse()) {
|
|
36
|
+
// A writable ancestor could replace even a private descendant. Sticky
|
|
37
|
+
// shared directories (such as /tmp) protect our owner/root-owned entries.
|
|
38
|
+
if (!privateTraversal && directory.mode & 0o022 && !(directory.mode & 0o1000)) throw liveError('untrusted_native_socket');
|
|
39
|
+
if (directory.uid === uid && !(directory.mode & 0o011)) privateTraversal = true;
|
|
40
|
+
}
|
|
41
|
+
// Socket chmod alone does not prevent connections on all supported Unix
|
|
42
|
+
// systems. Require an owner-private traversal barrier somewhere in the
|
|
43
|
+
// actual path; a permissive socket/parent below that barrier is legitimate.
|
|
44
|
+
if (!privateTraversal) throw liveError('untrusted_native_socket');
|
|
45
|
+
return { generation: `${info.dev}:${info.ino}:${info.ctimeMs}` };
|
|
46
|
+
} catch { throw liveError('untrusted_native_socket'); }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function resolveCodexLiveEndpoint(home, options = {}) {
|
|
50
|
+
const platform = options.platform ?? process.platform, windows = platform === 'win32';
|
|
51
|
+
let canonical, advertised;
|
|
52
|
+
try { canonical = await realpath(home); advertised = join(canonical, 'app-server-control', 'app-server-control.sock'); if (!windows) await lstat(advertised); }
|
|
53
|
+
catch { throw liveError('native_not_running'); }
|
|
54
|
+
const executable = options.executable ?? pathLookup('codex', platform, { pathEnv: (options.env ?? process.env).PATH ?? (options.env ?? process.env).Path ?? '' });
|
|
55
|
+
if (!executable) throw liveError('cli_unavailable');
|
|
56
|
+
const env = { ...(options.env ?? process.env), CODEX_HOME: canonical };
|
|
57
|
+
for (const key of Object.keys(env)) if (/^(OPENAI_API_KEY|CODEX_API_KEY)$/i.test(key)) delete env[key];
|
|
58
|
+
let result;
|
|
59
|
+
try {
|
|
60
|
+
const spec = spawnSpec(executable, ['app-server', 'daemon', 'version'], platform);
|
|
61
|
+
const output = await (options.execFile ?? runFile)(spec.file, spec.args, { ...spec.opts, env, timeout: 5000, maxBuffer: 256 * 1024, windowsHide: true });
|
|
62
|
+
result = JSON.parse(output.stdout);
|
|
63
|
+
} catch { throw liveError('native_unavailable'); }
|
|
64
|
+
const equalPath = windows ? (a, b) => win32.toNamespacedPath(a).toLowerCase() === win32.toNamespacedPath(b).toLowerCase() : (a, b) => resolve(a) === b;
|
|
65
|
+
if (result.status !== 'running' || !(windows ? win32.isAbsolute : isAbsolute)(result.socketPath ?? '') || !equalPath(result.socketPath, advertised)) throw liveError('native_not_running');
|
|
66
|
+
const version = String(result.appServerVersion ?? result.managedCodexVersion ?? '');
|
|
67
|
+
const v = version.match(/^(\d+)\.(\d+)\.(\d+)(?:$|[-+])/);
|
|
68
|
+
if (!v || Number(v[1]) === 0 && Number(v[2]) < 166) throw liveError('unsupported_version');
|
|
69
|
+
let socketPath;
|
|
70
|
+
if (windows) {
|
|
71
|
+
try {
|
|
72
|
+
const captured = await inspectWindowsPrivateSocket(advertised, { ...options.windowsPrivate, platform });
|
|
73
|
+
return { home: canonical, socketPath: captured.path, version, generation: captured.generation, executable, transport: 'windows-proxy' };
|
|
74
|
+
} catch { throw liveError('untrusted_native_socket'); }
|
|
75
|
+
}
|
|
76
|
+
try { socketPath = await realpath(advertised); }
|
|
77
|
+
catch { throw liveError('native_not_running'); }
|
|
78
|
+
const captured = await inspectPosixSocket(socketPath, options.uid);
|
|
79
|
+
return { home: canonical, socketPath, version, generation: captured.generation, executable };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export async function connectCodexLiveRpc(endpoint, options = {}) {
|
|
83
|
+
const windows = endpoint.transport === 'windows-proxy';
|
|
84
|
+
let guard, proxy;
|
|
85
|
+
if (windows) {
|
|
86
|
+
try {
|
|
87
|
+
guard = await holdWindowsPrivatePath(endpoint.socketPath, { ...options.windowsPrivate, kind: 'socket' });
|
|
88
|
+
if (win32.toNamespacedPath(guard.path).toLowerCase() !== win32.toNamespacedPath(endpoint.socketPath).toLowerCase()) throw liveError('untrusted_native_socket');
|
|
89
|
+
if (guard.generation !== endpoint.generation) throw liveError('native_endpoint_changed');
|
|
90
|
+
} catch (error) { await guard?.release(); throw error.code === 'native_endpoint_changed' ? error : liveError('untrusted_native_socket'); }
|
|
91
|
+
} else {
|
|
92
|
+
const before = await inspectPosixSocket(endpoint.socketPath);
|
|
93
|
+
if (before.generation !== endpoint.generation) throw liveError('native_endpoint_changed');
|
|
94
|
+
}
|
|
95
|
+
let ws;
|
|
96
|
+
try {
|
|
97
|
+
ws = new WebSocket(windows ? 'ws://localhost/' : `ws+unix://${endpoint.socketPath}:/`, {
|
|
98
|
+
handshakeTimeout: 5000, maxPayload: 64 * 1024 * 1024, perMessageDeflate: false,
|
|
99
|
+
...(windows ? { createConnection: () => { proxy = createCodexWindowsProxy(endpoint, options); return proxy; } } : {}),
|
|
100
|
+
});
|
|
101
|
+
} catch { await guard?.release(); proxy?.destroy(); throw liveError('native_connection_failed'); }
|
|
102
|
+
const pending = new Map(), prefix = `ccdeck-live-${randomUUID()}-`;
|
|
103
|
+
let serial = 0, closing = false;
|
|
104
|
+
const rejectPending = () => {
|
|
105
|
+
for (const p of pending.values()) { clearTimeout(p.timer); p.reject(liveError('native_disconnected')); }
|
|
106
|
+
pending.clear();
|
|
107
|
+
};
|
|
108
|
+
ws.on('error', () => {});
|
|
109
|
+
ws.on('close', () => { rejectPending(); if (!closing) options.onClose?.(); });
|
|
110
|
+
const send = message => {
|
|
111
|
+
if (ws.readyState !== WebSocket.OPEN || ws.bufferedAmount > 1024 * 1024) throw liveError('native_disconnected');
|
|
112
|
+
ws.send(JSON.stringify(message));
|
|
113
|
+
};
|
|
114
|
+
ws.on('message', (raw, binary) => {
|
|
115
|
+
if (binary) { ws.close(1003); return; }
|
|
116
|
+
let m;
|
|
117
|
+
try { m = JSON.parse(raw.toString()); } catch { ws.close(1007); return; }
|
|
118
|
+
if (!m || typeof m !== 'object' || Array.isArray(m)) { ws.close(1007); return; }
|
|
119
|
+
const p = !m.method && pending.get(m.id);
|
|
120
|
+
if (p) {
|
|
121
|
+
pending.delete(m.id); clearTimeout(p.timer);
|
|
122
|
+
if (m.error) p.reject(rejection(p.method, m.error));
|
|
123
|
+
else p.resolve(m.result);
|
|
124
|
+
} else if (m.method && m.id !== undefined) {
|
|
125
|
+
// Unrelated approval/tool requests must remain with their own client.
|
|
126
|
+
Promise.resolve().then(() => options.onRequest?.(m)).catch(() => {});
|
|
127
|
+
} else if (m.method) options.onNotification?.(m);
|
|
128
|
+
});
|
|
129
|
+
const rpc = {
|
|
130
|
+
send,
|
|
131
|
+
request(method, params) {
|
|
132
|
+
if (pending.size >= 32) return Promise.reject(liveError('native_busy'));
|
|
133
|
+
const id = prefix + (++serial);
|
|
134
|
+
return new Promise((resolveCall, reject) => {
|
|
135
|
+
// The Windows raw proxy and a busy native daemon can exceed seven
|
|
136
|
+
// seconds even for a history read. Keep a bounded wait, without replay.
|
|
137
|
+
const timer = setTimeout(() => { pending.delete(id); reject(liveError('native_request_timeout')); }, options.deadlineMs ?? (windows ? 30000 : 7000));
|
|
138
|
+
pending.set(id, { method, resolve: resolveCall, reject, timer });
|
|
139
|
+
try { send({ id, method, ...(params === undefined ? {} : { params }) }); }
|
|
140
|
+
catch (e) { pending.delete(id); clearTimeout(timer); reject(e); }
|
|
141
|
+
});
|
|
142
|
+
},
|
|
143
|
+
close() { closing = true; rejectPending(); ws.close(); const timer = setTimeout(() => { ws.terminate(); proxy?.destroy(); }, 500); timer.unref(); },
|
|
144
|
+
};
|
|
145
|
+
try {
|
|
146
|
+
await new Promise((ready, reject) => { ws.once('open', ready); ws.once('error', () => reject(liveError('native_connection_failed'))); });
|
|
147
|
+
const after = windows ? await inspectWindowsPrivateSocket(endpoint.socketPath, options.windowsPrivate) : await inspectPosixSocket(endpoint.socketPath);
|
|
148
|
+
if (after.generation !== endpoint.generation) throw liveError('native_endpoint_changed');
|
|
149
|
+
if (guard && !guard.valid()) throw liveError('untrusted_native_socket');
|
|
150
|
+
await rpc.request('initialize', { clientInfo: { name: 'ccdeck', title: 'ccdeck', version: '3.53.1' }, capabilities: { experimentalApi: true } });
|
|
151
|
+
send({ method: 'initialized', params: {} });
|
|
152
|
+
return rpc;
|
|
153
|
+
} catch (error) { rpc.close(); throw error; }
|
|
154
|
+
finally { await guard?.release(); }
|
|
155
|
+
}
|
|
@@ -9,6 +9,7 @@ import { noteQuotaHistory, forgetQuotaHistoryAccount } from "./quota-history.mjs
|
|
|
9
9
|
// optional, unknown values pass through verbatim, and a `partial` flag tells
|
|
10
10
|
// the UI when something was dropped instead of silently showing less.
|
|
11
11
|
import { readFile } from "node:fs/promises";
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
12
13
|
// One clamp for both quota readers: see the note on cooldownFromHeader. From
|
|
13
14
|
// quota-oauth.mjs, which owns it, rather than through quota.mjs, which only
|
|
14
15
|
// re-exported it and brings the whole Claude quota chain with it.
|
|
@@ -20,6 +21,7 @@ import { usesNativeCodexAccount, decodeJwt, codexCredentialFingerprint, getCodex
|
|
|
20
21
|
import { PRODUCT } from "./brand.mjs";
|
|
21
22
|
import { resetLabel } from "./reset-label.mjs";
|
|
22
23
|
import { readNativeCodexAccount } from "./codex-native-account.mjs";
|
|
24
|
+
import { readLiveCodexCredential } from "./codex-live-credentials.mjs";
|
|
23
25
|
|
|
24
26
|
// Resolved by codex-dir.mjs rather than here. This file used to spell it
|
|
25
27
|
// `process.env.CODEX_HOME ?? join(homedir(), ".codex")`, which keeps an empty
|
|
@@ -229,6 +231,37 @@ async function fetchResetCredits(base, auth) {
|
|
|
229
231
|
} catch { return null; }
|
|
230
232
|
}
|
|
231
233
|
|
|
234
|
+
// Native account/rateLimits/read omits the saved reset grants. Read their
|
|
235
|
+
// inventory separately, using only a validated file-backed login from the same
|
|
236
|
+
// profile. Codex remains the credential owner; this path never renews or redeems.
|
|
237
|
+
const nativeResetCache = new Map();
|
|
238
|
+
const configFingerprint = async home => createHash('sha256').update(await readFile(join(home, 'config.toml')).catch(() => '')).digest('hex');
|
|
239
|
+
async function nativeResetCredits(selected, home, native, fingerprint, credentialRead) {
|
|
240
|
+
if (!fingerprint || !/^[a-f0-9]{20}$/.test(selected.profileId ?? '')
|
|
241
|
+
|| await codexCredentialFingerprint({ home }) !== fingerprint) return null;
|
|
242
|
+
const config = await configFingerprint(home);
|
|
243
|
+
const key = `${selected.profileId}:${native.identityVersion}:${fingerprint}:${config}`;
|
|
244
|
+
const now = Date.now(), held = nativeResetCache.get(key);
|
|
245
|
+
if (held && now - held.at < CACHE_MS) return held.promise;
|
|
246
|
+
if (native.stale) return null;
|
|
247
|
+
if (nativeResetCache.size >= MAX_SELECTED_READERS) nativeResetCache.delete(nativeResetCache.keys().next().value);
|
|
248
|
+
const promise = (async () => {
|
|
249
|
+
try {
|
|
250
|
+
if (await codexCredentialFingerprint({ home }) !== fingerprint) return null;
|
|
251
|
+
const auth = await credentialRead(selected.profileId, { refresh: false });
|
|
252
|
+
const suffix = auth.accountId ? ` · ${createHash('sha256').update(auth.accountId).digest('hex').slice(0, 8)}` : '';
|
|
253
|
+
if (auth.profileId !== selected.profileId || ![auth.email, auth.email + suffix].includes(native.label)
|
|
254
|
+
|| auth.expiresAt <= Date.now() || await codexCredentialFingerprint({ home }) !== fingerprint) return null;
|
|
255
|
+
const base = await readBaseUrl(home);
|
|
256
|
+
if (!isCredentialHost(base)) return null;
|
|
257
|
+
const credits = await fetchResetCredits(base, auth);
|
|
258
|
+
return await codexCredentialFingerprint({ home }) === fingerprint && await configFingerprint(home) === config ? credits : null;
|
|
259
|
+
} catch { return null; }
|
|
260
|
+
})();
|
|
261
|
+
nativeResetCache.set(key, { at: now, promise });
|
|
262
|
+
return promise;
|
|
263
|
+
}
|
|
264
|
+
|
|
232
265
|
async function requestUsage(base, auth) {
|
|
233
266
|
return fetch(base + usagePath(base), {
|
|
234
267
|
headers: authHeaders(auth),
|
|
@@ -591,7 +624,7 @@ function selectedReader(selection) {
|
|
|
591
624
|
}
|
|
592
625
|
|
|
593
626
|
/** Capture the selected target once; reject a completion from any old revision. */
|
|
594
|
-
export async function fetchCodexQuota({ force = false, readSelection: read = readCodexSelection, enableNative = false, nativeRead = readNativeCodexAccount } = {}) {
|
|
627
|
+
export async function fetchCodexQuota({ force = false, readSelection: read = readCodexSelection, enableNative = false, nativeRead = readNativeCodexAccount, credentialRead = readLiveCodexCredential } = {}) {
|
|
595
628
|
let selected;
|
|
596
629
|
try { selected = await read(); }
|
|
597
630
|
catch { return { ok: false, reason: "selection_unavailable" }; }
|
|
@@ -609,7 +642,7 @@ export async function fetchCodexQuota({ force = false, readSelection: read = rea
|
|
|
609
642
|
try { result = authoritative ? { ok: false, reason: "no_token" } : await (entry?.reader ?? legacyReader).fetch({ force }); }
|
|
610
643
|
finally { if (entry) entry.active--; }
|
|
611
644
|
if (enableNative && result.reason === "no_token") {
|
|
612
|
-
const fingerprint =
|
|
645
|
+
const fingerprint = await codexCredentialFingerprint({ home });
|
|
613
646
|
const native = await nativeRead(home, { includeQuota: true, force: true });
|
|
614
647
|
if (!authoritative && await codexCredentialFingerprint({ home }) !== fingerprint) {
|
|
615
648
|
return { ok: false, reason: 'profile_changed' };
|
|
@@ -621,6 +654,7 @@ export async function fetchCodexQuota({ force = false, readSelection: read = rea
|
|
|
621
654
|
result = { ok: true, windows, extraWindows: [], plan: native.plan, planLabel: planLabel(native.plan),
|
|
622
655
|
email: native.label, partial: true, coverage: "standard_limits", refreshed: false, fetchedAt: native.fetchedAt,
|
|
623
656
|
...(native.stale ? { stale: true } : {}) };
|
|
657
|
+
result.resetCredits = await nativeResetCredits(selected, home, native, fingerprint, credentialRead);
|
|
624
658
|
_accountOfQuota.set(result, { accountId: `profile:${selected.profileId}`, profileId: selected.profileId, email: native.label });
|
|
625
659
|
} else result = { ok: false, reason: native.reason ?? (native.plan === 'api' ? 'api_key_mode' : 'no_token'), fetchedAt: native.fetchedAt,
|
|
626
660
|
...(native.stale ? { stale: true } : {}) };
|