@songsid/agend 2.3.5-alpha.5 → 2.3.5-alpha.6

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 (326) hide show
  1. package/THIRD_PARTY_NOTICES.md +0 -1
  2. package/dist/accounts-profiles.d.ts +96 -0
  3. package/dist/accounts-profiles.js +178 -0
  4. package/dist/accounts-profiles.js.map +1 -0
  5. package/dist/accounts-signout.d.ts +59 -0
  6. package/dist/accounts-signout.js +184 -0
  7. package/dist/accounts-signout.js.map +1 -0
  8. package/dist/accounts-view.d.ts +54 -0
  9. package/dist/accounts-view.js +55 -11
  10. package/dist/accounts-view.js.map +1 -1
  11. package/dist/agent-workspace.d.ts +11 -0
  12. package/dist/agent-workspace.js +28 -0
  13. package/dist/agent-workspace.js.map +1 -1
  14. package/dist/auth-api.js +27 -5
  15. package/dist/auth-api.js.map +1 -1
  16. package/dist/authority/session-authorizations.d.ts +2 -0
  17. package/dist/authority/session-authorizations.js +7 -1
  18. package/dist/authority/session-authorizations.js.map +1 -1
  19. package/dist/backend/codex.js +1 -0
  20. package/dist/backend/codex.js.map +1 -1
  21. package/dist/backend/types.d.ts +2 -0
  22. package/dist/backend/types.js.map +1 -1
  23. package/dist/build-provenance.json +1 -1
  24. package/dist/bundled-tmux-guard.d.ts +19 -0
  25. package/dist/bundled-tmux-guard.js +83 -0
  26. package/dist/bundled-tmux-guard.js.map +1 -0
  27. package/dist/classic-bindings.d.ts +13 -0
  28. package/dist/classic-bindings.js +28 -2
  29. package/dist/classic-bindings.js.map +1 -1
  30. package/dist/classic-channel-manager.d.ts +2 -0
  31. package/dist/classic-channel-manager.js +5 -1
  32. package/dist/classic-channel-manager.js.map +1 -1
  33. package/dist/cli.js +116 -11
  34. package/dist/cli.js.map +1 -1
  35. package/dist/config-validator.js +11 -0
  36. package/dist/config-validator.js.map +1 -1
  37. package/dist/config.js +3 -1
  38. package/dist/config.js.map +1 -1
  39. package/dist/daemon.d.ts +27 -2
  40. package/dist/daemon.js +107 -6
  41. package/dist/daemon.js.map +1 -1
  42. package/dist/doctor.js +3 -4
  43. package/dist/doctor.js.map +1 -1
  44. package/dist/e2e-isolation.js +5 -2
  45. package/dist/e2e-isolation.js.map +1 -1
  46. package/dist/fleet-control-audit.d.ts +1 -1
  47. package/dist/fleet-manager.d.ts +129 -0
  48. package/dist/fleet-manager.js +725 -53
  49. package/dist/fleet-manager.js.map +1 -1
  50. package/dist/general-knowledge/skills/credential-profiles/SKILL.md +10 -0
  51. package/dist/hub/compose/server.js +1 -0
  52. package/dist/hub/compose/server.js.map +1 -1
  53. package/dist/hub/directory/directory.d.ts +1 -1
  54. package/dist/hub/directory/directory.js +115 -3
  55. package/dist/hub/directory/directory.js.map +1 -1
  56. package/dist/hub/directory/groups.d.ts +29 -0
  57. package/dist/hub/directory/groups.js +29 -0
  58. package/dist/hub/directory/groups.js.map +1 -0
  59. package/dist/hub/directory/index.d.ts +1 -0
  60. package/dist/hub/directory/types.d.ts +4 -0
  61. package/dist/hub/directory/types.js.map +1 -1
  62. package/dist/hub/group-policy/model.d.ts +56 -0
  63. package/dist/hub/group-policy/model.js +46 -0
  64. package/dist/hub/group-policy/model.js.map +1 -0
  65. package/dist/hub/group-policy/resources.d.ts +52 -0
  66. package/dist/hub/group-policy/resources.js +166 -0
  67. package/dist/hub/group-policy/resources.js.map +1 -0
  68. package/dist/hub/group-policy/store.d.ts +52 -0
  69. package/dist/hub/group-policy/store.js +149 -0
  70. package/dist/hub/group-policy/store.js.map +1 -0
  71. package/dist/hub/http/compose.js +4 -3
  72. package/dist/hub/http/compose.js.map +1 -1
  73. package/dist/hub/pairing.d.ts +3 -1
  74. package/dist/hub/pairing.js +6 -3
  75. package/dist/hub/pairing.js.map +1 -1
  76. package/dist/hub/server.d.ts +2 -0
  77. package/dist/hub/server.js +12 -2
  78. package/dist/hub/server.js.map +1 -1
  79. package/dist/instance-config-impact.js +4 -3
  80. package/dist/instance-config-impact.js.map +1 -1
  81. package/dist/instance-lifecycle.d.ts +17 -0
  82. package/dist/instance-lifecycle.js +38 -1
  83. package/dist/instance-lifecycle.js.map +1 -1
  84. package/dist/locale.js +21 -0
  85. package/dist/locale.js.map +1 -1
  86. package/dist/login-controller.d.ts +5 -0
  87. package/dist/login-controller.js +11 -0
  88. package/dist/login-controller.js.map +1 -1
  89. package/dist/login-window-lock.d.ts +2 -1
  90. package/dist/login-window-lock.js.map +1 -1
  91. package/dist/ls-rows.d.ts +1 -1
  92. package/dist/ls-rows.js +1 -1
  93. package/dist/ls-rows.js.map +1 -1
  94. package/dist/machine-accounts.d.ts +110 -0
  95. package/dist/machine-accounts.js +229 -0
  96. package/dist/machine-accounts.js.map +1 -0
  97. package/dist/machine-signins.d.ts +89 -0
  98. package/dist/machine-signins.js +182 -0
  99. package/dist/machine-signins.js.map +1 -0
  100. package/dist/muse-usage-relay.d.ts +2 -0
  101. package/dist/muse-usage-relay.js +5 -3
  102. package/dist/muse-usage-relay.js.map +1 -1
  103. package/dist/needs-you-hub.d.ts +3 -0
  104. package/dist/needs-you-hub.js +13 -3
  105. package/dist/needs-you-hub.js.map +1 -1
  106. package/dist/needs-you.d.ts +35 -2
  107. package/dist/needs-you.js +19 -0
  108. package/dist/needs-you.js.map +1 -1
  109. package/dist/quickstart.js +7 -18
  110. package/dist/quickstart.js.map +1 -1
  111. package/dist/quiet-run.d.ts +31 -0
  112. package/dist/quiet-run.js +50 -0
  113. package/dist/quiet-run.js.map +1 -0
  114. package/dist/quota-notice-config.d.ts +22 -0
  115. package/dist/quota-notice-config.js +41 -0
  116. package/dist/quota-notice-config.js.map +1 -0
  117. package/dist/runtime-api.d.ts +13 -0
  118. package/dist/runtime-api.js +125 -1
  119. package/dist/runtime-api.js.map +1 -1
  120. package/dist/runtime-build-info.d.ts +2 -1
  121. package/dist/runtime-build-info.js +7 -3
  122. package/dist/runtime-build-info.js.map +1 -1
  123. package/dist/runtime-cli-install.d.ts +153 -0
  124. package/dist/runtime-cli-install.js +675 -0
  125. package/dist/runtime-cli-install.js.map +1 -0
  126. package/dist/runtime-cli.js +157 -12
  127. package/dist/runtime-cli.js.map +1 -1
  128. package/dist/runtime-client.d.ts +64 -2
  129. package/dist/runtime-client.js +277 -20
  130. package/dist/runtime-client.js.map +1 -1
  131. package/dist/runtime-coordinator.d.ts +10 -1
  132. package/dist/runtime-coordinator.js +93 -2
  133. package/dist/runtime-coordinator.js.map +1 -1
  134. package/dist/runtime-credential-profiles.d.ts +11 -2
  135. package/dist/runtime-credential-profiles.js +28 -4
  136. package/dist/runtime-credential-profiles.js.map +1 -1
  137. package/dist/runtime-install.js +9 -6
  138. package/dist/runtime-install.js.map +1 -1
  139. package/dist/runtime-pane-link.js +2 -1
  140. package/dist/runtime-pane-link.js.map +1 -1
  141. package/dist/runtime-pane-service.js +2 -2
  142. package/dist/runtime-pane-service.js.map +1 -1
  143. package/dist/runtime-pane-store.d.ts +10 -0
  144. package/dist/runtime-pane-store.js +13 -1
  145. package/dist/runtime-pane-store.js.map +1 -1
  146. package/dist/runtime-profile-ownership.d.ts +66 -0
  147. package/dist/runtime-profile-ownership.js +391 -0
  148. package/dist/runtime-profile-ownership.js.map +1 -0
  149. package/dist/runtime-protocol.d.ts +88 -2
  150. package/dist/runtime-protocol.js +40 -0
  151. package/dist/runtime-protocol.js.map +1 -1
  152. package/dist/runtime-remote-accounts.d.ts +197 -0
  153. package/dist/runtime-remote-accounts.js +663 -0
  154. package/dist/runtime-remote-accounts.js.map +1 -0
  155. package/dist/runtime-remote-setup.d.ts +105 -0
  156. package/dist/runtime-remote-setup.js +529 -0
  157. package/dist/runtime-remote-setup.js.map +1 -0
  158. package/dist/runtime-signin-transport.d.ts +39 -0
  159. package/dist/runtime-signin-transport.js +110 -0
  160. package/dist/runtime-signin-transport.js.map +1 -0
  161. package/dist/runtime-signin.d.ts +132 -0
  162. package/dist/runtime-signin.js +289 -0
  163. package/dist/runtime-signin.js.map +1 -0
  164. package/dist/runtime-update-attention.d.ts +4 -0
  165. package/dist/runtime-update-attention.js +11 -0
  166. package/dist/runtime-update-attention.js.map +1 -0
  167. package/dist/runtime-update-controller.d.ts +75 -0
  168. package/dist/runtime-update-controller.js +691 -0
  169. package/dist/runtime-update-controller.js.map +1 -0
  170. package/dist/runtime-update-ipc.d.ts +42 -0
  171. package/dist/runtime-update-ipc.js +144 -0
  172. package/dist/runtime-update-ipc.js.map +1 -0
  173. package/dist/runtime-update-journal.d.ts +5 -0
  174. package/dist/runtime-update-journal.js +7 -0
  175. package/dist/runtime-update-journal.js.map +1 -1
  176. package/dist/runtime-update-lock.js +17 -2
  177. package/dist/runtime-update-lock.js.map +1 -1
  178. package/dist/runtime-update-status.d.ts +30 -0
  179. package/dist/runtime-update-status.js +31 -0
  180. package/dist/runtime-update-status.js.map +1 -0
  181. package/dist/settings-api.js +3 -0
  182. package/dist/settings-api.js.map +1 -1
  183. package/dist/settings-change.js +8 -0
  184. package/dist/settings-change.js.map +1 -1
  185. package/dist/settings-instance-patch.js +1 -1
  186. package/dist/settings-instance-patch.js.map +1 -1
  187. package/dist/setup-wizard.js +3 -5
  188. package/dist/setup-wizard.js.map +1 -1
  189. package/dist/signin-keepalive.d.ts +203 -0
  190. package/dist/signin-keepalive.js +652 -0
  191. package/dist/signin-keepalive.js.map +1 -0
  192. package/dist/structured-signin-transport.js +4 -0
  193. package/dist/structured-signin-transport.js.map +1 -1
  194. package/dist/structured-signin.d.ts +7 -0
  195. package/dist/structured-signin.js +1 -1
  196. package/dist/structured-signin.js.map +1 -1
  197. package/dist/tmux-binary.d.ts +23 -23
  198. package/dist/tmux-binary.js +35 -46
  199. package/dist/tmux-binary.js.map +1 -1
  200. package/dist/tmux-exec-helper.js +3 -3
  201. package/dist/tmux-exec-helper.js.map +1 -1
  202. package/dist/tmux-legacy.d.ts +94 -0
  203. package/dist/tmux-legacy.js +309 -0
  204. package/dist/tmux-legacy.js.map +1 -0
  205. package/dist/tmux-manager.d.ts +7 -1
  206. package/dist/tmux-manager.js +21 -11
  207. package/dist/tmux-manager.js.map +1 -1
  208. package/dist/tmux-rollback.d.ts +31 -0
  209. package/dist/tmux-rollback.js +72 -0
  210. package/dist/tmux-rollback.js.map +1 -0
  211. package/dist/tmux-server.d.ts +102 -0
  212. package/dist/tmux-server.js +248 -0
  213. package/dist/tmux-server.js.map +1 -0
  214. package/dist/transcript-monitor.js +43 -5
  215. package/dist/transcript-monitor.js.map +1 -1
  216. package/dist/transcript-records.d.ts +2 -1
  217. package/dist/transcript-records.js +3 -0
  218. package/dist/transcript-records.js.map +1 -1
  219. package/dist/transcript-sources.js +3 -0
  220. package/dist/transcript-sources.js.map +1 -1
  221. package/dist/types.d.ts +3 -0
  222. package/dist/ui/accounts-keepalive.js +112 -0
  223. package/dist/ui/accounts-manage.js +237 -0
  224. package/dist/ui/accounts-view.js +175 -31
  225. package/dist/ui/agent-runtime-settings.js +2 -1
  226. package/dist/ui/app.html +8 -1
  227. package/dist/ui/hub-attachments.js +90 -0
  228. package/dist/ui/hub-chat-store.js +9 -4
  229. package/dist/ui/hub-client.js +20 -1
  230. package/dist/ui/hub-preview.js +101 -0
  231. package/dist/ui/machine-signin.js +56 -0
  232. package/dist/ui/panel-fleet.js +1 -1
  233. package/dist/ui/panel-hub.js +126 -31
  234. package/dist/ui/panel-needs.js +14 -8
  235. package/dist/ui/panel-notices.js +4 -3
  236. package/dist/ui/panel-runtimes.js +19 -6
  237. package/dist/ui/panel-settings.js +12 -6
  238. package/dist/ui/panel-windows-agent.js +2 -1
  239. package/dist/ui/preview-pages.js +3 -41
  240. package/dist/ui/preview-panel-actions.js +3 -161
  241. package/dist/ui/preview-panel.js +10 -557
  242. package/dist/ui/preview-versions.js +3 -155
  243. package/dist/ui/runtime-cli-install.js +114 -0
  244. package/dist/ui/runtime-update-commands.d.ts +2 -0
  245. package/dist/ui/runtime-update-commands.js +11 -0
  246. package/dist/ui/runtime-update-status.js +53 -0
  247. package/dist/ui/search-dialog.js +3 -2
  248. package/dist/ui/settings-guests.js +3 -2
  249. package/dist/ui/settings-hub-browser-certificate.js +2 -0
  250. package/dist/ui/settings-hub-membership.js +12 -6
  251. package/dist/ui/settings-hub-retention.js +2 -0
  252. package/dist/ui/settings-hub.js +11 -3
  253. package/dist/ui/settings-quota-notice.js +100 -0
  254. package/dist/ui/settings-registry.js +1 -0
  255. package/dist/ui/settings-strings.js +2 -2
  256. package/dist/ui/settings-web-authority.js +2 -1
  257. package/dist/ui/shared/accounts-keepalive.css +7 -0
  258. package/dist/ui/shared/accounts.css +13 -0
  259. package/dist/ui/shared/app-route.js +1 -1
  260. package/dist/ui/shared/app-shell.js +9 -3
  261. package/dist/ui/shared/app-store.js +2 -2
  262. package/dist/ui/shared/app.css +13 -0
  263. package/dist/ui/shared/app.js +2 -1
  264. package/dist/ui/shared/hub-chat.css +1 -0
  265. package/dist/ui/shared/hub-owner.css +1 -1
  266. package/dist/ui/shared/loading.css +37 -0
  267. package/dist/ui/shared/preview-pages.js +41 -0
  268. package/dist/ui/shared/preview-panel-actions.js +168 -0
  269. package/dist/ui/shared/preview-panel.js +565 -0
  270. package/dist/ui/shared/preview-versions.js +155 -0
  271. package/dist/ui/shared/runtime-install.css +4 -0
  272. package/dist/ui/shared/signin.js +68 -6
  273. package/dist/ui/shared/ui-states.js +14 -3
  274. package/dist/ui/shared/workspace-follow.css +19 -0
  275. package/dist/ui/signin.html +7 -3
  276. package/dist/ui/structured-signin.js +31 -7
  277. package/dist/ui/workspace-follow-strings.js +28 -0
  278. package/dist/ui/workspace-panel.js +225 -36
  279. package/dist/update-install.d.ts +7 -0
  280. package/dist/update-install.js +23 -0
  281. package/dist/update-install.js.map +1 -1
  282. package/dist/usage/providers.d.ts +5 -0
  283. package/dist/usage/providers.js +5 -0
  284. package/dist/usage/providers.js.map +1 -1
  285. package/dist/usage/quota-notices.d.ts +38 -0
  286. package/dist/usage/quota-notices.js +160 -0
  287. package/dist/usage/quota-notices.js.map +1 -0
  288. package/dist/usage/usage-api.d.ts +1 -0
  289. package/dist/usage/usage-api.js +16 -0
  290. package/dist/usage/usage-api.js.map +1 -1
  291. package/dist/web-api.d.ts +33 -0
  292. package/dist/web-api.js +342 -8
  293. package/dist/web-api.js.map +1 -1
  294. package/dist/web-login.d.ts +35 -1
  295. package/dist/web-login.js +51 -5
  296. package/dist/web-login.js.map +1 -1
  297. package/dist/web-session.d.ts +11 -0
  298. package/dist/web-session.js +38 -1
  299. package/dist/web-session.js.map +1 -1
  300. package/dist/web-shell-routes.d.ts +1 -1
  301. package/dist/web-shell-routes.js +1 -1
  302. package/dist/web-shell-routes.js.map +1 -1
  303. package/dist/web-signin-link.d.ts +42 -0
  304. package/dist/web-signin-link.js +110 -0
  305. package/dist/web-signin-link.js.map +1 -0
  306. package/dist/windows-cli-api.d.ts +6 -0
  307. package/dist/windows-cli-api.js +11 -0
  308. package/dist/windows-cli-api.js.map +1 -1
  309. package/dist/windows-cli-worker.d.ts +3 -1
  310. package/dist/windows-cli-worker.js +18 -3
  311. package/dist/windows-cli-worker.js.map +1 -1
  312. package/dist/workspace-follow-parse.d.ts +36 -0
  313. package/dist/workspace-follow-parse.js +208 -0
  314. package/dist/workspace-follow-parse.js.map +1 -0
  315. package/dist/workspace-follow-records.d.ts +17 -0
  316. package/dist/workspace-follow-records.js +88 -0
  317. package/dist/workspace-follow-records.js.map +1 -0
  318. package/dist/workspace-follow.d.ts +41 -0
  319. package/dist/workspace-follow.js +143 -0
  320. package/dist/workspace-follow.js.map +1 -0
  321. package/dist/wsl-detect.d.ts +1 -0
  322. package/dist/wsl-detect.js +20 -0
  323. package/dist/wsl-detect.js.map +1 -0
  324. package/launcher/tmux-bundle.cjs +26 -10
  325. package/package.json +6 -2
  326. package/templates/runtime-install/install.ps1 +154 -13
@@ -0,0 +1,652 @@
1
+ /**
2
+ * #3292: "Keep sign-in alive" — an opt-in, per-sign-in daily refresh for Claude Code and Codex logins nothing else is using,
3
+ * so an idle account does not lapse unnoticed, and a Needs-you item when one cannot be kept (or is about to end anyway).
4
+ *
5
+ * What refreshes, measured (static reading of Claude Code 2.1.319 and codex rust-v0.167.0, then the offline rigs in
6
+ * scripts/manual/signin-keepalive/ and one maintainer-approved real check each, #3292 comments 6703454802 / 6703504753):
7
+ * - Claude Code: `claude auth status --json` makes no model call; the start-up it shares with every subcommand renews the
8
+ * access token when it is expired or within five minutes of expiry (a server feature gate may turn that off for
9
+ * subcommands). Whether it did is read back from `.credentials.json` (`expiresAt` moved). A failed refresh the server
10
+ * refuses (`invalid_grant`) blanks the stored login (`expiresAt` 0, no refresh token) while `auth status` still says
11
+ * signed in, so "sign in again" is read from the file too, never from the answer. The login also has an absolute end
12
+ * (`refreshTokenExpiresAt`) a refresh can never move: that is warned about from ten days before, whatever this does.
13
+ * - Codex: `codex login status` never refreshes. `codex app-server` → `account/read {refreshToken:true}` forces one with
14
+ * no model call. It answers the same either way; what happened is read back: `last_refresh` in `auth.json` moved (it
15
+ * refreshed), the answer's account is null (the server refused the refresh token: sign in again), else a transient
16
+ * failure. It runs in a scratch CODEX_HOME whose `auth.json` is a link to the sign-in's own file (the same layout an
17
+ * agent's home uses), so the refresh lands in that file and nothing else is written beside it. Codex refresh tokens
18
+ * are single-use: a sign-in a running agent or room uses is never refreshed here (its use keeps it alive anyway).
19
+ *
20
+ * Never: a token value read out of a file (only dates, booleans and a plan name leave the readers), any CLI output
21
+ * logged or kept, a user-visible session, the default sign-in touched unless it is itself switched on, or a model call
22
+ * — except the Claude fallback a person switched on for that one sign-in (a single tiny request, disclosed in the UI).
23
+ */
24
+ import { existsSync, lstatSync, mkdirSync, readFileSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
25
+ import { join } from "node:path";
26
+ import { spawn } from "./child-process.js";
27
+ import { parseClaudeAuthStatus } from "./claude-auth-status.js";
28
+ import { writeFileAtomic } from "./backend/kiro-engine-ledger.js";
29
+ import { isCredentialProfileName } from "./backend/credential-profile.js";
30
+ export const KEEPALIVE_BACKENDS = Object.freeze(["claude-code", "codex"]);
31
+ export const isKeepAliveBackend = (b) => typeof b === "string" && KEEPALIVE_BACKENDS.includes(b);
32
+ const MIN = 60_000, HOUR = 60 * MIN, DAY = 24 * HOUR;
33
+ /** Claude Code's own window: it renews when the access token expires within five minutes. */
34
+ export const CLAUDE_REFRESH_WINDOW_MS = 5 * MIN;
35
+ /** Codex refreshes by itself after eight days; this keeps a margin under that. */
36
+ export const CODEX_REFRESH_AFTER_MS = 6 * DAY;
37
+ /** Claude Code's own warning starts ten days before the sign-in ends. */
38
+ export const END_WARNING_MS = 10 * DAY;
39
+ /** A transient failure becomes a Needs-you item on its second run in a row, or 48 hours after the first. */
40
+ export const TRANSIENT_RUNS = 2;
41
+ export const TRANSIENT_MS = 48 * HOUR;
42
+ /** Each sign-in is looked at about once a day; the timer itself wakes hourly. */
43
+ export const RUN_EVERY_MS = 23 * HOUR;
44
+ const WAKE_MS = HOUR, FIRST_WAKE_MS = 3 * MIN, SOON_MS = 2_000;
45
+ const CLAUDE_TIMEOUT_MS = 60_000, FALLBACK_TIMEOUT_MS = 120_000, CODEX_TIMEOUT_MS = 60_000;
46
+ export const SETTINGS_FILE = "signin-keepalive.json";
47
+ const WORK_DIR = "signin-keepalive";
48
+ const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : undefined;
49
+ const nonEmpty = (v) => typeof v === "string" && v.length > 0;
50
+ function readJson(path) {
51
+ let text;
52
+ try {
53
+ text = readFileSync(path, "utf8");
54
+ }
55
+ catch (err) {
56
+ return { ok: false, missing: err.code === "ENOENT" };
57
+ }
58
+ try {
59
+ const value = JSON.parse(text);
60
+ return value && typeof value === "object" && !Array.isArray(value) ? { ok: true, value: value } : { ok: false, missing: false };
61
+ }
62
+ catch {
63
+ return { ok: false, missing: false };
64
+ }
65
+ }
66
+ /** Claude Code's stored login, as dates and booleans. */
67
+ export function readClaudeMeta(home) {
68
+ const r = readJson(join(home, ".credentials.json"));
69
+ if (!r.ok)
70
+ return r.missing ? { state: "missing" } : { state: "unreadable" };
71
+ const o = r.value.claudeAiOauth;
72
+ if (!o || typeof o !== "object")
73
+ return { state: "missing" };
74
+ const expiresAt = num(o.expiresAt), endsAt = num(o.refreshTokenExpiresAt);
75
+ const plan = typeof o.subscriptionType === "string" && /^[a-z0-9_-]{1,32}$/i.test(o.subscriptionType) ? o.subscriptionType.toLowerCase() : undefined;
76
+ return { state: "ok", hasRefresh: nonEmpty(o.refreshToken), ...(expiresAt !== undefined ? { expiresAt } : {}), ...(endsAt !== undefined ? { endsAt } : {}), ...(plan ? { plan } : {}) };
77
+ }
78
+ /** A JWT's payload, decoded for its claims only (never verified: only dates and a plan name are read from it). */
79
+ function jwtClaims(token) {
80
+ if (typeof token !== "string")
81
+ return undefined;
82
+ const part = token.split(".")[1];
83
+ if (!part || part.length > 16_384)
84
+ return undefined;
85
+ try {
86
+ const v = JSON.parse(Buffer.from(part, "base64url").toString("utf8"));
87
+ return v && typeof v === "object" ? v : undefined;
88
+ }
89
+ catch {
90
+ return undefined;
91
+ }
92
+ }
93
+ /** Codex's `auth.json`, as dates, a plan name and booleans. */
94
+ export function readCodexMeta(authJson) {
95
+ const r = readJson(authJson);
96
+ if (!r.ok)
97
+ return r.missing ? { state: "missing" } : { state: "unreadable" };
98
+ const tokens = r.value.tokens;
99
+ if (!tokens || typeof tokens !== "object" || !nonEmpty(tokens.access_token))
100
+ return nonEmpty(r.value.OPENAI_API_KEY) ? { state: "api_key" } : { state: "missing" };
101
+ const lr = typeof r.value.last_refresh === "string" ? Date.parse(r.value.last_refresh) : NaN;
102
+ const exp = num(jwtClaims(tokens.access_token)?.exp);
103
+ const plan = jwtClaims(tokens.id_token)?.["https://api.openai.com/auth"]?.chatgpt_plan_type;
104
+ return {
105
+ state: "ok", hasRefresh: nonEmpty(tokens.refresh_token),
106
+ ...(Number.isFinite(lr) ? { lastRefresh: lr } : {}), ...(exp !== undefined ? { accessExp: exp * 1000 } : {}),
107
+ ...(typeof plan === "string" && /^[a-z0-9_-]{1,32}$/i.test(plan) ? { planType: plan.toLowerCase() } : {}),
108
+ };
109
+ }
110
+ export const claudeDue = (m, now) => m.expiresAt === undefined || m.expiresAt <= now + CLAUDE_REFRESH_WINDOW_MS;
111
+ export const codexDue = (m, now) => m.lastRefresh === undefined || now - m.lastRefresh >= CODEX_REFRESH_AFTER_MS || m.lastRefresh > now + HOUR
112
+ || (m.accessExp !== undefined && m.accessExp <= now + CLAUDE_REFRESH_WINDOW_MS);
113
+ /** A Claude login with no refresh token left, or one the CLI blanked after the server refused it. */
114
+ const claudeDead = (m) => m.state === "ok" && (!m.hasRefresh || m.expiresAt === 0);
115
+ /** The record after a run's outcome: failures counted, attention dated (pure). */
116
+ export function nextRecord(prev, outcome, now, facts = {}) {
117
+ const base = { ...(prev ?? {}), ...facts, lastAt: now, outcome };
118
+ if (outcome === "transient") {
119
+ const failCount = (prev?.outcome === "transient" ? prev.failCount ?? 0 : 0) + 1;
120
+ const failSince = prev?.outcome === "transient" && prev.failSince !== undefined ? prev.failSince : now;
121
+ const due = failCount >= TRANSIENT_RUNS || now - failSince >= TRANSIENT_MS;
122
+ return { ...base, failCount, failSince, attentionSince: due ? (prev?.outcome === "transient" && prev.attentionSince !== undefined ? prev.attentionSince : now) : undefined };
123
+ }
124
+ const { failCount: _c, failSince: _s, attentionSince: _a, ...rest } = base;
125
+ if (outcome === "needs_sign_in" || outcome === "not_renewed") {
126
+ return { ...rest, attentionSince: prev?.outcome === outcome && prev.attentionSince !== undefined ? prev.attentionSince : now };
127
+ }
128
+ return rest;
129
+ }
130
+ /** What wants a person now, from the switched-on sign-ins' records (pure; the end date is recomputed on each read). */
131
+ export function attentionOf(entries, now) {
132
+ const out = [];
133
+ for (const e of entries) {
134
+ if (!e.enabled || !e.record)
135
+ continue;
136
+ const r = e.record;
137
+ if ((r.outcome === "needs_sign_in" || r.outcome === "not_renewed" || r.outcome === "transient") && r.attentionSince !== undefined) {
138
+ out.push({ backend: e.backend, profile: e.profile, kind: r.outcome, since: r.attentionSince, ...(r.outcome === "transient" && r.failSince !== undefined ? { failedSince: r.failSince } : {}) });
139
+ }
140
+ // The end date: a refresh cannot move it, so it is said even when everything else is fine (not twice when a sign-in is already asked for).
141
+ if (r.endsAt !== undefined && r.endsAt - now <= END_WARNING_MS && r.outcome !== "needs_sign_in") {
142
+ out.push({ backend: e.backend, profile: e.profile, kind: r.endsAt <= now ? "ended" : "ending", since: Math.min(now, r.endsAt - END_WARNING_MS), endsAt: r.endsAt });
143
+ }
144
+ }
145
+ return out;
146
+ }
147
+ // ── Settings file ──────────────────────────────────────────────────────────────────────────────────────────────
148
+ const entryKey = (backend, profile) => `${backend}:${profile ?? ""}`;
149
+ /** Read the settings (and each sign-in's last record). Anything malformed is dropped, never guessed at. */
150
+ export function readEntries(dataDir) {
151
+ const r = readJson(join(dataDir, SETTINGS_FILE));
152
+ if (!r.ok || !Array.isArray(r.value.entries))
153
+ return [];
154
+ const seen = new Set(), out = [];
155
+ for (const raw of r.value.entries) {
156
+ if (!raw || typeof raw !== "object")
157
+ continue;
158
+ const e = raw;
159
+ const profile = e.profile === null ? null : typeof e.profile === "string" && isCredentialProfileName(e.profile) ? e.profile : undefined;
160
+ if (!isKeepAliveBackend(e.backend) || profile === undefined || typeof e.enabled !== "boolean")
161
+ continue;
162
+ const k = entryKey(e.backend, profile);
163
+ if (seen.has(k))
164
+ continue;
165
+ seen.add(k);
166
+ const rec = e.record && typeof e.record === "object" ? cleanRecord(e.record) : undefined;
167
+ out.push({ backend: e.backend, profile, enabled: e.enabled, ...(e.backend === "claude-code" && e.fallback === true ? { fallback: true } : {}), ...(rec ? { record: rec } : {}) });
168
+ }
169
+ return out;
170
+ }
171
+ const OUTCOMES = new Set(["refreshed", "fallback_refreshed", "not_needed", "checked", "in_use", "unsupported", "not_renewed", "needs_sign_in", "transient"]);
172
+ function cleanRecord(r) {
173
+ const out = {};
174
+ for (const k of ["lastAt", "expiresAt", "endsAt", "lastRefresh", "failCount", "failSince", "attentionSince"]) {
175
+ const v = num(r[k]);
176
+ if (v !== undefined)
177
+ out[k] = v;
178
+ }
179
+ if (typeof r.outcome === "string" && OUTCOMES.has(r.outcome))
180
+ out.outcome = r.outcome;
181
+ if (typeof r.planType === "string" && /^[a-z0-9_-]{1,32}$/.test(r.planType))
182
+ out.planType = r.planType;
183
+ return Object.keys(out).length ? out : undefined;
184
+ }
185
+ export function writeEntries(dataDir, entries) {
186
+ writeFileAtomic(join(dataDir, SETTINGS_FILE), JSON.stringify({ version: 1, entries }, null, 2) + "\n");
187
+ }
188
+ /** Variables a keep-alive run never inherits: another credential would answer instead of the sign-in being kept. */
189
+ const STRIP_ENV = ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY", "ANTHROPIC_PROFILE", "OPENAI_API_KEY", "CODEX_API_KEY"];
190
+ function runEnv(extra) {
191
+ const env = { ...process.env };
192
+ for (const k of STRIP_ENV)
193
+ delete env[k];
194
+ return { ...env, DISABLE_AUTOUPDATER: "1", ...extra };
195
+ }
196
+ const KILL_AFTER_MS = 5_000, CODEX_EXIT_GRACE_MS = 5_000;
197
+ /** `exited`: the child's exit code once it has exited — never before (null: by a signal, or it never started). `stop()`: SIGINT, then SIGKILL. */
198
+ export function watchChild(child) {
199
+ let stopping = false;
200
+ const exited = new Promise(resolve => {
201
+ child.once("exit", code => resolve(typeof code === "number" ? code : null));
202
+ child.once("error", () => { if (child.pid === undefined)
203
+ resolve(null); }); // it never started: nothing to wait for
204
+ });
205
+ const stop = () => {
206
+ if (stopping)
207
+ return;
208
+ stopping = true;
209
+ try {
210
+ child.kill("SIGINT");
211
+ }
212
+ catch { /* gone */ }
213
+ const k = setTimeout(() => { try {
214
+ child.kill("SIGKILL");
215
+ }
216
+ catch { /* gone */ } }, KILL_AFTER_MS);
217
+ k.unref?.();
218
+ void exited.then(() => clearTimeout(k));
219
+ };
220
+ return { exited, stop };
221
+ }
222
+ /** Run a CLI to its exit; keep only its stdout (bounded) for the caller to parse, never log it. Code null: timed out, stopped, or did not start. */
223
+ async function runCli(cmd, args, opts) {
224
+ if (opts.signal.aborted)
225
+ return { code: null, stdout: "" };
226
+ let child;
227
+ try {
228
+ child = spawn(cmd, args, { env: opts.env, cwd: opts.cwd, stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
229
+ }
230
+ catch {
231
+ return { code: null, stdout: "" };
232
+ }
233
+ let stdout = "", cut = false;
234
+ child.stdout?.on("data", (d) => { if (stdout.length < 64 * 1024)
235
+ stdout += d.toString("utf8"); });
236
+ const w = watchChild(child);
237
+ const end = () => { cut = true; w.stop(); };
238
+ const timer = setTimeout(end, opts.timeoutMs);
239
+ timer.unref?.();
240
+ opts.signal.addEventListener("abort", end, { once: true });
241
+ try {
242
+ const code = await w.exited;
243
+ return { code: cut ? null : code, stdout };
244
+ }
245
+ finally {
246
+ clearTimeout(timer);
247
+ opts.signal.removeEventListener("abort", end);
248
+ }
249
+ }
250
+ /** The runners for these binaries (tests point them at a scratch fake; the fleet uses `claude` and `codex` from PATH). */
251
+ export function makeRunners(bin) {
252
+ return {
253
+ async claudeStatus(configDir, cwd, signal) {
254
+ const r = await runCli(bin.claude, ["auth", "status", "--json"], { env: runEnv(configDir ? { CLAUDE_CONFIG_DIR: configDir } : {}), cwd, timeoutMs: CLAUDE_TIMEOUT_MS, signal });
255
+ if (r.code === null)
256
+ return { code: null, loggedIn: null };
257
+ const parsed = parseClaudeAuthStatus(r.stdout);
258
+ const m = /"loginExpiresAt"\s*:\s*"([0-9TZ:.+-]{10,40})"/.exec(r.stdout), at = m ? Date.parse(m[1]) : NaN;
259
+ return { code: r.code, loggedIn: parsed.loggedIn, ...(Number.isFinite(at) ? { loginExpiresAt: at } : {}) };
260
+ },
261
+ async claudeFallback(configDir, cwd, signal) {
262
+ const r = await runCli(bin.claude, ["-p", "Reply with the single word OK.", "--model", "haiku", "--max-turns", "1", "--tools", "", "--strict-mcp-config",
263
+ "--no-session-persistence", "--disable-slash-commands", "--setting-sources", "project", "--output-format", "json"], { env: runEnv(configDir ? { CLAUDE_CONFIG_DIR: configDir } : {}), cwd, timeoutMs: FALLBACK_TIMEOUT_MS, signal });
264
+ return { code: r.code };
265
+ },
266
+ async codexRefresh(runHome, signal) {
267
+ if (signal.aborted)
268
+ return { answered: false, accountNull: false };
269
+ let child;
270
+ try {
271
+ child = spawn(bin.codex, ["app-server"], { env: runEnv({ CODEX_HOME: runHome }), cwd: runHome, stdio: ["pipe", "pipe", "ignore"], windowsHide: true });
272
+ }
273
+ catch {
274
+ return { answered: false, accountNull: false };
275
+ }
276
+ const w = watchChild(child);
277
+ let buf = "", answered = false, accountNull = false, grace = null, ended = false;
278
+ // #3313 review r2: once stopped (withdrawn, stopped, or past its deadline) nothing more is sent — a late answer to
279
+ // `initialize` never starts the refresh — and the process is still owned until it exits.
280
+ const end = () => { ended = true; w.stop(); };
281
+ const send = (o) => { if (ended || signal.aborted)
282
+ return; try {
283
+ child.stdin?.write(JSON.stringify(o) + "\n");
284
+ }
285
+ catch { /* closed */ } };
286
+ // After its answer it is asked to leave (stdin closed); if it has not within the grace, it is stopped.
287
+ const finish = () => { if (grace)
288
+ return; ended = true; try {
289
+ child.stdin?.end();
290
+ }
291
+ catch { /* closed */ } grace = setTimeout(w.stop, CODEX_EXIT_GRACE_MS); grace.unref?.(); };
292
+ child.stdin?.on("error", () => { });
293
+ child.stdout?.on("data", (d) => {
294
+ buf += d.toString("utf8");
295
+ if (buf.length > 1024 * 1024) {
296
+ buf = "";
297
+ return;
298
+ }
299
+ let i;
300
+ while ((i = buf.indexOf("\n")) >= 0) {
301
+ const line = buf.slice(0, i);
302
+ buf = buf.slice(i + 1);
303
+ let m;
304
+ try {
305
+ m = JSON.parse(line);
306
+ }
307
+ catch {
308
+ continue;
309
+ }
310
+ if (m?.id === 1) {
311
+ send({ method: "initialized" });
312
+ send({ id: 2, method: "account/read", params: { refreshToken: true } });
313
+ }
314
+ else if (m?.id === 2 && !ended) {
315
+ answered = !m.error;
316
+ accountNull = !m.error && m.result?.account === null;
317
+ finish();
318
+ }
319
+ }
320
+ });
321
+ const timer = setTimeout(end, CODEX_TIMEOUT_MS);
322
+ timer.unref?.();
323
+ signal.addEventListener("abort", end, { once: true });
324
+ send({ id: 1, method: "initialize", params: { clientInfo: { name: "agend-signin-keepalive", version: "1" } } });
325
+ try {
326
+ await w.exited;
327
+ }
328
+ finally {
329
+ clearTimeout(timer);
330
+ if (grace)
331
+ clearTimeout(grace);
332
+ signal.removeEventListener("abort", end);
333
+ }
334
+ return { answered, accountNull };
335
+ },
336
+ };
337
+ }
338
+ export const realRunners = makeRunners({ claude: "claude", codex: "codex" });
339
+ const iso = (ms) => ms === undefined ? undefined : new Date(ms).toISOString();
340
+ /** A run whose setting changed (or whose service stopped) since it began: it does nothing more and records nothing. */
341
+ class Withdrawn extends Error {
342
+ }
343
+ export class SignInKeepAlive {
344
+ deps;
345
+ entries;
346
+ timer = null;
347
+ first = null;
348
+ soon = null;
349
+ running = null;
350
+ stopped = false;
351
+ /** Raised by each stop: a run begun before never goes on after it. */
352
+ epoch = 0;
353
+ /** Raised by each change of a sign-in's setting: its run in flight is withdrawn. */
354
+ generation = new Map();
355
+ /** The run in flight: which sign-in, and how to stop its CLI. */
356
+ inFlight = null;
357
+ runners;
358
+ now;
359
+ constructor(deps) {
360
+ this.deps = deps;
361
+ this.entries = readEntries(deps.dataDir);
362
+ this.runners = deps.runners ?? realRunners;
363
+ this.now = deps.now ?? Date.now;
364
+ }
365
+ start() {
366
+ this.stopped = false;
367
+ for (const t of [this.timer, this.first])
368
+ if (t)
369
+ clearTimeout(t);
370
+ this.first = setTimeout(() => { void this.tick(); }, FIRST_WAKE_MS);
371
+ this.first.unref?.();
372
+ this.timer = setInterval(() => { void this.tick(); }, WAKE_MS);
373
+ this.timer.unref?.();
374
+ }
375
+ /** No new run; the one in flight stops its CLI. Resolves once that run (and its CLI) has ended. */
376
+ stop() {
377
+ this.stopped = true;
378
+ this.epoch++;
379
+ for (const t of [this.timer, this.first, this.soon])
380
+ if (t)
381
+ clearTimeout(t);
382
+ this.timer = this.first = this.soon = null;
383
+ this.inFlight?.controller.abort();
384
+ return this.running ? this.running.then(() => undefined, () => undefined) : Promise.resolve();
385
+ }
386
+ list() { return this.entries; }
387
+ /** Switch a sign-in on or off (and, for Claude Code, its fallback). On: it is looked at within seconds. Any change withdraws its run in flight. */
388
+ set(backend, profile, enabled, fallback) {
389
+ if (!isKeepAliveBackend(backend))
390
+ return { ok: false, error: "backend" };
391
+ if (!(profile === null || (typeof profile === "string" && isCredentialProfileName(profile))))
392
+ return { ok: false, error: "profile" };
393
+ if (typeof enabled !== "boolean")
394
+ return { ok: false, error: "profile" };
395
+ if (fallback !== undefined && (typeof fallback !== "boolean" || (fallback && backend !== "claude-code")))
396
+ return { ok: false, error: "fallback" };
397
+ const next = this.entries.filter(e => !(e.backend === backend && e.profile === profile));
398
+ const prev = this.entries.find(e => e.backend === backend && e.profile === profile);
399
+ const fb = fallback === undefined ? prev?.fallback === true : fallback;
400
+ // Off forgets the record: switched on again, it starts clean (no old failure counted twice).
401
+ next.push({ backend, profile, enabled, ...(fb && backend === "claude-code" ? { fallback: true } : {}), ...(enabled && prev?.record ? { record: prev.record } : {}) });
402
+ try {
403
+ writeEntries(this.deps.dataDir, next);
404
+ }
405
+ catch {
406
+ return { ok: false, error: "write" };
407
+ }
408
+ this.entries = next;
409
+ const key = entryKey(backend, profile);
410
+ this.generation.set(key, (this.generation.get(key) ?? 0) + 1);
411
+ if (this.inFlight?.key === key)
412
+ this.inFlight.controller.abort();
413
+ this.deps.log("info", "Sign-in keep-alive setting changed", { backend, profile: profile ?? "(default)", enabled, fallback: fb && backend === "claude-code" });
414
+ this.deps.changed();
415
+ if (enabled && !this.stopped) {
416
+ if (this.soon)
417
+ clearTimeout(this.soon);
418
+ this.soon = setTimeout(() => { this.soon = null; void this.tick({ only: { backend, profile } }); }, SOON_MS);
419
+ this.soon.unref?.();
420
+ }
421
+ return { ok: true };
422
+ }
423
+ /** The Accounts row's part: the setting, the last run, and the dates read now from the sign-in's own file. */
424
+ view(backend, profile) {
425
+ if (!isKeepAliveBackend(backend))
426
+ return undefined;
427
+ const e = this.entries.find(x => x.backend === backend && x.profile === profile);
428
+ const r = e?.enabled ? e.record : undefined;
429
+ const home = this.deps.homeOf(backend, profile);
430
+ let endsAt = r?.endsAt, expiresAt = r?.expiresAt, planType = r?.planType;
431
+ if (home) {
432
+ if (backend === "claude-code") {
433
+ const m = readClaudeMeta(home);
434
+ if (m.state === "ok") {
435
+ endsAt = m.endsAt ?? endsAt;
436
+ expiresAt = m.expiresAt ?? expiresAt;
437
+ }
438
+ }
439
+ else {
440
+ const m = readCodexMeta(join(home, "auth.json"));
441
+ if (m.state === "ok") {
442
+ expiresAt = m.accessExp ?? expiresAt;
443
+ planType = m.planType ?? planType;
444
+ }
445
+ }
446
+ }
447
+ return {
448
+ enabled: e?.enabled === true, ...(backend === "claude-code" ? { fallback: e?.fallback === true } : {}),
449
+ ...(endsAt !== undefined && endsAt > 0 ? { endsAt: iso(endsAt) } : {}), ...(expiresAt !== undefined && expiresAt > 0 ? { expiresAt: iso(expiresAt) } : {}),
450
+ ...(r?.lastAt !== undefined ? { lastAt: iso(r.lastAt) } : {}), ...(r?.outcome ? { lastOutcome: r.outcome } : {}), ...(planType ? { planType } : {}),
451
+ };
452
+ }
453
+ attention() { return attentionOf(this.entries, this.now()); }
454
+ /** One pass: every switched-on sign-in not looked at for about a day (or just the one switched on), one at a time. */
455
+ tick(opts = {}) {
456
+ if (this.running)
457
+ return this.running.then(() => !this.stopped && (opts.only || opts.force) ? this.tick(opts) : undefined);
458
+ this.running = this.pass(opts).finally(() => { this.running = null; });
459
+ return this.running;
460
+ }
461
+ find(key) { return this.entries.find(x => entryKey(x.backend, x.profile) === key); }
462
+ async pass(opts) {
463
+ let changed = false;
464
+ // Each sign-in as it is NOW: one switched off while an earlier one ran is not run.
465
+ for (const key of this.entries.map(x => entryKey(x.backend, x.profile))) {
466
+ if (this.stopped)
467
+ break;
468
+ const e = this.find(key);
469
+ if (!e?.enabled)
470
+ continue;
471
+ if (opts.only && !(opts.only.backend === e.backend && opts.only.profile === e.profile))
472
+ continue;
473
+ const now = this.now(), last = e.record?.lastAt;
474
+ if (!opts.force && !opts.only && last !== undefined && now - last < RUN_EVERY_MS && last <= now + HOUR)
475
+ continue;
476
+ const home = this.deps.homeOf(e.backend, e.profile);
477
+ if (!home)
478
+ continue;
479
+ if (e.profile !== null && !existsSync(home)) { // the profile was removed: forget it, never ask anyone to sign it in
480
+ this.entries = this.entries.filter(x => x !== e);
481
+ changed = true;
482
+ continue;
483
+ }
484
+ let record;
485
+ const hold = this.deps.acquire(e.backend, e.profile);
486
+ if (hold === "busy")
487
+ continue; // a sign-in holds the window: the next wake tries again
488
+ if (hold === "in_use")
489
+ record = nextRecord(e.record, "in_use", now, this.datesOf(e.backend, home));
490
+ else {
491
+ const epoch = this.epoch, gen = this.generation.get(key) ?? 0, controller = new AbortController();
492
+ // Still wanted: the service not stopped, this sign-in's setting unchanged and on (and, for the fallback, allowing it).
493
+ const wanted = (fallback = false) => {
494
+ const cur = this.find(key);
495
+ if (this.stopped || this.epoch !== epoch || (this.generation.get(key) ?? 0) !== gen || !cur?.enabled || (fallback && cur.fallback !== true))
496
+ throw new Withdrawn();
497
+ };
498
+ this.inFlight = { key, controller };
499
+ try {
500
+ record = e.backend === "claude-code" ? await this.runClaude(e, home, now, wanted, controller.signal) : await this.runCodex(e, home, now, wanted, controller.signal);
501
+ wanted();
502
+ }
503
+ catch (err) {
504
+ if (err instanceof Withdrawn)
505
+ continue; // withdrawn: nothing more, nothing recorded
506
+ record = nextRecord(e.record, "transient", now);
507
+ }
508
+ finally {
509
+ if (this.inFlight?.controller === controller)
510
+ this.inFlight = null;
511
+ hold.release(); // only now: every CLI of this run has exited
512
+ }
513
+ }
514
+ const current = this.find(key);
515
+ if (!current?.enabled)
516
+ continue;
517
+ this.entries = this.entries.map(x => x === current ? { ...current, record } : x);
518
+ changed = true;
519
+ this.deps.log(record.outcome === "transient" || record.outcome === "needs_sign_in" || record.outcome === "not_renewed" ? "warn" : "info", "Sign-in keep-alive", {
520
+ backend: e.backend, profile: e.profile ?? "(default)", outcome: record.outcome,
521
+ ...(record.expiresAt ? { expiresAt: iso(record.expiresAt) } : {}), ...(record.endsAt ? { endsAt: iso(record.endsAt) } : {}),
522
+ ...(record.lastRefresh ? { lastRefresh: iso(record.lastRefresh) } : {}), ...(record.planType ? { planType: record.planType } : {}),
523
+ });
524
+ }
525
+ if (changed) {
526
+ try {
527
+ writeEntries(this.deps.dataDir, this.entries);
528
+ }
529
+ catch (err) {
530
+ this.deps.log("warn", "Sign-in keep-alive: could not save", { err: String(err?.message ?? err) });
531
+ }
532
+ this.deps.changed();
533
+ }
534
+ }
535
+ /** The dates a sign-in's own file says now (kept on a record that ran nothing). */
536
+ datesOf(backend, home) {
537
+ if (backend === "claude-code") {
538
+ const m = readClaudeMeta(home);
539
+ return m.state === "ok" ? { ...(m.expiresAt ? { expiresAt: m.expiresAt } : {}), ...(m.endsAt ? { endsAt: m.endsAt } : {}) } : {};
540
+ }
541
+ const m = readCodexMeta(join(home, "auth.json"));
542
+ return m.state === "ok" ? { ...(m.lastRefresh ? { lastRefresh: m.lastRefresh } : {}), ...(m.accessExp ? { expiresAt: m.accessExp } : {}), ...(m.planType ? { planType: m.planType } : {}) } : {};
543
+ }
544
+ workDir(sub) {
545
+ const dir = join(this.deps.dataDir, WORK_DIR, sub);
546
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
547
+ return dir;
548
+ }
549
+ /** `wanted()` is asked right before every CLI starts (it throws when the run was withdrawn). */
550
+ async runClaude(e, home, now, wanted, signal) {
551
+ const configDir = e.profile === null ? null : home, cwd = this.workDir("claude-cwd");
552
+ const before = readClaudeMeta(home);
553
+ const dates = (m) => m.state === "ok" ? { ...(m.expiresAt ? { expiresAt: m.expiresAt } : {}), ...(m.endsAt ? { endsAt: m.endsAt } : {}) } : {};
554
+ if (before.state === "unreadable")
555
+ return nextRecord(e.record, "transient", now);
556
+ if (before.state === "missing") {
557
+ // No file: signed out — or, on macOS, the login is in the Keychain and only the CLI can say (not whether it renewed).
558
+ if (!this.deps.claudeKeychain)
559
+ return nextRecord(e.record, "needs_sign_in", now);
560
+ wanted();
561
+ const r = await this.runners.claudeStatus(configDir, cwd, signal);
562
+ if (r.code === null || r.loggedIn === null)
563
+ return nextRecord(e.record, "transient", now);
564
+ return nextRecord(e.record, r.loggedIn ? "checked" : "needs_sign_in", now, r.loginExpiresAt ? { endsAt: r.loginExpiresAt } : {});
565
+ }
566
+ if (claudeDead(before))
567
+ return nextRecord(e.record, "needs_sign_in", now, dates(before));
568
+ if (!claudeDue(before, now))
569
+ return nextRecord(e.record, "not_needed", now, dates(before));
570
+ wanted();
571
+ const r = await this.runners.claudeStatus(configDir, cwd, signal);
572
+ wanted();
573
+ if (r.code === null)
574
+ return nextRecord(e.record, "transient", now, dates(before));
575
+ const after = readClaudeMeta(home);
576
+ if (after.state !== "ok")
577
+ return nextRecord(e.record, after.state === "missing" ? "needs_sign_in" : "transient", now, dates(before));
578
+ if (claudeDead(after))
579
+ return nextRecord(e.record, "needs_sign_in", now, dates(after));
580
+ const moved = (m) => m.state === "ok" && m.expiresAt !== undefined && m.expiresAt > now && (before.expiresAt === undefined || m.expiresAt > before.expiresAt);
581
+ if (moved(after))
582
+ return nextRecord(e.record, "refreshed", now, dates(after));
583
+ if (r.loggedIn === false)
584
+ return nextRecord(e.record, "needs_sign_in", now, dates(after));
585
+ // The fallback only when the person allows it NOW (it is a model request): asked again right before it starts.
586
+ if (this.find(entryKey(e.backend, e.profile))?.fallback !== true)
587
+ return nextRecord(e.record, "not_renewed", now, dates(after));
588
+ wanted(true);
589
+ const f = await this.runners.claudeFallback(configDir, cwd, signal);
590
+ const last = readClaudeMeta(home);
591
+ if (claudeDead(last))
592
+ return nextRecord(e.record, "needs_sign_in", now, dates(last));
593
+ if (moved(last))
594
+ return nextRecord(e.record, "fallback_refreshed", now, dates(last));
595
+ return nextRecord(e.record, f.code === null ? "transient" : "not_renewed", now, dates(last));
596
+ }
597
+ async runCodex(e, home, now, wanted, signal) {
598
+ const authJson = join(home, "auth.json");
599
+ const before = readCodexMeta(authJson);
600
+ const facts = (m) => m.state === "ok" ? { ...(m.lastRefresh ? { lastRefresh: m.lastRefresh } : {}), ...(m.accessExp ? { expiresAt: m.accessExp } : {}), ...(m.planType ? { planType: m.planType } : {}) } : {};
601
+ if (before.state === "missing")
602
+ return nextRecord(e.record, "needs_sign_in", now);
603
+ if (before.state === "api_key")
604
+ return nextRecord(e.record, "unsupported", now);
605
+ if (before.state === "unreadable")
606
+ return nextRecord(e.record, "transient", now);
607
+ if (!before.hasRefresh)
608
+ return nextRecord(e.record, "needs_sign_in", now, facts(before));
609
+ // Only a real file is refreshed through the link (a link would be replaced by a copy elsewhere, or point anywhere).
610
+ let st;
611
+ try {
612
+ st = lstatSync(authJson);
613
+ }
614
+ catch {
615
+ return nextRecord(e.record, "transient", now);
616
+ }
617
+ if (!st.isFile())
618
+ return nextRecord(e.record, "unsupported", now, facts(before));
619
+ if (!codexDue(before, now))
620
+ return nextRecord(e.record, "not_needed", now, facts(before));
621
+ wanted();
622
+ const runHome = this.workDir("codex-home"), link = join(runHome, "auth.json");
623
+ // The scratch home: this sign-in's auth.json linked in, codex told to keep it in that file (never a keyring).
624
+ writeFileSync(join(runHome, "config.toml"), 'cli_auth_credentials_store = "file"\n', { mode: 0o600 });
625
+ try {
626
+ unlinkSync(link);
627
+ }
628
+ catch { /* none */ }
629
+ symlinkSync(authJson, link);
630
+ let r;
631
+ // The link goes only once the app-server has exited (the runner resolves no sooner).
632
+ try {
633
+ r = await this.runners.codexRefresh(runHome, signal);
634
+ }
635
+ finally {
636
+ try {
637
+ unlinkSync(link);
638
+ }
639
+ catch { /* gone */ }
640
+ }
641
+ wanted();
642
+ const after = readCodexMeta(authJson);
643
+ if (after.state === "ok" && after.lastRefresh !== undefined && (before.lastRefresh === undefined || after.lastRefresh > before.lastRefresh))
644
+ return nextRecord(e.record, "refreshed", now, facts(after));
645
+ if (after.state === "missing")
646
+ return nextRecord(e.record, "needs_sign_in", now);
647
+ if (r.answered && r.accountNull)
648
+ return nextRecord(e.record, "needs_sign_in", now, facts(after));
649
+ return nextRecord(e.record, "transient", now, facts(after));
650
+ }
651
+ }
652
+ //# sourceMappingURL=signin-keepalive.js.map