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

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 (80) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +44 -10
  3. package/dist/adapters.d.ts +3 -2
  4. package/dist/adapters.js +6 -3
  5. package/dist/answer-json.d.ts +6 -2
  6. package/dist/answer-json.js +22 -4
  7. package/dist/api-only.js +2 -0
  8. package/dist/calendar/tools.js +3 -2
  9. package/dist/chatgpt-plan.d.ts +16 -1
  10. package/dist/chatgpt-plan.js +116 -12
  11. package/dist/claude-login.d.ts +34 -5
  12. package/dist/claude-login.js +31 -7
  13. package/dist/claude-sign-in.d.ts +35 -0
  14. package/dist/claude-sign-in.js +90 -0
  15. package/dist/console/assets/{backend-D5EmB4N3.js → backend-Boh7tC4i.js} +1 -1
  16. package/dist/console/assets/{index-DUYLaqiR.js → index-CQ3cJRzI.js} +130 -130
  17. package/dist/console/assets/index-DKkaS3a0.css +1 -0
  18. package/dist/console/index.html +2 -2
  19. package/dist/host-check.d.ts +4 -0
  20. package/dist/host-check.js +4 -0
  21. package/dist/key-refusal.d.ts +21 -5
  22. package/dist/key-refusal.js +231 -37
  23. package/dist/learn/secrets.d.ts +20 -10
  24. package/dist/learn/secrets.js +44 -184
  25. package/dist/llms.txt +1 -1
  26. package/dist/openapi.d.ts +3 -3
  27. package/dist/openapi.js +70 -18
  28. package/dist/place-offers.d.ts +14 -6
  29. package/dist/place-offers.js +26 -13
  30. package/dist/redact/match.d.ts +74 -0
  31. package/dist/redact/match.js +771 -0
  32. package/dist/run-timeline-served.d.ts +1 -1
  33. package/dist/run-timeline-served.js +4 -4
  34. package/dist/runner/adapter-loop.d.ts +3 -0
  35. package/dist/runner/adapter-loop.js +1 -1
  36. package/dist/runner/adapter-run-spec.js +4 -1
  37. package/dist/runner/beside.js +7 -3
  38. package/dist/runner/cli-run-spec.js +3 -1
  39. package/dist/runner/loop-contract.d.ts +4 -0
  40. package/dist/runner/main.js +8 -4
  41. package/dist/runner/presence.d.ts +4 -3
  42. package/dist/runner/presence.js +4 -2
  43. package/dist/runner/run-child-host.d.ts +2 -0
  44. package/dist/runner/run-child-host.js +2 -2
  45. package/dist/runner/runner.d.ts +4 -0
  46. package/dist/runner/runner.js +33 -3
  47. package/dist/server.d.ts +5 -2
  48. package/dist/server.js +41 -10
  49. package/dist/store/dialect.d.ts +3 -0
  50. package/dist/store/dialect.js +1 -0
  51. package/dist/store/index.d.ts +1 -1
  52. package/dist/store/index.js +1 -1
  53. package/dist/store/postgres/dialect.js +3 -0
  54. package/dist/store/sqlite/store.js +43 -13
  55. package/dist/store/store.d.ts +10 -1
  56. package/dist/store/store.js +7 -0
  57. package/dist/store-view.js +1 -1
  58. package/dist/template-eval.d.ts +2 -2
  59. package/dist/template-eval.js +9 -8
  60. package/dist/timeline/index.d.ts +1 -1
  61. package/dist/timeline/index.js +1 -1
  62. package/dist/timeline/timeline.d.ts +12 -7
  63. package/dist/timeline/timeline.js +14 -6
  64. package/dist/tool-gate.js +3 -1
  65. package/dist/validate.js +1 -1
  66. package/dist/workspace/computer-deps.d.ts +2 -1
  67. package/dist/workspace/computer-deps.js +5 -4
  68. package/dist/workspace/computer-for-claim.d.ts +8 -2
  69. package/dist/workspace/computer-for-claim.js +28 -9
  70. package/dist/workspace/computer-janitor.d.ts +15 -7
  71. package/dist/workspace/computer-janitor.js +33 -8
  72. package/dist/workspace/computer-kept.d.ts +52 -4
  73. package/dist/workspace/computer-kept.js +118 -6
  74. package/dist/workspace/run-end-computers.d.ts +5 -1
  75. package/dist/workspace/run-end-computers.js +27 -1
  76. package/dist/wrapped.d.ts +57 -0
  77. package/dist/wrapped.js +51 -0
  78. package/package.json +11 -11
  79. package/templates/README.md +8 -7
  80. package/dist/console/assets/index-DYhU4adm.css +0 -1
package/CHANGELOG.md CHANGED
@@ -2,6 +2,38 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## 0.1.0-beta.56 (2026-11-24)
6
+
7
+ - The console draws a share card as an image: one renderer for every picture card, a free run's receipt and each Wrapped card among them. A card says only the words and numbers its caller gives it: an eyebrow, a title, one big figure, up to six label and value rows, up to two bar charts (columns for hours, days or months; labelled rows for shares), and a footnote. A rows chart shows as many bars as fit, and the renderer says how many (`chartCapacity`), so a caller folds the rest into one "other" bar and drops none. A bar not measured yet draws as a dashed outline, left out of the chart's scale. It comes out as a 1200 by 675 SVG and the same image as a data URL an `<img>` shows, dark unless asked for light. Every colour is a console design token, the fonts are the console's with the system's after them, and the image loads nothing: no font, no picture, no style sheet. In the browser it can also be drawn as a PNG for a download. <!-- changes/card-image.md -->
8
+ - Four smaller fixes from review: <!-- changes/b46-low-bugs.md -->
9
+ - `deploy/fly/launch.sh` stops before it makes a secret when `fly secrets list --json` has entries without a `name` (a flyctl that spells it `Name`). Before, such a list read as no secrets, and a run on an app that had them made a new seal key and token over them.
10
+ - `install.sh --vps` no longer tries dpkg's lock again after apt-get's own 600 s wait for it, so a stuck dpkg stops the install instead of holding it for about 20 hours. The package lists' lock is still tried again for up to 600 s.
11
+ - When an earlier version's data stops a start in a folder the installer set up, the refusal says that moving the folder takes the installed agentrun with it (its Node in `node/`, `lib/` and `bin/agentrun`) and to run the installer again.
12
+ - `GET /v2/openapi.json` names the owner's session cookie as the console sets it: `agentrun-<port>-session` for the port the browser opened, or `__Host-agentrun-session` over https. It named `agentrun-<port>` for the server's own port, which no owner-only route takes.
13
+ - The Docker reason a server gives in a container now depends on which container it is. AgentRun's image says so itself (`AGENTRUN_IN_IMAGE=1`), so a Kubernetes pod, which has no `/.dockerenv`, gets the socket advice too. That advice now says the host's Docker socket is root on the host. Any other container, such as a dev container running `npx @parcha/agentrun`, gets the host's words, prefixed "This server runs in a container.", and no compose.yaml advice. <!-- changes/box-reason-image-marker.md -->
14
+ - A ChatGPT sign-in that ends without signing in now says why. OpenAI's tab says "Authentication successful" before the server exchanges the code, and a failure after that point (OpenAI refusing the code, an answer the server can't read, no route to OpenAI, a save that fails) used to leave the plan reading not signed in with nothing said anywhere. `GET /settings/chatgpt` now carries `problem`, the reason in words, until the next start, sign-in or sign-out. A plan OpenAI gives no use of says "This ChatGPT plan can't be used here", a workspace whose admin turned off open-source apps names the setting (External access → OSS → Use ChatGPT plan), any other refusal says a Free plan may be the reason, and a sign-in that waits out its 10 minutes says it timed out. The words are fixed: OpenAI's code goes to the log alone. Settings → API Keys shows it, under who is signed in too, and the server logs `event=chatgpt chatgpt=sign_in_failed reason=…` (OpenAI's status and error code, or `timed_out`; never a token or a code). `agentrun` started from a terminal says that line on stderr each time, where before it showed none of the sign-in's lines, and says `changed_failed` too: a sign-in saved whose change the server failed to take, which it now takes again at its next read of the sign-in instead of after a restart. A pasted address that fails the same way is refused with the same words. <!-- changes/chatgpt-sign-in-says-why.md -->
15
+ - A parked run whose desktop, phone or sandbox was kept at its park on a Docker engine, or on a machine that dials the server, now resumes on the runner that kept it while that runner is there (its word in the last 30 s, the same process, not refusing) and the keep's 10 minutes last, so a server with several runners gets the same machine back instead of a new one and no longer leaves the kept container running with nothing to end it. Another runner claims nothing for that run meanwhile, so an answer waits up to the keep's 10 minutes behind a runner whose loops are full, and its computer janitor leaves both the kept row and, in its sweep of each provider's computers, the kept machine to that runner, even once the run is over. A stop or a cancel never waits: any runner claims the run at once and ends it without touching the kept machine (also when the kept row can't be read at that moment), which the runner that kept it ends at the keep's time, or sooner at its janitor's next pass once the run is over. Once that runner is gone, any runner claims the run, starts a new machine, and the timeline says `The desktop wasn't kept: the runner that kept it is gone.`; a run kept on an exec vendor's machine or a phone is claimed by any runner, as before. The kept row (`computer_kept:<run id>` in settings) names the runner and its incarnation; there is no schema change. <!-- changes/claim-affinity.md -->
16
+ - Settings → Model keys' "Open the CLI's sign-in here" signs the claude CLI in at the login's own folder, so the login reads signed in afterwards. The sign-in ran with a temporary config dir, where `auth login` wrote the account it signed in (`.claude.json`); that folder was removed when the sign-in ended, and the login's folder stayed without it, so AgentRun kept saying "not signed in" while running the shown command by hand worked. The sign-in, the shown command and the status check now take their variables from one function (`claudeSignInEnv`), and the status check reads the login's folder as its config dir. <!-- changes/claude-sign-in-folder.md -->
17
+
18
+ - `GET /v2/settings/claude-login` says what became of a sign-in the server started, as `sign_in`: `waiting` for the browser since `started_at`, `signed_in`, `timed_out`, `failed` with the CLI's `exit_code`, or `not_started`. The console shows "Waiting for the browser…" from it, after a reload too. A sign-in no browser answers within 10 minutes is ended and says so, with the button to start it again; before, it ended silently and the browser's page then failed to reach it. A second press, turning the mode off, or stopping the server ends a sign-in that still waits; the stop waits for its CLI to exit, so no CLI keeps the browser's callback port from the next server.
19
+ - The view names the folder it asks about (`folder`), and this machine's own login folder for the claude CLI (`machine`). That folder follows the CLI's rule: `CLAUDE_CONFIG_DIR` when the server's environment sets it to an absolute path, else `~/.claude`. The console shows it in place of the fixed "(~/.claude)", and where the server saw no `CLAUDE_CONFIG_DIR` it says that a CLI using another folder needs AgentRun started with `CLAUDE_CONFIG_DIR` set to it.
20
+ - "This machine's" login on the CLI's default folder (`~/.claude`, no `CLAUDE_CONFIG_DIR`) is signed in as the person's own claude CLI runs: with no config or credentials dir set, in their home, so the sign-in writes the account in `~/.claude.json` and the tokens where their CLI keeps them, and the shown line is their own, clearing both variables (`env -u CLAUDE_CONFIG_DIR -u CLAUDE_SECURESTORAGE_CONFIG_DIR ...`) so a terminal that exports either signs in at that same login. Before, AgentRun set both dirs to `~/.claude`, which reads `~/.claude/.claude.json` (where the person's CLI keeps no account) and, on macOS, a Keychain item named from that folder rather than the person's own (the one with no suffix), so it read signed out there while the person's CLI was signed in. A run on it sets `CLAUDE_SECURESTORAGE_CONFIG_DIR` empty on macOS, which names that same item whatever the run's config dir, and `~/.claude` elsewhere. The harness's `claudeLoginEnv` takes the platform (this host's by default), and its login takes `home` for this place. A login in a `CLAUDE_CONFIG_DIR` folder keeps both dirs set to it, which is where the person's CLI with that variable keeps its login.
21
+ - The status check on "this machine's" login (either folder) never runs the claude CLI on the person's own account file. The CLI rewrites `.claude.json` on every start whose config version is not its own (and the first time adds `settings.json`, a backup and a lock beside it), so asking it in place rewrote the person's file on every view, every 2 seconds while a sign-in waited, and at every run's start. Each check now copies the file (opened only to read) into a folder of its own, gives the CLI that folder as its config dir and the tokens as a run reads them, and removes the folder however the check ends. The copy leaves out the fields that hold secrets (`primaryApiKey`, the API key an older CLI signed in with; `env`; every `mcpServers`), and a file that doesn't parse as a JSON object is not copied; a run's config dir has none of them either, so a login whose only key is that `primaryApiKey` reads signed out, as a run on it would be. The harness's login takes `shared` for this place, and `claudeLoginStatus` takes the platform.
22
+ - On macOS a login read signed out in AgentRun, and its runs failed in about 2 seconds with "signed out", while `claude auth status` in a terminal said signed in. The CLI reads its tokens there from the login keychain, which is under the person's home, and the status check ran AgentRun's own folder and a `CLAUDE_CONFIG_DIR` folder in a temporary home, and a run in the session's. The status check now runs in the person's home (the server's `HOME`) on every place and platform, keeping each place's credentials dir, which names the Keychain item ahead of the config dir; a run on the login on macOS gets that home too, its config and other dirs still the session's. `claudeLoginStatus` takes `home`, as `startClaudeLogin` does.
23
+ - The harness's `startClaudeLogin` returns the sign-in (`ended`, which says how it ended, and `stop()`) in place of nothing, and starts the CLI in the person's home rather than a temporary one when no home is given.
24
+ - The build composer on `#/agents/new` has a 14px corner, down from 16px, so it reads as one step softer than the console's 8px actions instead of a separate card. <!-- changes/console-composer-radius.md -->
25
+ - The server's redactor finds secret shapes and held values with one matcher (`redact/match.ts`) whose work grows with a text's length alone: each shape is read from its prefix forward, and no run is read again at each place in it. What it cuts is what it cut before, with these widenings: <!-- changes/redact-one-matcher.md -->
26
+ - A text that holds a held value only part of which a cut covers is now withheld whole. A credential parameter's value cut in place, with the rest of the same held value past a line break (`?token=<first half>` then `<second half>` on the next line), used to show the second half; the check for a held value now reads the text as it came, not the text after its cut. The same holds where an answer or a call's result is read in pieces and the split falls at a piece's edge: the whole answer or result is withheld. A held value's find is checked against the cuts each piece already made, so a value split inside one piece still blanks only that piece.
27
+ - An answer or a call's result read in pieces is checked once more as it is about to be shown, and withheld whole if that text holds a held value, however its pieces were put together (each cut, or an unread run shown as `[redacted]`, between them).
28
+ - A JWT is found from the first `eyJ` of its run of a part's characters at every site that looks for one, so a token glued to a word (`id_eyJ...`, `x9eyJ...`) is found too. The credential gate of the console's build (the console the server serves) can now fail a build whose bundle holds such a glued token, where it passed before. The computer's phone words cut it too.
29
+ - An `llm` grader in `agentrun-serve eval-template` reads each call's result whole, to 120,000 characters, instead of its first 8,000. A figure deep in a fetched page (past 8,000 characters of a 20,000-character page) used to be out of the grader's sight, so a rubric that checks a cited figure against its source failed a run that had it right. The grader's prompt still stays under 120,000 characters: past that, the longest results lose their middle first, as before. A call's result is redacted as it came, then its URLs lose their query values, and the 120,000 characters are counted as shown. A timeline read with `calls=whole` returns the same whole results, at most 100 rows a page: that is its default, and a `limit` over 100 with `calls=whole` is refused (400). <!-- changes/template-eval-whole-results.md -->
30
+
31
+ An answer that is one JSON object and nothing else (after trimming) now counts as its json block, as a last fenced `json` block does: for `output` and `result.output_error`, a grader's `target`, and an `llm` grader's own `{pass, reason}` verdict. An object inside prose, an array or two objects is still no json block.
32
+
33
+ A run's answer and a call's result as a grader reads it no longer turn compact JSON into `[redacted]` because it runs past 8,192 characters without whitespace: the redactor reads it in pieces cut at the end of a JSON string, never inside a URL's user and password (an array of numbers, at its commas), and still cuts a held value in it; a held value or a secret shape (a URL's password) that such a cut splits withholds the text whole, and a run too long to read is withheld from its start. A held value split by a line break before such a run, or just past the 120,000-character head a grader is shown, now withholds the text whole instead of showing the value's first characters. Where a call's read stops, the text after it is read as the matcher reads it (a "+" and percent-encoded whitespace count as whitespace, a whitespace run as one space), and a stop inside a cut run reads the rest of that run; padding of that kind longer than a piece withholds the text.
34
+ - The approvals route's description now says what an allowed call does when the runner loses its claim while the call runs. An allowed call runs once. If the claim lapses before the call's end is recorded, a read may run again on the run's next claim. A call with a side effect never runs again: the next claim answers it as interrupted, and the model is told so. A new test pins both cases with a forced lease lapse: a call with a side effect runs once on pi and on a CLI harness, and an approved web_fetch is fetched again on the next claim with its result recorded once. Each case checks that the lapse is recorded in the run's attempts. <!-- changes/approved-call-lost-claim.md -->
35
+ - `GET /v2/wrapped?year=YYYY` (and `agentrun wrapped --year`) reads a year of the work under this machine's home (Claude Code, Codex, pi and any other source the import package reads) as numbers: tokens, requests, days, hours of the day, weekdays and time at work, by model, harness and source, each bucketed by its request's time in the server's local zone, with the runs imported here beside it. It holds no prompt, title, path or project. Only a server on loopback with no public URL, reached by a loopback Host (localhost, 127.x, [::1]), answers it (any other, a Host name an operator allowed included, and the API-only profile, is 403), and the answer is kept for a minute. A year number is four digits from 1000, and `unread_files` counts the session files that could not be read (a number, no path), so a partial year is not shown as a whole one. <!-- changes/wrapped-route.md -->
36
+
5
37
  ## 0.1.0-beta.55 (2026-11-23)
6
38
 
7
39
  **Breaking:**
package/README.md CHANGED
@@ -416,7 +416,16 @@ A run's runner renews its claim on the run every 10 s, for a claim of 30 s. A ru
416
416
  time, writes nothing more to the run, and the store refuses any write under a claim the run has moved past. Once the
417
417
  claim lapses another runner claims the run and resumes it from its journal. A run's own computer doesn't survive a
418
418
  runner loss, a crash, a server stop or a park (the claim that resumes the run starts a new one, and says so on the
419
- timeline and, once, to the model as an "AgentRun server note"), and the agent's own computer, a persistent setting, does. `agentrun-serve runner --check --data DIR --name N`
419
+ timeline and, once, to the model as an "AgentRun server note"), and the agent's own computer, a persistent setting, does.
420
+ The exception is a park's keep: a desktop, phone or sandbox a park keeps for 10 minutes comes back to the run's resume.
421
+ One that only the runner that kept it can reach again (a Docker container, a machine that dials the server) holds the
422
+ parked run for that runner while it is there under the same process (its word in the last 30 s, not refusing) and the
423
+ keep lasts: no other runner claims the run to resume it, so a runner whose loops are full makes an answer wait until
424
+ then. A stop or a cancel never waits: any runner claims the run at once and ends it without taking the kept machine
425
+ (also when the kept row can't be read then), which the runner that kept it ends at its time, or sooner at its janitor's
426
+ next pass once the run is over; another runner's janitor leaves both the row and the machine. Once that runner
427
+ is gone, any runner claims it, starts a new one, and the timeline says `The desktop wasn't kept: the runner that kept it
428
+ is gone.` `agentrun-serve runner --check --data DIR --name N`
420
429
  (or `AGENTRUN_RUNNER_NAME=N` in place of `--name`) checks the runner's environment by name (its store, its seal key,
421
430
  every run-facing name its server holds, a forwarder on loopback) and whether the runner named `N` has a fresh
422
431
  heartbeat: it exits 0 when both hold, 1 when either does not, and 2 when no name is given. `--check --env` checks the
@@ -1542,20 +1551,45 @@ run agents on it.
1542
1551
 
1543
1552
  On a server one person runs on their own machine, Claude Agent can run on that person's Claude plan through the Claude
1544
1553
  Code CLI's own login. The CLI holds the login and calls Anthropic itself. AgentRun never reads, copies, stores or relays
1545
- the login. It tells the CLI where the login is and asks it `claude auth status`, nothing else. Settings → Model keys
1554
+ the login's tokens. It tells the CLI where the login is and asks it `claude auth status`, nothing else. Settings → Model keys
1546
1555
  has the row **Use Claude Code's login on this machine**, over these routes:
1547
1556
 
1548
1557
  - `PUT /v2/settings/claude-login` `{"only_me": true, "place": "agentrun"}` turns it on. `only_me` is the owner's word
1549
1558
  that they alone run agents on this server. `place` is where the login is: `agentrun` (the default) is AgentRun's own
1550
- login directory in the data folder, which you sign in once; `machine` is this machine's own Claude Code login
1551
- (`~/.claude`), which you opt into by name. A server where more than one person can start runs (more than one API
1552
- token, the API-only profile) refuses it with `403` and one line saying why, and a turn-on saved before is dropped
1553
- when such a server starts.
1559
+ login directory in the data folder, which you sign in once; `machine` is this machine's own Claude Code login, which
1560
+ you opt into by name. Its folder is the one the CLI uses: `CLAUDE_CONFIG_DIR` when the server's environment sets it to
1561
+ an absolute path, else `~/.claude`. A Claude Code that keeps its login in another folder is found only when AgentRun
1562
+ is started with `CLAUDE_CONFIG_DIR` set to that folder. A server where more than one person can start runs (more
1563
+ than one API token, the API-only profile) refuses it with `403` and one line saying why, and a turn-on saved before
1564
+ is dropped when such a server starts.
1554
1565
  - `GET /v2/settings/claude-login` says `state`: `off`, `signed_in` (with the `account` the CLI names: method, email,
1555
1566
  organization, plan), `signed_out`, `no_cli` (claude-agent's first run installs the pinned CLI), `unknown`, or
1556
- `other_machine`. `command` is the line that signs the CLI in at the login's place, for a terminal on the server's
1557
- machine. Where the console is on that machine (a server on loopback with no public address), `can_start` is true and
1558
- `POST /v2/settings/claude-login/login` starts the pinned CLI's own `auth login`, which opens a browser there.
1567
+ `other_machine`. `folder` is the folder whose login the CLI is asked about, and `machine` is this machine's own
1568
+ login folder (`machine.source`: `CLAUDE_CONFIG_DIR` or `default`). `command` is the line that signs the CLI in at
1569
+ the login's place, for a terminal on the server's machine. Where the console is on that machine (a server on loopback
1570
+ with no public address), `can_start` is true and `POST /v2/settings/claude-login/login` starts the pinned CLI's own
1571
+ `auth login`, which opens a browser there. It runs with the same variables as `command`, so it signs in at `folder`,
1572
+ and the status is read there too, since `auth login` writes the account it signed in to its config dir. On
1573
+ `machine` with the default `~/.claude`, the CLI is signed in as the person's own `claude` runs: no
1574
+ `CLAUDE_CONFIG_DIR` or `CLAUDE_SECURESTORAGE_CONFIG_DIR`, in their home, so it writes the account in `~/.claude.json`
1575
+ and the tokens where their Claude Code keeps them (in `~/.claude`; on macOS the Keychain item `Claude Code-credentials`).
1576
+ `command` there starts with `env -u CLAUDE_CONFIG_DIR -u CLAUDE_SECURESTORAGE_CONFIG_DIR`, so a terminal that exports
1577
+ either still signs in at that login. A run
1578
+ there reaches the same tokens: on macOS with `CLAUDE_SECURESTORAGE_CONFIG_DIR` set and empty, the CLI's way to name
1579
+ that item while the run has a config dir of its own; elsewhere with it set to `~/.claude`. On `machine`, either
1580
+ folder, the status check never runs the CLI on the person's own account file, which the CLI rewrites on every start
1581
+ whose config version is not its own: each check copies `.claude.json` (`~/.claude.json`, or the `CLAUDE_CONFIG_DIR`
1582
+ folder's), opening the original only to read it, into a folder of its own, gives the CLI that folder as its config
1583
+ dir and the tokens as a run reads them, and removes the folder however the check ends. The copy (0600, in a 0700
1584
+ folder) leaves out the fields that hold secrets: `primaryApiKey` (the API key an older Claude Code signed in with),
1585
+ `env` and every `mcpServers`, whose env and headers hold tokens; a file that doesn't parse as a JSON object is not
1586
+ copied at all. A run's config dir has none of them either, so the status says what a run gets. The status check
1587
+ runs in the person's home (the server's `HOME`) on every place, as the sign-in does, and so does a run on the login
1588
+ on macOS: the CLI reads its tokens there from the login keychain, which is under that home. `sign_in`
1589
+ says what became of that sign-in while the server runs: `waiting` for the browser since `started_at`, `signed_in`,
1590
+ `timed_out` (no answer from the browser within 10 minutes, so it was ended and a sign-in page still open can't
1591
+ finish), `failed` (the CLI ended without signing in, with its `exit_code`), or `not_started`. A second start ends a
1592
+ sign-in that still waits, and so do turning the mode off and stopping the server, which waits for that CLI to exit.
1559
1593
  - `DELETE /v2/settings/claude-login` turns it off. The login stays as the CLI keeps it.
1560
1594
 
1561
1595
  While it is on, a claude-agent run on an `anthropic/<model>` model goes on the login: its CLI gets no
@@ -3238,7 +3272,7 @@ failed, 2 when nothing ran. The runner, the graders and the report are in
3238
3272
  | `GET /capacity` | This server's own (`capacity/1`): the runs waiting for a runner and held by one, each live runner's version, slots and free slots, and the hand-backs within `?window=` minutes, read from the store ([capacity and health](#capacity-and-health)). Served under `AGENTRUN_API_ONLY=1` too. |
3239
3273
  | `GET /openapi.json` | Without a credential: this API as an OpenAPI 3.1 document, the `agentrun.v2/0` contract (vendored in `src/openapi/`, its source in `info`) with this server's own routes marked `x-agentrun-serve`, the operations it answers `501` marked `x-agentrun-serve-unsupported`, and a contract operation that takes more than the contract gives marked `x-agentrun-serve-changed` with each change named; `links.openapi` in capabilities points at it. |
3240
3274
  | `GET /capabilities` | Without a credential. `backend: local`, every feature flag present and true only when it works; `tools`, the tools an agentic revision may name; `workflows`, what a workflow revision's model nodes get and, in `workflows.decisions.providers`, the decision providers its typed questions run on; `models`, where models come from and the model of each tier. |
3241
- | `POST /agents`, `GET /agents`, `GET /agents/{id}` | `POST` takes `{definition, skills?, note?}` and makes the agent with its first revision, current. A definition has `instructions` (an agentic revision) or `workflow` (a workflow revision, checked by the DSL first), and `name`, `description`, `model` and `thinking` (agentic only), `harness` ([harnesses](#harnesses)), `place` ([place](#place)), `tools`, `tool_settings` ([search and fetch](#search-and-fetch)), `skills` (names; each `<name>/SKILL.md` is in `skills`) and `version`, which is the number the revision gets, and `max_cost_usd`, the agent's default cap (an agentic agent's or a workflow's), kept by an edit that leaves it out and cleared only by 0 ([spend cap](#spend-cap)), and `output_schema` (agentic only, at most 64 KiB): the JSON Schema the final answer's last fenced json block meets, which a completed run's `result.output` then holds (null when the answer doesn't meet it), kept by an edit that leaves it out. A template's answer schema is set here at apply, and a run a schedule trigger starts is handed that trigger's last completed `result.output` after its message; no other source's runs are, since each of their firings is a different event. Over 32 KiB, a scheduled run is handed only the fields the producing run's schema names in `x-carried`; carried arrays lose entries from the front until they fit, and the run is told how many. A save refuses an `x-carried` that is not unique root property names. `checkout` (agentic only): `pull_request` has the server check out, before each run's first turn, the pull request the run's GitHub event names, in `repo/` at its head with its base and merge base, using a read-only token of its GitHub App that the agent never holds ([GitHub triggers](#github-triggers-connect-github)); `none` clears it, and an edit that leaves it out keeps it. A field the store does not keep (`input_schema`) is `422 input_invalid` by name, and so is a definition that can never run here; one this host cannot run yet saves with `warnings` ([models](#models)). The ETag (`home_etag`) is the current revision's id. `GET /agents/{id}` adds `tools`, the tools its current revision grants with each one's provider ([search and fetch](#search-and-fetch)). It also adds `run_blockers` (`x-agentrun-serve: "runblockers/1"`): `{message, fields}` as a start with no overrides would be refused now (`409 agent_not_runnable`), or null. It is always null for an archived, native or SDK agent and for a revision whose MCP tools its first run pins, and the read asks no other service, so under the agent's `max_cost_usd` an OpenRouter decision model's missing price is named only once a save or a start has read OpenRouter's catalog: null is no promise that a start is accepted. |
3275
+ | `POST /agents`, `GET /agents`, `GET /agents/{id}` | `POST` takes `{definition, skills?, note?}` and makes the agent with its first revision, current. A definition has `instructions` (an agentic revision) or `workflow` (a workflow revision, checked by the DSL first), and `name`, `description`, `model` and `thinking` (agentic only), `harness` ([harnesses](#harnesses)), `place` ([place](#place)), `tools`, `tool_settings` ([search and fetch](#search-and-fetch)), `skills` (names; each `<name>/SKILL.md` is in `skills`) and `version`, which is the number the revision gets, and `max_cost_usd`, the agent's default cap (an agentic agent's or a workflow's), kept by an edit that leaves it out and cleared only by 0 ([spend cap](#spend-cap)), and `output_schema` (agentic only, at most 64 KiB): the JSON Schema the final answer's json block meets (its last fenced one, or the whole answer when it is one JSON object), which a completed run's `result.output` then holds (null when the answer doesn't meet it), kept by an edit that leaves it out. A template's answer schema is set here at apply, and a run a schedule trigger starts is handed that trigger's last completed `result.output` after its message; no other source's runs are, since each of their firings is a different event. Over 32 KiB, a scheduled run is handed only the fields the producing run's schema names in `x-carried`; carried arrays lose entries from the front until they fit, and the run is told how many. A save refuses an `x-carried` that is not unique root property names. `checkout` (agentic only): `pull_request` has the server check out, before each run's first turn, the pull request the run's GitHub event names, in `repo/` at its head with its base and merge base, using a read-only token of its GitHub App that the agent never holds ([GitHub triggers](#github-triggers-connect-github)); `none` clears it, and an edit that leaves it out keeps it. A field the store does not keep (`input_schema`) is `422 input_invalid` by name, and so is a definition that can never run here; one this host cannot run yet saves with `warnings` ([models](#models)). The ETag (`home_etag`) is the current revision's id. `GET /agents/{id}` adds `tools`, the tools its current revision grants with each one's provider ([search and fetch](#search-and-fetch)). It also adds `run_blockers` (`x-agentrun-serve: "runblockers/1"`): `{message, fields}` as a start with no overrides would be refused now (`409 agent_not_runnable`), or null. It is always null for an archived, native or SDK agent and for a revision whose MCP tools its first run pins, and the read asks no other service, so under the agent's `max_cost_usd` an OpenRouter decision model's missing price is named only once a save or a start has read OpenRouter's catalog: null is no promise that a start is accepted. |
3242
3276
  | `PUT /agents/{id}/definition` | The same body, checked [the same way](#models): a new revision, its parent the current one, made current. Without `skills` the current revision's skill files carry over. A definition that is the current revision already writes nothing, so a PUT sent twice makes one revision. An agent's id and name stay those it was made with (another name is `422` on `definition.name`). Its description is a label kept on the agent, not on a revision: a PUT that names a new one makes the next revision (even when nothing else changed) and writes the description with it in one commit, so a stale or refused edit changes neither; a PUT that leaves it out keeps it. `If-Match` that is not the current ETag is `412 precondition_failed`; the store compares it again inside the commit, so of two edits that read the same revision exactly one lands. The contract's body is taken too: the definition itself, with `If-Match` required (`412` without it) and `definition.version` greater than the current one (`422`). Any such version is taken, and always makes a new revision, the same definition included; the revision is numbered as this server numbers them, the next, and the answer says which; the route reads a body holding `definition` as this one, any other as the contract's. |
3243
3277
  | `GET /agents/{id}/revisions` | The agent's revisions, newest first: `revision`, `version`, `parent`, `kind`, `current`, `note`, `created_at` and the `definition`. |
3244
3278
  | `POST /agents/{id}/current` | `{revision}`: one of the agent's revisions becomes current again. |
@@ -23,8 +23,9 @@ export declare function installedHere(name: string, from?: string): string | und
23
23
  */
24
24
  export declare function npxLine(spec: string, env?: NodeJS.ProcessEnv, installed?: (name: string) => string | undefined): string;
25
25
  /**
26
- * A start `npx @parcha/agentrun` made (NPX_PACKAGE_ENV) that a data directory refused because an earlier version wrote it
27
- * (store.ts StoreFromEarlierVersion, or SchemaVersionUnknown on an earlier release's store): the refusal's own first line,
26
+ * A start the agentrun launcher made (NPX_PACKAGE_ENV: by npx, or by the installer's bin/agentrun and its service, the
27
+ * same launcher) that a data directory refused because an earlier version wrote it (store.ts StoreFromEarlierVersion,
28
+ * or SchemaVersionUnknown on an earlier release's store): the refusal's own first line,
28
29
  * then the two ways on as commands to paste. That command keeps its data in ~/.agentrun wherever it is run, so a new
29
30
  * folder alone is not a new AgentRun. First, the old folder moved aside whole, so the same command starts this version
30
31
  * where it was, and the earlier version still opens what it holds; then this version on a new, empty folder: the same
package/dist/adapters.js CHANGED
@@ -83,8 +83,9 @@ const freeName = (base, exists) => {
83
83
  return name;
84
84
  };
85
85
  /**
86
- * A start `npx @parcha/agentrun` made (NPX_PACKAGE_ENV) that a data directory refused because an earlier version wrote it
87
- * (store.ts StoreFromEarlierVersion, or SchemaVersionUnknown on an earlier release's store): the refusal's own first line,
86
+ * A start the agentrun launcher made (NPX_PACKAGE_ENV: by npx, or by the installer's bin/agentrun and its service, the
87
+ * same launcher) that a data directory refused because an earlier version wrote it (store.ts StoreFromEarlierVersion,
88
+ * or SchemaVersionUnknown on an earlier release's store): the refusal's own first line,
88
89
  * then the two ways on as commands to paste. That command keeps its data in ~/.agentrun wherever it is run, so a new
89
90
  * folder alone is not a new AgentRun. First, the old folder moved aside whole, so the same command starts this version
90
91
  * where it was, and the earlier version still opens what it holds; then this version on a new, empty folder: the same
@@ -108,7 +109,9 @@ export function earlierDataRefusal(error, data, env = {}, exists = existsSync) {
108
109
  const again = `${command}${dir === launcherData ? "" : ` --data ${shellWord(dir)}`}${flags}`;
109
110
  const fresh = freeName(`${dir}-new`, exists);
110
111
  const aside = freeName(`${dir}-earlier`, exists);
111
- const installed = exists(join(dir, "bin", "agentrun")) ? " Its bin/agentrun (the earlier installer's command) moves with it: run the installer again for this version's." : "";
112
+ // install.sh keeps its Node, its packages and the command in the folder beside the data (node/, lib/, bin/agentrun):
113
+ // that command, or the service that runs it, may be what started this. Moved, they go too, whichever version they are.
114
+ const installed = exists(join(dir, "bin", "agentrun")) ? " That takes the agentrun the installer put there with it (its Node in node/, lib/ and bin/agentrun): run the installer again to put this version's back." : "";
112
115
  return [
113
116
  refused.message.split("\n")[0],
114
117
  // Moved aside first: every later command (doctor, the harness commands, the service) then finds this version where it
@@ -1,7 +1,11 @@
1
1
  import { Compile } from "typebox/schema";
2
2
  /** The text of the last fenced `json` block in `text` (```json or a longer fence, ~~~ too), or undefined. */
3
3
  export declare function lastJsonBlock(text: string): string | undefined;
4
- /** The answer's last fenced json block, parsed, or why there is none. */
4
+ /** An answer's json block: its last fenced `json` block, else the whole answer when its trimmed text is one JSON object
5
+ * and nothing else (a reply that is the object alone). The one rule every reader of an answer's JSON keeps: a run's
6
+ * output, a template eval's target and its grader's verdict. */
7
+ export declare function jsonBlockOf(text: string): string | undefined;
8
+ /** The answer's json block (jsonBlockOf), parsed, or why there is none. */
5
9
  export declare function answerJson(answer: string): {
6
10
  value: unknown;
7
11
  } | {
@@ -33,7 +37,7 @@ export declare const outputRetryWords: (why: string) => string;
33
37
  /** Why `answer` misses `schema`, in the retry's words (structuredAnswer's why, less MISSES), or undefined when it meets
34
38
  * it. Undefined too when the schema does not compile (a save refuses one): asking the model again cannot mend a schema. */
35
39
  export declare function outputMiss(answer: string, schema: unknown): string | undefined;
36
- /** A final answer's structured part against an agent's output schema: the value of its last fenced json block when it
40
+ /** A final answer's structured part against an agent's output schema: the value of its json block (jsonBlockOf) when it
37
41
  * meets the schema, else why not (no block, not JSON, the first problems against the schema). */
38
42
  export declare function structuredAnswer(answer: string, schema: unknown): {
39
43
  value: unknown;
@@ -1,4 +1,5 @@
1
- // An answer's structured part: the last fenced `json` block of a final answer, parsed, and checked against an agent's
1
+ // An answer's structured part: the last fenced `json` block of a final answer (or the whole answer when it is one JSON
2
+ // object and nothing else), parsed, and checked against an agent's
2
3
  // output schema (definition.output_schema). The one reader of it: a completed agentic run's result.output (store-view.ts)
3
4
  // and a template eval's target graders (template-eval.ts) read an answer's JSON alike. The runner tells the
4
5
  // model the schema (outputContract, in every harness's system prompt) and asks once more on a miss (outputRetryWords,
@@ -22,9 +23,26 @@ export function lastJsonBlock(text) {
22
23
  }
23
24
  return found;
24
25
  }
25
- /** The answer's last fenced json block, parsed, or why there is none. */
26
+ /** An answer's json block: its last fenced `json` block, else the whole answer when its trimmed text is one JSON object
27
+ * and nothing else (a reply that is the object alone). The one rule every reader of an answer's JSON keeps: a run's
28
+ * output, a template eval's target and its grader's verdict. */
29
+ export function jsonBlockOf(text) {
30
+ const fenced = lastJsonBlock(text);
31
+ if (fenced !== undefined)
32
+ return fenced;
33
+ const whole = text.trim();
34
+ if (!whole.startsWith("{"))
35
+ return undefined;
36
+ try {
37
+ return isObject(JSON.parse(whole)) ? whole : undefined;
38
+ }
39
+ catch {
40
+ return undefined;
41
+ }
42
+ }
43
+ /** The answer's json block (jsonBlockOf), parsed, or why there is none. */
26
44
  export function answerJson(answer) {
27
- const block = lastJsonBlock(answer);
45
+ const block = jsonBlockOf(answer);
28
46
  if (block === undefined)
29
47
  return { why: "the answer has no fenced json block" };
30
48
  try {
@@ -80,7 +98,7 @@ export function outputMiss(answer, schema) {
80
98
  const read = structuredAnswer(answer, schema);
81
99
  return "why" in read ? read.why.replace(MISSES, "") : undefined;
82
100
  }
83
- /** A final answer's structured part against an agent's output schema: the value of its last fenced json block when it
101
+ /** A final answer's structured part against an agent's output schema: the value of its json block (jsonBlockOf) when it
84
102
  * meets the schema, else why not (no block, not JSON, the first problems against the schema). */
85
103
  export function structuredAnswer(answer, schema) {
86
104
  const compiled = schemaCheck(schema);
package/dist/api-only.js CHANGED
@@ -48,6 +48,8 @@ export const API_ONLY_ROUTES = new Set([
48
48
  "getCapabilities", "getHealth", "getUsage", "getCapacity", "listMcpServerNames",
49
49
  "importTemplate", "applyTemplate", "getAgent", "listRevisions", "setCurrent", "archiveAgent", "unarchiveAgent",
50
50
  "saveComposioServer", "deleteMcpServer",
51
+ // Refused in its own words (403): it reads the machine's session files, which a server behind a backend does not have to give.
52
+ "getWrapped",
51
53
  ]);
52
54
  /** The trigger sources an apply on an API-only server makes once the server has the launch hook: the ones that fire on
53
55
  * its own clock and need nothing a refused route sets up. Each firing goes to the backend in front of it
@@ -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,7 @@ 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. */
16
16
  export type PlanView = {
17
17
  state: PlanState;
18
18
  email?: string;
@@ -20,6 +20,7 @@ export type PlanView = {
20
20
  authorize_url?: string;
21
21
  expires_at?: string;
22
22
  models?: string[];
23
+ problem?: string;
23
24
  };
24
25
  /** The words a run or a request gets when there is no plan token to send. */
25
26
  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 +51,14 @@ export declare const planOf: (env: NodeJS.ProcessEnv) => PlanReader | undefined;
50
51
  export declare function withPlan<E extends NodeJS.ProcessEnv>(env: E, plan: PlanReader | undefined): E;
51
52
  /** Whether `env` runs on the plan now. */
52
53
  export declare const signedIn: (env: NodeJS.ProcessEnv) => boolean;
54
+ /** Why a sign-in past its browser step ended without signing in, from what pi-ai's flow or keep threw: `reason` for the
55
+ * log (OpenAI's status and error code, a missing field's name, a network error's code; never a token or a code) and
56
+ * `words` a person reads. pi-ai's page says the sign-in completed before it exchanges the code, so these are the only
57
+ * word of a failure after it. */
58
+ export declare function signInFailure(error: unknown): {
59
+ reason: string;
60
+ words: string;
61
+ };
53
62
  export interface ChatGPTPlanDeps {
54
63
  /** `settings`: where a server keeps its host id, for a sign-in; a runner, which never signs in, has none. */
55
64
  readonly store: {
@@ -98,6 +107,9 @@ export declare class ChatGPTPlan implements PlanReader {
98
107
  /** 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
108
  private hostId;
100
109
  private cancel;
110
+ /** Ends the sign-in waiting past its 10 minutes: a cancel, which says nothing by itself, that says it timed out. One
111
+ * whose code OpenAI answered is past waiting (it is being kept) and never times out. */
112
+ private expire;
101
113
  /** 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
114
  * minutes: the loopback callback finishes it where the browser runs on this machine; elsewhere finishSignIn does. */
103
115
  startSignIn(): Promise<{
@@ -112,6 +124,9 @@ export declare class ChatGPTPlan implements PlanReader {
112
124
  * of is revoked first, then replaced only while the row still holds it (a renewal of it that wrote back meanwhile is
113
125
  * read, revoked and replaced in turn), so no earlier pair is left alive. */
114
126
  private keep;
127
+ /** Takes again a sign-in's change the server failed to take (changed_failed), at the server's read of the sign-in, so
128
+ * what it offers does not wait for a restart. Nothing when none is owed; a failure again stays owed, said once. */
129
+ changeAgain(): Promise<void>;
115
130
  /** The plan's models from OpenAI's list (GET /v1/models with the token), those of the current families; the fallback
116
131
  * list when it can't be read. */
117
132
  private listModels;
@@ -101,6 +101,56 @@ function whoOf(token) {
101
101
  /** Whether a renewal's refusal is for good: the refresh token spent, expired or revoked (a 400 or 401 from the token
102
102
  * endpoint, as pi-ai words it), not a network fault or a 5xx. */
103
103
  const refusedForGood = (error) => /\((400|401)\)|invalid_grant|refresh_token_(reused|expired|invalidated)/.test(String(error?.message ?? ""));
104
+ /** A sign-in OpenAI finished whose credential this server could not keep (keep threw). */
105
+ class NotKept extends Error {
106
+ }
107
+ /** `value` as a log field or a code in words: letters, digits and `_` alone, 40 at most. */
108
+ const tag = (value) => String(value ?? "").replace(/[^A-Za-z0-9_]/g, "").slice(0, 40);
109
+ /** OpenAI's error code for a workspace whose admin has turned off open-source apps' use of its ChatGPT plans. */
110
+ const WORKSPACE_DENIED = "3p_delegated_access_policy_denied";
111
+ 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.";
112
+ /** A grant without DIRECT_SCOPE: OpenAI signed the account in but gave no use of its plan by apps. */
113
+ 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.";
114
+ /** 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
115
+ * apart. It never says Free can't be used: OpenAI changes which plans can. */
116
+ const FREE_OR_AGAIN = "a Free ChatGPT plan may be the reason; with a paid plan, start it again.";
117
+ const TIMED_OUT = "The sign-in timed out before OpenAI sent the code back: start it again.";
118
+ /** The words for OpenAI's refusal `code` at its sign-in page: fixed words, never the code. Anything on this machine can
119
+ * send the loopback callback an `error` while a sign-in waits, so the code goes to the log alone. */
120
+ const deniedWords = (code) => (tag(code) === WORKSPACE_DENIED ? ADMIN_OFF : `ChatGPT did not sign you in: ${FREE_OR_AGAIN}`);
121
+ /** Why a sign-in past its browser step ended without signing in, from what pi-ai's flow or keep threw: `reason` for the
122
+ * log (OpenAI's status and error code, a missing field's name, a network error's code; never a token or a code) and
123
+ * `words` a person reads. pi-ai's page says the sign-in completed before it exchanges the code, so these are the only
124
+ * word of a failure after it. */
125
+ export function signInFailure(error) {
126
+ const notKept = error instanceof NotKept;
127
+ const cause = notKept ? error.cause : error;
128
+ const message = String(cause?.message ?? "");
129
+ // 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
130
+ // code's exchange. Its code goes to the log; the words are fixed.
131
+ const denied = notKept ? null : /ChatGPT authorization failed: (\S+)/.exec(message);
132
+ const refused = notKept ? null : /token request failed \((\d{3})\)/.exec(message);
133
+ const code = denied ? tag(denied[1]) : refused ? tag(/"error"\s*:\s*"([^"]*)"/.exec(message)?.[1]) : "";
134
+ const reason = denied ? `authorize_${code || "error"}` : refused ? `token_${refused[1]}${code ? `_${code}` : ""}` : "";
135
+ // The workspace's refusal first: OpenAI's description of it may name the plan's scope.
136
+ if (code === WORKSPACE_DENIED)
137
+ return { reason, words: ADMIN_OFF };
138
+ if (message.includes(DIRECT_SCOPE))
139
+ return { reason: "no_direct_scope", words: PLAN_NOT_USABLE };
140
+ if (notKept)
141
+ return { reason: `not_saved${tag(cause?.code) ? `_${tag(cause.code)}` : ""}`, words: "OpenAI signed you in, but this server could not save the sign-in: start it again. The server's log says why." };
142
+ if (denied)
143
+ return { reason, words: deniedWords(code) };
144
+ if (refused)
145
+ return { reason, words: `OpenAI refused the sign-in: ${FREE_OR_AGAIN}` };
146
+ const unread = /token response (?:has invalid (\w+)|did not contain an (ID token)|must be an object)/.exec(message);
147
+ if (unread)
148
+ 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." };
149
+ const network = tag(cause?.cause?.code);
150
+ if (/fetch failed/.test(message) || network)
151
+ return { reason: `network${network ? `_${network}` : ""}`, words: "This server could not reach OpenAI to finish the sign-in: check its connection, then start again." };
152
+ return { reason: `other_${tag(cause?.name) || "error"}`, words: "The sign-in did not finish: start it again. The server's log says why." };
153
+ }
104
154
  /** Whether a renewal that failed surely left its refresh token unspent: OpenAI answered with a fault (a 5xx, a 429), or
105
155
  * the request never reached it (no address, no connection). A timeout, or a fault once it was sent, may have spent it. */
106
156
  function unspent(error) {
@@ -125,6 +175,11 @@ export class ChatGPTPlan {
125
175
  /** Set when a sign-in dropped by a sign-out (keep) could not have its revocation confirmed by OpenAI: that sign-out
126
176
  * answers revoked false. Cleared at each sign-out's start. */
127
177
  #droppedUnconfirmed = false;
178
+ /** Why the last sign-in ended without signing in (signInFailure's words past its browser step, or its timeout), until a
179
+ * sign-in starts, finishes or a sign-out. A cancelled one leaves none. */
180
+ #problem;
181
+ /** Set when the server's change callback failed after a sign-in was saved; cleared once it takes (changeAgain). */
182
+ #changeOwed = false;
128
183
  #watchers = new Set();
129
184
  #deps;
130
185
  constructor(deps) {
@@ -203,14 +258,15 @@ export class ChatGPTPlan {
203
258
  }
204
259
  view() {
205
260
  if (this.#pending && this.#pending.expiresAt <= this.now())
206
- this.cancel();
261
+ this.expire();
207
262
  const row = this.#snapshot;
208
263
  const who = row ? { ...(row.email ? { email: row.email } : {}), ...(row.plan ? { plan: row.plan } : {}) } : {};
209
264
  if (this.#pending)
210
265
  return { state: "pending", authorize_url: this.#pending.authorizeUrl, expires_at: new Date(this.#pending.expiresAt).toISOString(), ...who };
266
+ const problem = this.#problem ? { problem: this.#problem } : {};
211
267
  if (!row)
212
- return { state: "signed_out" };
213
- return { state: row.state, ...who, ...(row.state === "signed_in" ? { models: [...row.models] } : {}) };
268
+ return { state: "signed_out", ...problem };
269
+ return { state: row.state, ...who, ...(row.state === "signed_in" ? { models: [...row.models] } : {}), ...problem };
214
270
  }
215
271
  /** 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
272
  async hostId() {
@@ -229,12 +285,22 @@ export class ChatGPTPlan {
229
285
  clearTimeout(pending.timer);
230
286
  pending.abort.abort();
231
287
  }
288
+ /** Ends the sign-in waiting past its 10 minutes: a cancel, which says nothing by itself, that says it timed out. One
289
+ * whose code OpenAI answered is past waiting (it is being kept) and never times out. */
290
+ expire() {
291
+ if (!this.#pending || this.#pending.answered)
292
+ return;
293
+ this.cancel();
294
+ this.#problem = TIMED_OUT;
295
+ this.#deps.log?.({ chatgpt: "sign_in_failed", reason: "timed_out" });
296
+ }
232
297
  /** 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
298
  * minutes: the loopback callback finishes it where the browser runs on this machine; elsewhere finishSignIn does. */
234
299
  async startSignIn() {
235
300
  // A sign-in still finishing drops its credential (keep): this one is the person's latest.
236
301
  const epoch = ++this.#epoch;
237
302
  const before = this.#pending;
303
+ this.#problem = undefined;
238
304
  this.cancel();
239
305
  // pi-ai's callback listener on :1455 closes as its login ends: the one cancelled ends before this one listens.
240
306
  if (before)
@@ -259,17 +325,33 @@ export class ChatGPTPlan {
259
325
  this.#pending = undefined;
260
326
  };
261
327
  // 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);
328
+ const result = login.then((credential) => {
329
+ if (this.#pending?.abort === abort)
330
+ this.#pending.answered = true;
331
+ return this.keep(credential, epoch).catch((error) => {
332
+ throw new NotKept("not kept", { cause: error });
333
+ });
334
+ }).finally(settle);
335
+ // Past the browser step, the tab already says it completed: an end that is not a cancel (a newer start, a sign-out,
336
+ // the wait's end, the server's close) says why in the view and the log, whichever way the address came back.
337
+ let waiting = false;
338
+ result.catch((error) => {
339
+ if (!waiting || abort.signal.aborted || epoch !== this.#epoch)
340
+ return;
341
+ const { reason, words } = signInFailure(error);
342
+ this.#problem = words;
343
+ this.#deps.log?.({ chatgpt: "sign_in_failed", reason });
344
+ });
264
345
  const authorizeUrl = await Promise.race([link, result.then(() => undefined, (error) => {
265
346
  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
347
  })]);
267
348
  if (!authorizeUrl)
268
349
  throw new PlanSignInRefused("The sign-in could not start: try again.");
269
350
  const expiresAt = this.now() + PENDING_MS;
270
- const timer = setTimeout(() => (this.#pending?.abort === abort ? this.cancel() : undefined), PENDING_MS);
351
+ const timer = setTimeout(() => (this.#pending?.abort === abort ? this.expire() : undefined), PENDING_MS);
271
352
  timer.unref();
272
353
  this.#pending = { abort, state: new URL(authorizeUrl).searchParams.get("state") ?? "", authorizeUrl, expiresAt, paste, result, timer };
354
+ waiting = true;
273
355
  return { authorize_url: authorizeUrl, expires_at: new Date(expiresAt).toISOString() };
274
356
  }
275
357
  /** 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,7 +372,7 @@ export class ChatGPTPlan {
290
372
  throw new PlanSignInRefused(shape);
291
373
  const error = url.searchParams.get("error");
292
374
  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.`);
375
+ throw new PlanSignInRefused(deniedWords(error));
294
376
  if (url.searchParams.get("state") !== pending.state)
295
377
  throw new PlanSignInRefused("That address is from another sign-in: paste the one from the sign-in you started last, or start again.");
296
378
  if (!url.searchParams.get("code") || !url.searchParams.get("client_id"))
@@ -300,10 +382,7 @@ export class ChatGPTPlan {
300
382
  await pending.result;
301
383
  }
302
384
  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.");
385
+ throw new PlanSignInRefused(signInFailure(error).words);
307
386
  }
308
387
  return this.view();
309
388
  }
@@ -340,8 +419,32 @@ export class ChatGPTPlan {
340
419
  break;
341
420
  }
342
421
  this.#snapshot = row;
422
+ this.#problem = undefined;
343
423
  this.#deps.log?.({ chatgpt: "signed_in", ...(previousRevoked === undefined ? {} : { previous_revoked: String(previousRevoked) }) });
344
- await this.#deps.changed?.();
424
+ // Saved: what the server does with the change after it is not the sign-in's to fail. One it failed to take is owed,
425
+ // and taken again at its next read (changeAgain).
426
+ try {
427
+ await this.#deps.changed?.();
428
+ this.#changeOwed = false;
429
+ }
430
+ catch (error) {
431
+ this.#changeOwed = true;
432
+ const code = error?.code;
433
+ this.#deps.log?.({ chatgpt: "changed_failed", reason: String(typeof code === "string" ? code : error?.name ?? "error").replace(/[^A-Za-z0-9_]/g, "").slice(0, 40) || "error" });
434
+ }
435
+ }
436
+ /** Takes again a sign-in's change the server failed to take (changed_failed), at the server's read of the sign-in, so
437
+ * what it offers does not wait for a restart. Nothing when none is owed; a failure again stays owed, said once. */
438
+ async changeAgain() {
439
+ if (!this.#changeOwed)
440
+ return;
441
+ try {
442
+ await this.#deps.changed?.();
443
+ this.#changeOwed = false;
444
+ }
445
+ catch {
446
+ // Owed still: the next read takes it again.
447
+ }
345
448
  }
346
449
  /** The plan's models from OpenAI's list (GET /v1/models with the token), those of the current families; the fallback
347
450
  * list when it can't be read. */
@@ -487,6 +590,7 @@ export class ChatGPTPlan {
487
590
  * is not this answer's to give). */
488
591
  async signOut() {
489
592
  this.#droppedUnconfirmed = false;
593
+ this.#problem = undefined;
490
594
  this.#epoch += 1;
491
595
  const finishing = this.#pending;
492
596
  this.cancel();