@hienlh/ppm 0.20.0 → 0.20.2

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 (101) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/CLAUDE.md +1 -0
  3. package/assets/skills/ppm/SKILL.md +1 -1
  4. package/assets/skills/ppm/references/http-api.md +5 -1
  5. package/dist/web/assets/accounts-settings-section-DzDmIsPe.js +1 -0
  6. package/dist/web/assets/{ai-resource-editor-BgYIPGVP.js → ai-resource-editor-D7C9wmwA.js} +1 -1
  7. package/dist/web/assets/{ai-settings-section-iBRCQvBR.js → ai-settings-section-BW5a07-Z.js} +1 -1
  8. package/dist/web/assets/{ai-settings-section-Cywmtnps.js → ai-settings-section-DZuwllLy.js} +1 -1
  9. package/dist/web/assets/{appearance-settings-section-mhu9T6Fk.js → appearance-settings-section-RfH2N1rj.js} +1 -1
  10. package/dist/web/assets/chat-tab-Bz0pk0_E.js +15 -0
  11. package/dist/web/assets/{code-editor-Cv_pzHo7.js → code-editor-C4o1SyuO.js} +2 -2
  12. package/dist/web/assets/{conflict-editor-BnWaMSEa.js → conflict-editor-Dk65mBIe.js} +1 -1
  13. package/dist/web/assets/{csv-preview-DG4YAabr.js → csv-preview-DENi3CFz.js} +1 -1
  14. package/dist/web/assets/{database-viewer-B-wA2qT-.js → database-viewer-BiBC7ulB.js} +1 -1
  15. package/dist/web/assets/{diff-viewer-DRtzdfXk.js → diff-viewer-CSvZJHak.js} +1 -1
  16. package/dist/web/assets/{edit-diff-preview-6tzdk7Pn.js → edit-diff-preview-xdDQvPhs.js} +1 -1
  17. package/dist/web/assets/{explorer-body-uh8oJp6J.js → explorer-body-QXS0h4AF.js} +1 -1
  18. package/dist/web/assets/{explorer-window-content-DLn_4egF.js → explorer-window-content-CQgqoRsj.js} +1 -1
  19. package/dist/web/assets/{extension-manager-section-C_ZGYvWf.js → extension-manager-section-CyC7wX35.js} +1 -1
  20. package/dist/web/assets/{extension-webview-DbFWxJpj.js → extension-webview-Da8SIlRa.js} +1 -1
  21. package/dist/web/assets/{files-settings-section-BrUbJglA.js → files-settings-section-D8cebM51.js} +1 -1
  22. package/dist/web/assets/{general-settings-section-B9ZPZVso.js → general-settings-section-1HVTvlIw.js} +1 -1
  23. package/dist/web/assets/{git-log-panel-C0jnhmgC.js → git-log-panel-C7a4rp8f.js} +1 -1
  24. package/dist/web/assets/{glide-data-grid-CZVKIum-.js → glide-data-grid-BT9p_4AN.js} +1 -1
  25. package/dist/web/assets/{group-chat-tab-DnPtmbPc.js → group-chat-tab-BUHGnUyW.js} +1 -1
  26. package/dist/web/assets/index-CuYtJ5xF.css +2 -0
  27. package/dist/web/assets/{index-CHQAPZIX.js → index-kGmcC9cb.js} +5 -5
  28. package/dist/web/assets/{jira-watcher-section-Bjldyhru.js → jira-watcher-section-BxzwW4uQ.js} +1 -1
  29. package/dist/web/assets/{keybindings-store-DBVXZKp8.js → keybindings-store-DjJum4OS.js} +1 -1
  30. package/dist/web/assets/{keyboard-shortcuts-section-D7jaCPrv.js → keyboard-shortcuts-section-DDKG3BU1.js} +1 -1
  31. package/dist/web/assets/{markdown-renderer-B4B5oxQS.js → markdown-renderer-dHeak2mE.js} +2 -2
  32. package/dist/web/assets/{markdown-renderer-DwHh-jd_.js → markdown-renderer-iBw1fCI_.js} +1 -1
  33. package/dist/web/assets/{mobile-explorer-sheet-JJxZYWkV.js → mobile-explorer-sheet-CzL8SLtz.js} +1 -1
  34. package/dist/web/assets/{notification-store-CCWNUHsS.js → notification-store-DVi6Ds71.js} +1 -1
  35. package/dist/web/assets/{notifications-settings-section-DbbX7-Qp.js → notifications-settings-section-shQ-ugKh.js} +1 -1
  36. package/dist/web/assets/{pdf-preview-DxNjWa1v.js → pdf-preview-DB26KSzm.js} +1 -1
  37. package/dist/web/assets/{postgres-viewer-BScvk5ev.js → postgres-viewer-CJe2meyF.js} +1 -1
  38. package/dist/web/assets/{ppmbot-settings-section-jFA9Ncgo.js → ppmbot-settings-section-Ba4c9AI9.js} +1 -1
  39. package/dist/web/assets/{process-table-BexeYWQm.js → process-table-PXwLsMuG.js} +1 -1
  40. package/dist/web/assets/{proxy-settings-section-C_seKq56.js → proxy-settings-section-BHBhK6HC.js} +1 -1
  41. package/dist/web/assets/{query-audit-section-BWXJmPDV.js → query-audit-section-BD5ZVqDz.js} +1 -1
  42. package/dist/web/assets/{remote-desktop-mobile-sheet-B--PeL5i.js → remote-desktop-mobile-sheet-Di4QG8VX.js} +2 -2
  43. package/dist/web/assets/{remote-desktop-mobile-view-jgn8nmQa.js → remote-desktop-mobile-view-DzoZvAqc.js} +1 -1
  44. package/dist/web/assets/{remote-desktop-readiness-gate-CjDth-W_.js → remote-desktop-readiness-gate-CHO-KJ9Z.js} +1 -1
  45. package/dist/web/assets/{remote-desktop-window-content-CrHAUA03.js → remote-desktop-window-content-X324gYbW.js} +1 -1
  46. package/dist/web/assets/{schedules-settings-section-DMFn3mYL.js → schedules-settings-section-a4-h6THc.js} +1 -1
  47. package/dist/web/assets/{settings-body-Dz2vPTEP.js → settings-body-Fq7BVDw2.js} +2 -2
  48. package/dist/web/assets/{settings-tab-B5QbsvS4.js → settings-tab-CVLQy-ie.js} +1 -1
  49. package/dist/web/assets/{settings-window-content-iM2bPoX5.js → settings-window-content-Bi7M0iaZ.js} +1 -1
  50. package/dist/web/assets/{sql-query-editor-C0mGgLfX.js → sql-query-editor-D1r265fl.js} +1 -1
  51. package/dist/web/assets/{sqlite-viewer-Bs3RKf1X.js → sqlite-viewer-DHkIotRl.js} +1 -1
  52. package/dist/web/assets/{system-monitor-body-DvUmEdNe.js → system-monitor-body-y6VUkYTL.js} +2 -2
  53. package/dist/web/assets/{system-monitor-tab-CHZ5F_ZE.js → system-monitor-tab-DRAOejhk.js} +1 -1
  54. package/dist/web/assets/{system-monitor-window-content-DjzqoeCN.js → system-monitor-window-content-B5i57xHD.js} +1 -1
  55. package/dist/web/assets/{tab-host-window-content-DKeAr5mD.js → tab-host-window-content-SkyPFFlc.js} +1 -1
  56. package/dist/web/assets/{team-member-sheet-Cl9ZB3dl.js → team-member-sheet-BB63u-Lf.js} +2 -2
  57. package/dist/web/assets/{team-member-window-content-DfP7WdFD.js → team-member-window-content-D6tVTXuV.js} +1 -1
  58. package/dist/web/assets/{terminal-tab-J1Fqa_rm.js → terminal-tab-BYaHAkI5.js} +1 -1
  59. package/dist/web/assets/{tool-cards-DQghSuKX.js → tool-cards-DRJu20sL.js} +3 -3
  60. package/dist/web/assets/use-accounts-data-Ba1_uvEE.js +1 -0
  61. package/dist/web/assets/{use-monaco-theme-aa4-wjKQ.js → use-monaco-theme-Uakgj3hJ.js} +1 -1
  62. package/dist/web/assets/{use-remote-desktop-display-choice-B-TpQ-Ua.js → use-remote-desktop-display-choice-Cd3Xalca.js} +1 -1
  63. package/dist/web/assets/{use-websocket-BBslmv3D.js → use-websocket-BC_EGf5q.js} +1 -1
  64. package/dist/web/assets/{video-preview-Bd0lcK3d.js → video-preview-BUb43zWb.js} +1 -1
  65. package/dist/web/index.html +2 -2
  66. package/dist/web/sw.js +1 -1
  67. package/docs/deployment-guide.md +10 -0
  68. package/package.json +1 -1
  69. package/src/providers/codex-app-server/codex-event-mapper.ts +11 -0
  70. package/src/providers/codex-app-server/codex-history.ts +118 -45
  71. package/src/providers/codex-app-server/codex-provider.ts +277 -15
  72. package/src/providers/codex-app-server/codex-rollout-header.ts +99 -0
  73. package/src/providers/codex-app-server/codex-rollout-items.ts +6 -0
  74. package/src/providers/codex-app-server/codex-rollout-transfer.ts +58 -0
  75. package/src/providers/codex-app-server/codex-subagent-thread.ts +103 -0
  76. package/src/providers/codex-app-server/codex-usage-limit.ts +69 -0
  77. package/src/providers/codex-app-server/codex-usage-parser.ts +31 -14
  78. package/src/server/routes/chat.ts +23 -2
  79. package/src/server/routes/codex-accounts.ts +32 -3
  80. package/src/server/ws/chat.ts +15 -11
  81. package/src/services/codex-account-cooldown.ts +56 -0
  82. package/src/services/codex-account-login.ts +109 -34
  83. package/src/services/codex-account.service.ts +56 -10
  84. package/src/services/codex-login-callback.ts +57 -0
  85. package/src/web/components/chat/chat-tab.tsx +8 -2
  86. package/src/web/components/chat/codex-usage-panel.tsx +129 -165
  87. package/src/web/components/chat/edit-diff-preview.tsx +14 -7
  88. package/src/web/components/chat/usage-badge.tsx +38 -129
  89. package/src/web/components/chat/usage-panel-shell.tsx +153 -0
  90. package/src/web/components/settings/accounts/account-card.tsx +20 -3
  91. package/src/web/components/settings/accounts/codex-accounts-section.tsx +9 -2
  92. package/src/web/components/settings/accounts/codex-add-account-dialog.tsx +47 -27
  93. package/src/web/components/settings/accounts/codex-usage-rows.tsx +17 -6
  94. package/src/web/components/settings/accounts/use-codex-accounts.ts +90 -44
  95. package/src/web/components/shared/markdown-code-block.tsx +10 -5
  96. package/src/web/components/ui/tooltip.tsx +14 -1
  97. package/src/web/hooks/use-usage.ts +13 -1
  98. package/dist/web/assets/accounts-settings-section-BQyru31C.js +0 -1
  99. package/dist/web/assets/chat-tab-Bs9OD6ss.js +0 -15
  100. package/dist/web/assets/index-CoaVwAF6.css +0 -2
  101. package/dist/web/assets/use-accounts-data-KWcMgRlc.js +0 -1
@@ -10,8 +10,19 @@ import type {
10
10
  UsageInfo,
11
11
  } from "../provider.interface.ts";
12
12
  import { configService } from "../../services/config.service.ts";
13
- import { setSessionMetadata, getSessionProjectPath, setSessionProvider, setSessionCodexAccount, getSessionCodexAccount } from "../../services/db.service.ts";
14
- import { resolveCodexAccountForSession, getCodexAccount, listCodexAccounts, peekCodexAccount } from "../../services/codex-account.service.ts";
13
+ import { setSessionMetadata, getSessionProjectPath, setSessionProvider, setSessionCodexAccount, getSessionCodexAccount, getSessionTitles } from "../../services/db.service.ts";
14
+ import {
15
+ resolveCodexAccountForSession,
16
+ getCodexAccount,
17
+ listCodexAccounts,
18
+ peekCodexAccount,
19
+ selectCodexAccount,
20
+ getAllCodexUsages,
21
+ codexUsageLevel,
22
+ type CodexAccount,
23
+ } from "../../services/codex-account.service.ts";
24
+ import { isCodexAccountUsageLimited, markCodexAccountUsageLimited } from "../../services/codex-account-cooldown.ts";
25
+ import { isCodexUsageLimit, codexErrorMessage, parseCodexUsageLimitReset } from "./codex-usage-limit.ts";
15
26
  import { killProcessTree } from "../../services/windows-process-tree.ts";
16
27
  import { homedir } from "node:os";
17
28
  import { join } from "node:path";
@@ -24,6 +35,7 @@ import { getOrFetchUsage, registerUsageSource } from "../../services/provider-us
24
35
  import { codexUsageSource } from "./codex-usage-source.ts";
25
36
  import { AMBIENT_ACCOUNT_KEY } from "../../services/provider-usage/usage-source.ts";
26
37
  import { redactTruncate } from "./codex-redact.ts";
38
+ import { localizeRollout } from "./codex-rollout-transfer.ts";
27
39
  import {
28
40
  listCodexRollouts,
29
41
  findRolloutByThreadId,
@@ -54,16 +66,22 @@ const CODEX_SESSIONS_DIR = join(homedir(), ".codex", "sessions");
54
66
  * being served from the in-process transcript, and nothing on disk was ever
55
67
  * found for it.
56
68
  *
57
- * `sessionId` narrows to the bound account when there is one; without it the
58
- * caller gets every account, which is what listing a project's sessions needs.
69
+ * `sessionId` puts the bound account's directory FIRST, because a thread that
70
+ * has been continued on that account has its newest rollout there. It no longer
71
+ * restricts the search to it: an account switch — manual, or forced by a usage
72
+ * limit — leaves the conversation's history in the home of whichever account
73
+ * was serving when it was written. Searching the bound account alone is what
74
+ * made a switched session come back empty and silently start over as a new
75
+ * thread, since resume is only attempted when a rollout is found.
59
76
  */
60
77
  function codexSessionsDirs(sessionId?: string): string[] {
61
78
  const dirs: string[] = [];
62
79
  const boundId = sessionId ? getSessionCodexAccount(sessionId) : null;
63
- const accounts = boundId
64
- ? [getCodexAccount(boundId)].filter((a): a is NonNullable<typeof a> => a != null)
65
- : listCodexAccounts();
66
- for (const account of accounts) dirs.push(join(account.home, "sessions"));
80
+ const accounts = listCodexAccounts();
81
+ const ordered = boundId
82
+ ? [...accounts.filter((a) => a.id === boundId), ...accounts.filter((a) => a.id !== boundId)]
83
+ : accounts;
84
+ for (const account of ordered) dirs.push(join(account.home, "sessions"));
67
85
  dirs.push(CODEX_SESSIONS_DIR);
68
86
  return dirs;
69
87
  }
@@ -76,6 +94,29 @@ function fromCodexSessionsDirs<T>(sessionId: string | undefined, read: (dir: str
76
94
  }
77
95
  return null;
78
96
  }
97
+
98
+ /**
99
+ * The rollout for a thread AND the sessions directory it was found in.
100
+ *
101
+ * The directory is what a plain path cannot tell us, and resuming needs it: a rollout
102
+ * belonging to another account has to be copied into the serving account's own home before
103
+ * codex will resolve it, and the copy has to keep its position relative to that directory.
104
+ */
105
+ function locateRollout(
106
+ sessionId: string,
107
+ cwd: string,
108
+ ): { path: string; sessionsDir: string } | null {
109
+ for (const dir of codexSessionsDirs(sessionId)) {
110
+ const found = findRolloutByThreadId(dir, sessionId, cwd);
111
+ if (found) return { path: found, sessionsDir: dir };
112
+ }
113
+ return null;
114
+ }
115
+
116
+ /** Where the app-server on this account writes and looks for rollouts. */
117
+ function sessionsDirForHome(codexHome?: string): string {
118
+ return codexHome ? join(codexHome, "sessions") : CODEX_SESSIONS_DIR;
119
+ }
79
120
  const CLIENT_INFO = { name: "ppm", title: "PPM", version: "0.0.0" };
80
121
  const CAPABILITIES = { experimentalApi: true, requestAttestation: false, optOutNotificationMethods: null };
81
122
  const MODELS_CACHE_TTL = 5 * 60 * 1000;
@@ -118,6 +159,13 @@ interface LiveSession {
118
159
  interruptRequested?: boolean;
119
160
  /** Follow-ups waiting for the current turn, in the order they will be sent. */
120
161
  pendingTurns: QueuedTurn[];
162
+ /** A usage-limit rotation is underway: the old app-server is being torn down and
163
+ * replaced by one running on another account. Everything the dying subprocess still
164
+ * emits belongs to the turn being abandoned, so it is dropped rather than shown. */
165
+ rotating?: boolean;
166
+ /** The turn currently in flight, kept so a rotation can send it again on the new
167
+ * account. Cleared when the turn ends — there is then nothing to replay. */
168
+ lastTurnInput?: { message: string; opts?: SendMessageOpts };
121
169
  }
122
170
 
123
171
  /** A follow-up held back because a turn was already running. */
@@ -281,6 +329,11 @@ export class CodexAppServerProvider implements AIProvider {
281
329
  sessions.push(s);
282
330
  }
283
331
  }
332
+ // A title the user set by hand outranks the one derived from the opening
333
+ // prompt, and it is the only place a renamed codex session is recorded.
334
+ const customTitles = getSessionTitles(sessions.map((s) => s.id));
335
+ for (const s of sessions) s.title = customTitles[s.id] ?? s.title;
336
+
284
337
  // Backfill provider ownership so reopening a pre-existing codex thread routes
285
338
  // to codex (not the default provider) even after a restart.
286
339
  //
@@ -328,7 +381,15 @@ export class CodexAppServerProvider implements AIProvider {
328
381
  this.startTurn(live, content, opts);
329
382
  }
330
383
 
331
- private startTurn(live: LiveSession, message: string, opts?: SendMessageOpts): void {
384
+ /**
385
+ * Send a turn on the live thread.
386
+ *
387
+ * `replay` marks the same turn being sent again on a different account after a usage
388
+ * limit. It skips the transcript append only: the user typed the message once, and a
389
+ * second entry would both show it twice and shift every later `rollout-N` id, which
390
+ * fork anchors resolve against.
391
+ */
392
+ private startTurn(live: LiveSession, message: string, opts?: SendMessageOpts, replay = false): void {
332
393
  if (!live.threadId) return;
333
394
  // One turn at a time — anything sent now would be dropped without a trace.
334
395
  // `now` additionally cuts the running turn short so this one answers next.
@@ -351,7 +412,8 @@ export class CodexAppServerProvider implements AIProvider {
351
412
  });
352
413
  return;
353
414
  }
354
- live.transcript.push({ id: nextRolloutId(live), role: "user", content: message, timestamp: new Date().toISOString() });
415
+ if (!replay) live.transcript.push({ id: nextRolloutId(live), role: "user", content: message, timestamp: new Date().toISOString() });
416
+ live.lastTurnInput = { message, opts };
355
417
  live.currentAssistant = "";
356
418
  live.currentEvents = [];
357
419
  // Codex takes an image as a path, never as a payload, so the uploaded copy is what it
@@ -371,7 +433,12 @@ export class CodexAppServerProvider implements AIProvider {
371
433
  const id = (res as { turn?: { id?: string } })?.turn?.id;
372
434
  if (id && !live.activeTurnId) this.setActiveTurn(live, id);
373
435
  }).catch((err) => {
374
- if (!live.client.isClosed) live.channel.push({ type: "error", message: redactTruncate((err as Error)?.message ?? String(err), 256) });
436
+ const reason = (err as Error)?.message ?? String(err);
437
+ // A quota refusal can come back as the rejection of the request itself rather than
438
+ // as an `error` notification, and it is the same situation either way — move the
439
+ // turn to an account that still has room instead of showing the refusal.
440
+ if (isCodexUsageLimit(reason) && this.beginRotation(live, reason)) return;
441
+ if (!live.client.isClosed) live.channel.push({ type: "error", message: redactTruncate(reason, 256) });
375
442
  // No turn is running, so nothing will report `turn/completed` — release the
376
443
  // queue here or every later follow-up waits on a turn that never existed.
377
444
  this.endTurn(live);
@@ -410,10 +477,195 @@ export class CodexAppServerProvider implements AIProvider {
410
477
  live.turnInFlight = false;
411
478
  live.activeTurnId = null;
412
479
  live.interruptRequested = false;
480
+ live.lastTurnInput = undefined;
413
481
  const next = live.pendingTurns.shift();
414
482
  if (next) this.startTurn(live, next.message, next.opts);
415
483
  }
416
484
 
485
+ // ── Usage-limit rotation ──
486
+
487
+ /**
488
+ * Take over a turn Codex refused for an exhausted quota, if another account can serve it.
489
+ *
490
+ * Answers synchronously so the caller knows, before it decides what to show, whether the
491
+ * refusal is being handled or has to be reported. The rotation itself is asynchronous —
492
+ * it respawns a subprocess and resumes the thread — but whether one is possible is a
493
+ * question about which accounts exist, which needs no I/O.
494
+ *
495
+ * Returns false when nothing else could serve the turn, and the refusal then reaches the
496
+ * user untouched. That is the honest outcome: an error saying the quota is spent is worth
497
+ * more than a silent retry on the account that just said so.
498
+ */
499
+ private beginRotation(live: LiveSession, reason: string): boolean {
500
+ const threadId = live.threadId;
501
+ if (!threadId || live.rotating) return false;
502
+ const currentId = getSessionCodexAccount(threadId);
503
+ const candidates = listCodexAccounts().filter(
504
+ (a) => a.status !== "disabled" && a.id !== currentId && !isCodexAccountUsageLimited(a.id),
505
+ );
506
+ if (candidates.length === 0) return false;
507
+ live.rotating = true;
508
+ void this.rotateAccount(live, threadId, currentId, reason);
509
+ return true;
510
+ }
511
+
512
+ /** Park the spent account, move the session onto a fresh one, and send the turn again. */
513
+ private async rotateAccount(
514
+ live: LiveSession,
515
+ threadId: string,
516
+ currentId: string | null,
517
+ reason: string,
518
+ ): Promise<void> {
519
+ const pending = live.lastTurnInput;
520
+ const reset = parseCodexUsageLimitReset(reason);
521
+ if (currentId) markCodexAccountUsageLimited(currentId, reset?.atMs);
522
+
523
+ let next: CodexAccount | null = null;
524
+ try {
525
+ // Usage picks the emptiest of the remaining accounts rather than merely the next one,
526
+ // so a rotation forced by a limit does not land on an account that is nearly at its own.
527
+ const usages = await getAllCodexUsages();
528
+ next = selectCodexAccount({
529
+ usageOf: (id) => codexUsageLevel(usages[id]),
530
+ ...(currentId ? { exclude: [currentId] } : {}),
531
+ });
532
+ } catch {
533
+ next = selectCodexAccount(currentId ? { exclude: [currentId] } : undefined);
534
+ }
535
+
536
+ if (!next) { this.abandonRotation(live, reason, reset?.text); return; }
537
+
538
+ console.warn(`[codex] session=${threadId} usage limit — switching to ${next.id} (${next.label})`);
539
+ live.channel.push({
540
+ type: "account_retry",
541
+ reason: "Usage limit reached — switching account",
542
+ accountId: next.id,
543
+ accountLabel: next.label,
544
+ });
545
+
546
+ try {
547
+ await this.respawnOn(live, threadId, next);
548
+ } catch (e) {
549
+ console.error(`[codex] session=${threadId} rotation to ${next.id} failed: ${redactTruncate((e as Error)?.message, 200)}`);
550
+ this.abandonRotation(live, reason, reset?.text);
551
+ return;
552
+ }
553
+
554
+ live.rotating = false;
555
+ // The refused turn never reached `turn/completed`, so the flags it set are still on.
556
+ live.turnInFlight = false;
557
+ live.activeTurnId = null;
558
+ live.interruptRequested = false;
559
+ if (pending) this.startTurn(live, pending.message, pending.opts, true);
560
+ else this.endTurn(live);
561
+ }
562
+
563
+ /** No account could take the turn — report the refusal and close the turn out. */
564
+ private abandonRotation(live: LiveSession, reason: string, resetText?: string): void {
565
+ live.rotating = false;
566
+ const suffix = resetText ? ` Try again ${resetText}.` : "";
567
+ live.channel.push({
568
+ type: "error",
569
+ message: `${redactTruncate(reason, 512)}${suffix} Add another account in Settings → Accounts, or wait for the reset.`,
570
+ });
571
+ live.channel.push({ type: "done", sessionId: live.threadId ?? "", resultSubtype: "error_during_execution" });
572
+ this.endTurn(live);
573
+ }
574
+
575
+ /**
576
+ * Put this session's app-server on another account, keeping the session itself intact.
577
+ *
578
+ * The subprocess is replaced, not the `LiveSession`: the caller of `sendMessage` is
579
+ * iterating this session's channel, and handing it a new one would end its stream mid-turn
580
+ * and leave the rest of the answer with nobody listening. Transcript, history and pending
581
+ * follow-ups all survive for the same reason.
582
+ *
583
+ * The outgoing client's handlers are cleared before it is closed. `close()` only asks the
584
+ * process to exit, so its `close` event lands well after this returns — by which time
585
+ * `rotating` is off again, and the inherited `onClose` would tear down the session that
586
+ * had just been repaired.
587
+ */
588
+ private async respawnOn(live: LiveSession, threadId: string, account: CodexAccount): Promise<void> {
589
+ const old = live.client;
590
+ old.onNotification(() => {});
591
+ old.onServerRequest(() => {});
592
+ old.onClose(() => {});
593
+ const pid = old.pid;
594
+ const proc = old.process;
595
+ old.close();
596
+ if (process.platform === "win32" && pid) killProcessTree(pid);
597
+ else if (proc) setTimeout(() => { try { proc.kill("SIGKILL"); } catch { /* dead */ } }, 2000).unref?.();
598
+
599
+ // Written before the rollout lookup so the new account's own directory is searched
600
+ // first — on a second rotation that is where the freshest history sits.
601
+ setSessionCodexAccount(threadId, account.id);
602
+
603
+ const client = new CodexJsonRpcClient();
604
+ client.onNotification((n) => this.handleNotification(live, n));
605
+ client.onServerRequest((r) => this.handleServerRequest(live, r));
606
+ client.onClose(() => this.handleClose(live));
607
+ client.start({ cwd: live.cwd, codexHome: account.home });
608
+ live.client = client;
609
+
610
+ await client.request("initialize", { clientInfo: CLIENT_INFO, capabilities: CAPABILITIES }, CONTROL_REQUEST_TIMEOUT_MS);
611
+ client.notify("initialized");
612
+
613
+ const resumeBase = {
614
+ cwd: live.cwd,
615
+ sandbox: live.permission.sandbox,
616
+ approvalPolicy: live.permission.approvalPolicy,
617
+ ...(live.model ? { model: live.model } : {}),
618
+ };
619
+ const found = locateRollout(threadId, live.cwd);
620
+ if (found) {
621
+ await this.resumeThread(client, threadId, found, account.home, resumeBase);
622
+ return;
623
+ }
624
+ // No rollout yet means the limit hit the very first turn, before codex had written one.
625
+ // There is nothing to resume, so the thread starts fresh — and it comes back under a
626
+ // new id, which every map keyed by the old one has to learn about or the next turn is
627
+ // sent to a thread this app-server has never heard of.
628
+ const started = await client.request("thread/start", resumeBase);
629
+ const newId = extractThreadId(started);
630
+ if (!newId || newId === threadId) return;
631
+ live.threadId = newId;
632
+ this.live.set(newId, live);
633
+ const meta = this.sessions.get(threadId);
634
+ if (meta) { this.sessions.delete(threadId); meta.id = newId; this.sessions.set(newId, meta); }
635
+ setSessionMetadata(newId, meta?.projectName, live.cwd);
636
+ setSessionProvider(newId, this.id);
637
+ setSessionCodexAccount(newId, account.id);
638
+ live.channel.push({ type: "session_migrated", oldSessionId: threadId, newSessionId: newId });
639
+ }
640
+
641
+ /**
642
+ * Resume a thread from the rollout file we located, wherever it lives.
643
+ *
644
+ * The `path` matters because a rollout is written inside the CODEX_HOME of whichever
645
+ * account served the turn, and this app-server is running on the account serving the
646
+ * session NOW. Asked by thread id alone, it searches only its own home and answers "no
647
+ * rollout found for thread id …" for a conversation that plainly exists — which is how
648
+ * an account switch used to lose the history and open a brand-new thread instead.
649
+ *
650
+ * The id-only form is kept as a fallback for a codex build that predates `path`: there
651
+ * the argument is rejected outright, and a resume that can still work by id should not
652
+ * be downgraded into a new thread over a field name.
653
+ */
654
+ private async resumeThread(
655
+ client: CodexJsonRpcClient,
656
+ threadId: string,
657
+ found: { path: string; sessionsDir: string },
658
+ codexHome: string | undefined,
659
+ resumeBase: Record<string, unknown>,
660
+ ): Promise<unknown> {
661
+ const target = sessionsDirForHome(codexHome);
662
+ const path = localizeRollout(found.path, found.sessionsDir, target);
663
+ if (path !== found.path) {
664
+ console.log(`[codex] thread=${threadId} rollout copied into the serving account's home to resume`);
665
+ }
666
+ return client.request("thread/resume", { threadId, path, ...resumeBase });
667
+ }
668
+
417
669
  private async connect(sessionId: string, opts?: SendMessageOpts): Promise<LiveSession> {
418
670
  const meta = this.sessions.get(sessionId);
419
671
  const cwd = meta?.projectPath || getSessionProjectPath(sessionId) || process.cwd();
@@ -445,12 +697,12 @@ export class CodexAppServerProvider implements AIProvider {
445
697
  const resumeBase = { cwd, sandbox: permission.sandbox, approvalPolicy: permission.approvalPolicy, ...(model ? { model } : {}) };
446
698
  // Only treat as a resume when a rollout for this id is attributable to THIS
447
699
  // project (fail-closed cwd guard) — never resume another project's thread.
448
- const isResume = !!fromCodexSessionsDirs(sessionId, (d) => findRolloutByThreadId(d, sessionId, cwd));
449
- const result = isResume
450
- ? await client.request("thread/resume", { threadId: sessionId, ...resumeBase })
700
+ const found = locateRollout(sessionId, cwd);
701
+ const result = found
702
+ ? await this.resumeThread(client, sessionId, found, account?.home, resumeBase)
451
703
  : await client.request("thread/start", resumeBase);
452
704
 
453
- const threadId = extractThreadId(result) ?? (isResume ? sessionId : null);
705
+ const threadId = extractThreadId(result) ?? (found ? sessionId : null);
454
706
  if (!threadId) throw new Error("codex thread/start returned no thread id");
455
707
  live.threadId = threadId;
456
708
 
@@ -480,6 +732,16 @@ export class CodexAppServerProvider implements AIProvider {
480
732
  }
481
733
 
482
734
  private handleNotification(live: LiveSession, notif: JsonRpcNotification): void {
735
+ // A quota refusal is an ordinary `error` notification, so it has to be recognised
736
+ // before the mapper turns it into a plain error card in front of the user.
737
+ if (notif.method === "error" && !live.rotating) {
738
+ const reason = codexErrorMessage(notif.params);
739
+ if (isCodexUsageLimit(reason) && this.beginRotation(live, reason)) return;
740
+ }
741
+ // Mid-rotation the subprocess behind this session is being replaced. Anything it still
742
+ // emits describes the turn that was refused — including its `turn/completed`, which
743
+ // would close the turn the caller is about to be given a second time.
744
+ if (live.rotating) return;
483
745
  if (notif.method === "item/agentMessage/delta") {
484
746
  const d = (notif.params as { delta?: string })?.delta;
485
747
  if (typeof d === "string") live.currentAssistant += d;
@@ -0,0 +1,99 @@
1
+ import { mapRolloutItem } from "./codex-rollout-items.ts";
2
+
3
+ /**
4
+ * Line primitives for a codex rollout JSONL, plus the header a session list
5
+ * needs: which project the thread ran in, whether it is a thread of its own,
6
+ * and what to call it.
7
+ *
8
+ * Kept apart from the transcript parser because listing reads every rollout in
9
+ * the tree while parsing reads one — the listing path must be able to stop at
10
+ * the first few records instead of walking a multi-megabyte transcript.
11
+ */
12
+
13
+ export interface RolloutLine {
14
+ timestamp?: string;
15
+ type?: string;
16
+ payload?: Record<string, unknown>;
17
+ }
18
+
19
+ /** Split into complete, newline-terminated lines only (drop a trailing partial). */
20
+ export function completeLines(text: string): string[] {
21
+ const lines = text.split("\n");
22
+ // If the text does not end in a newline, the last element is a partial line.
23
+ if (!text.endsWith("\n")) lines.pop();
24
+ return lines.filter((l) => l.trim() !== "");
25
+ }
26
+
27
+ export function parseLine(line: string): RolloutLine | null {
28
+ try { return JSON.parse(line) as RolloutLine; } catch { return null; }
29
+ }
30
+
31
+ export interface RolloutHeader {
32
+ id?: string;
33
+ cwd?: string;
34
+ timestamp?: string;
35
+ /**
36
+ * The thread that spawned this one. Present ONLY on a subagent's own rollout,
37
+ * which codex writes into the same sessions tree as a real conversation — so
38
+ * this is what separates "a session the user started" from "one step inside
39
+ * one".
40
+ */
41
+ parentThreadId?: string;
42
+ /** First user prompt, trimmed to a session-list label. */
43
+ title?: string;
44
+ }
45
+
46
+ /** How far into a rollout to look for the opening prompt before giving up. */
47
+ const TITLE_SCAN_LINES = 2000;
48
+ const TITLE_MAX_CHARS = 80;
49
+
50
+ /** First user prompt → a one-line label. */
51
+ function toTitle(text: string): string | undefined {
52
+ const flat = text.replace(/\s+/g, " ").trim();
53
+ if (!flat) return undefined;
54
+ return flat.length > TITLE_MAX_CHARS ? `${flat.slice(0, TITLE_MAX_CHARS - 1)}…` : flat;
55
+ }
56
+
57
+ /**
58
+ * Read the `session_meta` header, and (when `withTitle`) the first user prompt.
59
+ *
60
+ * A subagent rollout has no user prompt at all — its task arrives as encrypted
61
+ * scaffolding — so the title scan is skipped for one rather than walking the
62
+ * whole file to find nothing.
63
+ */
64
+ export function readRolloutHeader(text: string, opts?: { withTitle?: boolean }): RolloutHeader | null {
65
+ let header: RolloutHeader | null = null;
66
+ let scanned = 0;
67
+
68
+ for (const line of completeLines(text)) {
69
+ const rec = parseLine(line);
70
+ if (!rec) continue;
71
+ const p = rec.payload ?? {};
72
+
73
+ if (rec.type === "session_meta" && !header) {
74
+ header = {
75
+ id: typeof p.id === "string" ? p.id : undefined,
76
+ cwd: typeof p.cwd === "string" ? p.cwd : undefined,
77
+ timestamp: typeof p.timestamp === "string" ? p.timestamp : rec.timestamp,
78
+ parentThreadId: typeof p.parent_thread_id === "string" ? p.parent_thread_id : undefined,
79
+ };
80
+ if (!opts?.withTitle || header.parentThreadId) return header;
81
+ continue;
82
+ }
83
+
84
+ if (!header || rec.type !== "event_msg") continue;
85
+ if (++scanned > TITLE_SCAN_LINES) break;
86
+
87
+ if (p.type === "user_message" && typeof p.message === "string") {
88
+ header.title = toTitle(p.message);
89
+ if (header.title) return header;
90
+ } else if (p.type === "item_completed") {
91
+ const mapped = mapRolloutItem(p.item);
92
+ if (mapped.kind === "user") {
93
+ header.title = toTitle(mapped.text);
94
+ if (header.title) return header;
95
+ }
96
+ }
97
+ }
98
+ return header;
99
+ }
@@ -1,5 +1,6 @@
1
1
  import type { ChatEvent } from "../provider.interface.ts";
2
2
  import { redactTruncate } from "./codex-redact.ts";
3
+ import { parseSubagentActivity, type SubagentActivity } from "./codex-subagent-thread.ts";
3
4
 
4
5
  /**
5
6
  * Rollout `item_completed` records → PPM chat events.
@@ -25,6 +26,9 @@ export type RolloutItemMapping =
25
26
  | { kind: "user"; text: string }
26
27
  | { kind: "assistant"; text: string }
27
28
  | { kind: "events"; events: ChatEvent[] }
29
+ // A spawned thread: the parser turns it into a card and hangs the child
30
+ // transcript under it, which needs the sessions dir it cannot reach itself.
31
+ | { kind: "subagent"; activity: SubagentActivity }
28
32
  | { kind: "ignore" };
29
33
 
30
34
  const IGNORED_ITEM_TYPES = new Set([
@@ -129,6 +133,8 @@ export function mapRolloutItem(item: unknown): RolloutItemMapping {
129
133
  const type = typeof it.type === "string" ? it.type : "";
130
134
 
131
135
  if (IGNORED_ITEM_TYPES.has(type)) return { kind: "ignore" };
136
+ const subagent = parseSubagentActivity(it);
137
+ if (subagent) return { kind: "subagent", activity: subagent };
132
138
  if (type === "UserMessage") {
133
139
  const text = textFrom(it.content);
134
140
  return text ? { kind: "user", text } : { kind: "ignore" };
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Moving a conversation's transcript into the CODEX_HOME that is about to serve it.
3
+ *
4
+ * Codex resolves a thread only against its OWN sessions directory. The `path` argument to
5
+ * `thread/resume` looks like an escape from that, and it is not: a path outside the running
6
+ * app-server's CODEX_HOME is refused with the same "no rollout found for thread id" as
7
+ * passing no path at all. Verified directly — the identical request succeeds when the
8
+ * app-server runs on the home the rollout lives in, and fails when it runs on another.
9
+ *
10
+ * So a session that changes account — because the user picked a different one, or because a
11
+ * usage limit forced the move — has its history sitting in a directory the new account's
12
+ * app-server will not look in, and resuming it is impossible until the file is there. It
13
+ * gets copied rather than moved: the account it came from may still be serving other
14
+ * sessions whose own history sits in the same tree, and the original is what PPM reads for
15
+ * any view of the conversation that is not this live thread.
16
+ *
17
+ * From here codex appends to the copy, so the newest history is in the account now serving
18
+ * the session — which is why `codexSessionsDirs` searches the bound account's directory
19
+ * first.
20
+ */
21
+
22
+ import { copyFileSync, existsSync, mkdirSync } from "node:fs";
23
+ import { dirname, join, relative, resolve } from "node:path";
24
+
25
+ /** Case-insensitive on win32, so two spellings of one directory compare equal. */
26
+ function samePath(a: string, b: string): boolean {
27
+ const norm = (p: string) => (process.platform === "win32" ? resolve(p).toLowerCase() : resolve(p));
28
+ return norm(a) === norm(b);
29
+ }
30
+
31
+ /**
32
+ * Ensure a rollout is inside `targetSessionsDir`, and return the path to use.
33
+ *
34
+ * A rollout already in the target directory is returned untouched — the common case, where
35
+ * the session is still on the account that wrote it, and nothing should be copied.
36
+ *
37
+ * The relative layout is preserved (`YYYY/MM/DD/rollout-….jsonl`) because that is where
38
+ * codex's own scan expects to find it.
39
+ *
40
+ * Failures are surfaced rather than swallowed: the caller's next act is a resume that
41
+ * cannot work without this, and a silent failure there turns into a conversation that
42
+ * quietly starts over as a new thread.
43
+ */
44
+ export function localizeRollout(
45
+ rolloutPath: string,
46
+ foundInSessionsDir: string,
47
+ targetSessionsDir: string,
48
+ ): string {
49
+ if (samePath(foundInSessionsDir, targetSessionsDir)) return rolloutPath;
50
+ const dest = join(targetSessionsDir, relative(foundInSessionsDir, rolloutPath));
51
+ if (existsSync(dest)) return dest;
52
+ const destDir = dirname(dest);
53
+ // Only create what is missing. A recursive mkdir over an existing Windows directory
54
+ // carrying the read-only attribute throws EEXIST rather than succeeding quietly.
55
+ if (!existsSync(destDir)) mkdirSync(destDir, { recursive: true });
56
+ copyFileSync(rolloutPath, dest);
57
+ return dest;
58
+ }
@@ -0,0 +1,103 @@
1
+ import type { ChatEvent, ChatMessage } from "../provider.interface.ts";
2
+ import { redactTruncate } from "./codex-redact.ts";
3
+
4
+ /**
5
+ * Subagent threads, rendered as one Agent card in the conversation that spawned
6
+ * them.
7
+ *
8
+ * Codex writes a spawned subagent as a rollout of its own, in the same sessions
9
+ * tree and with the same `cwd` as a real conversation. Left alone it surfaces
10
+ * twice over: once as a top-level session that opens mid-stream (it has no user
11
+ * prompt — the task is handed over as encrypted scaffolding), and once as two
12
+ * bare `SubAgentActivity` cards in the parent. Folding the child transcript into
13
+ * the parent's card is what makes it one step of one conversation again.
14
+ */
15
+
16
+ /** Codex spells the item PascalCase in a rollout and camelCase on the wire. */
17
+ export const SUBAGENT_ITEM_TYPES = new Set(["SubAgentActivity", "subAgentActivity"]);
18
+
19
+ export interface SubagentActivity {
20
+ /** Rollout id of the spawned thread — the link to its transcript. */
21
+ threadId: string;
22
+ /** Codex's name for the agent, e.g. `/root/simplify_login`. */
23
+ path: string;
24
+ done: boolean;
25
+ }
26
+
27
+ /** The transcript of a spawned thread, ready to hang under its card. */
28
+ export interface SubagentTranscript {
29
+ events: ChatEvent[];
30
+ /** The agent's closing message — its report back to the parent. */
31
+ finalText: string;
32
+ }
33
+
34
+ function str(v: unknown): string | undefined {
35
+ return typeof v === "string" && v ? v : undefined;
36
+ }
37
+
38
+ /** A `SubAgentActivity` item → normalized activity, or null if it is not one. */
39
+ export function parseSubagentActivity(item: unknown): SubagentActivity | null {
40
+ if (!item || typeof item !== "object") return null;
41
+ const it = item as Record<string, unknown>;
42
+ if (!SUBAGENT_ITEM_TYPES.has(String(it.type ?? ""))) return null;
43
+ const threadId = str(it.agent_thread_id) ?? str(it.agentThreadId);
44
+ if (!threadId) return null;
45
+ const kind = String(it.kind ?? "");
46
+ return {
47
+ threadId,
48
+ path: str(it.agent_path) ?? str(it.agentPath) ?? "subagent",
49
+ done: kind === "completed" || kind === "failed",
50
+ };
51
+ }
52
+
53
+ /**
54
+ * Card id derived from the spawned thread.
55
+ *
56
+ * The started and completed records carry DIFFERENT item ids (`call_…` vs
57
+ * `subagent-completed-…`), so pairing on the item id leaves the call unanswered
58
+ * and the completion orphaned as a second card. The thread they both name is
59
+ * the stable key.
60
+ */
61
+ export function subagentCardId(threadId: string): string {
62
+ return `subagent-${threadId}`;
63
+ }
64
+
65
+ /** The spawn, as the Agent card the chat already knows how to expand. */
66
+ export function subagentToolUse(activity: SubagentActivity, transcript?: SubagentTranscript | null): ChatEvent {
67
+ return {
68
+ type: "tool_use",
69
+ tool: "Agent",
70
+ input: { description: activity.path },
71
+ toolUseId: subagentCardId(activity.threadId),
72
+ ...(transcript?.events.length ? { children: transcript.events } : {}),
73
+ };
74
+ }
75
+
76
+ /** The completion, answering the card above with the agent's own report. */
77
+ export function subagentToolResult(activity: SubagentActivity, transcript?: SubagentTranscript | null): ChatEvent {
78
+ return {
79
+ type: "tool_result",
80
+ output: redactTruncate(transcript?.finalText || `${activity.path} finished`),
81
+ toolUseId: subagentCardId(activity.threadId),
82
+ };
83
+ }
84
+
85
+ /** A parsed child transcript → the flat event list a card nests. */
86
+ export function transcriptToEvents(messages: ChatMessage[]): ChatEvent[] {
87
+ const events: ChatEvent[] = [];
88
+ for (const m of messages) {
89
+ // An assistant turn with tool calls already carries its text as the last event.
90
+ if (m.events?.length) events.push(...m.events);
91
+ else if (m.content) events.push({ type: "text", content: m.content });
92
+ }
93
+ return events;
94
+ }
95
+
96
+ /** The agent's closing message, which is what it reported back. */
97
+ export function finalAssistantText(messages: ChatMessage[]): string {
98
+ for (let i = messages.length - 1; i >= 0; i--) {
99
+ const m = messages[i]!;
100
+ if (m.role === "assistant" && m.content) return m.content;
101
+ }
102
+ return "";
103
+ }