ccdeck 3.53.2 → 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.
Files changed (62) hide show
  1. package/README.md +56 -4
  2. package/THIRD_PARTY_NOTICES.md +31 -1
  3. package/dist/web/assets/{BrowserWatchModal-DedhCY8E.js → BrowserWatchModal-Bfvo_8H6.js} +1 -1
  4. package/dist/web/assets/{IntegrationModal-1m1mQQhW.js → IntegrationModal-GS5jIQ_J.js} +1 -1
  5. package/dist/web/assets/{RadioPanel-Sgo5WNTi.js → RadioPanel-Bxd2ElWb.js} +1 -1
  6. package/dist/web/assets/{TrafficRadar-BqjzLlO_.js → TrafficRadar-FgHBI2Oh.js} +1 -1
  7. package/dist/web/assets/{UsageHistoryModal-2pcftBwX.js → UsageHistoryModal-APwKtE2J.js} +1 -1
  8. package/dist/web/assets/{app-BZaB84m4.js → app-BzHVsgB2.js} +90 -90
  9. package/dist/web/assets/{index-D1WZBFCw.js → index-7whwMaPX.js} +1 -1
  10. package/dist/web/index.html +2 -2
  11. package/node_modules/ws/LICENSE +20 -0
  12. package/node_modules/ws/README.md +540 -0
  13. package/node_modules/ws/browser.js +8 -0
  14. package/node_modules/ws/index.js +22 -0
  15. package/node_modules/ws/lib/buffer-util.js +142 -0
  16. package/node_modules/ws/lib/constants.js +19 -0
  17. package/node_modules/ws/lib/event-target.js +292 -0
  18. package/node_modules/ws/lib/extension.js +203 -0
  19. package/node_modules/ws/lib/limiter.js +55 -0
  20. package/node_modules/ws/lib/permessage-deflate.js +530 -0
  21. package/node_modules/ws/lib/receiver.js +743 -0
  22. package/node_modules/ws/lib/sender.js +610 -0
  23. package/node_modules/ws/lib/stream.js +161 -0
  24. package/node_modules/ws/lib/subprotocol.js +62 -0
  25. package/node_modules/ws/lib/validation.js +152 -0
  26. package/node_modules/ws/lib/websocket-server.js +562 -0
  27. package/node_modules/ws/lib/websocket.js +1426 -0
  28. package/node_modules/ws/package.json +74 -0
  29. package/node_modules/ws/wrapper.mjs +21 -0
  30. package/package.json +5 -3
  31. package/release-notes.json +39 -1
  32. package/src/server/account-engine.mjs +87 -0
  33. package/src/server/account-routes.mjs +31 -3
  34. package/src/server/codex-auto.mjs +7 -18
  35. package/src/server/codex-engine-adapter.mjs +272 -0
  36. package/src/server/codex-engine-bridge.mjs +47 -0
  37. package/src/server/codex-engine-config.mjs +42 -0
  38. package/src/server/codex-engine-rpc.mjs +88 -0
  39. package/src/server/codex-handoff.mjs +20 -0
  40. package/src/server/codex-interactive-engine.mjs +335 -0
  41. package/src/server/codex-live-checkpoint.mjs +55 -0
  42. package/src/server/codex-live-credentials.mjs +214 -0
  43. package/src/server/codex-live-engine.mjs +577 -0
  44. package/src/server/codex-live-handoff.mjs +300 -0
  45. package/src/server/codex-live-lease.mjs +64 -0
  46. package/src/server/codex-live-rpc.mjs +155 -0
  47. package/src/server/codex-quota.mjs +36 -2
  48. package/src/server/codex-selection.mjs +62 -8
  49. package/src/server/codex-share.mjs +193 -0
  50. package/src/server/codex-terminal-runner.mjs +38 -1
  51. package/src/server/codex-terminal.mjs +15 -3
  52. package/src/server/codex-watch.mjs +3 -1
  53. package/src/server/codex-windows-private.mjs +96 -0
  54. package/src/server/codex-windows-private.ps1 +140 -0
  55. package/src/server/codex-windows-proxy.mjs +53 -0
  56. package/src/server/deck-prefs.mjs +6 -1
  57. package/src/server/index.mjs +9 -2
  58. package/src/server/login-service.mjs +2 -0
  59. package/src/server/pinned-build.mjs +2 -0
  60. package/src/server/reports-routes.mjs +10 -0
  61. package/src/server/reports.mjs +46 -5
  62. package/src/server/ui-language.mjs +17 -0
@@ -0,0 +1,577 @@
1
+ // The shared daemon retains its threads. Active responses use a controlled
2
+ // interrupt/login/continue handoff so auth cannot revoke an in-flight stream.
3
+ import { readFile, mkdir, chmod } from 'node:fs/promises';
4
+ import { join, resolve } from 'node:path';
5
+ import { createHash } from 'node:crypto';
6
+ import { deckDataDir } from './deck-home.mjs';
7
+ import { writeFileAtomic } from './atomic-write.mjs';
8
+ import { readCodexSelection } from './codex-selection.mjs';
9
+ import { readCodexAuto } from './codex-auto.mjs';
10
+ import { resolveCodexLiveEndpoint, connectCodexLiveRpc, liveError } from './codex-live-rpc.mjs';
11
+ import { acquireCodexLiveLease } from './codex-live-lease.mjs';
12
+ import { readLiveCodexCredential } from './codex-live-credentials.mjs';
13
+ import { prepareCodexLiveHandoff, assertCodexLiveQuiet, continueCodexLiveHandoff, confirmCodexLiveChildren, readCodexLiveTurn, retainCodexLiveHandoff } from './codex-live-handoff.mjs';
14
+ import { requestCodexLiveCheckpoints, inspectCodexLiveCheckpoints } from './codex-live-checkpoint.mjs';
15
+
16
+ const idPattern = /^[a-f0-9]{20}$/;
17
+ const publicReason = e => /^[a-z_]{1,64}$/.test(e?.code ?? '') ? e.code : 'live_switch_failed';
18
+ // 0.166's Account has no workspace ID. Its experimental response may expose
19
+ // workspaceRouting.chatgptAccountId; honor account-level IDs too if supplied.
20
+ // Labels are display data and never attest workspace equality across a gap.
21
+ const accountIds = snapshot => [snapshot?.account?.accountId, snapshot?.account?.id,
22
+ snapshot?.workspaceRouting?.chatgptAccountId].filter(id => id != null);
23
+ const sameAccount = (snapshot, credential, attest = false) => snapshot?.account?.type === 'chatgpt'
24
+ && typeof snapshot.account.email === 'string' && snapshot.account.email.toLowerCase() === credential.email.toLowerCase()
25
+ && (!attest || accountIds(snapshot).length > 0)
26
+ && accountIds(snapshot).every(id => typeof id === 'string' && id === credential.accountId);
27
+ const sameNativeAccount = (a, b) => a?.account?.type === b?.account?.type
28
+ && a?.account?.email === b?.account?.email && a?.account?.workspaceName === b?.account?.workspaceName
29
+ && accountIds(a).length === accountIds(b).length
30
+ && accountIds(a).every((id, i) => id === accountIds(b)[i]);
31
+ const endpointKey = endpoint => createHash('sha256').update(endpoint.generation).digest('hex');
32
+
33
+ export function createCodexLiveAccountController(input = {}) {
34
+ const options = { ...input, env: { ...(input.env ?? process.env) } };
35
+ const store = resolve(options.store ?? deckDataDir(undefined, options.env));
36
+ const metadata = join(store, 'codex-live-account.json');
37
+ const selection = options.readSelection ?? (() => readCodexSelection({ ...options, store }));
38
+ const credentialFor = options.readCredential ?? ((id, extra) => readLiveCodexCredential(id, { ...options, ...extra, store }));
39
+ const resolveEndpoint = options.resolveEndpoint ?? (home => resolveCodexLiveEndpoint(home, options));
40
+ const connect = options.connectRpc ?? ((ep, callbacks) => connectCodexLiveRpc(ep, callbacks));
41
+ let state = { state: 'idle', profileId: null, requestedProfileId: null, reason: null, continuation: 'none' };
42
+ let rpc = null, endpoint = null, lease = null, credential = null, desired = null, appliedIntent = null;
43
+ let owned = false, closed = false, ticking = false;
44
+ let ownershipEpoch = 0, connectionSerial = 0, ownershipPaused = false, pendingLogin = null;
45
+ let lastManual = 0, lastSelected = null, lastCheck = 0, lastRefresh = 0;
46
+ let chain = Promise.resolve(), pendingKey = '', pendingSwitch = null;
47
+ let restorePending = null, restoreRetryAt = 0;
48
+ let deferred = null;
49
+ let childContinuation = null;
50
+ let checkpointWork = null;
51
+ let releaseSubscriptions = null;
52
+ let recoveryNeeded = false;
53
+ let recoveryJournal = null;
54
+ const defer = (intent, refresh, automatic) => {
55
+ if (!refresh || !deferred || deferred.refresh) deferred = { intent: { ...intent }, refresh, automatic };
56
+ };
57
+ const status = () => ({ ...state, scope: 'shared_native_server' });
58
+ const update = patch => { state = { ...state, ...patch }; options.onState?.(status()); };
59
+ const enqueue = fn => { const next = chain.then(fn, fn); chain = next.catch(() => {}); return next; };
60
+ const save = async () => {
61
+ if (!endpoint || !desired) return;
62
+ const data = { version: 1, wasControlling: owned, profileId: credential?.profileId ?? null,
63
+ revision: appliedIntent?.revision ?? desired.revision, endpoint: endpointKey(endpoint) };
64
+ if (options.persistState) return options.persistState(data);
65
+ await mkdir(store, { recursive: true, mode: 0o700 });
66
+ await writeFileAtomic(metadata, JSON.stringify(data) + '\n'); await chmod(metadata, 0o600);
67
+ };
68
+ const saveHandoff = async data => {
69
+ if (options.persistHandoff) return options.persistHandoff(data);
70
+ await mkdir(store, { recursive: true, mode: 0o700 });
71
+ const file = join(store, 'codex-live-handoff.json');
72
+ await writeFileAtomic(file, JSON.stringify(data) + '\n'); await chmod(file, 0o600);
73
+ };
74
+ async function releaseHandoff() {
75
+ const release = releaseSubscriptions; releaseSubscriptions = null; await release?.();
76
+ }
77
+ async function disconnect() {
78
+ await releaseHandoff();
79
+ connectionSerial++; rpc?.close(); rpc = null; await lease?.release(); lease = null;
80
+ }
81
+ async function verifyAccount() {
82
+ if (!owned || !rpc || !credential || closed) return;
83
+ const actual = await rpc.request('account/read', { refreshToken: false });
84
+ if (!sameAccount(actual, credential)) await externalChange();
85
+ }
86
+ async function externalChange(reason = 'account_changed_outside_deck') {
87
+ if (closed) return;
88
+ ownershipPaused = true;
89
+ owned = false; credential = null; deferred = null;
90
+ update({ state: 'external_change', profileId: null, reason,
91
+ ...(childContinuation || checkpointWork ? { continuation: 'manual_required' } : {}) });
92
+ if (childContinuation || checkpointWork) {
93
+ recoveryNeeded = true; recoveryJournal = childContinuation?.journal ?? checkpointWork?.journal;
94
+ }
95
+ childContinuation = null;
96
+ checkpointWork = null;
97
+ await save().catch(() => {});
98
+ await disconnect();
99
+ }
100
+ function invalidateOwnership(reason = 'account_changed_outside_deck') {
101
+ // Invalidate synchronously: queued cleanup cannot authorize an in-flight
102
+ // credential read, checkpoint, login or continuation to finish first.
103
+ ownershipEpoch++; ownershipPaused = true; deferred = null;
104
+ pendingLogin?.reject(liveError(reason));
105
+ void enqueue(() => externalChange(reason)).catch(() => {});
106
+ }
107
+ function accountNotification(message) {
108
+ const login = pendingLogin;
109
+ if (login && !login.acknowledged && ['account/login/completed', 'account/updated'].includes(message.method)) {
110
+ invalidateOwnership(); return;
111
+ }
112
+ if (message.method === 'account/login/completed') {
113
+ if (login && !login.completed && message.params?.loginId === null && message.params?.success === true) login.completed = true;
114
+ else if (login) invalidateOwnership();
115
+ } else if (message.method === 'account/updated') {
116
+ // Native external-token login sends its RPC result, then login/completed,
117
+ // then updated (account_processor.rs, rust-v0.166.0). Consume only that
118
+ // one ordered pair. An in-flight operation alone cannot identify its update.
119
+ if (login && login.completed && !login.updated && message.params?.authMode === 'chatgptAuthTokens'
120
+ && (login.planType == null || message.params?.planType === login.planType)) {
121
+ login.updated = true; login.resolve();
122
+ } else invalidateOwnership();
123
+ }
124
+ }
125
+ function expectLoginNotifications(next) {
126
+ let resolve, reject;
127
+ const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
128
+ promise.catch(() => {}); // A rejected login RPC may end before this waiter.
129
+ const timer = setTimeout(() => reject(liveError('native_login_unconfirmed')),
130
+ options.loginNotificationTimeoutMs ?? 30_000);
131
+ const login = { planType: next.planType, acknowledged: false, completed: false, updated: false, promise, resolve, reject,
132
+ close() { clearTimeout(timer); if (pendingLogin === login) pendingLogin = null; } };
133
+ pendingLogin = login;
134
+ return login;
135
+ }
136
+ async function serverRequest(message) {
137
+ if (message.method !== 'account/chatgptAuthTokens/refresh' || !owned || !credential || closed || ownershipPaused) return;
138
+ const owner = rpc, previous = credential.accountId, epoch = ownershipEpoch;
139
+ if (message.params?.previousAccountId && message.params.previousAccountId !== previous) return;
140
+ // Refreshes and logins share one queue. No asynchronous refresh of A may
141
+ // supply A's credentials after a queued selection has committed B.
142
+ return enqueue(async () => {
143
+ if (owner !== rpc || !owned || closed || ownershipPaused || epoch !== ownershipEpoch) return;
144
+ if (credential.accountId !== previous) {
145
+ owner.send({ id: message.id, error: { code: -32000, message: 'Codex account changed during renewal.' } });
146
+ return;
147
+ }
148
+ try {
149
+ const next = await credentialFor(credential.profileId, { refresh: true });
150
+ if (closed || owner !== rpc || !owned || ownershipPaused || epoch !== ownershipEpoch) return;
151
+ if (next.accountId !== previous) throw liveError('profile_changed');
152
+ const actual = await owner.request('account/read', { refreshToken: false });
153
+ if (closed || owner !== rpc || ownershipPaused || epoch !== ownershipEpoch) return;
154
+ if (!sameAccount(actual, next)) { await externalChange(); return; }
155
+ // ExternalAuthBridge::refresh returns the auth directly; it does not
156
+ // emit account/updated. Do not leave a notification-suppression window.
157
+ credential = next; lastRefresh = Date.now();
158
+ owner.send({ id: message.id, result: { accessToken: next.accessToken, chatgptAccountId: next.accountId, chatgptPlanType: next.planType } });
159
+ } catch {
160
+ // Never return paths, token values or provider error text on the wire.
161
+ try { owner.send({ id: message.id, error: { code: -32000, message: 'Selected Codex login could not be renewed.' } }); } catch { /* connection ended */ }
162
+ update({ state: 'failed', reason: 'credential_refresh_failed' });
163
+ }
164
+ });
165
+ }
166
+ async function ensureRpc(originalHome) {
167
+ if (rpc) return;
168
+ const next = await resolveEndpoint(originalHome);
169
+ if (!lease) lease = await (options.acquireLease ?? acquireCodexLiveLease)(next.home, options);
170
+ if (!await lease.valid()) throw liveError('native_control_lost');
171
+ endpoint = next;
172
+ const serial = ++connectionSerial;
173
+ rpc = await connect(next, {
174
+ onRequest: m => serial === connectionSerial ? serverRequest(m) : undefined,
175
+ onNotification: m => {
176
+ const observe = () => { if (!closed && serial === connectionSerial) accountNotification(m); };
177
+ // A WebSocket read can contain the result and both notifications. Let
178
+ // its already-resolved RPC continuation mark the acknowledgement first,
179
+ // preserving wire order without accepting notifications before a result.
180
+ if (pendingLogin) queueMicrotask(observe); else observe();
181
+ },
182
+ onClose: () => {
183
+ if (serial !== connectionSerial) return;
184
+ ownershipEpoch++; pendingLogin?.reject(liveError('native_disconnected'));
185
+ rpc = null; if (!closed && owned) update({ state: 'disconnected', reason: 'native_disconnected' });
186
+ },
187
+ });
188
+ const account = await rpc.request('account/read', { refreshToken: false });
189
+ if (account.account && account.account.type !== 'chatgpt') { rpc.close(); rpc = null; owned = false; throw liveError('unsupported_auth_mode'); }
190
+ }
191
+ async function loginCredential(id, refresh = false) {
192
+ let next;
193
+ try { next = await credentialFor(id, { refresh }); }
194
+ catch (error) {
195
+ if (refresh || error?.code !== 'credential_expired') throw error;
196
+ next = await credentialFor(id, { refresh: true }); refresh = true;
197
+ }
198
+ // Renew before submitting; a callback cannot wait on its own login queue.
199
+ if (next.expiresAt - Date.now() < 60_000 && !refresh) next = await credentialFor(id, { refresh: true });
200
+ if (next.expiresAt - Date.now() < 60_000) throw liveError('credential_expiring');
201
+ if (next.profileId !== id) throw liveError('profile_changed');
202
+ return next;
203
+ }
204
+ async function applyCore(intent, refresh = false, automatic = false, checkpoint = null) {
205
+ const epoch = ownershipEpoch;
206
+ const currentIntent = () => refresh ? appliedIntent : desired;
207
+ if (closed || ownershipPaused || currentIntent()?.revision !== intent.revision || currentIntent().id !== intent.id) return status();
208
+ if (recoveryNeeded) {
209
+ update({ state: 'failed', requestedProfileId: intent.id, continuation: 'manual_required', reason: 'native_continue_unconfirmed' }); return status();
210
+ }
211
+ if (childContinuation || checkpointWork) {
212
+ defer(intent, refresh, automatic);
213
+ update({ state: 'waiting', requestedProfileId: intent.id,
214
+ reason: childContinuation?.expired ? 'native_continue_unconfirmed' : 'native_tools_active',
215
+ continuation: childContinuation?.expired ? 'manual_required' : 'waiting' }); return status();
216
+ }
217
+ if (automatic && !(await (options.readAuto ?? (() => readCodexAuto({ ...options, store })))()).enabled) {
218
+ update({ state: owned ? 'applied' : 'idle', reason: 'auto_switch_disabled', continuation: 'none' }); return status();
219
+ }
220
+ update({ state: 'switching', requestedProfileId: intent.id, reason: null, continuation: 'none' });
221
+ let maybeApplied = false, handoff = null, resumeIdentity = null;
222
+ const journal = checkpoint?.journal ?? { version: 1, phase: 'paused', profileId: intent.id, revision: intent.revision, entries: [] };
223
+ const record = async (entry, phase, turnId) => {
224
+ if (!journal.entries.some(e => e.messageId === entry.messageId)) journal.entries.push(entry);
225
+ Object.assign(entry, { phase, ...(turnId ? { continuedTurnId: turnId } : {}) });
226
+ journal.phase = journal.entries.every(e => ['continued', 'skipped'].includes(e.phase)) ? 'finished' : 'pending';
227
+ await saveHandoff(journal);
228
+ };
229
+ const authCurrent = () => !closed && !ownershipPaused && epoch === ownershipEpoch;
230
+ const owner = () => authCurrent() && currentIntent()?.revision === intent.revision && currentIntent()?.id === intent.id;
231
+ const verifyOwnership = async () => {
232
+ if (!await lease?.valid()) throw liveError('native_control_lost');
233
+ const actual = await rpc.request('account/read', { refreshToken: false });
234
+ if (!authCurrent() || !sameNativeAccount(actual, resumeIdentity)) throw liveError('account_changed_outside_deck');
235
+ };
236
+ const resume = async () => continueCodexLiveHandoff(rpc, handoff, {
237
+ isCurrent: () => authCurrent() && !!rpc,
238
+ beforeSend: async entry => {
239
+ if (!await lease?.valid()) throw liveError('native_control_lost');
240
+ const actual = await rpc.request('account/read', { refreshToken: false });
241
+ if (!authCurrent() || !sameNativeAccount(actual, resumeIdentity)) throw liveError('account_changed_outside_deck');
242
+ await record(entry, 'sent');
243
+ if (!authCurrent()) throw liveError('account_changed_outside_deck');
244
+ },
245
+ afterSend: (entry, turnId) => record(entry, 'continued', turnId),
246
+ onSkip: entry => record(entry, 'skipped'),
247
+ onDelegate: entry => record(entry, 'delegated'),
248
+ });
249
+ try {
250
+ const s = await selection();
251
+ if (!s.profiles?.some(p => p.id === intent.id && p.available !== false)) throw liveError('profile_unavailable');
252
+ await ensureRpc(s.originalHome);
253
+ const next = await loginCredential(intent.id, refresh);
254
+ if (!owner()) throw liveError('account_changed_outside_deck');
255
+ if (!await lease.valid()) throw liveError('native_control_lost');
256
+ const before = await rpc.request('account/read', { refreshToken: false });
257
+ resumeIdentity = before;
258
+ handoff = await prepareCodexLiveHandoff(rpc, { isCurrent: owner,
259
+ beforeInterrupt: async entry => {
260
+ await record(entry, 'interrupt_sent');
261
+ if (!owner()) throw liveError('account_changed_outside_deck');
262
+ }, afterInterrupt: (entry, phase) => record(entry, phase) });
263
+ if (handoff.checkpoint) {
264
+ if (checkpoint) handoff.checkpoint.unshift(...checkpoint.handoff.paused);
265
+ const previousRelease = releaseSubscriptions;
266
+ const release = await retainCodexLiveHandoff(rpc, handoff.checkpoint);
267
+ releaseSubscriptions = async () => { await release(); await previousRelease?.(); };
268
+ checkpointWork = { rpc, entries: handoff.checkpoint, intent: { ...intent }, refresh, automatic, journal, record,
269
+ identity: resumeIdentity, deadline: Date.now() + (options.checkpointTimeoutMs ?? 120_000), current: owner };
270
+ try { await requestCodexLiveCheckpoints(rpc, handoff.checkpoint, { record, beforeSend: verifyOwnership }); }
271
+ catch (error) { checkpointWork = null; recoveryNeeded = true; recoveryJournal = journal; throw error; }
272
+ update({ state: 'waiting', reason: 'native_tools_active', continuation: 'waiting' }); return status();
273
+ }
274
+ if (handoff.waiting) {
275
+ if (checkpoint) {
276
+ checkpointWork = checkpoint.work;
277
+ update({ state: 'waiting', reason: 'native_tools_active', continuation: 'waiting' }); return status();
278
+ }
279
+ defer(intent, refresh, automatic);
280
+ update({ state: 'waiting', reason: 'native_tools_active', continuation: 'waiting' }); return status();
281
+ }
282
+ if (checkpoint) handoff.paused.push(...checkpoint.handoff.paused);
283
+ deferred = null;
284
+ if (!owner()) throw liveError('native_switch_superseded');
285
+ await assertCodexLiveQuiet(rpc);
286
+ const current = await rpc.request('account/read', { refreshToken: false });
287
+ if (!owner() || !sameNativeAccount(current, before)) throw liveError('account_changed_outside_deck');
288
+ if (!await lease.valid()) throw liveError('native_control_lost');
289
+ // Authentication crosses only this owner-validated local socket. Codex
290
+ // stores external tokens in memory, not either profile's credential file.
291
+ maybeApplied = true;
292
+ const login = expectLoginNotifications(next);
293
+ let account;
294
+ try {
295
+ const result = await rpc.request('account/login/start', { type: 'chatgptAuthTokens', accessToken: next.accessToken,
296
+ chatgptAccountId: next.accountId, chatgptPlanType: next.planType });
297
+ if (result?.type !== 'chatgptAuthTokens') throw liveError('unsupported_protocol');
298
+ login.acknowledged = true;
299
+ await login.promise;
300
+ account = await rpc.request('account/read', { refreshToken: false });
301
+ if (!authCurrent()) throw liveError('account_changed_outside_deck');
302
+ if (!sameAccount(account, next)) throw liveError('native_identity_mismatch');
303
+ } finally { login.close(); }
304
+ credential = next; appliedIntent = { ...intent }; owned = true; lastRefresh = Date.now(); lastCheck = Date.now();
305
+ resumeIdentity = account;
306
+ update({ state: 'applied', profileId: intent.id, requestedProfileId: intent.id, reason: null });
307
+ // The daemon has acknowledged this login. Keep renewal ownership even
308
+ // if local metadata cannot be saved; losing it would strand live auth.
309
+ await save().catch(() => update({ reason: 'ownership_not_saved' }));
310
+ if (handoff.paused.length) {
311
+ try {
312
+ const result = await resume();
313
+ if (result.delegated?.length) {
314
+ childContinuation = { rpc, entries: result.delegated, deadline: Date.now() + (options.delegationTimeoutMs ?? 60_000),
315
+ record, journal, identity: resumeIdentity };
316
+ }
317
+ update({ continuation: result.delegated?.length ? 'waiting' : result.resumed ? 'automatic' : 'none' });
318
+ }
319
+ catch { update({ reason: 'native_continue_unconfirmed', continuation: 'manual_required' }); }
320
+ }
321
+ } catch (error) {
322
+ handoff ??= error.handoff;
323
+ const lostControl = ['native_control_lost', 'account_changed_outside_deck', 'native_disconnected'].includes(error.code);
324
+ if (!maybeApplied && !lostControl && handoff?.paused?.length && rpc && !closed) {
325
+ try { await resume(); } catch { update({ continuation: 'manual_required' }); }
326
+ }
327
+ if (handoff?.paused?.length && (maybeApplied || lostControl)) update({ continuation: 'manual_required' });
328
+ if (journal.entries.length && journal.phase !== 'finished') update({ continuation: 'manual_required' });
329
+ if (maybeApplied) { credential = null; owned = false; }
330
+ const reason = publicReason(error);
331
+ update({ state: ['native_not_running', 'cli_unavailable'].includes(reason) ? 'unavailable' : 'failed',
332
+ ...(maybeApplied ? { profileId: null } : {}), reason });
333
+ if (!owned) await disconnect();
334
+ } finally {
335
+ if (journal.entries.length && journal.phase !== 'finished' && !childContinuation && !checkpointWork) {
336
+ recoveryNeeded = true; recoveryJournal = journal;
337
+ update({ continuation: 'manual_required', reason: 'native_continue_unconfirmed' });
338
+ }
339
+ }
340
+ return status();
341
+ }
342
+ async function apply(intent, refresh = false, automatic = false, checkpoint = null) {
343
+ try { await applyCore(intent, refresh, automatic, checkpoint); }
344
+ finally {
345
+ // A checkpoint is already real work, even if admission exits early (for
346
+ // example Auto-switch was disabled). Never drop its recovery protection.
347
+ if (checkpoint?.journal.entries.length && checkpoint.journal.phase !== 'finished' && !checkpointWork && !childContinuation) {
348
+ recoveryNeeded = true; recoveryJournal = checkpoint.journal;
349
+ update({ continuation: 'manual_required', reason: 'native_continue_unconfirmed' });
350
+ }
351
+ if (!checkpointWork && !childContinuation) await releaseHandoff();
352
+ }
353
+ return status();
354
+ }
355
+ async function request(intent, automatic = false) {
356
+ await ready;
357
+ if (closed || automatic && ownershipPaused) return status();
358
+ if (!idPattern.test(intent?.id ?? '') || !Number.isSafeInteger(intent.revision) || intent.revision < 1) throw liveError('invalid_selection');
359
+ const key = `${intent.revision}:${intent.id}`;
360
+ if (pendingKey === key && pendingSwitch) return pendingSwitch;
361
+ if (desired && intent.revision < desired.revision) return status();
362
+ restorePending = null;
363
+ deferred = null;
364
+ desired = { id: intent.id, revision: intent.revision };
365
+ pendingKey = key;
366
+ const epoch = ownershipEpoch;
367
+ pendingSwitch = enqueue(() => {
368
+ if (!automatic && epoch === ownershipEpoch) ownershipPaused = false;
369
+ return apply(intent, false, automatic);
370
+ });
371
+ return pendingSwitch;
372
+ }
373
+ async function restorePrevious(saved, intent, actual) {
374
+ restorePending = null;
375
+ const epoch = ownershipEpoch;
376
+ const previous = await loginCredential(saved.profileId);
377
+ if (ownershipPaused || epoch !== ownershipEpoch) { await externalChange(); return; }
378
+ if (endpointKey(endpoint) === saved.endpoint && sameAccount(actual, previous, true)) {
379
+ credential = previous; appliedIntent = { id: saved.profileId, revision: saved.revision }; owned = true;
380
+ lastCheck = Date.now(); lastRefresh = Date.now();
381
+ update({ state: 'failed', profileId: saved.profileId, requestedProfileId: intent.id, reason: 'native_login_unconfirmed' });
382
+ } else {
383
+ await externalChange();
384
+ }
385
+ }
386
+ async function restore(saved) {
387
+ const epoch = ownershipEpoch;
388
+ if (closed || restorePending !== saved) return;
389
+ try {
390
+ const s = await selection();
391
+ if (saved?.version !== 1 || saved.wasControlling !== true || !idPattern.test(saved.profileId ?? '')
392
+ || !Number.isSafeInteger(saved.revision) || saved.revision < 1 || saved.revision > s.revision
393
+ || !s.profiles?.some(p => p.id === saved.profileId && p.available !== false)) {
394
+ restorePending = null; return;
395
+ }
396
+ let intent = { id: saved.profileId, revision: saved.revision };
397
+ if (s.runningSelection?.revision > intent.revision) intent = { ...s.runningSelection };
398
+ if (s.profileId !== intent.id && s.revision > intent.revision) {
399
+ const auto = await (options.readAuto ?? (() => readCodexAuto({ ...options, store })))();
400
+ if (auto.enabled) intent = { id: s.profileId, revision: s.revision };
401
+ }
402
+ if (closed || restorePending !== saved) return;
403
+ desired = intent;
404
+ await ensureRpc(s.originalHome);
405
+ const actual = await rpc.request('account/read', { refreshToken: false });
406
+ if (!accountIds(actual).length) {
407
+ restorePending = null; await externalChange('native_identity_unattested'); return;
408
+ }
409
+ let next;
410
+ try { next = await loginCredential(intent.id); }
411
+ catch (error) {
412
+ if (intent.revision <= saved.revision) throw error;
413
+ await restorePrevious(saved, intent, actual); return;
414
+ }
415
+ if (closed || restorePending !== saved) return;
416
+ if (ownershipPaused || epoch !== ownershipEpoch) { restorePending = null; await externalChange(); return; }
417
+ if (intent.revision > saved.revision && !sameAccount(actual, next, true)) {
418
+ // The newer request has no persisted acknowledgement. It may have
419
+ // timed out after sending: reconcile it, never replay it on restart.
420
+ await restorePrevious(saved, intent, actual); return;
421
+ }
422
+ if (intent.revision === saved.revision && endpointKey(endpoint) === saved.endpoint && !sameAccount(actual, next, true)) {
423
+ restorePending = null; await externalChange(); return;
424
+ }
425
+ if (sameAccount(actual, next, true) && (endpointKey(endpoint) === saved.endpoint || intent.revision > saved.revision)) {
426
+ // Adopt the surviving login without another account-change notification.
427
+ credential = next; appliedIntent = { ...intent }; owned = true;
428
+ lastCheck = Date.now(); lastRefresh = Date.now();
429
+ update({ state: 'applied', profileId: intent.id, requestedProfileId: intent.id, reason: null });
430
+ if (recoveryNeeded) update({ reason: 'native_continue_unconfirmed', continuation: 'manual_required' });
431
+ await save().catch(() => update({ reason: 'ownership_not_saved' }));
432
+ restorePending = null; return;
433
+ }
434
+ // Only discovery is retried. An ambiguous native login must not replay.
435
+ restorePending = null; await externalChange();
436
+ } catch (error) {
437
+ if (!owned) await disconnect();
438
+ const reason = publicReason(error);
439
+ const retry = ['native_not_running', 'cli_unavailable', 'native_unavailable', 'native_connection_failed', 'native_disconnected', 'native_control_busy'].includes(reason);
440
+ update({ state: retry ? 'unavailable' : 'failed', reason });
441
+ if (!retry) restorePending = null;
442
+ restoreRetryAt = Date.now() + (options.restoreRetryMs ?? 5000);
443
+ }
444
+ }
445
+ const ready = (async () => {
446
+ try {
447
+ const savedHandoff = options.loadHandoff ? await options.loadHandoff() : await readFile(join(store, 'codex-live-handoff.json'), 'utf8').then(JSON.parse).catch(() => null);
448
+ recoveryNeeded = savedHandoff?.version === 1 && savedHandoff.phase !== 'finished' && savedHandoff.entries?.some(e => !['continued', 'skipped'].includes(e.phase)) === true;
449
+ if (recoveryNeeded) recoveryJournal = savedHandoff;
450
+ const s = await selection(); lastManual = s.runningSelection?.revision ?? 0; lastSelected = s.profileId;
451
+ restorePending = options.loadState ? await options.loadState() : JSON.parse(await readFile(metadata, 'utf8'));
452
+ if (restorePending) await enqueue(() => restore(restorePending));
453
+ } catch { /* No prior ownership means no native authentication mutation. */ }
454
+ finally { if (recoveryNeeded) update({ continuation: 'manual_required', reason: 'native_continue_unconfirmed' }); }
455
+ })();
456
+ async function confirmChildren() {
457
+ const work = childContinuation;
458
+ if (!work) return;
459
+ try {
460
+ if (work.rpc !== rpc || !owned || !await lease?.valid()) throw liveError('native_control_lost');
461
+ const actual = await rpc.request('account/read', { refreshToken: false });
462
+ if (ownershipPaused || !sameNativeAccount(actual, work.identity)) throw liveError('account_changed_outside_deck');
463
+ const result = await confirmCodexLiveChildren(rpc, work.entries, {
464
+ onConfirmed: (entry, id) => work.record(entry, 'continued', id), onSkip: entry => work.record(entry, 'skipped'),
465
+ });
466
+ work.entries = result.pending;
467
+ if (!work.entries.length) {
468
+ childContinuation = null; await releaseHandoff(); update({ continuation: work.expired ? 'none' : 'automatic', reason: null });
469
+ } else if (Date.now() >= work.deadline) throw liveError('native_continue_unconfirmed');
470
+ } catch (error) {
471
+ // These are observations only. A slow daemon does not authorize replaying
472
+ // input, but may be observed again within the existing bounded window.
473
+ if (error.code === 'native_request_timeout' && Date.now() < work.deadline) return;
474
+ work.expired = true; update({ continuation: 'manual_required', reason: 'native_continue_unconfirmed' });
475
+ await releaseHandoff();
476
+ }
477
+ }
478
+ async function prepareCheckpoint() {
479
+ const work = checkpointWork;
480
+ if (!work) return;
481
+ try {
482
+ if (!work.current() || work.rpc !== rpc || !await lease?.valid()) throw liveError('native_control_lost');
483
+ const account = await rpc.request('account/read', { refreshToken: false });
484
+ if (ownershipPaused || !sameNativeAccount(account, work.identity)) throw liveError('account_changed_outside_deck');
485
+ const handoff = await inspectCodexLiveCheckpoints(rpc, work.entries, { record: work.record });
486
+ if (!handoff) {
487
+ if (Date.now() >= work.deadline) throw liveError('native_continue_unconfirmed');
488
+ return;
489
+ }
490
+ checkpointWork = null;
491
+ await apply(work.intent, work.refresh, work.automatic, { handoff, journal: work.journal, work });
492
+ } catch (error) {
493
+ if (error.code === 'native_request_timeout' && Date.now() < work.deadline) return;
494
+ checkpointWork = null; recoveryNeeded = true; recoveryJournal = work.journal;
495
+ await releaseHandoff();
496
+ update({ state: 'failed', continuation: 'manual_required', reason: 'native_continue_unconfirmed' });
497
+ }
498
+ }
499
+ async function reconcileRecovery() {
500
+ if (!recoveryNeeded || !recoveryJournal) return;
501
+ try {
502
+ const s = await selection(); await ensureRpc(s.originalHome);
503
+ for (const entry of recoveryJournal.entries) {
504
+ if (['continued', 'skipped'].includes(entry.phase)) continue;
505
+ const t = (await rpc.request('thread/read', { threadId: entry.threadId, includeTurns: false }))?.thread;
506
+ if (!t || t.status?.type === 'notLoaded') return;
507
+ const turn = await readCodexLiveTurn(rpc, t);
508
+ if (!turn || !['inProgress', 'completed'].includes(turn.status)) return;
509
+ if (turn.id === entry.turnId && (entry.phase !== 'interrupt_sent' || turn.status !== 'completed' || entry.checkpointReady)) return;
510
+ // New work is an observed owner action, never permission to replay us.
511
+ entry.phase = 'skipped';
512
+ }
513
+ recoveryJournal.phase = 'finished'; await saveHandoff(recoveryJournal);
514
+ recoveryNeeded = false; recoveryJournal = null;
515
+ update({ continuation: 'none', reason: null });
516
+ } catch { /* Keep the durable recovery intent until its outcome is known. */ }
517
+ }
518
+ async function reconnect() {
519
+ const s = await selection(); await ensureRpc(s.originalHome);
520
+ const actual = await rpc.request('account/read', { refreshToken: false });
521
+ // Notifications were unobservable during the gap. Email/workspace labels
522
+ // cannot restore authority; require a native ID or a fresh manual selection.
523
+ if (!accountIds(actual).length) await externalChange('native_identity_unattested');
524
+ else if (!ownershipPaused && sameAccount(actual, credential, true)) {
525
+ lastCheck = Date.now(); update({ state: 'applied', profileId: credential.profileId, reason: null });
526
+ } else await externalChange();
527
+ }
528
+ async function tick() {
529
+ if (closed || ticking) return;
530
+ ticking = true;
531
+ try {
532
+ await ready;
533
+ if (recoveryNeeded) await enqueue(reconcileRecovery);
534
+ if (childContinuation) await enqueue(confirmChildren);
535
+ if (checkpointWork) await enqueue(prepareCheckpoint);
536
+ const s = await selection();
537
+ if (s.runningSelection && s.runningSelection.revision > lastManual) {
538
+ lastManual = s.runningSelection.revision; await request(s.runningSelection);
539
+ } else if (s.profileId !== lastSelected) {
540
+ const auto = await (options.readAuto ?? (() => readCodexAuto({ ...options, store })))();
541
+ if (auto.enabled) await request({ id: s.profileId, revision: s.revision }, true);
542
+ }
543
+ lastSelected = s.profileId;
544
+ if (restorePending && Date.now() >= restoreRetryAt) await enqueue(() => restore(restorePending));
545
+ if (deferred && !childContinuation && !checkpointWork && !recoveryNeeded) { const retry = deferred; deferred = null; await enqueue(() => apply(retry.intent, retry.refresh, retry.automatic)); }
546
+ if (owned && !rpc && appliedIntent) await enqueue(reconnect);
547
+ if (owned && credential && appliedIntent && Date.now() - lastRefresh > 60_000 && credential.expiresAt - Date.now() < 10 * 60_000) {
548
+ lastRefresh = Date.now(); await enqueue(() => apply(appliedIntent, true));
549
+ }
550
+ if (owned && rpc && credential && Date.now() - lastCheck > 30_000) {
551
+ lastCheck = Date.now();
552
+ await enqueue(verifyAccount);
553
+ }
554
+ } catch { /* Temporary discovery failure never authorizes an account change. */ }
555
+ finally { ticking = false; }
556
+ }
557
+ const timer = setInterval(() => { void tick(); }, options.pollMs ?? 1000); timer.unref();
558
+ return { ready, status, request, tick,
559
+ async close() { closed = true; clearInterval(timer); pendingLogin?.reject(liveError('native_disconnected')); await ready; await chain.catch(() => {}); credential = null; await disconnect(); },
560
+ };
561
+ }
562
+
563
+ const controllers = new Map();
564
+ const keyFor = options => resolve(options.store ?? deckDataDir(undefined, options.env));
565
+ export function startCodexLiveAccounts(options = {}) {
566
+ const key = keyFor(options);
567
+ if (!controllers.has(key)) {
568
+ const disabled = (options.env ?? process.env).AGENTS_DECK_NO_CODEX_LIVE === '1';
569
+ const idle = () => ({ state: 'disabled', profileId: null });
570
+ controllers.set(key, disabled ? { ready: Promise.resolve(), status: idle, request: async () => idle(), close: async () => {} }
571
+ : createCodexLiveAccountController({ ...options, store: key }));
572
+ }
573
+ return controllers.get(key);
574
+ }
575
+ export function codexLiveAccountStatus(options = {}) { return controllers.get(keyFor(options))?.status() ?? { state: 'idle', profileId: null }; }
576
+ export async function requestCodexLiveAccount(intent, options = {}) { return startCodexLiveAccounts(options).request(intent); }
577
+ export async function stopCodexLiveAccounts(options = {}) { const key = keyFor(options), c = controllers.get(key); controllers.delete(key); await c?.close(); }