@parcha/agentrun-serve 0.1.0-beta.56 → 0.1.0-beta.57

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 (275) hide show
  1. package/CHANGELOG.md +229 -0
  2. package/README.md +201 -52
  3. package/dist/acp-package.d.ts +2 -0
  4. package/dist/adapters.d.ts +15 -3
  5. package/dist/adapters.js +17 -6
  6. package/dist/agent-package.d.ts +3 -3
  7. package/dist/agent-package.js +17 -8
  8. package/dist/api-keys.d.ts +76 -0
  9. package/dist/api-keys.js +217 -0
  10. package/dist/api-only.d.ts +17 -5
  11. package/dist/api-only.js +34 -8
  12. package/dist/browser-hold.d.ts +23 -0
  13. package/dist/browser-hold.js +48 -0
  14. package/dist/browser-person.d.ts +3 -0
  15. package/dist/browser-person.js +4 -1
  16. package/dist/chatgpt-plan.d.ts +18 -8
  17. package/dist/chatgpt-plan.js +91 -34
  18. package/dist/claude-login.d.ts +74 -16
  19. package/dist/claude-login.js +215 -56
  20. package/dist/claude-sign-in.d.ts +17 -6
  21. package/dist/claude-sign-in.js +42 -39
  22. package/dist/cli.js +63 -6
  23. package/dist/composio-made.d.ts +4 -0
  24. package/dist/composio-made.js +4 -0
  25. package/dist/composio-preset.d.ts +43 -2
  26. package/dist/composio-preset.js +92 -4
  27. package/dist/computer-held-routes.d.ts +5 -4
  28. package/dist/computer-held-routes.js +29 -8
  29. package/dist/computer-held.d.ts +6 -1
  30. package/dist/computer-held.js +14 -0
  31. package/dist/computer-record.js +4 -2
  32. package/dist/computer-viewer.js +4 -1
  33. package/dist/console/assets/{backend-Boh7tC4i.js → backend-DVhHzJX2.js} +19 -19
  34. package/dist/console/assets/index-Bwn1oTem.css +1 -0
  35. package/dist/console/assets/index-okP-y8PK.js +747 -0
  36. package/dist/console/index.html +2 -2
  37. package/dist/decisions.d.ts +1 -1
  38. package/dist/decisions.js +1 -1
  39. package/dist/docker-host-addresses.d.ts +22 -11
  40. package/dist/docker-host-addresses.js +38 -26
  41. package/dist/env-switch.d.ts +10 -0
  42. package/dist/env-switch.js +33 -2
  43. package/dist/errors.d.ts +1 -0
  44. package/dist/errors.js +2 -0
  45. package/dist/fal-price.d.ts +58 -20
  46. package/dist/fal-price.js +341 -82
  47. package/dist/handed-values.d.ts +43 -1
  48. package/dist/handed-values.js +119 -2
  49. package/dist/harness-archive.d.ts +13 -10
  50. package/dist/harness-archive.js +60 -34
  51. package/dist/harness-check.d.ts +3 -1
  52. package/dist/harness-check.js +25 -46
  53. package/dist/harness-keys.d.ts +73 -27
  54. package/dist/harness-keys.js +194 -61
  55. package/dist/harness-recipe-entry.d.ts +8 -7
  56. package/dist/harness-recipe-entry.js +21 -32
  57. package/dist/harness-recipe.d.ts +38 -25
  58. package/dist/harness-recipe.js +49 -36
  59. package/dist/harness-sign-in.js +12 -23
  60. package/dist/harness-table.d.ts +10 -3
  61. package/dist/harness-table.js +26 -21
  62. package/dist/harness.d.ts +1 -0
  63. package/dist/harness.js +17 -5
  64. package/dist/hosted-search.d.ts +1 -1
  65. package/dist/hosted-search.js +1 -2
  66. package/dist/import-worker.d.ts +4 -2
  67. package/dist/import-worker.js +9 -2
  68. package/dist/in-flight.d.ts +26 -0
  69. package/dist/in-flight.js +52 -0
  70. package/dist/key-refusal.d.ts +9 -4
  71. package/dist/key-refusal.js +107 -25
  72. package/dist/learn/secrets.d.ts +13 -3
  73. package/dist/learn/secrets.js +118 -17
  74. package/dist/learning-cost.d.ts +6 -3
  75. package/dist/learning-cost.js +4 -2
  76. package/dist/link-check.js +1 -1
  77. package/dist/llms.txt +1 -1
  78. package/dist/marketplace.d.ts +77 -0
  79. package/dist/marketplace.js +224 -0
  80. package/dist/mcp-api-only-origins.d.ts +30 -0
  81. package/dist/mcp-api-only-origins.js +57 -0
  82. package/dist/mcp-gateway.d.ts +7 -5
  83. package/dist/mcp-gateway.js +9 -12
  84. package/dist/mcp-secret-writes.js +5 -3
  85. package/dist/mcp-servers-store.d.ts +28 -6
  86. package/dist/mcp-servers-store.js +53 -4
  87. package/dist/media-duration.d.ts +3 -0
  88. package/dist/media-duration.js +90 -9
  89. package/dist/model-form.d.ts +5 -4
  90. package/dist/model-form.js +11 -7
  91. package/dist/model.d.ts +5 -2
  92. package/dist/model.js +9 -5
  93. package/dist/ollama-provider.d.ts +7 -1
  94. package/dist/ollama-provider.js +14 -2
  95. package/dist/openapi.js +178 -27
  96. package/dist/otel/genai.d.ts +65 -0
  97. package/dist/otel/genai.js +116 -0
  98. package/dist/otel/tracer.d.ts +55 -0
  99. package/dist/otel/tracer.js +308 -0
  100. package/dist/page.d.ts +2 -0
  101. package/dist/page.js +3 -1
  102. package/dist/paid-calls.d.ts +1 -32
  103. package/dist/paid-calls.js +4 -39
  104. package/dist/provider.d.ts +9 -0
  105. package/dist/provider.js +50 -3
  106. package/dist/redact/match.d.ts +30 -3
  107. package/dist/redact/match.js +422 -41
  108. package/dist/refusal-words.d.ts +11 -0
  109. package/dist/refusal-words.js +11 -0
  110. package/dist/run-census.d.ts +67 -0
  111. package/dist/run-census.js +240 -0
  112. package/dist/run-computer.d.ts +6 -3
  113. package/dist/run-computer.js +4 -1
  114. package/dist/run-cut.d.ts +15 -6
  115. package/dist/run-cut.js +30 -9
  116. package/dist/run-files.d.ts +3 -0
  117. package/dist/run-files.js +3 -0
  118. package/dist/run-launch.d.ts +12 -1
  119. package/dist/run-launch.js +9 -10
  120. package/dist/run-learning-served.d.ts +2 -0
  121. package/dist/run-model-key.d.ts +8 -0
  122. package/dist/run-model-key.js +31 -1
  123. package/dist/run-reads-over-store.d.ts +24 -6
  124. package/dist/run-reads-over-store.js +67 -23
  125. package/dist/run-recordings.d.ts +5 -1
  126. package/dist/run-recordings.js +39 -14
  127. package/dist/run-timeline-served.d.ts +2 -0
  128. package/dist/run-timeline-served.js +2 -2
  129. package/dist/run-usage.d.ts +1 -0
  130. package/dist/runnable.d.ts +10 -1
  131. package/dist/runnable.js +20 -8
  132. package/dist/runner/adapter-loop.d.ts +11 -0
  133. package/dist/runner/adapter-loop.js +55 -10
  134. package/dist/runner/adapter-run-spec.d.ts +45 -8
  135. package/dist/runner/adapter-run-spec.js +150 -28
  136. package/dist/runner/adapters/pi.js +25 -3
  137. package/dist/runner/beside.js +4 -3
  138. package/dist/runner/big-writes.js +1 -10
  139. package/dist/runner/claim-secrets.d.ts +18 -3
  140. package/dist/runner/claim-secrets.js +35 -6
  141. package/dist/runner/cli-run-spec.d.ts +6 -0
  142. package/dist/runner/cli-run-spec.js +82 -35
  143. package/dist/runner/computer-journal.d.ts +9 -1
  144. package/dist/runner/computer-journal.js +26 -0
  145. package/dist/runner/conformance/harness.js +1 -1
  146. package/dist/runner/feedback-round.js +3 -0
  147. package/dist/runner/harness-loops.d.ts +6 -5
  148. package/dist/runner/harness-loops.js +7 -7
  149. package/dist/runner/held.d.ts +11 -5
  150. package/dist/runner/journal-kinds.d.ts +5 -0
  151. package/dist/runner/journal-kinds.js +5 -0
  152. package/dist/runner/main.js +7 -2
  153. package/dist/runner/mcp-claim.js +30 -3
  154. package/dist/runner/mcp-run.d.ts +12 -0
  155. package/dist/runner/mcp-run.js +12 -5
  156. package/dist/runner/model-route.d.ts +17 -0
  157. package/dist/runner/model-route.js +120 -2
  158. package/dist/runner/run-child-host.d.ts +3 -0
  159. package/dist/runner/run-child-host.js +69 -28
  160. package/dist/runner/run-child.js +5 -2
  161. package/dist/runner/runner.d.ts +14 -3
  162. package/dist/runner/runner.js +129 -33
  163. package/dist/runner/store-port.d.ts +1 -1
  164. package/dist/runner/store-secrets.d.ts +6 -0
  165. package/dist/runner/store-secrets.js +49 -7
  166. package/dist/runner/subagent.js +4 -40
  167. package/dist/runner/workflow-first.d.ts +11 -4
  168. package/dist/runner/workflow-first.js +14 -8
  169. package/dist/runner/workflow-spec.js +3 -2
  170. package/dist/runs-over-store.d.ts +15 -6
  171. package/dist/runs-over-store.js +33 -21
  172. package/dist/scrub-command.d.ts +73 -0
  173. package/dist/scrub-command.js +307 -0
  174. package/dist/secret-cut.d.ts +73 -0
  175. package/dist/secret-cut.js +291 -4
  176. package/dist/secret-rules.d.ts +143 -0
  177. package/dist/secret-rules.js +2564 -0
  178. package/dist/secrets.d.ts +7 -0
  179. package/dist/secrets.js +20 -0
  180. package/dist/server-keys.d.ts +20 -0
  181. package/dist/server-keys.js +25 -6
  182. package/dist/server.d.ts +52 -11
  183. package/dist/server.js +345 -118
  184. package/dist/skills/agentrun-serve/SKILL.md +4 -0
  185. package/dist/store/index.d.ts +1 -1
  186. package/dist/store/index.js +1 -1
  187. package/dist/store/journal/storage.js +1 -1
  188. package/dist/store/postgres/migrations/0027_run_launch_census.sql +31 -0
  189. package/dist/store/schema.d.ts +6 -0
  190. package/dist/store/schema.js +11 -1
  191. package/dist/store/seal.d.ts +6 -1
  192. package/dist/store/seal.js +5 -3
  193. package/dist/store/sqlite/run-launch.d.ts +9 -1
  194. package/dist/store/sqlite/run-launch.js +24 -13
  195. package/dist/store/sqlite/run-patch.d.ts +1 -1
  196. package/dist/store/sqlite/run-patch.js +13 -4
  197. package/dist/store/sqlite/store.js +34 -4
  198. package/dist/store/store.d.ts +43 -2
  199. package/dist/store/store.js +20 -0
  200. package/dist/store-reads/learning.d.ts +6 -3
  201. package/dist/store-reads/learning.js +22 -7
  202. package/dist/store-view.d.ts +3 -0
  203. package/dist/store-view.js +3 -3
  204. package/dist/suggestions.js +3 -2
  205. package/dist/template-eval.d.ts +20 -9
  206. package/dist/template-eval.js +115 -33
  207. package/dist/template-import.d.ts +10 -0
  208. package/dist/template-import.js +16 -7
  209. package/dist/templates.d.ts +10 -2
  210. package/dist/templates.js +28 -8
  211. package/dist/timeline/labels.d.ts +6 -4
  212. package/dist/timeline/labels.js +18 -6
  213. package/dist/timeline/timeline.d.ts +5 -0
  214. package/dist/timeline/timeline.js +14 -8
  215. package/dist/timeline/util.js +1 -1
  216. package/dist/timeline/web-calls.d.ts +26 -9
  217. package/dist/timeline/web-calls.js +124 -37
  218. package/dist/tool-gate.d.ts +42 -3
  219. package/dist/tool-gate.js +66 -5
  220. package/dist/tool-keys-store.d.ts +2 -4
  221. package/dist/tool-keys-store.js +5 -21
  222. package/dist/tool-keys.d.ts +2 -2
  223. package/dist/tool-keys.js +2 -2
  224. package/dist/tool-list.js +1 -1
  225. package/dist/tool-plane.d.ts +2 -2
  226. package/dist/tool-plane.js +35 -33
  227. package/dist/tools.js +13 -7
  228. package/dist/trigger-targets.d.ts +4 -0
  229. package/dist/trigger-targets.js +9 -2
  230. package/dist/triggers.d.ts +67 -4
  231. package/dist/triggers.js +171 -22
  232. package/dist/until.d.ts +3 -0
  233. package/dist/until.js +11 -0
  234. package/dist/web-fake.d.ts +1 -3
  235. package/dist/web-fake.js +7 -18
  236. package/dist/web-fetch.d.ts +6 -72
  237. package/dist/web-fetch.js +11 -265
  238. package/dist/web-run.d.ts +31 -0
  239. package/dist/web-run.js +90 -0
  240. package/dist/web-save.d.ts +6 -4
  241. package/dist/web-save.js +9 -12
  242. package/dist/web-search.d.ts +9 -127
  243. package/dist/web-search.js +23 -259
  244. package/dist/wires.d.ts +13 -0
  245. package/dist/wires.js +11 -0
  246. package/dist/workflow-run.d.ts +5 -4
  247. package/dist/workflow-run.js +5 -4
  248. package/dist/workspace/computer-deps.d.ts +2 -1
  249. package/dist/workspace/computer-deps.js +9 -2
  250. package/dist/workspace/computer-for-claim.d.ts +12 -1
  251. package/dist/workspace/computer-for-claim.js +77 -8
  252. package/dist/workspace/computer-kept.d.ts +3 -0
  253. package/dist/workspace/computer-kept.js +11 -2
  254. package/dist/workspace/index.d.ts +1 -1
  255. package/dist/workspace/index.js +1 -1
  256. package/dist/workspace/kind-skills.d.ts +4 -0
  257. package/dist/workspace/kind-skills.js +9 -0
  258. package/dist/workspace/synced-folder.js +3 -4
  259. package/dist/wrapped.d.ts +13 -5
  260. package/dist/wrapped.js +52 -26
  261. package/package.json +17 -11
  262. package/skills/agentrun-serve/SKILL.md +4 -0
  263. package/templates/README.md +30 -8
  264. package/dist/console/assets/index-CQ3cJRzI.js +0 -746
  265. package/dist/console/assets/index-DKkaS3a0.css +0 -1
  266. package/dist/exa-keyless.d.ts +0 -34
  267. package/dist/exa-keyless.js +0 -118
  268. package/dist/firecrawl-keyless.d.ts +0 -41
  269. package/dist/firecrawl-keyless.js +0 -152
  270. package/dist/keyless-mcp.d.ts +0 -36
  271. package/dist/keyless-mcp.js +0 -127
  272. package/dist/text-urls.d.ts +0 -38
  273. package/dist/text-urls.js +0 -170
  274. package/dist/web-fetch-direct.d.ts +0 -119
  275. package/dist/web-fetch-direct.js +0 -190
@@ -10,8 +10,9 @@
10
10
  // harness selection reads no setting, so claude-agent runs on the model keys as it does without the mode. The mode is
11
11
  // for a server one person runs: it is refused where more than one person can start runs, `on` included, and the owner
12
12
  // confirms they alone run agents here. It runs only in a runner place, on the machine the owner turned it on for.
13
- import { accessSync, constants, existsSync, mkdirSync } from "node:fs";
14
- import { homedir, hostname } from "node:os";
13
+ import { randomBytes } from "node:crypto";
14
+ import { accessSync, chmodSync, constants, existsSync, linkSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
15
+ import { homedir } from "node:os";
15
16
  import { delimiter, isAbsolute, join } from "node:path";
16
17
  import { facts as claudeFacts } from "@parcha/agentrun-harness-claude/facts";
17
18
  import { registerSecretWrite } from "./secret-writes.js";
@@ -46,41 +47,102 @@ export const LOGIN_DEFAULT_MODEL = "anthropic/claude-sonnet-5-5";
46
47
  /** Where the login is: AgentRun's own directory in its data (`agentrun`, the default), or this machine's own Claude Code
47
48
  * login (`machine`, which the owner opts into by name). */
48
49
  export const LOGIN_PLACES = ["agentrun", "machine"];
50
+ /** The file in the data folder that holds this machine's id (machineId). */
51
+ export const MACHINE_ID_FILE = "machine-id";
52
+ const MACHINE_ID = /^[0-9a-f]{32}$/;
53
+ /** This machine's id, which names the machine the login was turned on for: a random one, made once in
54
+ * `<data>/machine-id` (0600) and read back by every later start. Never the hostname, which moves with the network (a
55
+ * laptop's at home is not its name at the office), while the data folder stays. A missing file, or one that holds no
56
+ * id or can't be read, gets a fresh id, so a setting saved under the old one reads as another machine's until turned on
57
+ * again. The file appears whole: written aside, then linked in place, so a start beside this one that made an id first
58
+ * keeps its own, and both read that one. */
59
+ export function machineId(data) {
60
+ const file = join(data, MACHINE_ID_FILE);
61
+ const read = () => {
62
+ try {
63
+ const id = readFileSync(file, "utf8").trim();
64
+ return MACHINE_ID.test(id) ? id : undefined;
65
+ }
66
+ catch {
67
+ return undefined;
68
+ }
69
+ };
70
+ const known = read();
71
+ if (known)
72
+ return known;
73
+ const id = randomBytes(16).toString("hex");
74
+ const aside = `${file}.${process.pid}.${randomBytes(4).toString("hex")}`;
75
+ writeFileSync(aside, `${id}\n`, { mode: 0o600, flag: "wx" });
76
+ try {
77
+ // The umask may take more than 0600 leaves; never less.
78
+ chmodSync(aside, 0o600);
79
+ try {
80
+ linkSync(aside, file);
81
+ }
82
+ catch (error) {
83
+ if (error.code !== "EEXIST")
84
+ throw error;
85
+ // Another start made one first: that one. Else what is there holds no id, and this one takes its place.
86
+ const theirs = read();
87
+ if (theirs)
88
+ return theirs;
89
+ renameSync(aside, file);
90
+ }
91
+ }
92
+ finally {
93
+ rmSync(aside, { force: true });
94
+ }
95
+ return id;
96
+ }
49
97
  /** This machine's own Claude Code login folder as the CLI finds it for the server's user, by the CLI's own rule: its
50
98
  * config dir is `CLAUDE_CONFIG_DIR` when set, else `~/.claude`, and its credentials are kept there too unless
51
99
  * `CLAUDE_SECURESTORAGE_CONFIG_DIR` says otherwise. Read from the server's env, so a Claude Code started with another
52
100
  * `CLAUDE_CONFIG_DIR` is found only when AgentRun was started with it as well. A relative one is not taken: the CLI would
53
- * read it against a working directory this server does not share. `source` says which rule gave the folder. */
101
+ * read it against a working directory this server does not share. `source` says which rule gave the folder.
102
+ * `credentials`: the server's `CLAUDE_SECURESTORAGE_CONFIG_DIR` when it sets one the CLI takes as it is (an absolute
103
+ * path, or empty: `~/.claude`, and on macOS the Keychain item with no suffix), where the CLI keeps the tokens apart
104
+ * from the folder; a relative one is not taken, as above. */
54
105
  export function machineFolder(env = process.env) {
106
+ const secure = env.CLAUDE_SECURESTORAGE_CONFIG_DIR;
107
+ const credentials = secure === "" || (secure && isAbsolute(secure)) ? { credentials: secure } : {};
55
108
  if (env.CLAUDE_CONFIG_DIR && isAbsolute(env.CLAUDE_CONFIG_DIR))
56
- return { folder: env.CLAUDE_CONFIG_DIR, source: "CLAUDE_CONFIG_DIR" };
57
- const home = env.HOME && isAbsolute(env.HOME) ? env.HOME : homedir();
58
- return { folder: join(home, ".claude"), source: "default" };
109
+ return { folder: env.CLAUDE_CONFIG_DIR, source: "CLAUDE_CONFIG_DIR", ...credentials };
110
+ return { folder: join(homeOf(env), ".claude"), source: "default", ...credentials };
59
111
  }
112
+ /** The person's home as the server's env says it: its `HOME` when absolute, else `os.homedir()`. The person's own CLI
113
+ * reads its home as Node does (`os.homedir()`, which is `HOME` when set), so the two agree for the server's own env;
114
+ * reading the env handed in first keeps it the one source a test or an embedding host can set. */
115
+ const homeOf = (env) => (env.HOME && isAbsolute(env.HOME) ? env.HOME : homedir());
60
116
  /** The directories of a login at `place`: AgentRun's in `data`, or this machine's (machineFolder, and the Anthropic
61
117
  * profiles where the CLI looks for them: `ANTHROPIC_CONFIG_DIR`, else `$XDG_CONFIG_HOME/anthropic`, else
62
118
  * `~/.config/anthropic`). This machine's on the CLI's default folder carries the person's home too, so the harness
63
119
  * points the CLI at it as their own CLI runs, with no folder variable (the harness's signInEnv and loginEnv). This
64
- * machine's is `shared` with the person's own CLI, so a status check runs on a copy of its account file
65
- * (the harness's claudeLoginStatus). */
120
+ * machine's with a credentials dir in the server's env (machineFolder's `credentials`) carries it as `secure`, absolute
121
+ * (empty: `~/.claude`, `unsuffixed`), so the CLI keeps the tokens where the person's own CLI with it does. A status
122
+ * check at either place runs on a copy of the account file (the harness's claudeLoginStatus). Every login carries the
123
+ * person's home as `userHome`, read here once (homeOf), so the status check, the sign-in and a run on macOS all run in
124
+ * that one home whatever reads it later (the harness's personHome). */
66
125
  export function loginAt(place, data, env = process.env) {
126
+ const home = homeOf(env);
67
127
  if (place === "agentrun")
68
- return { dir: join(data, "claude-login"), profiles: join(data, "claude-login", "anthropic") };
69
- const home = env.HOME && isAbsolute(env.HOME) ? env.HOME : homedir();
128
+ return { dir: join(data, "claude-login"), profiles: join(data, "claude-login", "anthropic"), userHome: home };
70
129
  const config = env.XDG_CONFIG_HOME && isAbsolute(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : join(home, ".config");
71
- const { folder, source } = machineFolder(env);
72
- return { dir: folder, profiles: env.ANTHROPIC_CONFIG_DIR && isAbsolute(env.ANTHROPIC_CONFIG_DIR) ? env.ANTHROPIC_CONFIG_DIR : join(config, "anthropic"), ...(source === "default" ? { home } : {}), shared: true };
130
+ const { folder, source, credentials } = machineFolder(env);
131
+ const secure = credentials === undefined ? {} : credentials === "" ? { secure: join(home, ".claude"), unsuffixed: true } : { secure: credentials };
132
+ return { dir: folder, profiles: env.ANTHROPIC_CONFIG_DIR && isAbsolute(env.ANTHROPIC_CONFIG_DIR) ? env.ANTHROPIC_CONFIG_DIR : join(config, "anthropic"), ...(source === "default" ? { home } : {}), ...secure, userHome: home };
73
133
  }
74
134
  /** The setting as saved, or undefined when the mode is not on (or the row is not one this reads). */
75
135
  export async function claudeLoginSetting(settings) {
76
136
  const row = (await settings.get(CLAUDE_LOGIN_SETTING));
77
- if (!row || row.v !== 1 || !LOGIN_PLACES.includes(row.place) || typeof row.host !== "string" || row.only_me !== true)
137
+ if (!row || row.v !== 1 || !LOGIN_PLACES.includes(row.place) || (row.machine !== undefined && typeof row.machine !== "string") || row.only_me !== true)
78
138
  return undefined;
79
139
  return row;
80
140
  }
141
+ /** Whether `setting` was turned on for this machine: the one whose data folder (`data`) holds its id (machineId). */
142
+ const thisMachine = (setting, data) => setting.machine === machineId(data);
81
143
  /** The login a run here goes on: the setting's, when the switch is not off and this is the machine it was turned on for. */
82
144
  export function loginOf(setting, data, env) {
83
- if (!setting || claudeLoginOff(env) || setting.host !== hostname())
145
+ if (!setting || claudeLoginOff(env) || !thisMachine(setting, data))
84
146
  return undefined;
85
147
  return loginAt(setting.place, data, env);
86
148
  }
@@ -137,8 +199,19 @@ export function whyNotOneOwner(facts) {
137
199
  return "This server has no owner (the API-only profile), so anyone with its token starts runs: a Claude plan is one person's.";
138
200
  if (facts.tokens > 1)
139
201
  return `This server takes ${facts.tokens} API tokens, so more than one person can start runs here: a Claude plan is one person's.`;
202
+ // A key made in the console for an app (api-keys.ts) is one more caller that starts runs, as a second token is.
203
+ // `keysDormant`: the keys open nothing on this server (api-keys.ts dormant), and would at a start that takes them.
204
+ const keys = facts.keys ?? 0;
205
+ if (keys > 0) {
206
+ const [what, it] = keys === 1 ? ["an API key", "it"] : [`${keys} API keys`, "them"];
207
+ return facts.keysDormant
208
+ ? `This server keeps ${what} made for apps (Settings → AgentRun API keys). ${keys === 1 ? "It opens" : "They open"} nothing here, and would open the server at a start that takes keys again: a Claude plan is one person's. Revoke ${it} first.`
209
+ : `This server has ${what} made for apps (Settings → AgentRun API keys), so more than one caller can start runs here: a Claude plan is one person's. Revoke ${it} first.`;
210
+ }
140
211
  return undefined;
141
212
  }
213
+ /** Why a server with Claude Code's login on makes no API key for an app, in one line: the same rule from the other side. */
214
+ export const LOGIN_REFUSES_API_KEYS = "Claude Code's login on this machine is on, and a Claude plan is one person's: an API key would let an app start runs on it. Turn the login off under Settings → Model keys first.";
142
215
  /** The account's words, as the view shows them. */
143
216
  export const accountOf = (status) => ({ ...(status.method ? { method: status.method } : {}), ...(status.email ? { email: status.email } : {}), ...(status.organization ? { organization: status.organization } : {}), ...(status.plan ? { plan: status.plan } : {}) });
144
217
  /** The body of a turn-on, checked: where the login is, and the owner's word that they alone run agents here. */
@@ -150,12 +223,12 @@ export function turnOnBody(body) {
150
223
  return { problem: "only_me must be true: confirm you alone run agents on this server, since its runs would use your Claude plan" };
151
224
  return { place: given.place ?? "agentrun" };
152
225
  }
153
- /** The setting a turn-on saves, for this machine. AgentRun's own login directory is made (0700) so the CLI can keep its
154
- * login there; nothing in it is read. */
226
+ /** The setting a turn-on saves, for this machine (machineId). AgentRun's own login directory is made (0700) so the CLI
227
+ * can keep its login there; nothing in it is read. */
155
228
  export function settingFor(place, data) {
156
229
  if (place === "agentrun")
157
230
  mkdirSync(join(data, "claude-login"), { recursive: true, mode: 0o700 });
158
- return { v: 1, place, host: hostname(), only_me: true };
231
+ return { v: 1, place, machine: machineId(data), only_me: true };
159
232
  }
160
233
  /** The login a run of `harness` on this runner goes on: the saved setting's, read now, when the switch is not off, the
161
234
  * harness runs on it, the run is in a runner place (`place`), and this is the machine it was turned on for; else none,
@@ -168,6 +241,13 @@ export async function loginForRun(settings, data, env, harness, place) {
168
241
  /** The routes here (server.ts): every one answers 404, by its name, while the mode is off (`why`). */
169
242
  export const CLAUDE_LOGIN_ROUTES = new Set(["getClaudeLogin", "turnOnClaudeLogin", "turnOffClaudeLogin", "startClaudeLogin"]);
170
243
  export const claudeLoginRouteOff = (name, why) => `${name}: Claude Code's login on this machine is off on this server: ${why}.`;
244
+ /** What the one-owner rule gives the login's routes over a server's keys: `refused`, which counts the keys each time
245
+ * it is asked, and `turn`, the keys' own. The server's routes take both from here, and so does the test that runs the
246
+ * turn-on against a held revocation: neither is a value read once, or a turn of its own. */
247
+ export const oneOwnerDeps = (facts, keys) => ({
248
+ refused: () => whyNotOneOwner({ ...facts, keys: keys.count }),
249
+ turn: (work) => keys.inTurn(work),
250
+ });
171
251
  /** A route's refusal in words, answered as its `code` (server.ts makes it an ApiError). */
172
252
  export class ClaudeLoginRefused extends Error {
173
253
  code;
@@ -183,86 +263,165 @@ export async function claudeLoginView(deps) {
183
263
  const login = loginAt(place, deps.data, deps.env);
184
264
  const cli = loginCli(await deps.pinned(), deps.env);
185
265
  const signIn = deps.signIns.view();
186
- const base = { place, command: (await deps.claude()).claudeLoginCommand(login, cli ?? "claude"), can_start: deps.sameMachine && cli !== undefined && deps.refused === undefined, ...(deps.refused ? { refused: deps.refused } : {}), folder: login.dir, machine: machineFolder(deps.env), ...(signIn ? { sign_in: signIn } : {}) };
266
+ const refused = deps.refused();
267
+ const base = { place, command: (await deps.claude()).claudeLoginCommand(login, cli ?? "claude"), can_start: deps.sameMachine && cli !== undefined && refused === undefined, ...(refused ? { refused } : {}), folder: login.dir, machine: machineFolder(deps.env), ...(signIn ? { sign_in: signIn } : {}) };
187
268
  if (!setting)
188
269
  return { state: "off", ...base };
189
- if (setting.host !== hostname())
270
+ if (!thisMachine(setting, deps.data))
190
271
  return { state: "other_machine", ...base, can_start: false };
191
272
  if (!cli)
192
273
  return { state: "no_cli", ...base };
193
274
  try {
275
+ // Asked once: a person waits on this read. Its answer is a run's too (loginBeforeRun), so one who just saw the
276
+ // login signed in here has a run on a slow host go on.
194
277
  const said = await (await deps.claude()).claudeLoginStatus(cli, login, pathOf(deps.env));
278
+ noteAnswer(login, said, Date.now());
195
279
  return said.signedIn ? { state: "signed_in", ...base, account: accountOf(said) } : { state: "signed_out", ...base };
196
280
  }
197
281
  catch {
198
282
  return { state: "unknown", ...base };
199
283
  }
200
284
  }
201
- /** PUT /settings/claude-login: turned on, refused in one line where more than one person can start runs. */
285
+ /** PUT /settings/claude-login: turned on, refused in one line where more than one person can start runs. A turn-on that
286
+ * moves the login to another place first ends a sign-in this server started that still waits: its CLI signs in at the
287
+ * old place, which the login no longer reads. One at the same place leaves it waiting, as it still signs in there. */
202
288
  export async function turnOnClaudeLogin(deps, body) {
203
- if (deps.refused)
204
- throw new ClaudeLoginRefused("forbidden", deps.refused);
205
- const asked = turnOnBody(body);
206
- if ("problem" in asked)
207
- throw new ClaudeLoginRefused("input_invalid", asked.problem);
208
- await deps.settings.put(CLAUDE_LOGIN_SETTING, settingFor(asked.place, deps.data));
289
+ // `refused` is asked only in the keys' turn (deps.turn), where a key being made or revoked has landed, or been undone.
290
+ // Asked once before the sign-in is touched, so a turn-on refused or malformed then leaves a waiting sign-in as it was;
291
+ // and again with the write, in one turn, so no key is made between the decision and the setting. A key made between
292
+ // the two turns, on a turn-on that moves the place, is the one case that both stops the sign-in and refuses: nothing
293
+ // is written, and the person starts the sign-in again once the key is revoked. The sign-in's stop and
294
+ // what follows the write (the reading again, the CLI's status) are outside the keys' turn, so a key's revocation never
295
+ // waits on the CLI.
296
+ const refusal = () => {
297
+ const refused = deps.refused();
298
+ if (refused)
299
+ throw new ClaudeLoginRefused("forbidden", refused);
300
+ };
301
+ const asked = await deps.turn(async () => {
302
+ refusal();
303
+ const asked = turnOnBody(body);
304
+ if ("problem" in asked)
305
+ throw new ClaudeLoginRefused("input_invalid", asked.problem);
306
+ return asked;
307
+ });
308
+ await deps.signIns.serial(async (turn) => {
309
+ if ((await claudeLoginSetting(deps.settings))?.place !== asked.place)
310
+ await turn.stop();
311
+ await deps.turn(async () => {
312
+ refusal();
313
+ const setting = settingFor(asked.place, deps.data);
314
+ await deps.settings.put(CLAUDE_LOGIN_SETTING, setting);
315
+ deps.saved(loginOf(setting, deps.data, deps.env));
316
+ });
317
+ });
209
318
  await deps.changed();
210
319
  return claudeLoginView(deps);
211
320
  }
212
321
  /** DELETE /settings/claude-login: turned off, and a sign-in this server started that still waits is ended. The login
213
322
  * itself stays as the CLI keeps it; nothing here signs it out. */
214
323
  export async function turnOffClaudeLogin(deps) {
215
- await deps.signIns.stop();
216
- await deps.settings.remove(CLAUDE_LOGIN_SETTING);
324
+ await deps.signIns.serial(async (turn) => {
325
+ await turn.stop();
326
+ await deps.settings.remove(CLAUDE_LOGIN_SETTING);
327
+ deps.saved(undefined);
328
+ });
217
329
  await deps.changed();
218
330
  return claudeLoginView(deps);
219
331
  }
220
332
  /** POST /settings/claude-login/login: the CLI's own sign-in, started on this machine, where it opens a browser, with the
221
333
  * shown line's own variables (the harness's signInEnv), so it signs in where the status reads. A sign-in that
222
334
  * still waits is ended first (deps.signIns). The browser code goes to the CLI, never here; the answer is the view as it
223
- * is when the sign-in starts, its `sign_in` waiting. */
335
+ * is when the sign-in starts, its `sign_in` waiting. The setting is read, and the CLI started on it, in one turn. */
224
336
  export async function startLoginHere(deps) {
225
- if (deps.refused)
226
- throw new ClaudeLoginRefused("forbidden", deps.refused);
227
- const setting = await claudeLoginSetting(deps.settings);
228
- if (!setting)
229
- throw new ClaudeLoginRefused("agent_not_runnable", "Turn on Claude Code's login on this machine first.");
230
- if (setting.host !== hostname())
231
- throw new ClaudeLoginRefused("agent_not_runnable", "It was turned on for another machine: sign in there.");
232
- if (!deps.sameMachine)
233
- throw new ClaudeLoginRefused("forbidden", "The CLI's sign-in opens a browser on the server's machine: run the command shown in a terminal there.");
234
- const cli = loginCli(await deps.pinned(), deps.env);
235
- if (!cli)
236
- throw new ClaudeLoginRefused("agent_not_runnable", "No Claude Code CLI here yet: claude-agent's first run installs it, or run the command shown.");
237
- // The person's home and desktop, so the CLI can open their browser.
238
- const claude = await deps.claude();
239
- const login = loginAt(setting.place, deps.data, deps.env);
240
- await deps.signIns.start((timeoutMs) => claude.startClaudeLogin(cli, login, { ...pathOf(deps.env), ...(deps.env.HOME ? { home: deps.env.HOME } : {}), display: deps.env, timeoutMs }));
337
+ const refused = deps.refused();
338
+ if (refused)
339
+ throw new ClaudeLoginRefused("forbidden", refused);
340
+ await deps.signIns.serial(async (signIn) => {
341
+ const setting = await claudeLoginSetting(deps.settings);
342
+ if (!setting)
343
+ throw new ClaudeLoginRefused("agent_not_runnable", "Turn on Claude Code's login on this machine first.");
344
+ if (!thisMachine(setting, deps.data))
345
+ throw new ClaudeLoginRefused("agent_not_runnable", "It was turned on for another machine: sign in there.");
346
+ if (!deps.sameMachine)
347
+ throw new ClaudeLoginRefused("forbidden", "The CLI's sign-in opens a browser on the server's machine: run the command shown in a terminal there.");
348
+ const cli = loginCli(await deps.pinned(), deps.env);
349
+ if (!cli)
350
+ throw new ClaudeLoginRefused("agent_not_runnable", "No Claude Code CLI here yet: claude-agent's first run installs it, or run the command shown.");
351
+ // The person's home (the login's `userHome`) and desktop, so the CLI can open their browser.
352
+ const claude = await deps.claude();
353
+ const login = loginAt(setting.place, deps.data, deps.env);
354
+ await signIn.start((timeoutMs) => claude.startClaudeLogin(cli, login, { ...pathOf(deps.env), display: deps.env, timeoutMs }));
355
+ });
241
356
  return claudeLoginView(deps);
242
357
  }
243
358
  /** At the server's start: a setting saved where the mode is now off or refused (`why`: the switch, a listen address past
244
359
  * loopback, a second token, the API-only profile) goes, so no runner, in this process or another, runs on it; the reason
245
- * is logged. */
246
- export async function dropRefusedLogin(settings, why, log) {
247
- if (!why || !(await claudeLoginSetting(settings)))
360
+ * is logged. A turn on `signIns`' queue, as every change of the setting is. */
361
+ export async function dropRefusedLogin(signIns, settings, why, log) {
362
+ if (!why)
248
363
  return;
249
- await settings.remove(CLAUDE_LOGIN_SETTING);
250
- log(`Claude Code's login on this machine turned off: ${why}`);
364
+ await signIns.serial(async () => {
365
+ if (!(await claudeLoginSetting(settings)))
366
+ return;
367
+ await settings.remove(CLAUDE_LOGIN_SETTING);
368
+ log(`Claude Code's login on this machine turned off: ${why}`);
369
+ });
251
370
  }
252
371
  const pathOf = (env) => (env.PATH ? { path: env.PATH } : {});
372
+ /** How long a signed-in answer stands in for a check that gives none (loginBeforeRun). */
373
+ export const LOGIN_ANSWER_STANDS_MS = 10 * 60_000;
374
+ /** When each login last answered signed in, in this server process: in memory only, never on disk, and nothing but the
375
+ * time. A signed-out answer removes its entry. */
376
+ const signedInAt = new Map();
377
+ /** What tells one login from another here: its folder and its credentials dir. */
378
+ const loginKey = (login) => JSON.stringify([login.dir, login.secure ?? null, login.unsuffixed === true]);
379
+ /** Notes what the CLI said of `login` at `now`: signed in, the time; signed out, nothing (the earlier time goes). */
380
+ function noteAnswer(login, said, now) {
381
+ if (said.signedIn)
382
+ signedInAt.set(loginKey(login), now);
383
+ else
384
+ signedInAt.delete(loginKey(login));
385
+ }
386
+ /** The harness's codes for a status check that gave no answer (claudeLoginStatus's ClaudeLoginTimedOut and
387
+ * ClaudeLoginNoStatus), read by code as the harness loads only when asked. */
388
+ const NO_ANSWER = new Set(["timed_out", "no_status"]);
389
+ const gaveNoAnswer = (error) => NO_ANSWER.has(error?.code);
390
+ /** The run's refusal when its login's CLI could not say, with the check's own words. */
391
+ const unknownLogin = (error) => new Error(`${LOGIN_UNKNOWN}: ${String(error?.message ?? error).slice(0, 200)}`);
253
392
  /** Before a run on the login: its CLI says it is signed in, or the run is refused in words (never a silent switch to a
254
393
  * key). `cli`: the CLI that answers (loginCli); none, nothing to ask yet. `status`: the CLI's status check (the harness's
255
- * claudeLoginStatus). */
256
- export async function loginBeforeRun(login, cli, status) {
394
+ * claudeLoginStatus, which asks once and, when the CLI gives no answer, throws with `code` "timed_out" or "no_status").
395
+ * A check that gives no answer (it timed out, or the CLI said nothing that reads as a status) is asked once more, since
396
+ * a loaded host can take past the limit with the login fine. Still none: the run goes on when this login answered
397
+ * signed in within LOGIN_ANSWER_STANDS_MS in this server process (a run's check here, or the Settings view's), as its
398
+ * own CLI still fails in words if the login is gone; else it is refused with LOGIN_UNKNOWN and why. Any other failure (a
399
+ * CLI that is not at its path, say) is refused with LOGIN_UNKNOWN and its own words at once, asked once and never
400
+ * waved through by an earlier answer. A signed-out answer is the answer: never asked again nor overridden, refused at
401
+ * once, and the earlier signed-in time goes. `now`: the clock (Date.now). */
402
+ export async function loginBeforeRun(login, cli, status, options = {}) {
257
403
  if (!login || !cli)
258
404
  return;
405
+ const now = options.now ?? Date.now;
259
406
  let said;
260
- try {
261
- said = await status(cli, login);
407
+ let lastError;
408
+ for (let attempt = 0; attempt < 2 && said === undefined; attempt++) {
409
+ try {
410
+ said = await status(cli, login);
411
+ }
412
+ catch (error) {
413
+ if (!gaveNoAnswer(error))
414
+ throw unknownLogin(error);
415
+ lastError = error;
416
+ }
262
417
  }
263
- catch (error) {
264
- throw new Error(`${LOGIN_UNKNOWN}: ${String(error?.message ?? error).slice(0, 200)}`);
418
+ if (said === undefined) {
419
+ const at = signedInAt.get(loginKey(login));
420
+ if (at !== undefined && now() - at <= LOGIN_ANSWER_STANDS_MS)
421
+ return;
422
+ throw unknownLogin(lastError);
265
423
  }
424
+ noteAnswer(login, said, now());
266
425
  if (!said.signedIn)
267
426
  throw new Error(LOGIN_SIGNED_OUT);
268
427
  }
@@ -14,6 +14,12 @@ export type SignInView = {
14
14
  signal?: string;
15
15
  error?: string;
16
16
  };
17
+ /** What a turn on the sign-ins' queue (ClaudeSignIns.serial) does to the sign-in, at once, as the turn holds the queue:
18
+ * end the one that waits and start another (`start`), or end it and forget it (`stop`). */
19
+ export type SignInTurn = {
20
+ start(begin: (limitMs: number) => ClaudeSignIn): Promise<SignInView>;
21
+ stop(): Promise<void>;
22
+ };
17
23
  /** The one sign-in this server started, and its start and stop. `limitMs`: how long a sign-in waits for its browser
18
24
  * (SIGN_IN_LIMIT_MS by default; a test's is short). `now`: the clock its times are read from. */
19
25
  export declare class ClaudeSignIns {
@@ -25,11 +31,16 @@ export declare class ClaudeSignIns {
25
31
  });
26
32
  /** The sign-in as it stands, or undefined when none was started here (or it was stopped). */
27
33
  view(): SignInView | undefined;
28
- /** Start a sign-in with `begin` (the harness's startClaudeLogin, given the limit), after ending one that waits. */
29
- start(begin: (limitMs: number) => ClaudeSignIn): Promise<SignInView>;
30
- /** End a sign-in that waits, and forget the one there is (a turn-off). */
31
- stop(): Promise<void>;
32
- /** The server's stop: as stop(), resolving once a CLI that waited is gone, and a start asked after it (a request still
33
- * in flight) spawns nothing. A CLI left waiting would keep the browser's callback port from the next server's sign-in. */
34
+ /** One turn on the queue: `work` runs alone, after every turn asked before it and before every one asked after, and
35
+ * starts or ends the sign-in through its `turn`. Every change of the login's setting and every start of a sign-in is a
36
+ * turn (claude-login.ts: the turn-on, the turn-off, the sign-in's start and the drop at the server's start), each
37
+ * reading the setting inside it, so none lands between another's read and its start or save. A turn lasts while it
38
+ * decides and starts: a sign-in's wait for its browser is no turn's. A turn that throws rejects its own answer alone;
39
+ * the next turn runs as if it had ended. A sign-in starts and ends only through a turn's `start` and `stop`: there is no
40
+ * start or stop beside them, since one called inside a turn would wait for that turn to end, for ever. */
41
+ serial<T>(work: (turn: SignInTurn) => Promise<T>): Promise<T>;
42
+ /** The server's stop: a turn that ends a sign-in that waits and forgets it, resolving once its CLI is gone; a start
43
+ * asked after it (a request still in flight) spawns nothing. A CLI left waiting would keep the browser's callback port
44
+ * from the next server's sign-in. */
34
45
  close(): Promise<void>;
35
46
  }
@@ -14,7 +14,7 @@ function endedView(started, end, at) {
14
14
  case "failed":
15
15
  return { ...ended, state: "not_started", error: end.message };
16
16
  case "stopped":
17
- // Only this server stops one, and it forgets it as it does (stop), so this view is never kept.
17
+ // Only this server stops one, and it forgets it as it does (a turn's stop), so this view is never kept.
18
18
  return { ...ended, state: "failed" };
19
19
  }
20
20
  }
@@ -24,9 +24,10 @@ export class ClaudeSignIns {
24
24
  limitMs;
25
25
  #now;
26
26
  #current;
27
- // Each start or stop is a turn of its own: an end that arrives after a later turn began is not kept.
28
- #turn = 0;
29
- // Starts and stops, one after another, so two presses at once never leave two CLIs waiting on one port.
27
+ // Each start or stop counts one: an end that arrives after a later start or stop is not kept.
28
+ #epoch = 0;
29
+ // The turns (serial), one after another, so two presses at once never leave two CLIs waiting on one port, and a change
30
+ // of the login's setting never lands between a sign-in's read of it and its start.
30
31
  #queue = Promise.resolve();
31
32
  // Set at the server's stop (close): no start after it spawns a CLI.
32
33
  #closed = false;
@@ -38,49 +39,51 @@ export class ClaudeSignIns {
38
39
  view() {
39
40
  return this.#current ? { ...this.#current.view } : undefined;
40
41
  }
41
- /** Start a sign-in with `begin` (the harness's startClaudeLogin, given the limit), after ending one that waits. */
42
- start(begin) {
43
- const next = this.#queue.then(async () => {
44
- await this.#end();
45
- const turn = ++this.#turn;
46
- const started = { started_at: new Date(this.#now()).toISOString(), limit_ms: this.limitMs };
47
- if (this.#closed) {
48
- this.#current = { view: { ...started, state: "not_started", ended_at: started.started_at, error: "this server is stopping" } };
49
- return this.view();
50
- }
51
- let handle;
52
- try {
53
- handle = begin(this.limitMs);
54
- }
55
- catch (error) {
56
- this.#current = { view: { ...started, state: "not_started", ended_at: started.started_at, error: words(error) } };
57
- return this.view();
58
- }
59
- this.#current = { view: { ...started, state: "waiting" }, handle };
60
- void handle.ended.then((end) => {
61
- if (turn === this.#turn)
62
- this.#current = { view: endedView(started, end, new Date(this.#now()).toISOString()) };
63
- });
64
- return this.view();
65
- });
66
- this.#queue = next.catch(() => { });
67
- return next;
68
- }
69
- /** End a sign-in that waits, and forget the one there is (a turn-off). */
70
- stop() {
71
- const next = this.#queue.then(() => this.#end());
42
+ /** One turn on the queue: `work` runs alone, after every turn asked before it and before every one asked after, and
43
+ * starts or ends the sign-in through its `turn`. Every change of the login's setting and every start of a sign-in is a
44
+ * turn (claude-login.ts: the turn-on, the turn-off, the sign-in's start and the drop at the server's start), each
45
+ * reading the setting inside it, so none lands between another's read and its start or save. A turn lasts while it
46
+ * decides and starts: a sign-in's wait for its browser is no turn's. A turn that throws rejects its own answer alone;
47
+ * the next turn runs as if it had ended. A sign-in starts and ends only through a turn's `start` and `stop`: there is no
48
+ * start or stop beside them, since one called inside a turn would wait for that turn to end, for ever. */
49
+ serial(work) {
50
+ const next = this.#queue.then(() => work({ start: (begin) => this.#start(begin), stop: () => this.#end() }));
72
51
  this.#queue = next.catch(() => { });
73
52
  return next;
74
53
  }
75
- /** The server's stop: as stop(), resolving once a CLI that waited is gone, and a start asked after it (a request still
76
- * in flight) spawns nothing. A CLI left waiting would keep the browser's callback port from the next server's sign-in. */
54
+ /** The server's stop: a turn that ends a sign-in that waits and forgets it, resolving once its CLI is gone; a start
55
+ * asked after it (a request still in flight) spawns nothing. A CLI left waiting would keep the browser's callback port
56
+ * from the next server's sign-in. */
77
57
  close() {
78
58
  this.#closed = true;
79
- return this.stop();
59
+ return this.serial((turn) => turn.stop());
60
+ }
61
+ async #start(begin) {
62
+ await this.#end();
63
+ const epoch = ++this.#epoch;
64
+ const started = { started_at: new Date(this.#now()).toISOString(), limit_ms: this.limitMs };
65
+ if (this.#closed) {
66
+ this.#current = { view: { ...started, state: "not_started", ended_at: started.started_at, error: "this server is stopping" } };
67
+ return this.view();
68
+ }
69
+ let handle;
70
+ try {
71
+ handle = begin(this.limitMs);
72
+ }
73
+ catch (error) {
74
+ this.#current = { view: { ...started, state: "not_started", ended_at: started.started_at, error: words(error) } };
75
+ return this.view();
76
+ }
77
+ this.#current = { view: { ...started, state: "waiting" }, handle };
78
+ void handle.ended.then((end) => {
79
+ if (epoch === this.#epoch)
80
+ this.#current = { view: endedView(started, end, new Date(this.#now()).toISOString()) };
81
+ });
82
+ return this.view();
80
83
  }
81
84
  async #end() {
82
85
  const current = this.#current;
83
- this.#turn++;
86
+ this.#epoch++;
84
87
  this.#current = undefined;
85
88
  if (current?.view.state !== "waiting" || !current.handle)
86
89
  return;