@parcha/agentrun-serve 0.1.0-beta.55 → 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 (296) hide show
  1. package/CHANGELOG.md +261 -0
  2. package/README.md +228 -45
  3. package/dist/acp-package.d.ts +2 -0
  4. package/dist/adapters.d.ts +18 -5
  5. package/dist/adapters.js +23 -9
  6. package/dist/agent-package.d.ts +3 -3
  7. package/dist/agent-package.js +17 -8
  8. package/dist/answer-json.d.ts +6 -2
  9. package/dist/answer-json.js +22 -4
  10. package/dist/api-keys.d.ts +76 -0
  11. package/dist/api-keys.js +217 -0
  12. package/dist/api-only.d.ts +17 -5
  13. package/dist/api-only.js +36 -8
  14. package/dist/browser-hold.d.ts +23 -0
  15. package/dist/browser-hold.js +48 -0
  16. package/dist/browser-person.d.ts +3 -0
  17. package/dist/browser-person.js +4 -1
  18. package/dist/calendar/tools.js +3 -2
  19. package/dist/chatgpt-plan.d.ts +28 -3
  20. package/dist/chatgpt-plan.js +182 -21
  21. package/dist/claude-login.d.ts +101 -14
  22. package/dist/claude-login.js +232 -49
  23. package/dist/claude-sign-in.d.ts +46 -0
  24. package/dist/claude-sign-in.js +93 -0
  25. package/dist/cli.js +63 -6
  26. package/dist/composio-made.d.ts +4 -0
  27. package/dist/composio-made.js +4 -0
  28. package/dist/composio-preset.d.ts +43 -2
  29. package/dist/composio-preset.js +92 -4
  30. package/dist/computer-held-routes.d.ts +5 -4
  31. package/dist/computer-held-routes.js +29 -8
  32. package/dist/computer-held.d.ts +6 -1
  33. package/dist/computer-held.js +14 -0
  34. package/dist/computer-record.js +4 -2
  35. package/dist/computer-viewer.js +4 -1
  36. package/dist/console/assets/{backend-D5EmB4N3.js → backend-DVhHzJX2.js} +19 -19
  37. package/dist/console/assets/index-Bwn1oTem.css +1 -0
  38. package/dist/console/assets/index-okP-y8PK.js +747 -0
  39. package/dist/console/index.html +2 -2
  40. package/dist/decisions.d.ts +1 -1
  41. package/dist/decisions.js +1 -1
  42. package/dist/docker-host-addresses.d.ts +22 -11
  43. package/dist/docker-host-addresses.js +38 -26
  44. package/dist/env-switch.d.ts +10 -0
  45. package/dist/env-switch.js +33 -2
  46. package/dist/errors.d.ts +1 -0
  47. package/dist/errors.js +2 -0
  48. package/dist/fal-price.d.ts +58 -20
  49. package/dist/fal-price.js +341 -82
  50. package/dist/handed-values.d.ts +43 -1
  51. package/dist/handed-values.js +119 -2
  52. package/dist/harness-archive.d.ts +13 -10
  53. package/dist/harness-archive.js +60 -34
  54. package/dist/harness-check.d.ts +3 -1
  55. package/dist/harness-check.js +25 -46
  56. package/dist/harness-keys.d.ts +73 -27
  57. package/dist/harness-keys.js +194 -61
  58. package/dist/harness-recipe-entry.d.ts +8 -7
  59. package/dist/harness-recipe-entry.js +21 -32
  60. package/dist/harness-recipe.d.ts +38 -25
  61. package/dist/harness-recipe.js +49 -36
  62. package/dist/harness-sign-in.js +12 -23
  63. package/dist/harness-table.d.ts +10 -3
  64. package/dist/harness-table.js +26 -21
  65. package/dist/harness.d.ts +1 -0
  66. package/dist/harness.js +17 -5
  67. package/dist/host-check.d.ts +4 -0
  68. package/dist/host-check.js +4 -0
  69. package/dist/hosted-search.d.ts +1 -1
  70. package/dist/hosted-search.js +1 -2
  71. package/dist/import-worker.d.ts +4 -2
  72. package/dist/import-worker.js +9 -2
  73. package/dist/in-flight.d.ts +26 -0
  74. package/dist/in-flight.js +52 -0
  75. package/dist/key-refusal.d.ts +26 -5
  76. package/dist/key-refusal.js +313 -37
  77. package/dist/learn/secrets.d.ts +31 -11
  78. package/dist/learn/secrets.js +152 -191
  79. package/dist/learning-cost.d.ts +6 -3
  80. package/dist/learning-cost.js +4 -2
  81. package/dist/link-check.js +1 -1
  82. package/dist/llms.txt +2 -2
  83. package/dist/marketplace.d.ts +77 -0
  84. package/dist/marketplace.js +224 -0
  85. package/dist/mcp-api-only-origins.d.ts +30 -0
  86. package/dist/mcp-api-only-origins.js +57 -0
  87. package/dist/mcp-gateway.d.ts +7 -5
  88. package/dist/mcp-gateway.js +9 -12
  89. package/dist/mcp-secret-writes.js +5 -3
  90. package/dist/mcp-servers-store.d.ts +28 -6
  91. package/dist/mcp-servers-store.js +53 -4
  92. package/dist/media-duration.d.ts +3 -0
  93. package/dist/media-duration.js +90 -9
  94. package/dist/model-form.d.ts +5 -4
  95. package/dist/model-form.js +11 -7
  96. package/dist/model.d.ts +5 -2
  97. package/dist/model.js +9 -5
  98. package/dist/ollama-provider.d.ts +7 -1
  99. package/dist/ollama-provider.js +14 -2
  100. package/dist/openapi.d.ts +3 -3
  101. package/dist/openapi.js +245 -42
  102. package/dist/otel/genai.d.ts +65 -0
  103. package/dist/otel/genai.js +116 -0
  104. package/dist/otel/tracer.d.ts +55 -0
  105. package/dist/otel/tracer.js +308 -0
  106. package/dist/page.d.ts +2 -0
  107. package/dist/page.js +3 -1
  108. package/dist/paid-calls.d.ts +1 -32
  109. package/dist/paid-calls.js +4 -39
  110. package/dist/place-offers.d.ts +14 -6
  111. package/dist/place-offers.js +26 -13
  112. package/dist/provider.d.ts +9 -0
  113. package/dist/provider.js +50 -3
  114. package/dist/redact/match.d.ts +101 -0
  115. package/dist/redact/match.js +1152 -0
  116. package/dist/refusal-words.d.ts +11 -0
  117. package/dist/refusal-words.js +11 -0
  118. package/dist/run-census.d.ts +67 -0
  119. package/dist/run-census.js +240 -0
  120. package/dist/run-computer.d.ts +6 -3
  121. package/dist/run-computer.js +4 -1
  122. package/dist/run-cut.d.ts +15 -6
  123. package/dist/run-cut.js +30 -9
  124. package/dist/run-files.d.ts +3 -0
  125. package/dist/run-files.js +3 -0
  126. package/dist/run-launch.d.ts +12 -1
  127. package/dist/run-launch.js +9 -10
  128. package/dist/run-learning-served.d.ts +2 -0
  129. package/dist/run-model-key.d.ts +8 -0
  130. package/dist/run-model-key.js +31 -1
  131. package/dist/run-reads-over-store.d.ts +24 -6
  132. package/dist/run-reads-over-store.js +67 -23
  133. package/dist/run-recordings.d.ts +5 -1
  134. package/dist/run-recordings.js +39 -14
  135. package/dist/run-timeline-served.d.ts +3 -1
  136. package/dist/run-timeline-served.js +4 -4
  137. package/dist/run-usage.d.ts +1 -0
  138. package/dist/runnable.d.ts +10 -1
  139. package/dist/runnable.js +20 -8
  140. package/dist/runner/adapter-loop.d.ts +14 -0
  141. package/dist/runner/adapter-loop.js +56 -11
  142. package/dist/runner/adapter-run-spec.d.ts +45 -8
  143. package/dist/runner/adapter-run-spec.js +154 -29
  144. package/dist/runner/adapters/pi.js +25 -3
  145. package/dist/runner/beside.js +11 -6
  146. package/dist/runner/big-writes.js +1 -10
  147. package/dist/runner/claim-secrets.d.ts +18 -3
  148. package/dist/runner/claim-secrets.js +35 -6
  149. package/dist/runner/cli-run-spec.d.ts +6 -0
  150. package/dist/runner/cli-run-spec.js +85 -36
  151. package/dist/runner/computer-journal.d.ts +9 -1
  152. package/dist/runner/computer-journal.js +26 -0
  153. package/dist/runner/conformance/harness.js +1 -1
  154. package/dist/runner/feedback-round.js +3 -0
  155. package/dist/runner/harness-loops.d.ts +6 -5
  156. package/dist/runner/harness-loops.js +7 -7
  157. package/dist/runner/held.d.ts +11 -5
  158. package/dist/runner/journal-kinds.d.ts +5 -0
  159. package/dist/runner/journal-kinds.js +5 -0
  160. package/dist/runner/loop-contract.d.ts +4 -0
  161. package/dist/runner/main.js +15 -6
  162. package/dist/runner/mcp-claim.js +30 -3
  163. package/dist/runner/mcp-run.d.ts +12 -0
  164. package/dist/runner/mcp-run.js +12 -5
  165. package/dist/runner/model-route.d.ts +17 -0
  166. package/dist/runner/model-route.js +120 -2
  167. package/dist/runner/presence.d.ts +4 -3
  168. package/dist/runner/presence.js +4 -2
  169. package/dist/runner/run-child-host.d.ts +5 -0
  170. package/dist/runner/run-child-host.js +71 -30
  171. package/dist/runner/run-child.js +5 -2
  172. package/dist/runner/runner.d.ts +18 -3
  173. package/dist/runner/runner.js +162 -36
  174. package/dist/runner/store-port.d.ts +1 -1
  175. package/dist/runner/store-secrets.d.ts +6 -0
  176. package/dist/runner/store-secrets.js +49 -7
  177. package/dist/runner/subagent.js +4 -40
  178. package/dist/runner/workflow-first.d.ts +11 -4
  179. package/dist/runner/workflow-first.js +14 -8
  180. package/dist/runner/workflow-spec.js +3 -2
  181. package/dist/runs-over-store.d.ts +15 -6
  182. package/dist/runs-over-store.js +33 -21
  183. package/dist/scrub-command.d.ts +73 -0
  184. package/dist/scrub-command.js +307 -0
  185. package/dist/secret-cut.d.ts +73 -0
  186. package/dist/secret-cut.js +291 -4
  187. package/dist/secret-rules.d.ts +143 -0
  188. package/dist/secret-rules.js +2564 -0
  189. package/dist/secrets.d.ts +7 -0
  190. package/dist/secrets.js +20 -0
  191. package/dist/server-keys.d.ts +20 -0
  192. package/dist/server-keys.js +25 -6
  193. package/dist/server.d.ts +57 -13
  194. package/dist/server.js +371 -113
  195. package/dist/skills/agentrun-serve/SKILL.md +4 -0
  196. package/dist/store/dialect.d.ts +3 -0
  197. package/dist/store/dialect.js +1 -0
  198. package/dist/store/index.d.ts +1 -1
  199. package/dist/store/index.js +1 -1
  200. package/dist/store/journal/storage.js +1 -1
  201. package/dist/store/postgres/dialect.js +3 -0
  202. package/dist/store/postgres/migrations/0027_run_launch_census.sql +31 -0
  203. package/dist/store/schema.d.ts +6 -0
  204. package/dist/store/schema.js +11 -1
  205. package/dist/store/seal.d.ts +6 -1
  206. package/dist/store/seal.js +5 -3
  207. package/dist/store/sqlite/run-launch.d.ts +9 -1
  208. package/dist/store/sqlite/run-launch.js +24 -13
  209. package/dist/store/sqlite/run-patch.d.ts +1 -1
  210. package/dist/store/sqlite/run-patch.js +13 -4
  211. package/dist/store/sqlite/store.js +76 -16
  212. package/dist/store/store.d.ts +53 -3
  213. package/dist/store/store.js +27 -0
  214. package/dist/store-reads/learning.d.ts +6 -3
  215. package/dist/store-reads/learning.js +22 -7
  216. package/dist/store-view.d.ts +3 -0
  217. package/dist/store-view.js +4 -4
  218. package/dist/suggestions.js +3 -2
  219. package/dist/template-eval.d.ts +22 -11
  220. package/dist/template-eval.js +124 -41
  221. package/dist/template-import.d.ts +10 -0
  222. package/dist/template-import.js +16 -7
  223. package/dist/templates.d.ts +10 -2
  224. package/dist/templates.js +28 -8
  225. package/dist/timeline/index.d.ts +1 -1
  226. package/dist/timeline/index.js +1 -1
  227. package/dist/timeline/labels.d.ts +6 -4
  228. package/dist/timeline/labels.js +18 -6
  229. package/dist/timeline/timeline.d.ts +17 -7
  230. package/dist/timeline/timeline.js +28 -14
  231. package/dist/timeline/util.js +1 -1
  232. package/dist/timeline/web-calls.d.ts +26 -9
  233. package/dist/timeline/web-calls.js +124 -37
  234. package/dist/tool-gate.d.ts +42 -3
  235. package/dist/tool-gate.js +69 -6
  236. package/dist/tool-keys-store.d.ts +2 -4
  237. package/dist/tool-keys-store.js +5 -21
  238. package/dist/tool-keys.d.ts +2 -2
  239. package/dist/tool-keys.js +2 -2
  240. package/dist/tool-list.js +1 -1
  241. package/dist/tool-plane.d.ts +2 -2
  242. package/dist/tool-plane.js +35 -33
  243. package/dist/tools.js +13 -7
  244. package/dist/trigger-targets.d.ts +4 -0
  245. package/dist/trigger-targets.js +9 -2
  246. package/dist/triggers.d.ts +67 -4
  247. package/dist/triggers.js +171 -22
  248. package/dist/until.d.ts +3 -0
  249. package/dist/until.js +11 -0
  250. package/dist/validate.js +1 -1
  251. package/dist/web-fake.d.ts +1 -3
  252. package/dist/web-fake.js +7 -18
  253. package/dist/web-fetch.d.ts +6 -72
  254. package/dist/web-fetch.js +11 -265
  255. package/dist/web-run.d.ts +31 -0
  256. package/dist/web-run.js +90 -0
  257. package/dist/web-save.d.ts +6 -4
  258. package/dist/web-save.js +9 -12
  259. package/dist/web-search.d.ts +9 -127
  260. package/dist/web-search.js +23 -259
  261. package/dist/wires.d.ts +13 -0
  262. package/dist/wires.js +11 -0
  263. package/dist/workflow-run.d.ts +5 -4
  264. package/dist/workflow-run.js +5 -4
  265. package/dist/workspace/computer-deps.d.ts +3 -1
  266. package/dist/workspace/computer-deps.js +12 -4
  267. package/dist/workspace/computer-for-claim.d.ts +19 -2
  268. package/dist/workspace/computer-for-claim.js +101 -13
  269. package/dist/workspace/computer-janitor.d.ts +15 -7
  270. package/dist/workspace/computer-janitor.js +33 -8
  271. package/dist/workspace/computer-kept.d.ts +55 -4
  272. package/dist/workspace/computer-kept.js +129 -8
  273. package/dist/workspace/index.d.ts +1 -1
  274. package/dist/workspace/index.js +1 -1
  275. package/dist/workspace/kind-skills.d.ts +4 -0
  276. package/dist/workspace/kind-skills.js +9 -0
  277. package/dist/workspace/run-end-computers.d.ts +5 -1
  278. package/dist/workspace/run-end-computers.js +27 -1
  279. package/dist/workspace/synced-folder.js +3 -4
  280. package/dist/wrapped.d.ts +65 -0
  281. package/dist/wrapped.js +77 -0
  282. package/package.json +17 -11
  283. package/skills/agentrun-serve/SKILL.md +4 -0
  284. package/templates/README.md +38 -15
  285. package/dist/console/assets/index-DUYLaqiR.js +0 -746
  286. package/dist/console/assets/index-DYhU4adm.css +0 -1
  287. package/dist/exa-keyless.d.ts +0 -34
  288. package/dist/exa-keyless.js +0 -118
  289. package/dist/firecrawl-keyless.d.ts +0 -41
  290. package/dist/firecrawl-keyless.js +0 -152
  291. package/dist/keyless-mcp.d.ts +0 -36
  292. package/dist/keyless-mcp.js +0 -127
  293. package/dist/text-urls.d.ts +0 -38
  294. package/dist/text-urls.js +0 -170
  295. package/dist/web-fetch-direct.d.ts +0 -119
  296. package/dist/web-fetch-direct.js +0 -190
package/dist/api-only.js CHANGED
@@ -2,7 +2,8 @@
2
2
  // deploy's routes alone, and refuses every other address before anything else reads the request: the console at "/" and
3
3
  // its assets, sign-in and setup, settings but the MCP servers' names, a Composio server's save and the delete of a server
4
4
  // (the secret-write gate lets the token save over or delete only a server it saved, mcp-secret-writes.ts), the MCP
5
- // endpoint, triggers and their webhook hooks, the rest of agents and templates. Off by default.
5
+ // endpoint, triggers and their webhook hooks (all but a firing's release, which the launch hook's host sends), the rest
6
+ // of agents and templates. Off by default.
6
7
  import { API_ONLY_ENV } from "./env-switch.js";
7
8
  import { NOT_SET_UP } from "./runnable.js";
8
9
  import { LAUNCH_HOOK_SECRET_ENV, LAUNCH_HOOK_URL_ENV } from "./trigger-launch-hook.js";
@@ -32,9 +33,14 @@ import { LAUNCH_HOOK_SECRET_ENV, LAUNCH_HOOK_URL_ENV } from "./trigger-launch-ho
32
33
  * (mcp-secret-writes.ts tokenWriteOverRefused), and never writes a secret (secret-writes.ts). A Composio server names
33
34
  * its key by api_key_env (COMPOSIO_API_KEY, on the launcher's list of secrets, read at each use through secrets.ts
34
35
  * secret, sent to Composio's origin alone: composio-made.ts composioEnvKey), and its body names no address or headers.
35
- * There is no list or read of the servers here (listMcpServerNames above is the listing), and no generic save (saveMcpServer), so the
36
- * token saves no server at an address or with headers of its own. Previews, refreshes, sign-ins and Composio's
37
- * triggers stay refused. */
36
+ * There is no list or read of the servers here (listMcpServerNames above is the listing). The generic save
37
+ * (saveMcpServer) is served only when the operator names MCP origins (API_ONLY_MCP_ORIGINS_ENV), and then saves a
38
+ * per_run server (which keeps no credential) at one of those origins alone (apiOnlyMcpSave); unset, it is refused as
39
+ * any other route, so the token saves no server at an address or with headers of its own. Previews, refreshes,
40
+ * sign-ins and Composio's triggers stay refused;
41
+ * - the launch hook's host (the backend in front of this server) releases a firing it took and will start no run for
42
+ * (releaseTriggerFiring, triggers.ts release), so its trigger's room frees at once; with no launch hook the route is
43
+ * the route's own 422. */
38
44
  export const API_ONLY_ROUTES = new Set([
39
45
  "createRun", "createInlineRun", "getComputerDaemon",
40
46
  "getRunComputer", "takeOverRunComputer", "handBackRunComputer", "createRunComputerViewer",
@@ -47,7 +53,9 @@ export const API_ONLY_ROUTES = new Set([
47
53
  "createFile", "listFiles", "getFile", "uploadFile", "deleteFile",
48
54
  "getCapabilities", "getHealth", "getUsage", "getCapacity", "listMcpServerNames",
49
55
  "importTemplate", "applyTemplate", "getAgent", "listRevisions", "setCurrent", "archiveAgent", "unarchiveAgent",
50
- "saveComposioServer", "deleteMcpServer",
56
+ "saveComposioServer", "deleteMcpServer", "releaseTriggerFiring",
57
+ // Refused in its own words (403): it reads the machine's session files, which a server behind a backend does not have to give.
58
+ "getWrapped",
51
59
  ]);
52
60
  /** The trigger sources an apply on an API-only server makes once the server has the launch hook: the ones that fire on
53
61
  * its own clock and need nothing a refused route sets up. Each firing goes to the backend in front of it
@@ -67,18 +75,38 @@ export function apiOnlyTriggerSkipped(packageName, trigger, hooked) {
67
75
  return undefined;
68
76
  return { reason: NOT_SET_UP, message: `${named} and has no launch hook, so its firings have nowhere to go. Start its runs through the API, or set the launch hook (${LAUNCH_HOOK_URL_ENV} and ${LAUNCH_HOOK_SECRET_ENV}) and apply again: each firing then goes to your backend, which starts its run.` };
69
77
  }
78
+ /** Whether an API-only server saves `body` through the generic save (saveMcpServer) over the name its path gives: a
79
+ * per_run server (no credential kept) whose url's origin is one of `origins`, under a name that is not a Composio
80
+ * preset's (`preset`; Composio's own route saves those). Checked before anything reaches the address. A body that
81
+ * carries a credential never gets here: the secret-write gate refuses it first (403), as it refuses the token's save
82
+ * over a server it did not save or one that seals a credential (mcp-secret-writes.ts tokenWriteOverRefused). */
83
+ export function apiOnlyMcpSave(body, preset, origins) {
84
+ if (preset || origins.length === 0 || body === null || typeof body !== "object")
85
+ return false;
86
+ const { url, auth } = body;
87
+ if (auth === null || typeof auth !== "object" || auth.type !== "per_run" || typeof url !== "string")
88
+ return false;
89
+ try {
90
+ return origins.includes(new URL(url).origin);
91
+ }
92
+ catch {
93
+ return false;
94
+ }
95
+ }
70
96
  /** A run's computer live view: its page, files and socket, which take the viewer credential alone here (server.ts). */
71
97
  const COMPUTER_LIVE = /^\/v2\/runs\/[^/]+\/computer\/live\//;
72
98
  /** Whether an API-only server serves `method` on `raw` (the path as sent, its query cut): a /v2 path one of
73
- * API_ONLY_ROUTES matches for that method (HEAD as GET), or a GET of a run's computer live view. */
74
- export function servedApiOnly(routes, method, raw) {
99
+ * API_ONLY_ROUTES matches for that method (HEAD as GET), the generic MCP save when the operator names MCP origins
100
+ * (`mcpSave`, its body checked at the route: apiOnlyMcpSave), or a GET of a run's computer live view. */
101
+ export function servedApiOnly(routes, method, raw, mcpSave = false) {
75
102
  if (!raw.startsWith("/v2/"))
76
103
  return false;
77
104
  const path = raw.slice(3);
78
105
  const asked = method === "HEAD" ? "GET" : method;
79
106
  if (asked === "GET" && COMPUTER_LIVE.test(raw))
80
107
  return true;
81
- return routes.some((route) => API_ONLY_ROUTES.has(route.name) && route.method === asked && route.pattern.test(path));
108
+ const served = (name) => API_ONLY_ROUTES.has(name) || (name === "saveMcpServer" && mcpSave);
109
+ return routes.some((route) => served(route.name) && route.method === asked && route.pattern.test(path));
82
110
  }
83
111
  /** The refusal's words for `raw` on an API-only server. */
84
112
  export const apiOnlyRefusal = (raw) => `this server serves the run API only (${API_ONLY_ENV}=1): ${raw} is not served here`;
@@ -0,0 +1,23 @@
1
+ import type { WaitEndedSettings } from "./browser-wait-ended.js";
2
+ /** A take of the run's browser in force: the session's tag and when it went live (ISO). */
3
+ export type BrowserHeld = {
4
+ session: string;
5
+ at: string;
6
+ };
7
+ /** The settings key a run's browser take is kept under (the run's delete removes it: server.ts). */
8
+ export declare const browserHoldKey: (runId: string) => string;
9
+ /** The run's process, as a take of its browser goes live. */
10
+ export declare function markBrowserHeld(settings: WaitEndedSettings, runId: string, held: BrowserHeld, epoch?: number): Promise<void>;
11
+ /** The run's process, as a take ends (given back, idle, away, the cap, the session gone, an answered ask), as a browser
12
+ * session opens, or at the run's end. Given the claim's `epoch`, a take a later claim wrote stays. Given `session`, only
13
+ * that session's take goes (another session's take, live meanwhile, stays). */
14
+ export declare function clearBrowserHeld(settings: WaitEndedSettings, runId: string, epoch?: number, session?: string): Promise<void>;
15
+ /** Whether the owner holds the run's browser now: one settings read; a value of another shape is no take. */
16
+ export declare function browserHeld(settings: Pick<WaitEndedSettings, "get">, runId: string): Promise<boolean>;
17
+ /** The run's process's writes of its browser's take, each after the one before it, so a quick take and hand-back can never
18
+ * land backward (the hand-back's removal reading before the take's write is in). The first removes any take an earlier
19
+ * process of the run left: this process's viewers start with nobody holding the browser. A write that fails leaves the
20
+ * ones after it to run. */
21
+ export declare function browserHoldWriter(settings: WaitEndedSettings, runId: string, epoch?: number): {
22
+ held(tag: string, on: boolean, at: number): Promise<void>;
23
+ };
@@ -0,0 +1,48 @@
1
+ // Whether the owner drives a run's browser now, for the run read's `computer.state` (`taken_over`) and so for Running now's
2
+ // "You drive". A browser is taken over in its live view, in the run's process (browser-person.ts personHands.take), not
3
+ // through the server's command rows as a desktop or a phone is (computer-commands.ts), so the server learns it from one
4
+ // small setting per run (`browser_hold:<run id>`: { session, at, epoch }), as it learns an ended wait
5
+ // (browser-wait-ended.ts). The run's process writes it as a take goes live and removes it as the take ends, however it
6
+ // ends, one change after another (browserHoldWriter); it removes any row an earlier process of the run left as it
7
+ // starts, since its viewers start with nobody holding the browser, so a take a crashed process never ended is not read as
8
+ // still in force. The runner removes it at the run's end.
9
+ const keyOf = (runId) => `browser_hold:${runId}`;
10
+ /** The settings key a run's browser take is kept under (the run's delete removes it: server.ts). */
11
+ export const browserHoldKey = keyOf;
12
+ /** The run's process, as a take of its browser goes live. */
13
+ export async function markBrowserHeld(settings, runId, held, epoch) {
14
+ await settings.put(keyOf(runId), epoch === undefined ? held : { ...held, epoch });
15
+ }
16
+ /** The run's process, as a take ends (given back, idle, away, the cap, the session gone, an answered ask), as a browser
17
+ * session opens, or at the run's end. Given the claim's `epoch`, a take a later claim wrote stays. Given `session`, only
18
+ * that session's take goes (another session's take, live meanwhile, stays). */
19
+ export async function clearBrowserHeld(settings, runId, epoch, session) {
20
+ if (epoch !== undefined || session !== undefined) {
21
+ const written = (await settings.get(keyOf(runId)));
22
+ if (!written)
23
+ return;
24
+ if (epoch !== undefined && typeof written.epoch === "number" && written.epoch > epoch)
25
+ return;
26
+ if (session !== undefined && written.session !== session)
27
+ return;
28
+ }
29
+ await settings.remove(keyOf(runId));
30
+ }
31
+ /** Whether the owner holds the run's browser now: one settings read; a value of another shape is no take. */
32
+ export async function browserHeld(settings, runId) {
33
+ const value = await settings.get(keyOf(runId));
34
+ if (!value || typeof value !== "object")
35
+ return false;
36
+ const { session, at } = value;
37
+ return typeof session === "string" && typeof at === "string";
38
+ }
39
+ /** The run's process's writes of its browser's take, each after the one before it, so a quick take and hand-back can never
40
+ * land backward (the hand-back's removal reading before the take's write is in). The first removes any take an earlier
41
+ * process of the run left: this process's viewers start with nobody holding the browser. A write that fails leaves the
42
+ * ones after it to run. */
43
+ export function browserHoldWriter(settings, runId, epoch) {
44
+ let last = clearBrowserHeld(settings, runId, epoch).catch(() => undefined);
45
+ return {
46
+ held: (tag, on, at) => (last = last.then(() => (on ? markBrowserHeld(settings, runId, { session: tag, at: new Date(at).toISOString() }, epoch) : clearBrowserHeld(settings, runId, epoch, tag))).catch(() => undefined)),
47
+ };
48
+ }
@@ -58,6 +58,9 @@ export declare function personHands(options: {
58
58
  /** A wait on the person's answer ended with its browser let go (its window, the cap, its session gone): when (ms) and
59
59
  * the timeline row's words, for the Screen tab's ended state (browser-wait-ended.ts). Never throws out. */
60
60
  waitEnded?(at: number, why: string): void;
61
+ /** A take of session `tag` went live (`on`, at `at` ms) or ended, however it ended: for the run read's
62
+ * `computer.state` (browser-hold.ts). Never throws out. */
63
+ held?(tag: string, on: boolean, at: number): void;
61
64
  holdMs?: number;
62
65
  pollMs?: number;
63
66
  /** For tests: the timer functions the person's time is held again by. */
@@ -413,7 +413,9 @@ export function personHands(options) {
413
413
  if (ended || live)
414
414
  return;
415
415
  live = true;
416
- void note(HOST_PHASE, { summary: TAKEN, at: now() });
416
+ const at = now();
417
+ options.held?.(tag, true, at);
418
+ void note(HOST_PHASE, { summary: TAKEN, at });
417
419
  },
418
420
  // No hold started after all: what was held for it goes, and no row was written for it.
419
421
  cancel: () => {
@@ -432,6 +434,7 @@ export function personHands(options) {
432
434
  // they took it, so none says how it came back. An answered ask writes its own row.
433
435
  if (!live)
434
436
  return Promise.resolve();
437
+ options.held?.(tag, false, now());
435
438
  // Handed back by the person (the viewer's Hand back): their word that they are done, so the agent's open ask on
436
439
  // this session is answered done, as the hand-back route would answer it (first answer wins). Never on any other
437
440
  // end (cap, idle, away, released, answered): the person did not say they were done. The answer's own row
@@ -14,8 +14,9 @@ import { openCalendar, scrubAddress } from "./address.js";
14
14
  import { CALENDAR_ANSWER_MAX_CHARS, CALENDAR_DESCRIPTION, CALENDAR_ERROR_MAX_CHARS, CALENDAR_EVENTS, NAME_MAX, NO_CALENDAR } from "./names.js";
15
15
  import { held } from "../runner/held.js";
16
16
  /** `value` as JSON with a line break before each field and item: the longest line is one field's cut value. The run's
17
- * redactor (key-refusal.ts redactedAnswer) reads an answer in pieces split at whitespace and gives "[redacted]" for a run
18
- * of 8,192 characters with none, which compact JSON of a busy week (one-word titles, no description) is. */
17
+ * redactor (key-refusal.ts redactedAnswer) reads an answer in pieces split at whitespace, a run of 8,192 characters with
18
+ * none at a JSON string's end, and gives "[redacted]" for such a run with no such end; a line a field keeps every cut at
19
+ * whitespace, whatever a value holds. */
19
20
  const lined = (value) => {
20
21
  if (Array.isArray(value))
21
22
  return value.length ? `[\n${value.map(lined).join(",\n")}\n]` : "[]";
@@ -12,7 +12,8 @@ export declare const PLAN_FALLBACK_MODELS: readonly string[];
12
12
  /** The model a run on the plan gets when it names none. */
13
13
  export declare const PLAN_DEFAULT_MODEL = "gpt-6.1-sol";
14
14
  export type PlanState = "signed_out" | "pending" | "signed_in" | "expired";
15
- /** GET /settings/chatgpt: never a token. */
15
+ /** GET /settings/chatgpt: never a token. `problem`: why the last sign-in ended without signing in, in words. `hint`: on a
16
+ * sign-in waiting past its first minute, why it may be stuck (STILL_WAITING). */
16
17
  export type PlanView = {
17
18
  state: PlanState;
18
19
  email?: string;
@@ -20,6 +21,8 @@ export type PlanView = {
20
21
  authorize_url?: string;
21
22
  expires_at?: string;
22
23
  models?: string[];
24
+ problem?: string;
25
+ hint?: string;
23
26
  };
24
27
  /** The words a run or a request gets when there is no plan token to send. */
25
28
  export declare const SIGNED_OUT = "This server is not signed in to ChatGPT: sign in under Settings \u2192 Model keys, or name a model on a key.";
@@ -50,6 +53,14 @@ export declare const planOf: (env: NodeJS.ProcessEnv) => PlanReader | undefined;
50
53
  export declare function withPlan<E extends NodeJS.ProcessEnv>(env: E, plan: PlanReader | undefined): E;
51
54
  /** Whether `env` runs on the plan now. */
52
55
  export declare const signedIn: (env: NodeJS.ProcessEnv) => boolean;
56
+ /** Why a sign-in past its browser step ended without signing in, from what pi-ai's flow or keep threw: `reason` for the
57
+ * log (OpenAI's status and error code, a missing field's name, a network error's code; never a token or a code) and
58
+ * `words` a person reads. pi-ai's page says the sign-in completed before it exchanges the code, so these are the only
59
+ * word of a failure after it. */
60
+ export declare function signInFailure(error: unknown): {
61
+ reason: string;
62
+ words: string;
63
+ };
53
64
  export interface ChatGPTPlanDeps {
54
65
  /** `settings`: where a server keeps its host id, for a sign-in; a runner, which never signs in, has none. */
55
66
  readonly store: {
@@ -98,6 +109,10 @@ export declare class ChatGPTPlan implements PlanReader {
98
109
  /** This server's id at OpenAI (its agent host id): a UUID made once and kept in the store's settings. Not a credential. */
99
110
  private hostId;
100
111
  private cancel;
112
+ /** Ends the sign-in waiting past its 10 minutes: a cancel, which says nothing by itself, that says it timed out (with
113
+ * no admin guess when a code came back and its exchange was cut off). One whose code OpenAI answered is past waiting
114
+ * (it is being kept) and never times out. */
115
+ private expire;
101
116
  /** Starts a sign-in (one at a time: a new start cancels the one waiting) and gives the address to open. It lasts 10
102
117
  * minutes: the loopback callback finishes it where the browser runs on this machine; elsewhere finishSignIn does. */
103
118
  startSignIn(): Promise<{
@@ -112,6 +127,15 @@ export declare class ChatGPTPlan implements PlanReader {
112
127
  * of is revoked first, then replaced only while the row still holds it (a renewal of it that wrote back meanwhile is
113
128
  * read, revoked and replaced in turn), so no earlier pair is left alive. */
114
129
  private keep;
130
+ /** Tells the server the sign-in changed (its change callback: env read again, the listings relisted, the offers
131
+ * probed). What the server does with it is not the change's to fail: a failure is owed, said in the log (once: not
132
+ * again for `again`, a retry of one owed), and taken again at the server's next read (refresh). */
133
+ private tellChanged;
134
+ /** The sign-in as the store holds it now, read at the server's read of it: a runner may have renewed it, found it
135
+ * expired, or another server signed in or out. A change is told to the server, and so is one it failed to take, so
136
+ * what it offers does not wait for a restart. One at a time: a read while one is out waits for that one (the console
137
+ * polls, and each change relists and probes). */
138
+ refresh(): Promise<void>;
115
139
  /** The plan's models from OpenAI's list (GET /v1/models with the token), those of the current families; the fallback
116
140
  * list when it can't be read. */
117
141
  private listModels;
@@ -151,8 +175,9 @@ export declare class ChatGPTPlan implements PlanReader {
151
175
  * confirmed it. The endpoint is taken from OpenAI's discovery document only when it is https on auth.openai.com, so a
152
176
  * refresh token goes nowhere else. Never throws. */
153
177
  private revoke;
154
- /** Stops the sign-in waiting, at the server's close. */
155
- close(): void;
178
+ /** Stops the sign-in waiting, at the server's close. Resolves once every sign-in cancelled (by this, a newer start, a
179
+ * sign-out or its 10 minutes) has ended, whatever its end said in the log. */
180
+ close(): Promise<void>;
156
181
  }
157
182
  /** For a run on a plan model (`model`, the one its claim chose): the plan's token read once before anything starts, so a
158
183
  * sign-in that is gone, or that OpenAI refuses to renew, fails the run at once, in words (PlanUnavailable). */
@@ -38,6 +38,8 @@ const DIRECT_SCOPE = "chatgpt.tokens.use.direct";
38
38
  const AGENT_NAME = "AgentRun";
39
39
  const HOST_ID_SETTING = "chatgpt_host_id";
40
40
  const PENDING_MS = 10 * 60_000;
41
+ /** How long a sign-in waits before its view says why it may be stuck (STILL_WAITING): long before PENDING_MS ends it. */
42
+ const HINT_AFTER_MS = 60_000;
41
43
  const REFRESH_MARGIN_MS = 5 * 60_000;
42
44
  /** The longest one refresh call at OpenAI may take: its holder gives it up by then. */
43
45
  const REFRESH_CALL_MS = 15_000;
@@ -101,6 +103,67 @@ function whoOf(token) {
101
103
  /** Whether a renewal's refusal is for good: the refresh token spent, expired or revoked (a 400 or 401 from the token
102
104
  * endpoint, as pi-ai words it), not a network fault or a 5xx. */
103
105
  const refusedForGood = (error) => /\((400|401)\)|invalid_grant|refresh_token_(reused|expired|invalidated)/.test(String(error?.message ?? ""));
106
+ /** A sign-in OpenAI finished whose credential this server could not keep (keep threw). */
107
+ class NotKept extends Error {
108
+ }
109
+ /** `value` as a log field or a code in words: letters, digits and `_` alone, 40 at most. */
110
+ const tag = (value) => String(value ?? "").replace(/[^A-Za-z0-9_]/g, "").slice(0, 40);
111
+ /** OpenAI's error code for a workspace whose admin has turned off open-source apps' use of its ChatGPT plans. */
112
+ const WORKSPACE_DENIED = "3p_delegated_access_policy_denied";
113
+ const ADMIN_OFF = "Your ChatGPT workspace's admin has turned off open-source apps (External access → OSS → Use ChatGPT plan): ask them to turn it on, or sign in with another account.";
114
+ /** A grant without DIRECT_SCOPE: OpenAI signed the account in but gave no use of its plan by apps. */
115
+ const PLAN_NOT_USABLE = "This ChatGPT plan can't be used here: OpenAI's sign-in gave AgentRun no use of it. Free plans usually can't; sign in with a paid one.";
116
+ /** What a refusal whose reason OpenAI doesn't name ends with: a Free plan's sign-in has ended in one, and nothing tells it
117
+ * apart. It never says Free can't be used: OpenAI changes which plans can. */
118
+ const FREE_OR_AGAIN = "a Free ChatGPT plan may be the reason; with a paid plan, start it again.";
119
+ /** The likely cause of a sign-in OpenAI never sends back: a workspace whose admin has turned off open-source apps gets
120
+ * OpenAI's refusal on OpenAI's own page, with no way back to this server, so nothing here can tell it from a tab left
121
+ * open. Named first in a sign-in still waiting (STILL_WAITING) and in its timeout. */
122
+ const ADMIN_LIKELY = "If OpenAI's page showed an error instead of signing you in, your ChatGPT workspace's admin has likely turned off open-source apps (External access → OSS → Use ChatGPT plan): ask them to turn it on, or sign in with another account.";
123
+ const TIMED_OUT = `The sign-in timed out: OpenAI never sent the code back. ${ADMIN_LIKELY} Otherwise, start it again.`;
124
+ /** A pending view's `hint` from HINT_AFTER_MS into its wait on, while no code is in: a sign-in that goes through is back
125
+ * well within it. */
126
+ const STILL_WAITING = `OpenAI hasn't sent the code back yet. ${ADMIN_LIKELY}`;
127
+ /** The timeout of a sign-in whose code came back (the browser's return or a paste) while OpenAI was still answering it:
128
+ * no admin guess, since OpenAI's page did send the browser back. */
129
+ const CUT_OFF = "The sign-in timed out while OpenAI was still answering its code: start it again.";
130
+ /** The words for OpenAI's refusal `code` at its sign-in page: fixed words, never the code. Anything on this machine can
131
+ * send the loopback callback an `error` while a sign-in waits, so the code goes to the log alone. */
132
+ const deniedWords = (code) => (code === WORKSPACE_DENIED ? ADMIN_OFF : `ChatGPT did not sign you in: ${FREE_OR_AGAIN}`);
133
+ /** Why a sign-in past its browser step ended without signing in, from what pi-ai's flow or keep threw: `reason` for the
134
+ * log (OpenAI's status and error code, a missing field's name, a network error's code; never a token or a code) and
135
+ * `words` a person reads. pi-ai's page says the sign-in completed before it exchanges the code, so these are the only
136
+ * word of a failure after it. */
137
+ export function signInFailure(error) {
138
+ const notKept = error instanceof NotKept;
139
+ const cause = notKept ? error.cause : error;
140
+ const message = String(cause?.message ?? "");
141
+ // OpenAI's refusal at its sign-in page, sent back to the loopback in place of a code (pi-ai's words for it), or of the
142
+ // code's exchange. Its code goes to the log; the words are fixed.
143
+ const denied = notKept ? null : /ChatGPT authorization failed: (\S+)/.exec(message);
144
+ const refused = notKept ? null : /token request failed \((\d{3})\)/.exec(message);
145
+ const code = denied ? tag(denied[1]) : refused ? tag(/"error"\s*:\s*"([^"]*)"/.exec(message)?.[1]) : "";
146
+ const reason = denied ? `authorize_${code || "error"}` : refused ? `token_${refused[1]}${code ? `_${code}` : ""}` : "";
147
+ // The workspace's refusal first: OpenAI's description of it may name the plan's scope.
148
+ if (code === WORKSPACE_DENIED)
149
+ return { reason, words: ADMIN_OFF };
150
+ if (message.includes(DIRECT_SCOPE))
151
+ return { reason: "no_direct_scope", words: PLAN_NOT_USABLE };
152
+ const unsaved = notKept ? tag(cause?.code) : "";
153
+ if (notKept)
154
+ return { reason: `not_saved${unsaved ? `_${unsaved}` : ""}`, words: "OpenAI signed you in, but this server could not save the sign-in: start it again. The server's log says why." };
155
+ if (denied)
156
+ return { reason, words: deniedWords(code) };
157
+ if (refused)
158
+ return { reason, words: `OpenAI refused the sign-in: ${FREE_OR_AGAIN}` };
159
+ const unread = /token response (?:has invalid (\w+)|did not contain an (ID token)|must be an object)/.exec(message);
160
+ if (unread)
161
+ return { reason: `token_answer_${tag((unread[1] ?? unread[2] ?? "shape").replace(" ", "_"))}`, words: "OpenAI's answer to the sign-in was not one AgentRun can read: start it again. The server's log says what was missing." };
162
+ const network = tag(cause?.cause?.code);
163
+ if (/fetch failed/.test(message) || network)
164
+ return { reason: `network${network ? `_${network}` : ""}`, words: "This server could not reach OpenAI to finish the sign-in: check its connection, then start again." };
165
+ return { reason: `other_${tag(cause?.name) || "error"}`, words: "The sign-in did not finish: start it again. The server's log says why." };
166
+ }
104
167
  /** Whether a renewal that failed surely left its refresh token unspent: OpenAI answered with a fault (a 5xx, a 429), or
105
168
  * the request never reached it (no address, no connection). A timeout, or a fault once it was sent, may have spent it. */
106
169
  function unspent(error) {
@@ -125,6 +188,18 @@ export class ChatGPTPlan {
125
188
  /** Set when a sign-in dropped by a sign-out (keep) could not have its revocation confirmed by OpenAI: that sign-out
126
189
  * answers revoked false. Cleared at each sign-out's start. */
127
190
  #droppedUnconfirmed = false;
191
+ /** Why the last sign-in ended without signing in (signInFailure's words past its browser step, or its timeout), until a
192
+ * sign-in starts, finishes or a sign-out. A cancelled one leaves none. */
193
+ #problem;
194
+ /** Set when the server's change callback failed (tellChanged); cleared once one that started after it takes. */
195
+ #changeOwed = false;
196
+ /** Moved on by each change callback that fails: one that takes clears what is owed only if none failed since it began,
197
+ * so a change that read an earlier sign-in never clears a later one's. */
198
+ #failedChanges = 0;
199
+ /** The server's read in flight (refresh), which a read while it is out waits for. */
200
+ #refreshing;
201
+ /** The ends of the sign-ins cancelled and not yet ended (close waits for them). */
202
+ #ending = new Set();
128
203
  #watchers = new Set();
129
204
  #deps;
130
205
  constructor(deps) {
@@ -203,14 +278,19 @@ export class ChatGPTPlan {
203
278
  }
204
279
  view() {
205
280
  if (this.#pending && this.#pending.expiresAt <= this.now())
206
- this.cancel();
281
+ this.expire();
207
282
  const row = this.#snapshot;
208
283
  const who = row ? { ...(row.email ? { email: row.email } : {}), ...(row.plan ? { plan: row.plan } : {}) } : {};
209
- if (this.#pending)
210
- return { state: "pending", authorize_url: this.#pending.authorizeUrl, expires_at: new Date(this.#pending.expiresAt).toISOString(), ...who };
284
+ if (this.#pending) {
285
+ // Past its first minute with no code back, it says why it may be stuck. Once a code is in (the browser's return or a
286
+ // paste), OpenAI is answering it, and one it answered is being kept: neither is stuck at OpenAI's page.
287
+ const stuck = !this.#pending.codeIn && !this.#pending.answered && this.now() >= this.#pending.startedAt + HINT_AFTER_MS;
288
+ return { state: "pending", authorize_url: this.#pending.authorizeUrl, expires_at: new Date(this.#pending.expiresAt).toISOString(), ...who, ...(stuck ? { hint: STILL_WAITING } : {}) };
289
+ }
290
+ const problem = this.#problem ? { problem: this.#problem } : {};
211
291
  if (!row)
212
- return { state: "signed_out" };
213
- return { state: row.state, ...who, ...(row.state === "signed_in" ? { models: [...row.models] } : {}) };
292
+ return { state: "signed_out", ...problem };
293
+ return { state: row.state, ...who, ...(row.state === "signed_in" ? { models: [...row.models] } : {}), ...problem };
214
294
  }
215
295
  /** This server's id at OpenAI (its agent host id): a UUID made once and kept in the store's settings. Not a credential. */
216
296
  async hostId() {
@@ -228,6 +308,20 @@ export class ChatGPTPlan {
228
308
  this.#pending = undefined;
229
309
  clearTimeout(pending.timer);
230
310
  pending.abort.abort();
311
+ const ended = pending.result.then(() => undefined, () => undefined);
312
+ this.#ending.add(ended);
313
+ void ended.then(() => this.#ending.delete(ended));
314
+ }
315
+ /** Ends the sign-in waiting past its 10 minutes: a cancel, which says nothing by itself, that says it timed out (with
316
+ * no admin guess when a code came back and its exchange was cut off). One whose code OpenAI answered is past waiting
317
+ * (it is being kept) and never times out. */
318
+ expire() {
319
+ if (!this.#pending || this.#pending.answered)
320
+ return;
321
+ const codeIn = this.#pending.codeIn;
322
+ this.cancel();
323
+ this.#problem = codeIn ? CUT_OFF : TIMED_OUT;
324
+ this.#deps.log?.({ chatgpt: "sign_in_failed", reason: "timed_out" });
231
325
  }
232
326
  /** Starts a sign-in (one at a time: a new start cancels the one waiting) and gives the address to open. It lasts 10
233
327
  * minutes: the loopback callback finishes it where the browser runs on this machine; elsewhere finishSignIn does. */
@@ -235,6 +329,7 @@ export class ChatGPTPlan {
235
329
  // A sign-in still finishing drops its credential (keep): this one is the person's latest.
236
330
  const epoch = ++this.#epoch;
237
331
  const before = this.#pending;
332
+ this.#problem = undefined;
238
333
  this.cancel();
239
334
  // pi-ai's callback listener on :1455 closes as its login ends: the one cancelled ends before this one listens.
240
335
  if (before)
@@ -249,7 +344,13 @@ export class ChatGPTPlan {
249
344
  const link = new Promise((resolve) => (linked = resolve));
250
345
  const login = oauth.login({
251
346
  signal: abort.signal,
252
- notify: (event) => void (event.type === "auth_url" ? linked(event.url) : undefined),
347
+ // pi-ai's progress note comes as a code is in, from the browser's return or a paste, before it asks OpenAI for tokens.
348
+ notify: (event) => {
349
+ if (event.type === "auth_url")
350
+ linked(event.url);
351
+ else if (event.type === "progress" && this.#pending?.abort === abort)
352
+ this.#pending.codeIn = true;
353
+ },
253
354
  prompt: (prompt) => (prompt.type === "manual_code" ? Promise.race([pasted, new Promise((_, reject) => prompt.signal?.addEventListener("abort", () => reject(new Error("closed")), { once: true }))]) : Promise.reject(new Error("not asked here"))),
254
355
  }, { getDeviceId: () => hostId, agentName: AGENT_NAME });
255
356
  const settle = () => {
@@ -259,17 +360,34 @@ export class ChatGPTPlan {
259
360
  this.#pending = undefined;
260
361
  };
261
362
  // Pending until the credential is kept or dropped, so a sign-out meanwhile cancels it (keep's epoch).
262
- const result = login.then((credential) => this.keep(credential, epoch)).finally(settle);
263
- result.catch(() => undefined);
363
+ const result = login.then((credential) => {
364
+ if (this.#pending?.abort === abort)
365
+ this.#pending.answered = true;
366
+ return this.keep(credential, epoch, settle).catch((error) => {
367
+ throw new NotKept("not kept", { cause: error });
368
+ });
369
+ }).finally(settle);
370
+ // Past the browser step, the tab already says it completed: an end that is not a cancel (a newer start, a sign-out,
371
+ // the wait's end, the server's close) says why in the view and the log, whichever way the address came back.
372
+ let waiting = false;
373
+ result.catch((error) => {
374
+ if (!waiting || abort.signal.aborted || epoch !== this.#epoch)
375
+ return;
376
+ const { reason, words } = signInFailure(error);
377
+ this.#problem = words;
378
+ this.#deps.log?.({ chatgpt: "sign_in_failed", reason });
379
+ });
264
380
  const authorizeUrl = await Promise.race([link, result.then(() => undefined, (error) => {
265
381
  throw new PlanSignInRefused(/in use/.test(String(error?.message)) ? "Another sign-in holds this machine's port 1455: finish or cancel it, then start again." : "The sign-in could not start: try again.");
266
382
  })]);
267
383
  if (!authorizeUrl)
268
384
  throw new PlanSignInRefused("The sign-in could not start: try again.");
269
- const expiresAt = this.now() + PENDING_MS;
270
- const timer = setTimeout(() => (this.#pending?.abort === abort ? this.cancel() : undefined), PENDING_MS);
385
+ const startedAt = this.now();
386
+ const expiresAt = startedAt + PENDING_MS;
387
+ const timer = setTimeout(() => (this.#pending?.abort === abort ? this.expire() : undefined), PENDING_MS);
271
388
  timer.unref();
272
- this.#pending = { abort, state: new URL(authorizeUrl).searchParams.get("state") ?? "", authorizeUrl, expiresAt, paste, result, timer };
389
+ this.#pending = { abort, state: new URL(authorizeUrl).searchParams.get("state") ?? "", authorizeUrl, startedAt, expiresAt, paste, result, timer };
390
+ waiting = true;
273
391
  return { authorize_url: authorizeUrl, expires_at: new Date(expiresAt).toISOString() };
274
392
  }
275
393
  /** Finishes the sign-in waiting with the address its browser tab ended on, pasted. A URL that is not that sign-in's end
@@ -290,20 +408,23 @@ export class ChatGPTPlan {
290
408
  throw new PlanSignInRefused(shape);
291
409
  const error = url.searchParams.get("error");
292
410
  if (error)
293
- throw new PlanSignInRefused(`ChatGPT did not sign you in (${error.replace(/[^a-z_]/gi, "").slice(0, 40)}): start the sign-in again.`);
411
+ throw new PlanSignInRefused(deniedWords(tag(error)));
294
412
  if (url.searchParams.get("state") !== pending.state)
295
413
  throw new PlanSignInRefused("That address is from another sign-in: paste the one from the sign-in you started last, or start again.");
296
414
  if (!url.searchParams.get("code") || !url.searchParams.get("client_id"))
297
415
  throw new PlanSignInRefused(`That address has no sign-in code in it. ${shape}`);
416
+ // A code is in from here (pi-ai's progress note says the same a moment later): a view meanwhile shows no hint.
417
+ pending.codeIn = true;
298
418
  pending.paste(url.href);
299
419
  try {
300
420
  await pending.result;
301
421
  }
302
422
  catch (error) {
303
- const words = String(error?.message ?? "");
304
- if (words.includes(DIRECT_SCOPE))
305
- throw new PlanSignInRefused("This ChatGPT account did not allow its plan to be used by apps: sign in with an account whose plan allows it.");
306
- throw new PlanSignInRefused("OpenAI refused the sign-in: start it again.");
423
+ // Cancelled while its code's exchange was out (a newer start, a sign-out, the 10 minutes): the log has no line of
424
+ // it, so the words say what the view says, or that it was cancelled.
425
+ if (pending.abort.signal.aborted)
426
+ throw new PlanSignInRefused(this.#problem ?? "That sign-in was replaced or signed out: start it again.");
427
+ throw new PlanSignInRefused(signInFailure(error).words);
307
428
  }
308
429
  return this.view();
309
430
  }
@@ -311,7 +432,7 @@ export class ChatGPTPlan {
311
432
  * sign-in since then wins: the credential is dropped, never written, and revoked at OpenAI. A sign-in it takes the place
312
433
  * of is revoked first, then replaced only while the row still holds it (a renewal of it that wrote back meanwhile is
313
434
  * read, revoked and replaced in turn), so no earlier pair is left alive. */
314
- async keep(credential, epoch) {
435
+ async keep(credential, epoch, saved) {
315
436
  if (credential.scopes && !credential.scopes.includes(DIRECT_SCOPE))
316
437
  throw new Error(`the grant did not include ${DIRECT_SCOPE}`);
317
438
  this.hold(credential);
@@ -340,8 +461,45 @@ export class ChatGPTPlan {
340
461
  break;
341
462
  }
342
463
  this.#snapshot = row;
464
+ this.#problem = undefined;
343
465
  this.#deps.log?.({ chatgpt: "signed_in", ...(previousRevoked === undefined ? {} : { previous_revoked: String(previousRevoked) }) });
344
- await this.#deps.changed?.();
466
+ // Saved: no longer waiting, so it reads signed in while the server takes the change (`saved`, the sign-in's settle).
467
+ saved?.();
468
+ await this.tellChanged();
469
+ }
470
+ /** Tells the server the sign-in changed (its change callback: env read again, the listings relisted, the offers
471
+ * probed). What the server does with it is not the change's to fail: a failure is owed, said in the log (once: not
472
+ * again for `again`, a retry of one owed), and taken again at the server's next read (refresh). */
473
+ async tellChanged(again = false) {
474
+ const failed = this.#failedChanges;
475
+ try {
476
+ await this.#deps.changed?.();
477
+ if (this.#failedChanges === failed)
478
+ this.#changeOwed = false;
479
+ }
480
+ catch (error) {
481
+ this.#failedChanges += 1;
482
+ this.#changeOwed = true;
483
+ if (again)
484
+ return;
485
+ const code = error?.code;
486
+ this.#deps.log?.({ chatgpt: "changed_failed", reason: tag(typeof code === "string" ? code : error?.name) || "error" });
487
+ }
488
+ }
489
+ /** The sign-in as the store holds it now, read at the server's read of it: a runner may have renewed it, found it
490
+ * expired, or another server signed in or out. A change is told to the server, and so is one it failed to take, so
491
+ * what it offers does not wait for a restart. One at a time: a read while one is out waits for that one (the console
492
+ * polls, and each change relists and probes). */
493
+ refresh() {
494
+ // Cleared in a reaction, never inside the function: a read that throws at once would run a `finally` there before
495
+ // the assignment, and leave a settled promise in flight for good.
496
+ return (this.#refreshing ??= (async () => {
497
+ const was = this.state;
498
+ if ((await this.load()).state !== was)
499
+ await this.tellChanged();
500
+ else if (this.#changeOwed)
501
+ await this.tellChanged(true);
502
+ })().finally(() => (this.#refreshing = undefined)));
345
503
  }
346
504
  /** The plan's models from OpenAI's list (GET /v1/models with the token), those of the current families; the fallback
347
505
  * list when it can't be read. */
@@ -449,7 +607,7 @@ export class ChatGPTPlan {
449
607
  if (await this.swap(bytes, expired)) {
450
608
  this.#snapshot = expired;
451
609
  this.#deps.log?.({ chatgpt: "expired" });
452
- await this.#deps.changed?.();
610
+ await this.tellChanged();
453
611
  throw new PlanUnavailable(EXPIRED);
454
612
  }
455
613
  return this.adopt();
@@ -487,6 +645,7 @@ export class ChatGPTPlan {
487
645
  * is not this answer's to give). */
488
646
  async signOut() {
489
647
  this.#droppedUnconfirmed = false;
648
+ this.#problem = undefined;
490
649
  this.#epoch += 1;
491
650
  const finishing = this.#pending;
492
651
  this.cancel();
@@ -508,7 +667,7 @@ export class ChatGPTPlan {
508
667
  }
509
668
  this.#snapshot = undefined;
510
669
  this.#deps.log?.({ chatgpt: "signed_out", revoked: String(revoked) });
511
- await this.#deps.changed?.();
670
+ await this.tellChanged();
512
671
  return { revoked };
513
672
  }
514
673
  /** `credential`'s session revoked at OpenAI (its documented revocation endpoint, with the refresh token): whether OpenAI
@@ -527,9 +686,11 @@ export class ChatGPTPlan {
527
686
  return false;
528
687
  }
529
688
  }
530
- /** Stops the sign-in waiting, at the server's close. */
689
+ /** Stops the sign-in waiting, at the server's close. Resolves once every sign-in cancelled (by this, a newer start, a
690
+ * sign-out or its 10 minutes) has ended, whatever its end said in the log. */
531
691
  close() {
532
692
  this.cancel();
693
+ return Promise.all([...this.#ending]).then(() => undefined);
533
694
  }
534
695
  }
535
696
  /** For a run on a plan model (`model`, the one its claim chose): the plan's token read once before anything starts, so a