@hienlh/ppm 0.25.3 → 0.25.5

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/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.25.5] - 2026-11-14
4
+
5
+ ### Fixed
6
+
7
+ - **A background agent resumed with SendMessage is no longer killed** when the chat's sign-in token is renewed: PPM tracks background work by task, so the chat is woken when the agent finishes instead of going silent.
8
+ - **Token renewal waits** while a chat's CLI has reported background activity in the last 3 minutes.
9
+
10
+ ## [0.25.4] - 2026-11-14
11
+
12
+ ### Changed
13
+
14
+ - **A Telegram card with several questions asks them one at a time in one message**: "Question 2/3" with that question's own buttons, Back and Next, and a summary with Send; nothing is answered until Send.
15
+
16
+ ### Fixed
17
+
18
+ - **The Codex model list uses the account a chat would use**, and keeps the last list instead of starting Codex when no account can serve.
19
+ - **A signed-out Codex account is retried less and less often** (5 minutes up to hourly), and its errors name the account and are logged once an hour instead of every 5 minutes.
20
+
3
21
  ## [0.25.3] - 2026-11-14
4
22
 
5
23
  ### Fixed
@@ -83,4 +83,4 @@ This skill covers the `ppm` CLI, its HTTP API, and its config DB. It does **not*
83
83
  - Third-party extensions (inspect via `ppm ext list`).
84
84
  - The Claude Agent SDK internals (separate skill).
85
85
 
86
- <!-- Generated for PPM v0.25.3 at build time. Re-run `ppm export skill --install` to refresh. -->
86
+ <!-- Generated for PPM v0.25.5 at build time. Re-run `ppm export skill --install` to refresh. -->
@@ -842,4 +842,4 @@ Authenticate with `?token=<token>` (see Authentication).
842
842
  - `/ws/android`
843
843
  - `/ws/project/<project>/<type>/<id>` — `<type>`: `terminal`, `chat`, `group`, `lsp` (for `chat`, `<id>` is the session id)
844
844
 
845
- <!-- Generated from src/server/routes/ for PPM v0.25.3 -->
845
+ <!-- Generated from src/server/routes/ for PPM v0.25.5 -->
@@ -1125,10 +1125,19 @@ lifecycle bus (`chat-collab-approval-relay.ts`), so they reach Telegram under th
1125
1125
  is showing, through the session tools' broker, as Allow once or Deny; nothing settles them "for the
1126
1126
  session", and the Assistant answering a card never does.
1127
1127
 
1128
- Questions show their choices as buttons (several at once: toggle, then Send); a question that
1129
- only takes typed text points to PPM. Buttons carry random codes bound to the chat they were sent
1130
- to (`assistant-telegram-button-codes.ts`): pressing one spends every code of that card, and after
1131
- a restart every code is "no longer valid", so nothing pressed on an old card can run.
1128
+ Questions show their choices as buttons. One question with one choice is answered by the press.
1129
+ Anything else — several questions, or a question that takes several choices — is asked one
1130
+ question at a time in the same message (`assistant-telegram-question-wizard.ts`): "Question k/n"
1131
+ with only that question's buttons, a pick moving on, ticks (✓) plus Next for a question that takes
1132
+ several, Back from the second step on, and a summary with Send and Back at the end. Each step edits
1133
+ the message; only Send answers the card, every question at once. A card with a question that
1134
+ only takes typed or private text is shown whole and points to PPM. Buttons carry random codes bound
1135
+ to the chat they were sent to (`assistant-telegram-button-codes.ts`), all made when the card is
1136
+ shown: a step only chooses which to show, and a button left over from another step changes
1137
+ nothing but redraws the current step. A step that cannot be drawn ends the card on Telegram ("answer
1138
+ it in PPM"), and a full code store evicts whole cards, never part of one.
1139
+ Answering spends every code of that card, and after a restart every code is "no longer valid", so
1140
+ nothing pressed on an old card can run.
1132
1141
 
1133
1142
  **Relayed cards** (`assistant-telegram-relay.ts`). A watched chat's card goes to the chats bound to
1134
1143
  the Assistant session that set the watch, or to every connected chat when that session is
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hienlh/ppm",
3
- "version": "0.25.3",
3
+ "version": "0.25.5",
4
4
  "description": "Personal Project Manager — mobile-first web IDE with AI assistance",
5
5
  "author": "hienlh",
6
6
  "license": "SEE LICENSE IN LICENSE",
@@ -3,6 +3,7 @@ import { basename } from "node:path";
3
3
  import { StringDecoder } from "node:string_decoder";
4
4
  import { resolveBunPath } from "../../services/autostart-generator.ts";
5
5
  import { redactTruncate } from "./codex-redact.ts";
6
+ import { codexLoginTag, codexStderrLogLine } from "./codex-stderr-log.ts";
6
7
  import type { JsonRpcResponse, ServerRequest, JsonRpcNotification } from "./codex-protocol.ts";
7
8
  import { AI_CHAT_MARK } from "../../services/ai-chat-env.ts";
8
9
  import { ppmInstanceEnv } from "../../services/ppm-instance-env.ts";
@@ -104,13 +105,20 @@ export class CodexJsonRpcClient {
104
105
  private purpose: "chat" | "login" | "control" = "control";
105
106
  /** The last stderr line logged, for the exit line (redacted). */
106
107
  private lastStderr = "";
108
+ /** The login this app-server runs on, named on each of its stderr lines. */
109
+ private account = "unknown";
107
110
 
108
111
  /** Spawn the subprocess. Injectable streams allow unit testing without a real spawn.
109
112
  * `codexHome` selects which account's auth the app-server uses (CODEX_HOME); `env` adds
110
113
  * variables this one session needs (a design session's MCP token). `purpose` only sets
111
114
  * the log level of its start and exit: a chat or a login is lifecycle at INFO, while
112
- * the short-lived control spawns (usage sweep, model and skill lists, fork) are DEBUG. */
113
- start(opts?: { cwd?: string; codexHome?: string; env?: Record<string, string>; purpose?: "chat" | "login" | "control" }): void {
115
+ * the short-lived control spawns (usage sweep, model and skill lists, fork) are DEBUG.
116
+ * `loginHome` names the login on stderr lines when `codexHome` is not the login's own
117
+ * folder (an Assistant home); `null` there means `~/.codex`. */
118
+ start(opts?: {
119
+ cwd?: string; codexHome?: string; loginHome?: string | null;
120
+ env?: Record<string, string>; purpose?: "chat" | "login" | "control";
121
+ }): void {
114
122
  const env = { ...buildSpawnEnv(), ...(opts?.env ?? {}) };
115
123
  if (opts?.codexHome) env.CODEX_HOME = opts.codexHome;
116
124
  const [cmd, ...args] = codexCommand("app-server");
@@ -121,6 +129,7 @@ export class CodexJsonRpcClient {
121
129
  windowsHide: true,
122
130
  });
123
131
  this.purpose = opts?.purpose ?? "control";
132
+ this.account = codexLoginTag(opts?.loginHome !== undefined ? opts.loginHome ?? undefined : opts?.codexHome);
124
133
  // So the Task Manager's kill route can tell an AI chat to use chat_stop instead of ending this.
125
134
  this.proc.once("close", registerChatProviderPid(this.proc.pid, "codex"));
126
135
  // CODEX_HOME is <ppm dir>/codex-accounts/<account id>, so its name is the account id.
@@ -144,16 +153,13 @@ export class CodexJsonRpcClient {
144
153
  attach(stdout: NodeJS.ReadableStream, stderr?: NodeJS.ReadableStream | null): void {
145
154
  stdout.on("data", (chunk: Buffer) => this.onStdout(chunk));
146
155
  stderr?.on("data", (chunk: Buffer) => {
147
- // codex's stderr is Rust tracing ("<time> ERROR codex_x::y: …", ANSI-coloured), so its
148
- // own level decides ours: a failed cache write is not a PPM ERROR. An untagged line is
149
- // `bun x` resolving the package unless it reads like a failure.
156
+ // ANSI-coloured Rust tracing; `codexStderrLogLine` picks the level, names the login
157
+ // and folds repeats.
150
158
  for (const line of chunk.toString().replace(/\x1b\[[0-9;]*m/g, "").split("\n")) {
151
- const s = line.trim();
152
- if (!s || /warning|trace-warnings|circular dependency/i.test(s)) continue;
153
- const tag = /^(?:\S+\s+)?(ERROR|WARN|INFO|DEBUG|TRACE)\b/.exec(s)?.[1];
154
- const loud = tag ? tag === "ERROR" || tag === "WARN" : /error|panic|fatal|fail/i.test(s);
155
- this.lastStderr = redactTruncate(s, 200);
156
- (loud ? log.warn : log.debug)(`stderr: ${this.lastStderr}`);
159
+ const out = codexStderrLogLine(this.account, line, Date.now(), this.purpose === "control");
160
+ if (!out) continue;
161
+ this.lastStderr = out.text;
162
+ log[out.level](out.message);
157
163
  }
158
164
  });
159
165
  }
@@ -17,6 +17,8 @@ import { withSharedContext } from "../../shared/provider-context.ts";
17
17
  import { setSessionMetadata, getSessionProjectPath, setSessionProvider, setSessionCodexAccount, getSessionCodexAccount, getSessionTitles, insertTurnUsage } from "../../services/db.service.ts";
18
18
  import {
19
19
  resolveCodexAccountForSession,
20
+ codexLoginForListing,
21
+ type CodexListingLogin,
20
22
  getCodexAccount,
21
23
  listCodexAccounts,
22
24
  peekCodexAccount,
@@ -927,7 +929,7 @@ export class CodexAppServerProvider implements AIProvider {
927
929
  client.onServerRequest((r) => this.handleServerRequest(live, r));
928
930
  client.onClose(() => this.handleClose(live));
929
931
  const codexHome = live.assistant ? assistantSpawnHome(account.home) : account.home;
930
- client.start({ cwd: live.cwd, codexHome, env: { ...liveMcpEnv(live), ...(live.assistant ? assistantShellEnv() : {}) }, purpose: "chat" });
932
+ client.start({ cwd: live.cwd, codexHome, loginHome: account.home, env: { ...liveMcpEnv(live), ...(live.assistant ? assistantShellEnv() : {}) }, purpose: "chat" });
931
933
  live.client = client;
932
934
 
933
935
  await client.request("initialize", { clientInfo: CLIENT_INFO, capabilities: CAPABILITIES }, CHAT_INITIALIZE_TIMEOUT_MS);
@@ -1042,7 +1044,7 @@ export class CodexAppServerProvider implements AIProvider {
1042
1044
  // An Assistant app-server runs on a home of its own that shares only the account's login and
1043
1045
  // sessions folder, so the user's AGENTS.md, config.toml and skills stay behind.
1044
1046
  const codexHome = live.assistant ? assistantSpawnHome(account?.home) : account?.home;
1045
- client.start({ cwd, codexHome, env: { ...liveMcpEnv(live), ...(live.assistant ? assistantShellEnv() : {}) }, purpose: "chat" });
1047
+ client.start({ cwd, codexHome, loginHome: account?.home ?? null, env: { ...liveMcpEnv(live), ...(live.assistant ? assistantShellEnv() : {}) }, purpose: "chat" });
1046
1048
 
1047
1049
  // A cold first start can outlast a control call's bound; failing here would cost the user's turn.
1048
1050
  await client.request("initialize", { clientInfo: CLIENT_INFO, capabilities: CAPABILITIES }, CHAT_INITIALIZE_TIMEOUT_MS);
@@ -1568,14 +1570,25 @@ export class CodexAppServerProvider implements AIProvider {
1568
1570
  }
1569
1571
 
1570
1572
  private async loadModels(): Promise<ModelOption[]> {
1573
+ // Read on the login a new chat would run on. Without a CODEX_HOME the app-server uses the
1574
+ // machine's own ~/.codex login, which is right only when a chat would too: on a machine
1575
+ // that manages accounts it is usually stale, and its failed refreshes filled the log.
1576
+ let login: CodexListingLogin;
1577
+ try {
1578
+ login = await codexLoginForListing();
1579
+ } catch (err) {
1580
+ this.warnListFailure("model/list", "unresolved", err);
1581
+ return this.modelsCache?.models ?? [];
1582
+ }
1583
+ if (login.kind === "none") {
1584
+ // A chat would be refused too, so there is nothing to read the list on. Keep what we had.
1585
+ log.debug(`model/list skipped: ${login.reason}`);
1586
+ return this.modelsCache?.models ?? [];
1587
+ }
1588
+ const account = login.kind === "account" ? login.account : null;
1589
+ const accountId = account ? account.id.slice(0, 8) : "ambient";
1571
1590
  const client = new CodexJsonRpcClient();
1572
- let accountId: string | null = null;
1573
1591
  try {
1574
- // Without a CODEX_HOME the app-server falls back to the machine's own
1575
- // ~/.codex login, which may be stale or absent — the model list then comes
1576
- // from an account PPM does not use, or fails outright on a refresh error.
1577
- const account = await resolveCodexAccountForSession();
1578
- accountId = account?.id ?? null;
1579
1592
  client.start({ cwd: process.cwd(), ...(account ? { codexHome: account.home } : {}) });
1580
1593
  await client.request("initialize", { clientInfo: CLIENT_INFO, capabilities: CAPABILITIES }, CONTROL_REQUEST_TIMEOUT_MS);
1581
1594
  client.notify("initialized");
@@ -1590,9 +1603,13 @@ export class CodexAppServerProvider implements AIProvider {
1590
1603
  if (models.length > 0) this.modelsCache = { models, expiry: Date.now() + MODELS_CACHE_TTL };
1591
1604
  return models;
1592
1605
  } catch (err) {
1593
- // The picker shows an empty list either way; this is the only record of why.
1594
- this.warnListFailure("model/list", accountId ?? "ambient", err);
1595
- return [];
1606
+ // The picker keeps what it had either way; this is the only record of why.
1607
+ this.warnListFailure("model/list", accountId, err);
1608
+ // A refused login benches the account now rather than at the next usage sweep.
1609
+ if (account && isCodexAuthFailure(codexErrorText(err))) {
1610
+ markCodexAccountAuthFailed(account.id, redactTruncate(codexErrorText(err), 256));
1611
+ }
1612
+ return this.modelsCache?.models ?? [];
1596
1613
  } finally {
1597
1614
  client.close();
1598
1615
  }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * How one line of a codex app-server's stderr reaches PPM's log.
3
+ *
4
+ * Every line names the login it came from (`account=<first 8 chars of the account id>` or
5
+ * `account=ambient` for `~/.codex`), because codex's own lines never do. And for the
6
+ * background spawns the same error is written loudly once per account per hour: codex
7
+ * prints a failed token refresh six times per process, and the usage sweep starts one
8
+ * process per account every five minutes, which put the same unattributed line into the log
9
+ * hundreds of times a day. Repeats still go out at DEBUG, and the next loud line says how
10
+ * many there were.
11
+ */
12
+ import { redactTruncate } from "./codex-redact.ts";
13
+
14
+ const REPEAT_WINDOW_MS = 60 * 60 * 1000;
15
+ /** Distinct (account, message) pairs remembered; the oldest is dropped past this. */
16
+ const MAX_TRACKED = 256;
17
+ /** codex's tracing prefix, e.g. `2026-11-14T13:46:02.779305Z `, which differs on every line. */
18
+ const TRACE_TIMESTAMP = /^\d{4}-\d\d-\d\dT[\d:.]+Z\s+/;
19
+
20
+ interface Seen { at: number; repeats: number }
21
+ const seen = new Map<string, Seen>();
22
+
23
+ export interface CodexStderrLogLine {
24
+ level: "warn" | "debug";
25
+ message: string;
26
+ /** The redacted line, for the client's exit message. */
27
+ text: string;
28
+ }
29
+
30
+ /** The short name of the login a CODEX_HOME belongs to, for log lines. */
31
+ export function codexLoginTag(codexHome: string | undefined): string {
32
+ if (!codexHome) return "ambient";
33
+ const parts = codexHome.split(/[\\/]/).filter(Boolean);
34
+ return (parts[parts.length - 1] ?? "unknown").slice(0, 8);
35
+ }
36
+
37
+ /**
38
+ * Null for a line not worth logging at all. `account` comes from {@link codexLoginTag}.
39
+ *
40
+ * `fold` is for the short-lived control spawns (usage sweep, model and skill lists), which
41
+ * repeat the same failure on a timer. A chat's error is always logged loudly: it may be the
42
+ * only record of why that one chat failed, whatever another chat said earlier.
43
+ */
44
+ export function codexStderrLogLine(account: string, line: string, now = Date.now(), fold = true): CodexStderrLogLine | null {
45
+ const s = line.trim();
46
+ if (!s || /warning|trace-warnings|circular dependency/i.test(s)) return null;
47
+ // codex's stderr is Rust tracing ("<time> ERROR codex_x::y: …"), so its own level decides
48
+ // ours: a failed cache write is not a PPM ERROR. An untagged line is `bun x` resolving
49
+ // the package unless it reads like a failure.
50
+ const tag = /^(?:\S+\s+)?(ERROR|WARN|INFO|DEBUG|TRACE)\b/.exec(s)?.[1];
51
+ const loud = tag ? tag === "ERROR" || tag === "WARN" : /error|panic|fatal|fail/i.test(s);
52
+ const text = redactTruncate(s, 200);
53
+ const prefix = `stderr account=${account}: `;
54
+ if (!loud) return { level: "debug", message: prefix + text, text };
55
+ if (!fold) return { level: "warn", message: prefix + text, text };
56
+
57
+ const key = `${account}\0${text.replace(TRACE_TIMESTAMP, "")}`;
58
+ const prev = seen.get(key);
59
+ if (prev && now - prev.at < REPEAT_WINDOW_MS) {
60
+ prev.repeats++;
61
+ return { level: "debug", message: prefix + text, text };
62
+ }
63
+ seen.delete(key);
64
+ if (seen.size >= MAX_TRACKED) seen.delete(seen.keys().next().value!);
65
+ seen.set(key, { at: now, repeats: 0 });
66
+ const more = prev?.repeats
67
+ ? ` (seen ${prev.repeats} more time${prev.repeats === 1 ? "" : "s"} since ${new Date(prev.at).toISOString()})`
68
+ : "";
69
+ return { level: "warn", message: prefix + text + more, text };
70
+ }
71
+
72
+ /** Test seam: forget which lines were already logged. */
73
+ export function _resetCodexStderrLogForTesting(): void {
74
+ seen.clear();
75
+ }
@@ -4,7 +4,9 @@ import { AMBIENT_ACCOUNT_KEY } from "../../services/provider-usage/usage-source.
4
4
  import { listCodexAccounts, getCodexAccount } from "../../services/codex-account.service.ts";
5
5
  import { fetchCodexUsageLive } from "./codex-usage-fetch.ts";
6
6
  import { isCodexAuthFailure } from "./codex-auth-failure.ts";
7
- import { markCodexAccountAuthFailed, clearCodexAccountAuthFailure } from "../../services/codex-account-auth-state.ts";
7
+ import {
8
+ markCodexAccountAuthFailed, clearCodexAccountAuthFailure, isCodexAccountAuthRecheckPending,
9
+ } from "../../services/codex-account-auth-state.ts";
8
10
 
9
11
  /**
10
12
  * Codex's plug into the shared usage layer.
@@ -21,6 +23,12 @@ export const codexUsageSource: ProviderUsageSource = {
21
23
  return listCodexAccounts().map((a) => a.id);
22
24
  },
23
25
 
26
+ // A signed-out account is read again on a widening interval rather than on every sweep:
27
+ // each read spawns an app-server that only repeats the refusal. Its last reading stays.
28
+ shouldSkip(accountId: string): boolean {
29
+ return accountId !== AMBIENT_ACCOUNT_KEY && isCodexAccountAuthRecheckPending(accountId);
30
+ },
31
+
24
32
  async fetch(accountId: string): Promise<UsageInfo> {
25
33
  // No managed accounts configured — read whatever login `~/.codex` holds.
26
34
  if (accountId === AMBIENT_ACCOUNT_KEY) return fetchCodexUsageLive();
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Which SDK background tasks are running in a session's subprocess, keyed by the SDK's own task id.
3
+ *
4
+ * The CLI reports every task it runs past a tool call (a backgrounded Agent, a background Bash, an
5
+ * agent woken again by `SendMessage`) with `task_started`, and its end with a terminal status on
6
+ * `task_updated` / `task_notification`. Reading liveness from those, rather than from the text of
7
+ * the tool result that launched the task, is what covers an agent resumed by `SendMessage`: its
8
+ * result says "Resuming agent …", not the launch acknowledgement, and the task id is one that
9
+ * already ended once. Missing it let the token rotation close the CLI under a reviewer still at
10
+ * work, which killed the reviewer and left the chat waiting for a notification that never came.
11
+ *
12
+ * Kept free of the chat layer so the bookkeeping can be tested on its own; `chat.ts` owns the
13
+ * state on each session entry.
14
+ */
15
+
16
+ /** Statuses after which a task is no longer running. */
17
+ const TERMINAL_TASK_STATUSES = new Set(["completed", "failed", "stopped", "killed"]);
18
+
19
+ /**
20
+ * How long after the subprocess last showed signs of background work (a subagent's own events, a
21
+ * task progress tick) the token rotation still leaves it alone. A safety net under the task
22
+ * tracking, for work the CLI runs without reporting a task: closing the subprocess kills that
23
+ * work silently, while waiting costs nothing, since an early renewal has two hours of slack.
24
+ */
25
+ export const BACKGROUND_EVENT_QUIET_MS = 3 * 60_000;
26
+
27
+ export interface BackgroundTaskState {
28
+ /** SDK task ids that have started and not yet reported a terminal status. */
29
+ runningTaskIds?: Set<string>;
30
+ /** When the subprocess last emitted a subagent event or a task progress tick (ms epoch). */
31
+ lastBackgroundEventAt?: number;
32
+ }
33
+
34
+ export function isTerminalTaskStatus(status: string | undefined): boolean {
35
+ return !!status && TERMINAL_TASK_STATUSES.has(status);
36
+ }
37
+
38
+ /**
39
+ * Fold one `task_*` system event into the state. A `task_started` marks the task running even if
40
+ * it already ended once, which is what an agent resumed by `SendMessage` looks like; a terminal
41
+ * status on any of the three ends it. Returns whether the set of running tasks changed.
42
+ */
43
+ export function noteTaskEvent(
44
+ state: BackgroundTaskState,
45
+ subtype: string,
46
+ taskId: string | undefined,
47
+ status: string | undefined,
48
+ ): boolean {
49
+ if (!taskId) return false;
50
+ if (isTerminalTaskStatus(status)) return state.runningTaskIds?.delete(taskId) ?? false;
51
+ if (subtype !== "task_started") return false;
52
+ const running = (state.runningTaskIds ??= new Set());
53
+ if (running.has(taskId)) return false;
54
+ running.add(taskId);
55
+ return true;
56
+ }
57
+
58
+ export function hasRunningTasks(state: BackgroundTaskState): boolean {
59
+ return (state.runningTaskIds?.size ?? 0) > 0;
60
+ }
61
+
62
+ /** Record that the subprocess just showed background activity. */
63
+ export function noteBackgroundEvent(state: BackgroundTaskState, now = Date.now()): void {
64
+ state.lastBackgroundEventAt = now;
65
+ }
66
+
67
+ /** Whether background activity was seen within the quiet window. */
68
+ export function backgroundEventRecent(
69
+ state: BackgroundTaskState,
70
+ now = Date.now(),
71
+ quietMs = BACKGROUND_EVENT_QUIET_MS,
72
+ ): boolean {
73
+ return state.lastBackgroundEventAt != null && now - state.lastBackgroundEventAt < quietMs;
74
+ }
75
+
76
+ /**
77
+ * Forget every task: the subprocess that ran them is gone, so nothing it started is still
78
+ * running. Without this, a task whose end was never reported would keep the session busy forever.
79
+ */
80
+ export function clearBackgroundTasks(state: BackgroundTaskState): void {
81
+ state.runningTaskIds?.clear();
82
+ state.lastBackgroundEventAt = undefined;
83
+ }
@@ -35,6 +35,13 @@ export interface LiveSubprocess {
35
35
  credential: SubprocessCredential;
36
36
  /** A turn, an approval or background work is running in it — dropping it would lose work. */
37
37
  busy: boolean;
38
+ /**
39
+ * Not busy, but showed background activity a moment ago: renewing now would revoke the token
40
+ * work it runs without reporting may still need, so the early renewal waits. Unlike `busy` it
41
+ * never keeps a subprocess on a token already replaced — that token is revoked, and whatever
42
+ * still runs on it fails at its next request either way.
43
+ */
44
+ holdRenewal?: boolean;
38
45
  }
39
46
 
40
47
  export interface RenewalCandidate {
@@ -44,7 +51,7 @@ export interface RenewalCandidate {
44
51
  renewable: boolean;
45
52
  }
46
53
 
47
- /** Accounts to renew now: in use by some subprocess, near expiry, and busy in none. */
54
+ /** Accounts to renew now: in use by some subprocess, near expiry, and busy or holding in none. */
48
55
  export function accountsToRenewNow(candidates: RenewalCandidate[], live: LiveSubprocess[], nowS: number): string[] {
49
56
  const inUse = new Set<string>();
50
57
  const busy = new Set<string>();
@@ -52,7 +59,7 @@ export function accountsToRenewNow(candidates: RenewalCandidate[], live: LiveSub
52
59
  const id = p.credential.accountId;
53
60
  if (!id || !p.credential.oauthToken) continue;
54
61
  inUse.add(id);
55
- if (p.busy) busy.add(id);
62
+ if (p.busy || p.holdRenewal) busy.add(id);
56
63
  }
57
64
  return candidates
58
65
  .filter((c) => {
@@ -26,6 +26,14 @@ import { configService } from "../../services/config.service.ts";
26
26
  import { prefixTokens } from "../../shared/turn-usage.ts";
27
27
  import type { PromptCacheState } from "../../shared/prompt-cache-idle.ts";
28
28
  import { isAsyncAgentLaunchAck, isTerminalAgentStatus } from "../../shared/background-agent-status.ts";
29
+ import {
30
+ backgroundEventRecent,
31
+ clearBackgroundTasks,
32
+ hasRunningTasks,
33
+ noteBackgroundEvent,
34
+ noteTaskEvent,
35
+ type BackgroundTaskState,
36
+ } from "./chat-background-tasks.ts";
29
37
  import { cacheReleaseDelayMs, selectWarmIdleEvictions } from "../../services/subprocess-retention.ts";
30
38
  import { needsAuthServerNames } from "../../services/mcp-oauth/mcp-oauth-redirect.ts";
31
39
  import { mcpStatusEvent, registerMcpSignInSync } from "./chat-mcp-sign-in-sync.ts";
@@ -299,7 +307,7 @@ export function chatSocketData(sessionId: string, projectName: string, query: UR
299
307
  };
300
308
  }
301
309
 
302
- export interface SessionEntry {
310
+ export interface SessionEntry extends BackgroundTaskState {
303
311
  providerId: string;
304
312
  clients: Set<ChatWsSocket>;
305
313
  projectPath?: string;
@@ -633,9 +641,16 @@ export function dropIdleSubprocess(sessionId: string, reason: string, note: stri
633
641
  log.info(`session=${sessionId} released subprocess (${reason}): ${note}`);
634
642
  }
635
643
 
636
- /** Whether a background agent or shell the session started is still running in its subprocess. */
644
+ /**
645
+ * Whether a background agent or shell the session started is still running in its subprocess.
646
+ * The SDK's own task lifecycle is the primary signal (`chat-background-tasks.ts`): it is the only
647
+ * one that sees an agent resumed by `SendMessage`. The launch-ack set and the shell registry stay
648
+ * as well, since each was the only signal for its kind of work before.
649
+ */
637
650
  export function hasBackgroundWork(sessionId: string): boolean {
638
- if ((activeSessions.get(sessionId)?.backgroundToolUseIds?.size ?? 0) > 0) return true;
651
+ const entry = activeSessions.get(sessionId);
652
+ if (entry && hasRunningTasks(entry)) return true;
653
+ if ((entry?.backgroundToolUseIds?.size ?? 0) > 0) return true;
639
654
  return backgroundShellRegistry.list(sessionId).some((sh) => sh.status !== "stopped");
640
655
  }
641
656
 
@@ -791,7 +806,10 @@ const tokenRotationDeps: TokenRotationDeps = {
791
806
  // `idle` with `isStreamingActive` still set. A subprocess with no entry here belongs to
792
807
  // something else (a scheduled run) and is never ours to judge idle.
793
808
  const busy = !entry || entry.phase !== "idle" || !!entry.pendingApprovalEvent || hasBackgroundWork(sessionId);
794
- return { sessionId, credential, busy };
809
+ // A renewal revokes the token and can wait, so it also holds off while the CLI is still
810
+ // emitting background events: the safety net for work it runs without reporting a task.
811
+ const holdRenewal = !!entry && !busy && backgroundEventRecent(entry);
812
+ return { sessionId, credential, busy, holdRenewal };
795
813
  });
796
814
  },
797
815
  dropIdle: (sessionId) => dropIdleSubprocess(
@@ -1563,6 +1581,7 @@ async function startSessionConsumer(sessionId: string, providerId: string, conte
1563
1581
  // Child streams can outlive the root turn. Their content and terminal
1564
1582
  // events belong to the Agent card, never to the root turn's lifecycle.
1565
1583
  if (ev.parentToolUseId) {
1584
+ noteBackgroundEvent(entry);
1566
1585
  emitNestedChild(sessionId, event);
1567
1586
  continue;
1568
1587
  }
@@ -1605,12 +1624,21 @@ async function startSessionConsumer(sessionId: string, providerId: string, conte
1605
1624
  entry.compactStatus = null;
1606
1625
  log.debug(`session=${sessionId} compact_status=done (via compact_boundary)`);
1607
1626
  broadcast(sessionId, { type: "compact_status", status: "done" });
1627
+ } else if (sub === "task_progress") {
1628
+ // One per step of a running task, still arriving after the turn that started it ended.
1629
+ // Not a timer: a task blocked on one long command sends none, which the task tracking covers.
1630
+ noteBackgroundEvent(entry);
1608
1631
  } else if (sub === "task_started" || sub === "task_updated" || sub === "task_notification") {
1609
1632
  // Background command (local_bash) lifecycle. shellId === SDK task_id.
1610
1633
  const taskId = (ev as any).taskId as string | undefined;
1611
1634
  const taskStatus = (ev as any).taskStatus as string | undefined;
1612
1635
  const taskToolUseId = (ev as any).taskToolUseId as string | undefined;
1613
1636
  const outputFile = (ev as any).outputFile as string | undefined;
1637
+ // What the subprocess counts as running. An agent woken again by SendMessage appears
1638
+ // only here: its tool result is not the launch ack, and its task id already ended once.
1639
+ if (noteTaskEvent(entry, sub, taskId, taskStatus)) {
1640
+ bgShellLog.info(`session=${sessionId} task ${taskId} ${entry.runningTaskIds?.has(taskId!) ? "running" : `ended (${taskStatus})`} tasksRunning=${entry.runningTaskIds?.size ?? 0}`);
1641
+ }
1614
1642
  // A backgrounded Agent reports its outcome only here — its tool_result was a
1615
1643
  // launch ack the card must not read as "finished". Forward the terminal state so
1616
1644
  // the card can settle. Harmless for background bash tasks: no card matches them.
@@ -2054,6 +2082,10 @@ async function startSessionConsumer(sessionId: string, providerId: string, conte
2054
2082
  bashOutputSpy.stopAllForSession(sessionId);
2055
2083
  // SDK subprocess teardown kills its background children — reflect as stopped
2056
2084
  backgroundShellRegistry.markAllStopped(sessionId);
2085
+ // and forget the tasks and launches it was running, or one whose end never arrived would keep
2086
+ // the session busy (never released, never moved onto a renewed token) for good.
2087
+ clearBackgroundTasks(entry);
2088
+ entry.backgroundToolUseIds?.clear();
2057
2089
  broadcastBackgroundRegistry(sessionId);
2058
2090
  // Cleanup team watchers
2059
2091
  for (const w of entry.teamWatchers.values()) w.cleanup();
@@ -8,10 +8,16 @@ export interface CardPress {
8
8
  kind: "card";
9
9
  sessionId: string;
10
10
  requestId: string;
11
- /** allow/deny decide the card; pick answers a one-question card; toggle and send build a multi-choice answer. */
12
- op: "allow" | "deny" | "pick" | "toggle" | "send";
11
+ /**
12
+ * allow/deny decide the card. pick answers a one-question card at once; on a card asked one
13
+ * question at a time it records the choice and moves on. toggle ticks a choice of a question
14
+ * that takes several, next leaves it, back returns to the question before, send answers them all.
15
+ */
16
+ op: "allow" | "deny" | "pick" | "toggle" | "next" | "back" | "send";
13
17
  questionId?: string;
14
18
  option?: string;
19
+ /** back: the step the button was shown on, so a press left over from another step does nothing. */
20
+ step?: number;
15
21
  }
16
22
 
17
23
  /** A button on one of the PPM Assistant's own cards (a manager's report, a rules change). */
@@ -29,8 +29,14 @@ export class ButtonCodes<T> {
29
29
  /** A fresh code for `action`, as the button's `callback_data`. */
30
30
  mint(chatId: string, group: string, action: T): string {
31
31
  this.prune();
32
- // Oldest first out: a Map iterates in insertion order.
33
- while (this.codes.size >= MAX_CODES) this.codes.delete(this.codes.keys().next().value!);
32
+ // Oldest first out (a Map iterates in insertion order), a whole card at a time: a card left with
33
+ // some of its buttons — a step-by-step question card's first question gone, its Send still
34
+ // live — would be half usable, where one with none is plainly "no longer valid" everywhere.
35
+ while (this.codes.size >= MAX_CODES) {
36
+ const [code, held] = this.codes.entries().next().value!;
37
+ if (held.group === group) this.codes.delete(code);
38
+ else this.dropGroup(held.group);
39
+ }
34
40
  const code = randomBytes(12).toString("base64url");
35
41
  this.codes.set(code, { chatId, group, action, expiresAt: this.now() + CODE_TTL_MS });
36
42
  return `${CODE_PREFIX}${code}`;
@@ -55,6 +61,18 @@ export class ButtonCodes<T> {
55
61
  return found;
56
62
  }
57
63
 
64
+ /**
65
+ * Moves a group's codes to the newest end, so a card still being answered is the last whose
66
+ * buttons the store evicts when it is full (a step-by-step card makes all its codes up front).
67
+ */
68
+ touchGroup(group: string): void {
69
+ for (const [code, held] of [...this.codes]) {
70
+ if (held.group !== group) continue;
71
+ this.codes.delete(code);
72
+ this.codes.set(code, held);
73
+ }
74
+ }
75
+
58
76
  dropGroup(group: string): void {
59
77
  for (const [code, held] of this.codes) if (held.group === group) this.codes.delete(code);
60
78
  }
@@ -93,14 +93,20 @@ export function needsPpm(q: NormalizedQuestion): boolean {
93
93
  return q.secret === true || q.options.length === 0;
94
94
  }
95
95
 
96
+ /** User text inside a card: secrets hidden, then escaped. */
97
+ export const redactedHtml = (s: string): string => esc(redactSecretsForTelegram(s).text);
98
+
99
+ /** One question as a card shows it: the question, then every choice with its description. */
100
+ export function questionBlock(q: NormalizedQuestion): string[] {
101
+ const lines = [`${q.header ? `<b>${redactedHtml(q.header)}</b> — ` : ""}${redactedHtml(q.question)}${q.multiSelect ? " <i>(choose any)</i>" : ""}`];
102
+ for (const o of q.options) lines.push(`• ${redactedHtml(o.label)}${o.description ? ` — <i>${redactedHtml(o.description)}</i>` : ""}`);
103
+ if (needsPpm(q)) lines.push(`<i>${q.secret ? "This answer is private: give it in PPM." : "This needs a typed answer: give it in PPM."}</i>`);
104
+ return lines;
105
+ }
106
+
96
107
  export function formatQuestionCard(questions: readonly NormalizedQuestion[], headline: string): string {
97
108
  const lines = [`❓ <b>${esc(headline)}</b>`];
98
- for (const q of questions) {
99
- const red = (s: string) => esc(redactSecretsForTelegram(s).text);
100
- lines.push("", `${q.header ? `<b>${red(q.header)}</b> — ` : ""}${red(q.question)}${q.multiSelect ? " <i>(choose any)</i>" : ""}`);
101
- for (const o of q.options) lines.push(`• ${red(o.label)}${o.description ? ` — <i>${red(o.description)}</i>` : ""}`);
102
- if (needsPpm(q)) lines.push(`<i>${q.secret ? "This answer is private: give it in PPM." : "This needs a typed answer: give it in PPM."}</i>`);
103
- }
109
+ for (const q of questions) lines.push("", ...questionBlock(q));
104
110
  return lines.join("\n");
105
111
  }
106
112
 
@@ -120,7 +126,10 @@ export function resolutionLine(r: { approved: boolean; reason: string; by?: stri
120
126
  const where = r.by === "telegram" ? "here" : r.by === "assistant" ? "by the Assistant" : "in PPM";
121
127
  if (isQuestion) {
122
128
  if (!r.approved) return `<i>Skipped ${where}.</i>`;
123
- const answers = r.answers && typeof r.answers === "object" ? Object.values(r.answers as Record<string, unknown>).map(String) : [];
129
+ // A question that takes several choices answers with a list; it reads as "a, b", not "a,b".
130
+ const answers = r.answers && typeof r.answers === "object"
131
+ ? Object.values(r.answers as Record<string, unknown>).map((a) => (Array.isArray(a) ? a.map(String).join(", ") : String(a)))
132
+ : [];
124
133
  const shown = answers.length ? `: ${esc(redactSecretsForTelegram(answers.join("; ")).text.slice(0, 500))}` : "";
125
134
  return `<i>Answered ${where}${shown}</i>`;
126
135
  }
@@ -10,8 +10,9 @@
10
10
  * that chat's name and linking to it; their buttons answer that chat.
11
11
  *
12
12
  * Each card is a new message (an edit would not buzz the phone). Pressing Allow or Deny spends
13
- * every button of that card; a question with several choices keeps its buttons while choices are
14
- * ticked, until Send.
13
+ * every button of that card. A question card with more than one question, or one question that
14
+ * takes several choices, is asked one question at a time in that same message and answered only
15
+ * by Send on its summary (`assistant-telegram-question-wizard.ts`).
15
16
  */
16
17
  import { chatControl, type LiveApprovalCard } from "../chat-control/chat-control.ts";
17
18
  import type { ChatLifecycleEvents } from "../chat-control/chat-lifecycle.ts";
@@ -23,14 +24,18 @@ import type { CardPress } from "./assistant-telegram-actions.ts";
23
24
  import type { BridgeCards, BridgeDeps } from "./assistant-telegram.service.ts";
24
25
  import { formatApprovalCard, formatQuestionCard, needsPpm, resolutionLine } from "./assistant-telegram-card-format.ts";
25
26
  import { placeLink } from "./assistant-telegram-links.ts";
26
- import { outcomeOf, sendMessageTask } from "./assistant-telegram-send-queue.ts";
27
+ import {
28
+ EARLIER_STEP, applyWizardPress, asksStepByStep, buttonLabel, mintWizardCodes, questionListHtml, wizardStepHtml, wizardStepRows,
29
+ wizardWorstCaseSteps, type Mint, type Selection, type WizardState,
30
+ } from "./assistant-telegram-question-wizard.ts";
31
+ import { BUTTON_URL_INVALID, EDIT_INTERVAL_MS, outcomeOf, sendMessageTask } from "./assistant-telegram-send-queue.ts";
32
+ import type { TelegramBotClient } from "../telegram/telegram-bot-client.ts";
27
33
  import { createLogger } from "../logger.ts";
28
34
 
29
35
  const log = createLogger("assistant-telegram");
30
36
 
31
37
  /** Room left under Telegram's 4096 for the link line under a card. */
32
38
  const CARD_VISIBLE_MAX = 3900;
33
- const LABEL_MAX = 60;
34
39
  const CARD_TITLE_MAX = 80;
35
40
 
36
41
  /** A card of a chat other than the Assistant's own, and where that chat lives. */
@@ -77,25 +82,24 @@ interface ShownCard {
77
82
  sessionId: string;
78
83
  requestId: string;
79
84
  group: string;
85
+ /** What it says once it is no longer waiting; on a card shown in one step, also what it says until then. */
80
86
  html: string;
81
87
  isQuestion: boolean;
82
88
  questions: NormalizedQuestion[];
83
- /** Ticked choices of a card answered with Send. */
84
- selection: Map<string, string[]>;
85
- /** The buttons as last sent, rebuilt when a tick changes. */
86
- rows: (selection: Map<string, string[]>) => InlineKeyboardButton[][];
89
+ /** Choices picked or ticked on a card asked step by step, sent together by Send. */
90
+ selection: Selection;
91
+ /** A card asked one question at a time: the step it is on (`questions.length` is the summary). */
92
+ wizard: WizardState | null;
93
+ /** Its text and buttons as they stand now. */
94
+ view: () => { html: string; rows: InlineKeyboardButton[][] };
95
+ /** Telegram refused the Open in PPM button: the card carries the link in its text instead. */
96
+ linkRefused: boolean;
87
97
  messageId: number | null;
88
98
  done: boolean;
89
99
  /** Why it is no longer waiting, shown under it once it is done. */
90
100
  endLine: string | null;
91
101
  }
92
102
 
93
- /** A button's text: plain, so not escaped, but redacted like everything else sent. */
94
- const label = (raw: string) => {
95
- const s = redactForTelegram(raw);
96
- return s.length > LABEL_MAX ? `${s.slice(0, LABEL_MAX - 1)}…` : s;
97
- };
98
-
99
103
  export class AssistantTelegramCards implements BridgeCards {
100
104
  private readonly cards = new Map<string, ShownCard>();
101
105
 
@@ -145,7 +149,8 @@ export class AssistantTelegramCards implements BridgeCards {
145
149
  const questions = p.card.isQuestion ? p.card.questions ?? [] : [];
146
150
  const card: ShownCard = {
147
151
  chatId, sessionId: p.sessionId, requestId: p.card.requestId, group, html: "", isQuestion: p.card.isQuestion,
148
- questions, selection: new Map(), rows: () => [], messageId: null, done: false, endLine: null,
152
+ questions, selection: new Map(), wizard: null, view: () => ({ html: card.html, rows: [] }), linkRefused: false,
153
+ messageId: null, done: false, endLine: null,
149
154
  };
150
155
  // Registered before the link is looked up, so a card answered meanwhile is known to be done.
151
156
  this.cards.set(key, card);
@@ -154,10 +159,19 @@ export class AssistantTelegramCards implements BridgeCards {
154
159
  this.cards.delete(key);
155
160
  return;
156
161
  }
157
- const mint = (press: Omit<CardPress, "kind" | "sessionId" | "requestId">) =>
162
+ const mint: Mint = (press) =>
158
163
  this.deps.codes.mint(chatId, group, { kind: "card", sessionId: p.sessionId, requestId: p.card.requestId, ...press });
159
164
 
160
- let rows: ShownCard["rows"] = () => [];
165
+ const inlineLink = link.inline ? `\n\n${link.inline}` : "";
166
+ const linkRow = link.button ? [[link.button]] : [];
167
+ // Telegram refusing the link as a button: the link goes in the text instead.
168
+ const linkText = link.button ? `\n\n${escapeTelegramHtml(link.button.text)}: ${escapeTelegramHtml(link.button.url!)}` : "";
169
+ /** What the link adds to the text at most, whichever way it ends up shown. */
170
+ const linkRoom = Math.max(visibleLength(inlineLink), visibleLength(linkText));
171
+
172
+ let rows: () => InlineKeyboardButton[][] = () => [];
173
+ /** A step-by-step card's current step; anything else shows `card.html` throughout. */
174
+ let stepHtml: (() => string) | null = null;
161
175
  if (how.titleOnly !== undefined) {
162
176
  // The project keeps its details off the phone: the title, and nothing that acts on the rest.
163
177
  const headline = card.isQuestion ? how.questionHeadline : how.approvalHeadline;
@@ -167,9 +181,27 @@ export class AssistantTelegramCards implements BridgeCards {
167
181
  rows = () => [deny];
168
182
  }
169
183
  } else if (card.isQuestion) {
170
- card.html = formatQuestionCard(questions, how.questionHeadline);
171
- if (visibleLength(card.html) > CARD_VISIBLE_MAX) card.html = `❓ <b>${escapeTelegramHtml(how.questionHeadline)}</b>\nThis question is too long to show here — answer it in PPM.`;
172
- else if (questions.length > 0 && !questions.some(needsPpm)) rows = questionRows(questions, mint);
184
+ const headline = how.questionHeadline;
185
+ const tooLong = `❓ <b>${escapeTelegramHtml(headline)}</b>\nThis question is too long to show here — answer it in PPM.`;
186
+ const answerable = questions.length > 0 && !questions.some(needsPpm);
187
+ if (answerable && asksStepByStep(questions)) {
188
+ if (wizardWorstCaseSteps(questions, headline).some((h) => visibleLength(h) + linkRoom > CARD_VISIBLE_MAX)) {
189
+ card.html = tooLong;
190
+ } else {
191
+ const codes = mintWizardCodes(questions, mint);
192
+ const wizard = { step: 0, codes };
193
+ card.wizard = wizard;
194
+ card.html = questionListHtml(questions, headline);
195
+ if (visibleLength(card.html) > CARD_VISIBLE_MAX) card.html = `❓ <b>${escapeTelegramHtml(headline)}</b>`;
196
+ stepHtml = () => wizardStepHtml(questions, wizard.step, card.selection, headline);
197
+ rows = () => wizardStepRows(questions, wizard.step, card.selection, codes);
198
+ }
199
+ } else {
200
+ // One question, one choice — or a question only PPM can take, shown whole with no buttons.
201
+ card.html = formatQuestionCard(questions, headline);
202
+ if (visibleLength(card.html) > CARD_VISIBLE_MAX) card.html = tooLong;
203
+ else if (answerable) rows = singlePickRows(questions[0]!, mint);
204
+ }
173
205
  } else {
174
206
  // The deciding part is capped well under Telegram's limit, so the card always fits.
175
207
  const formatted = formatApprovalCard(p.card, how.approvalHeadline);
@@ -180,21 +212,29 @@ export class AssistantTelegramCards implements BridgeCards {
180
212
  ];
181
213
  rows = () => [buttons];
182
214
  }
183
- if (link.inline) card.html += `\n\n${link.inline}`;
184
- const linkRow = link.button ? [[link.button]] : [];
185
- card.rows = (selection) => [...rows(selection), ...linkRow];
215
+ card.html += inlineLink;
216
+ card.view = () => {
217
+ const html = stepHtml ? stepHtml() + inlineLink : card.html;
218
+ return card.linkRefused ? { html: html + linkText, rows: rows() } : { html, rows: [...rows(), ...linkRow] };
219
+ };
220
+ const first = card.view();
186
221
  this.deps.queue.enqueue(chatId, sendMessageTask(this.deps.queue, chatId, {
187
- html: card.html,
188
- markup: { inline_keyboard: card.rows(card.selection) },
189
- // Telegram refusing the link as a button: the link goes in the text instead.
190
- ...(link.button ? { fallbackHtml: `${card.html}\n\n${escapeTelegramHtml(link.button.text)}: ${escapeTelegramHtml(link.button.url!)}` } : {}),
222
+ html: first.html,
223
+ markup: { inline_keyboard: first.rows },
224
+ ...(link.button ? { fallbackHtml: first.html + linkText } : {}),
191
225
  }, {
192
226
  label: "approval card",
193
227
  onSent: (sent) => {
194
228
  card.messageId = sent.message_id;
229
+ // Sent again without its link button: every later step has to leave the button out too.
230
+ if (link.button && !sent.reply_markup?.inline_keyboard.flat().some((b) => b.url)) card.linkRefused = true;
195
231
  try { how.onSent?.(sent.message_id); } catch (e) { log.warn(`card ${card.requestId}: ${(e as Error).message}`); }
196
232
  if (card.done) this.finish(card);
197
- else this.deps.state.add(chatId, "cards", sent.message_id);
233
+ else {
234
+ this.deps.state.add(chatId, "cards", sent.message_id);
235
+ // Pressed on before Telegram said the message was there: it still shows the first step.
236
+ if (card.wizard && (card.wizard.step > 0 || card.selection.size > 0)) this.redraw(card);
237
+ }
198
238
  },
199
239
  onDropped: () => { this.cards.delete(key); this.deps.codes.dropGroup(group); },
200
240
  }));
@@ -220,7 +260,12 @@ export class AssistantTelegramCards implements BridgeCards {
220
260
  this.deps.codes.dropGroup(group);
221
261
  return "This card is no longer waiting.";
222
262
  }
223
- if (press.op === "toggle") return this.toggle(card, press);
263
+ if (card.wizard && press.op !== "send" && press.op !== "allow" && press.op !== "deny") return this.step(card, card.wizard, press);
264
+ if (press.op === "toggle" || press.op === "next" || press.op === "back") return "This button is no longer valid.";
265
+ if (press.op === "send" && card.wizard?.step !== card.questions.length) {
266
+ if (card.wizard) this.redraw(card);
267
+ return EARLIER_STEP;
268
+ }
224
269
  let answer: { approved: boolean; answersById?: AnswersById };
225
270
  if (press.op === "allow" || press.op === "deny") {
226
271
  answer = { approved: press.op === "allow" };
@@ -243,27 +288,52 @@ export class AssistantTelegramCards implements BridgeCards {
243
288
  return press.op === "deny" ? "Denied." : press.op === "allow" ? "Allowed." : "Answer sent.";
244
289
  }
245
290
 
246
- private toggle(card: ShownCard, press: CardPress): string {
247
- const q = card.questions.find((x) => x.id === press.questionId);
248
- if (!q || !press.option) return "This button is no longer valid.";
249
- const now = card.selection.get(q.id) ?? [];
250
- const on = !now.includes(press.option);
251
- const next = q.multiSelect ? (on ? [...now, press.option] : now.filter((o) => o !== press.option)) : on ? [press.option] : [];
252
- if (next.length) card.selection.set(q.id, next);
253
- else card.selection.delete(q.id);
291
+ /**
292
+ * A press on a step-by-step card that does not answer it: records a choice or moves between
293
+ * questions (`applyWizardPress`), then redraws the message — also after a press left over from
294
+ * another step, which changes nothing but says the message is behind the card.
295
+ */
296
+ private step(card: ShownCard, wizard: WizardState, press: CardPress): string {
297
+ // A card in use keeps its buttons longest when the code store is full.
298
+ this.deps.codes.touchGroup(card.group);
299
+ const { toast, redraw } = applyWizardPress(card.questions, wizard, card.selection, press);
300
+ if (redraw) this.redraw(card);
301
+ return toast;
302
+ }
303
+
304
+ /**
305
+ * Edits the card's message to its current step. Queued under one key per card, so presses
306
+ * faster than Telegram takes edits become one edit, drawn from the card as it is when it runs.
307
+ */
308
+ private redraw(card: ShownCard): void {
254
309
  const messageId = card.messageId;
255
- if (messageId !== null) {
256
- const markup = { inline_keyboard: card.rows(card.selection) };
257
- this.deps.queue.enqueue(card.chatId, {
258
- key: `ticks:${card.group}`, final: false, label: "card ticks",
259
- run: async (client) => {
260
- if (card.done) return { kind: "done" };
261
- const res = await client.editMessageReplyMarkup(card.chatId, messageId, markup);
262
- return res.ok ? { kind: "done" } : { kind: "failed", why: `${res.errorCode} ${res.description}` };
263
- },
264
- });
265
- }
266
- return on ? "Ticked." : "Unticked.";
310
+ if (messageId === null) return;
311
+ let attempts = 0;
312
+ this.deps.queue.enqueue(card.chatId, {
313
+ key: `step:${card.group}`, final: true, label: "question step",
314
+ run: async (client: TelegramBotClient) => {
315
+ if (card.done) return { kind: "done" };
316
+ const view = card.view();
317
+ const res = await client.editMessageText(card.chatId, messageId, view.html, { replyMarkup: { inline_keyboard: view.rows } });
318
+ if (!res.ok && !("throttled" in res) && res.errorCode === 400 && BUTTON_URL_INVALID.test(res.description) && !card.linkRefused) {
319
+ card.linkRefused = true;
320
+ return { kind: "retry", afterMs: EDIT_INTERVAL_MS, why: "link button refused" };
321
+ }
322
+ return outcomeOf(res, ++attempts);
323
+ },
324
+ // Refused for good, or failing past the deadline: buttons that no longer match what the
325
+ // message says would only answer "from an earlier step", so the card ends here instead.
326
+ onDropped: () => this.giveUp(card),
327
+ });
328
+ }
329
+
330
+ /** Ends a card on Telegram that cannot be kept up to date there; it still waits in PPM. */
331
+ private giveUp(card: ShownCard): void {
332
+ if (card.done) return;
333
+ card.done = true;
334
+ card.endLine = "<i>This card could not be updated here — answer it in PPM.</i>";
335
+ this.deps.codes.dropGroup(card.group);
336
+ this.finish(card);
267
337
  }
268
338
 
269
339
  /** Takes the card's buttons away and says why it is no longer waiting (once it was sent). */
@@ -285,27 +355,10 @@ export class AssistantTelegramCards implements BridgeCards {
285
355
  }
286
356
  }
287
357
 
288
- type Mint = (press: Omit<CardPress, "kind" | "sessionId" | "requestId">) => string;
289
-
290
- /**
291
- * One question with one choice: a button per option answers at once. Anything else: buttons
292
- * tick choices (✓) and Send answers them all, so nothing is sent half-answered.
293
- */
294
- function questionRows(questions: readonly NormalizedQuestion[], mint: Mint): (s: Map<string, string[]>) => InlineKeyboardButton[][] {
295
- if (questions.length === 1 && !questions[0]!.multiSelect) {
296
- const q = questions[0]!;
297
- const rows = q.options.map((o) => [{ text: label(o.label), callback_data: mint({ op: "pick", questionId: q.id, option: o.label }) }]);
298
- return () => rows;
299
- }
300
- const codes = questions.map((q) => q.options.map((o) => ({ q, o, data: mint({ op: "toggle", questionId: q.id, option: o.label }) })));
301
- const send = mint({ op: "send" });
302
- return (selection) => [
303
- ...codes.flat().map(({ q, o, data }) => [{
304
- text: `${selection.get(q.id)?.includes(o.label) ? "✓ " : ""}${questions.length > 1 ? `${label(q.header ?? q.id)}: ` : ""}${label(o.label)}`,
305
- callback_data: data,
306
- }]),
307
- [{ text: "Send", callback_data: send }],
308
- ];
358
+ /** One question with one choice: a button per option answers it at once. */
359
+ function singlePickRows(q: NormalizedQuestion, mint: Mint): () => InlineKeyboardButton[][] {
360
+ const rows = q.options.map((o) => [{ text: buttonLabel(o.label), callback_data: mint({ op: "pick", questionId: q.id, option: o.label }) }]);
361
+ return () => rows;
309
362
  }
310
363
 
311
364
  /** What Telegram counts against its limit: the text after the markup is parsed. */
@@ -0,0 +1,185 @@
1
+ /**
2
+ * A question card asked one question at a time, inside one Telegram message.
3
+ *
4
+ * Several questions in one message, with every choice of every question in one column of buttons,
5
+ * left a phone with buttons whose question was cut off — nobody could tell which button answered
6
+ * what. So a card with more than one question, or one question that takes several choices, shows
7
+ * only the question being asked ("Question 2/3", the question, its choices and their
8
+ * descriptions) with that question's buttons under it, each naming its whole choice. Picking a
9
+ * single choice moves on; a question that takes several ticks choices (✓) and moves on with Next;
10
+ * Back returns to the question before. After the last question comes a summary of every answer
11
+ * with Send and Back, and only Send answers the card — all questions at once, never part of them.
12
+ *
13
+ * Moving between steps edits the same message (text and buttons), so the chat does not fill up
14
+ * with one message per question. Every button's code is made once, when the card is shown: the
15
+ * steps only choose which of them to show.
16
+ *
17
+ * This module only draws; `assistant-telegram-cards.ts` holds the state and answers the presses.
18
+ */
19
+ import type { NormalizedQuestion } from "../../shared/approval-questions.ts";
20
+ import type { InlineKeyboardButton } from "../telegram/telegram-types.ts";
21
+ import { redactForTelegram } from "../telegram/telegram-html-format.ts";
22
+ import { escapeTelegramHtml } from "../notification-format.ts";
23
+ import { questionBlock } from "./assistant-telegram-card-format.ts";
24
+ import type { CardPress } from "./assistant-telegram-actions.ts";
25
+
26
+ const LABEL_MAX = 60;
27
+ /** How much of a question the summary repeats, and of its answers. */
28
+ const SUMMARY_QUESTION_MAX = 200;
29
+ const SUMMARY_ANSWER_MAX = 300;
30
+
31
+ export type Mint = (press: Omit<CardPress, "kind" | "sessionId" | "requestId">) => string;
32
+
33
+ /** The ticked or picked choices so far, by question id. */
34
+ export type Selection = Map<string, string[]>;
35
+
36
+ /** User text in a card, cut to `max`: secrets hidden before the cut, so a cut cannot split one. */
37
+ const shortHtml = (raw: string, max: number) =>
38
+ escapeTelegramHtml(cutChars(redactForTelegram(raw).trim().replace(/\n{3,}/g, "\n\n"), max));
39
+
40
+ /**
41
+ * Text cut to `max` characters with an ellipsis. Counted in characters, not UTF-16 units: half
42
+ * of an emoji is not valid text, and Telegram refusing it would leave the card stuck on a step.
43
+ */
44
+ function cutChars(text: string, max: number): string {
45
+ const chars = Array.from(text);
46
+ return chars.length <= max ? text : `${chars.slice(0, max - 1).join("").trimEnd()}…`;
47
+ }
48
+
49
+ /** A button's text: plain, so not escaped, but redacted like everything else sent. */
50
+ export function buttonLabel(raw: string): string {
51
+ return cutChars(redactForTelegram(raw), LABEL_MAX);
52
+ }
53
+
54
+ /** One question with one choice is answered with one press; anything else is asked step by step. */
55
+ export function asksStepByStep(questions: readonly NormalizedQuestion[]): boolean {
56
+ return !(questions.length === 1 && !questions[0]!.multiSelect);
57
+ }
58
+
59
+ /** Every button of a step-by-step card, made once. */
60
+ export interface WizardCodes {
61
+ /** [question][option]: a pick for a one-choice question, a toggle for one that takes several. */
62
+ choices: string[][];
63
+ /** [question]: Next, made only for questions that take several choices. */
64
+ next: (string | null)[];
65
+ /** [step]: Back, made for every step after the first (the summary is step `questions.length`). */
66
+ back: (string | null)[];
67
+ send: string;
68
+ }
69
+
70
+ /** Where a step-by-step card is: its step (`questions.length` is the summary) and its buttons. */
71
+ export interface WizardState {
72
+ step: number;
73
+ codes: WizardCodes;
74
+ }
75
+
76
+ export const EARLIER_STEP = "This button is from an earlier step.";
77
+ const INVALID = "This button is no longer valid.";
78
+
79
+ /**
80
+ * A press that does not answer the card: picks or ticks a choice, or moves between questions.
81
+ * Only a button of the step on screen counts. One left over from another step (a double tap while
82
+ * the message was being edited, or a message that fell behind) changes nothing, but asks for a
83
+ * redraw so the message catches up with the card.
84
+ */
85
+ export function applyWizardPress(
86
+ questions: readonly NormalizedQuestion[],
87
+ wizard: WizardState,
88
+ selection: Selection,
89
+ press: Pick<CardPress, "op" | "questionId" | "option" | "step">,
90
+ ): { toast: string; redraw: boolean } {
91
+ if (press.op === "back") {
92
+ if (press.step !== wizard.step || wizard.step === 0) return { toast: EARLIER_STEP, redraw: true };
93
+ wizard.step--;
94
+ return { toast: "Back.", redraw: true };
95
+ }
96
+ const q = questions[wizard.step];
97
+ if (!q || press.questionId !== q.id) return { toast: EARLIER_STEP, redraw: true };
98
+ const movedOn = () => {
99
+ wizard.step++;
100
+ return { toast: wizard.step < questions.length ? "Next question." : "Check your answers, then Send.", redraw: true };
101
+ };
102
+ if (press.op === "next") {
103
+ if (!q.multiSelect) return { toast: INVALID, redraw: false };
104
+ return selection.get(q.id)?.length ? movedOn() : { toast: "Tick at least one choice first.", redraw: false };
105
+ }
106
+ const option = q.options.find((o) => o.label === press.option)?.label;
107
+ if (option === undefined || (press.op !== "pick" && press.op !== "toggle") || (press.op === "pick") === q.multiSelect) {
108
+ return { toast: INVALID, redraw: false };
109
+ }
110
+ if (press.op === "pick") {
111
+ selection.set(q.id, [option]);
112
+ return movedOn();
113
+ }
114
+ const now = selection.get(q.id) ?? [];
115
+ const on = !now.includes(option);
116
+ // Kept in the order the choices are listed, whatever order they were ticked in.
117
+ const next = q.options.map((o) => o.label).filter((l) => (l === option ? on : now.includes(l)));
118
+ if (next.length) selection.set(q.id, next);
119
+ else selection.delete(q.id);
120
+ return { toast: on ? "Ticked." : "Unticked.", redraw: true };
121
+ }
122
+
123
+ export function mintWizardCodes(questions: readonly NormalizedQuestion[], mint: Mint): WizardCodes {
124
+ return {
125
+ choices: questions.map((q) => q.options.map((o) => mint({ op: q.multiSelect ? "toggle" : "pick", questionId: q.id, option: o.label }))),
126
+ next: questions.map((q) => (q.multiSelect ? mint({ op: "next", questionId: q.id }) : null)),
127
+ back: Array.from({ length: questions.length + 1 }, (_, step) => (step > 0 ? mint({ op: "back", step }) : null)),
128
+ send: mint({ op: "send" }),
129
+ };
130
+ }
131
+
132
+ /** A question as the summary repeats it. */
133
+ const asked = (q: NormalizedQuestion) => (q.header ? `${q.header} — ${q.question}` : q.question);
134
+
135
+ /** The text of one step: a question (step < questions.length), or the summary. */
136
+ export function wizardStepHtml(questions: readonly NormalizedQuestion[], step: number, selection: Selection, headline: string): string {
137
+ const lines = [`❓ <b>${escapeTelegramHtml(headline)}</b>`];
138
+ const q = questions[step];
139
+ if (q) {
140
+ lines.push(`<b>Question ${step + 1}/${questions.length}</b>`, "", ...questionBlock(q));
141
+ return lines.join("\n");
142
+ }
143
+ lines.push("<b>Your answers</b> — check them, then Send.");
144
+ questions.forEach((x, i) => {
145
+ const answer = selection.get(x.id)?.join(", ");
146
+ lines.push("", `${i + 1}. ${shortHtml(asked(x), SUMMARY_QUESTION_MAX)}`, answer ? `→ <b>${shortHtml(answer, SUMMARY_ANSWER_MAX)}</b>` : "→ <i>not answered</i>");
147
+ });
148
+ return lines.join("\n");
149
+ }
150
+
151
+ /** The buttons of one step. */
152
+ export function wizardStepRows(questions: readonly NormalizedQuestion[], step: number, selection: Selection, codes: WizardCodes): InlineKeyboardButton[][] {
153
+ const back = codes.back[step] ? [{ text: "« Back", callback_data: codes.back[step]! }] : [];
154
+ const q = questions[step];
155
+ if (!q) return [[...back, { text: "Send", callback_data: codes.send }]];
156
+ const chosen = selection.get(q.id) ?? [];
157
+ const rows: InlineKeyboardButton[][] = q.options.map((o, i) => [{
158
+ text: `${chosen.includes(o.label) ? "✓ " : ""}${buttonLabel(o.label)}`,
159
+ callback_data: codes.choices[step]![i]!,
160
+ }]);
161
+ const next = codes.next[step] ? [{ text: "Next »", callback_data: codes.next[step]! }] : [];
162
+ if (back.length || next.length) rows.push([...back, ...next]);
163
+ return rows;
164
+ }
165
+
166
+ /**
167
+ * What the message says once the card is no longer waiting: the questions, numbered, without
168
+ * their choices — the line under it says how it ended and what was answered.
169
+ */
170
+ export function questionListHtml(questions: readonly NormalizedQuestion[], headline: string): string {
171
+ const lines = [`❓ <b>${escapeTelegramHtml(headline)}</b>`];
172
+ questions.forEach((q, i) => {
173
+ lines.push(`${i + 1}. ${shortHtml(asked(q), SUMMARY_QUESTION_MAX)}`);
174
+ });
175
+ return lines.join("\n");
176
+ }
177
+
178
+ /**
179
+ * The longest each step can get, for the length check made before the card is shown: every
180
+ * question as it is, and the summary with every choice of every question picked.
181
+ */
182
+ export function wizardWorstCaseSteps(questions: readonly NormalizedQuestion[], headline: string): string[] {
183
+ const all: Selection = new Map(questions.map((q) => [q.id, q.options.map((o) => o.label)]));
184
+ return Array.from({ length: questions.length + 1 }, (_, step) => wizardStepHtml(questions, step, all, headline));
185
+ }
@@ -163,7 +163,7 @@ export class AssistantTelegramSendQueue {
163
163
  }
164
164
 
165
165
  /** A button Telegram refused for its URL: the message is sent again without URL buttons. */
166
- const BUTTON_URL_INVALID = /BUTTON_URL_INVALID|wrong http url|unsupported url protocol/i;
166
+ export const BUTTON_URL_INVALID = /BUTTON_URL_INVALID|wrong http url|unsupported url protocol/i;
167
167
 
168
168
  /**
169
169
  * A task that sends one new message. `fallbackHtml` replaces the text when Telegram refuses a URL
@@ -15,4 +15,4 @@
15
15
  - **Restart semantics are the old ones, on purpose**: commands used to live in `ppm.service` and die with it (`KillMode=mixed`); now they live outside it. So `gracefulShutdown` stops every `ppmcmd-*` scope and the startup pass stops those left by a server that died without one; units the agent made itself survive a restart, as they always did. The startup pass ignores "busy": it runs in the same tick routing is switched on, so nothing in a slice can be this server's yet.
16
16
  - **`systemctl stop a b c` stops none of them when any one is gone**: systemd 262 answers "Failed to enqueue jobs: Unit … not loaded." (exit 5) whatever the order, and a command scope ending between the cgroupfs listing and the stop is ordinary. So `stopUnits` and `stopCommandScopesSync` stop everything in one call and, when that fails, one unit at a time, taking exit 5 as "gone already". The shutdown test raced on exactly this — `agentUnit()`'s own `systemd-run` scope is still being torn down — and was red or green per run; the two "…gone already" tests make it deterministic with a `ppmcmd-*.scope` directory made in cgroupfs that systemd has no unit for.
17
17
  - **A fork's first CLI is untracked**: it resumes the source session under an id the CLI picks itself, so `chatSessionIdOf` returns nothing rather than filing its processes under the session it was forked from.
18
- - **A running background Bash task keeps its session busy**: `hasBackgroundWork` counts `run_in_background` shells, so a dev server started that way holds back the sweep of everything else the session left until the shell stops or the session entry is cleaned up. It is attached to the live CLI anyway, so the sweep would not stop it itself.
18
+ - **A running background task keeps its session busy**: `hasBackgroundWork` counts every task the CLI reports as started and not yet ended (`chat-background-tasks.ts`): `run_in_background` shells, backgrounded agents, an agent resumed by `SendMessage`, and shells a subagent started or the CLI moved to the background after its timeout. So a dev server started that way holds back the sweep of everything else the session left until the shell stops or the session entry is cleaned up. It is attached to the live CLI anyway, so the sweep would not stop it itself.
@@ -10,27 +10,49 @@
10
10
  * subprocess and ~24s of codex retrying before it says so. That is what let a burst of
11
11
  * proxy requests pin the server until the supervisor killed it.
12
12
  *
13
- * The mark lapses on its own so a misread error cannot bench an account forever, and the
14
- * usage sweep (every 5 minutes) renews it for as long as the account really is signed out.
15
- * A successful usage read, a completed turn or a fresh sign-in clears it at once.
13
+ * The usage sweep is what notices a signed-out account and keeps it benched, and it backs off
14
+ * while the account stays signed out: each refusal in a row doubles the wait before the next
15
+ * read (5, 10, 20, 40, then every 60 minutes). Reading a dead login every five minutes spawned
16
+ * an app-server for nothing and wrote the same refresh error into the log 288 times a day.
17
+ * The mark outlives the wait by `MARK_TTL_MS`, so the account stays benched between reads,
18
+ * yet a misread error still cannot bench an account forever. A successful usage read, a
19
+ * completed turn or a fresh sign-in clears it at once.
16
20
  */
17
21
 
18
22
  const MARK_TTL_MS = 15 * 60 * 1000;
23
+ const FIRST_RECHECK_MS = 5 * 60 * 1000;
24
+ const MAX_RECHECK_MS = 60 * 60 * 1000;
19
25
 
20
26
  interface AuthFailure {
21
27
  until: number;
22
28
  reason: string;
23
29
  since: number;
30
+ /** Refusals seen in a row, the first one included. */
31
+ strikes: number;
32
+ /** Before this, the background sweep leaves the account alone. */
33
+ recheckAt: number;
24
34
  }
25
35
 
26
36
  const failures = new Map<string, AuthFailure>();
27
37
 
38
+ /** The wait before the next background read after `strikes` refusals in a row. */
39
+ export function codexAuthRecheckDelayMs(strikes: number): number {
40
+ return Math.min(FIRST_RECHECK_MS * 2 ** Math.max(0, strikes - 1), MAX_RECHECK_MS);
41
+ }
42
+
28
43
  /** Record that this account's login was refused. */
29
44
  export function markCodexAccountAuthFailed(accountId: string, reason: string): void {
30
45
  const now = Date.now();
31
46
  const prev = failures.get(accountId);
32
47
  const fresh = !prev || prev.until <= now;
33
- failures.set(accountId, { until: now + MARK_TTL_MS, reason, since: fresh ? now : prev.since });
48
+ // Only a refusal on a read that was due widens the wait. Several turns in flight on one
49
+ // account all fail on the same transient 401 within a second; counting each would bench a
50
+ // recovered account for an hour instead of re-reading it at the next sweep.
51
+ const due = fresh || now >= prev.recheckAt;
52
+ const strikes = fresh ? 1 : due ? prev.strikes + 1 : prev.strikes;
53
+ const recheckAt = due ? now + codexAuthRecheckDelayMs(strikes) : prev.recheckAt;
54
+ const until = Math.max(fresh ? 0 : prev.until, recheckAt + MARK_TTL_MS);
55
+ failures.set(accountId, { until, reason, since: fresh ? now : prev.since, strikes, recheckAt });
34
56
  if (fresh) console.warn(`[codex] account ${accountId} is signed out — skipping it until it signs in again`);
35
57
  }
36
58
 
@@ -42,6 +64,14 @@ export function isCodexAccountAuthFailed(accountId: string): boolean {
42
64
  return true;
43
65
  }
44
66
 
67
+ /**
68
+ * Whether the background sweep should leave this account alone for now: it is known to be
69
+ * signed out and its next read is not due yet. An account that is not marked is always due.
70
+ */
71
+ export function isCodexAccountAuthRecheckPending(accountId: string): boolean {
72
+ return isCodexAccountAuthFailed(accountId) && Date.now() < failures.get(accountId)!.recheckAt;
73
+ }
74
+
45
75
  /** When the account was first seen signed out, or null if it is not. */
46
76
  export function codexAccountAuthFailedSince(accountId: string): number | null {
47
77
  return isCodexAccountAuthFailed(accountId) ? failures.get(accountId)!.since : null;
@@ -392,6 +392,43 @@ export async function resolveCodexAccountForSession(sessionId?: string): Promise
392
392
  return selectCodexAccount({ usageOf: (id) => codexUsageLevel(usages[id]) });
393
393
  }
394
394
 
395
+ /** Which login a listing (the model list) should be read on. */
396
+ export type CodexListingLogin =
397
+ | { kind: "ambient" }
398
+ | { kind: "account"; account: CodexAccount }
399
+ | { kind: "none"; reason: string };
400
+
401
+ /**
402
+ * The login a session-less listing runs on: the same one a new chat would, never a different
403
+ * one, and without advancing the round-robin cursor the way `resolveCodexAccountForSession`
404
+ * would.
405
+ *
406
+ * - No account switched on (none configured, or every one off): a new chat runs on the
407
+ * machine's own `~/.codex` login, so the listing does too.
408
+ * - Accounts are on but a new chat would be refused (every one signed out, or every one held
409
+ * back by its daily guard): `none`. The listing must not fall through to `~/.codex` here.
410
+ * That login belongs to no account PPM uses and is usually stale, so every refresh of it
411
+ * failed in the log.
412
+ * - Otherwise an account a new chat could get, preferring one with quota left. If every
413
+ * account is out of quota, a chat still gets one, and so does the listing.
414
+ */
415
+ export async function codexLoginForListing(): Promise<CodexListingLogin> {
416
+ if (!listCodexAccounts().some((a) => a.status !== "disabled")) return { kind: "ambient" };
417
+ const servable = servableAccounts();
418
+ if (servable.length === 0) return { kind: "none", reason: "every enabled Codex account is signed out" };
419
+ const usable = servable.filter((a) => !isCodexAccountUsageLimited(a.id));
420
+ let candidates = usable.length > 0 ? usable : servable;
421
+ const guarded = usable.filter((a) => a.dailyGuardEnabled);
422
+ if (guarded.length > 0) {
423
+ const blocked = dailyGuardBlockedIds(guarded, await getAllCodexUsages());
424
+ if (blocked.length > 0 && blocked.length === usable.length) {
425
+ return { kind: "none", reason: "the daily guard holds back every Codex account" };
426
+ }
427
+ candidates = candidates.filter((a) => !blocked.includes(a.id));
428
+ }
429
+ return { kind: "account", account: candidates[0]! };
430
+ }
431
+
395
432
  // ── Usage (per account) ──
396
433
  // Both read through the shared provider-usage layer, so the accounts screen is
397
434
  // served from the same cache and snapshot store as the chat toolbar and cannot