@parcha/agentrun-serve 0.1.0-beta.57 → 0.1.0-beta.59
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +376 -0
- package/README.md +393 -118
- package/dist/acp-package.d.ts +5 -1
- package/dist/acp-package.js +19 -2
- package/dist/adapters.d.ts +23 -2
- package/dist/adapters.js +106 -33
- package/dist/agents-store.js +1 -1
- package/dist/answer-text.d.ts +3 -0
- package/dist/answer-text.js +22 -0
- package/dist/api-only.d.ts +2 -4
- package/dist/api-only.js +2 -4
- package/dist/attach-conformance.js +5 -4
- package/dist/box-paths.d.ts +7 -5
- package/dist/box-paths.js +12 -8
- package/dist/browser-computer.d.ts +3 -8
- package/dist/browser-computer.js +12 -35
- package/dist/browser-cost.js +94 -20
- package/dist/capacity.d.ts +1 -1
- package/dist/capacity.js +3 -3
- package/dist/chatgpt-plan.d.ts +5 -0
- package/dist/chatgpt-plan.js +25 -11
- package/dist/claude-login-token.d.ts +121 -0
- package/dist/claude-login-token.js +797 -0
- package/dist/claude-login.d.ts +119 -34
- package/dist/claude-login.js +551 -79
- package/dist/claude-sign-in.d.ts +3 -0
- package/dist/claude-sign-in.js +10 -1
- package/dist/cli.js +325 -328
- package/dist/composio-made.d.ts +1 -6
- package/dist/composio-made.js +1 -6
- package/dist/composio-owners.d.ts +26 -0
- package/dist/composio-owners.js +36 -0
- package/dist/composio-preset.d.ts +56 -23
- package/dist/composio-preset.js +173 -77
- package/dist/composio-triggers.d.ts +4 -4
- package/dist/composio-triggers.js +6 -7
- package/dist/compute-cost.js +11 -2
- package/dist/computer-attach.d.ts +40 -19
- package/dist/computer-attach.js +326 -62
- package/dist/computer-held-routes.d.ts +1 -1
- package/dist/computer-held-routes.js +9 -4
- package/dist/computer-keys.d.ts +11 -1
- package/dist/computer-keys.js +26 -1
- package/dist/computer-record.js +3 -1
- package/dist/computer-view.d.ts +5 -3
- package/dist/computer-view.js +10 -6
- package/dist/computer-viewer.js +36 -7
- package/dist/computers.d.ts +12 -11
- package/dist/computers.js +11 -8
- package/dist/console/THIRD-PARTY-NOTICES.txt +50 -0
- package/dist/console/assets/backend-BztxEAvb.js +166 -0
- package/dist/console/assets/index-LwNL4L9q.js +619 -0
- package/dist/console/assets/share-L84tlUDW.js +6 -0
- package/dist/console/assets/styles-CaRKlHke.js +291 -0
- package/dist/console/assets/styles-DQo8rzY-.css +1 -0
- package/dist/console/index.html +4 -3
- package/dist/console/share.html +17 -0
- package/dist/decisions.d.ts +17 -7
- package/dist/decisions.js +41 -15
- package/dist/dial-relay.d.ts +25 -4
- package/dist/dial-relay.js +139 -5
- package/dist/docker-daemon.js +4 -5
- package/dist/docker-host-addresses.js +29 -11
- package/dist/email/account.d.ts +6 -0
- package/dist/email/account.js +6 -0
- package/dist/email/authentication.d.ts +21 -0
- package/dist/email/authentication.js +106 -0
- package/dist/email/email-faux.d.ts +11 -2
- package/dist/email/email-faux.js +21 -5
- package/dist/email/mail.d.ts +25 -0
- package/dist/email/mail.js +58 -2
- package/dist/email/names.js +2 -2
- package/dist/email/tools.d.ts +9 -4
- package/dist/email/tools.js +95 -13
- package/dist/env-switch.d.ts +13 -5
- package/dist/env-switch.js +24 -6
- package/dist/errors.d.ts +1 -0
- package/dist/errors.js +2 -0
- package/dist/fal-price.d.ts +12 -4
- package/dist/fal-price.js +110 -26
- package/dist/faux-computers.js +1 -1
- package/dist/filed-answer.d.ts +2 -2
- package/dist/filed-answer.js +2 -2
- package/dist/graph-served.d.ts +10 -5
- package/dist/graph-served.js +40 -10
- package/dist/handed-values.js +1 -2
- package/dist/harness-check.d.ts +2 -1
- package/dist/harness-check.js +45 -12
- package/dist/harness-keys.js +9 -6
- package/dist/harness-opencode/facts.js +2 -0
- package/dist/harness-recipe-entry.d.ts +9 -3
- package/dist/harness-recipe-entry.js +18 -9
- package/dist/harness-recipe.d.ts +21 -0
- package/dist/harness-recipe.js +25 -3
- package/dist/harness-table.d.ts +8 -0
- package/dist/harness-table.js +17 -6
- package/dist/helper-env.d.ts +4 -1
- package/dist/helper-env.js +4 -1
- package/dist/host-check.d.ts +2 -3
- package/dist/host-check.js +13 -7
- package/dist/hosted-search.js +1 -1
- package/dist/import.d.ts +11 -8
- package/dist/import.js +437 -186
- package/dist/key-refusal.d.ts +9 -2
- package/dist/key-refusal.js +86 -32
- package/dist/learn/audit.d.ts +8 -5
- package/dist/learn/audit.js +15 -7
- package/dist/learn/compile.d.ts +5 -2
- package/dist/learn/compile.js +45 -21
- package/dist/learn/field-check.d.ts +111 -0
- package/dist/learn/field-check.js +174 -0
- package/dist/learn/ledger.d.ts +173 -0
- package/dist/learn/ledger.js +225 -0
- package/dist/learn/promote.d.ts +82 -39
- package/dist/learn/promote.js +61 -66
- package/dist/learn/secrets.d.ts +4 -0
- package/dist/learn/secrets.js +12 -0
- package/dist/learned-nodes.d.ts +8 -5
- package/dist/learned-nodes.js +8 -5
- package/dist/learned-workflow.d.ts +2 -1
- package/dist/learned-workflow.js +13 -10
- package/dist/learning-cost.d.ts +40 -21
- package/dist/learning-cost.js +30 -21
- package/dist/learning-setting.d.ts +6 -0
- package/dist/learning-setting.js +11 -1
- package/dist/listen-first.d.ts +5 -4
- package/dist/listen-first.js +4 -5
- package/dist/live-reach.d.ts +9 -0
- package/dist/live-reach.js +9 -0
- package/dist/mcp-api-only-origins.d.ts +23 -3
- package/dist/mcp-api-only-origins.js +57 -17
- package/dist/mcp-gateway.d.ts +16 -2
- package/dist/mcp-gateway.js +41 -3
- package/dist/mcp-oauth.d.ts +1 -1
- package/dist/mcp-oauth.js +3 -2
- package/dist/mcp-probe.d.ts +3 -0
- package/dist/mcp-probe.js +3 -0
- package/dist/mcp-secret-writes.d.ts +24 -2
- package/dist/mcp-secret-writes.js +30 -2
- package/dist/mcp-servers-store.d.ts +52 -14
- package/dist/mcp-servers-store.js +165 -61
- package/dist/mcp-sources.d.ts +1 -2
- package/dist/mcp-sources.js +1 -2
- package/dist/mcp-store.d.ts +5 -5
- package/dist/mcp-store.js +3 -3
- package/dist/mcp.js +1 -1
- package/dist/micro.d.ts +2 -0
- package/dist/micro.js +2 -0
- package/dist/model-gateway.d.ts +1 -1
- package/dist/model-gateway.js +20 -36
- package/dist/model.d.ts +5 -4
- package/dist/model.js +7 -6
- package/dist/monid.d.ts +14 -1
- package/dist/monid.js +103 -26
- package/dist/ollama-provider.d.ts +23 -9
- package/dist/ollama-provider.js +49 -20
- package/dist/openapi.js +234 -61
- package/dist/otel/genai.d.ts +83 -7
- package/dist/otel/genai.js +69 -9
- package/dist/otel/tracer.d.ts +42 -13
- package/dist/otel/tracer.js +241 -56
- package/dist/page.d.ts +7 -1
- package/dist/page.js +76 -22
- package/dist/paid-calls.d.ts +6 -4
- package/dist/paid-calls.js +15 -7
- package/dist/place-offers.d.ts +59 -34
- package/dist/place-offers.js +100 -58
- package/dist/place.d.ts +13 -14
- package/dist/place.js +56 -41
- package/dist/print.js +1 -1
- package/dist/provider.d.ts +5 -4
- package/dist/provider.js +26 -13
- package/dist/redact/match.d.ts +27 -9
- package/dist/redact/match.js +266 -57
- package/dist/run-census.d.ts +1 -1
- package/dist/run-census.js +4 -5
- package/dist/run-cut.js +4 -5
- package/dist/run-export-store.d.ts +15 -0
- package/dist/run-export-store.js +30 -0
- package/dist/run-export.d.ts +139 -0
- package/dist/run-export.js +379 -0
- package/dist/run-file-cut.d.ts +5 -0
- package/dist/run-file-cut.js +13 -0
- package/dist/run-launch.js +16 -3
- package/dist/run-learning-served.d.ts +2 -2
- package/dist/run-model-key.d.ts +15 -6
- package/dist/run-model-key.js +30 -31
- package/dist/run-reads-over-store.js +4 -4
- package/dist/run-secrets.js +3 -5
- package/dist/run-timeline-served.js +3 -1
- package/dist/run-view.d.ts +1 -2
- package/dist/run-view.js +2 -1
- package/dist/runnable.js +2 -2
- package/dist/runner/adapter-loop.d.ts +35 -18
- package/dist/runner/adapter-loop.js +97 -63
- package/dist/runner/adapter-run-spec.d.ts +34 -14
- package/dist/runner/adapter-run-spec.js +120 -75
- package/dist/runner/adapters/pi.js +4 -2
- package/dist/runner/audit.d.ts +8 -5
- package/dist/runner/audit.js +37 -17
- package/dist/runner/beside.d.ts +9 -2
- package/dist/runner/beside.js +29 -13
- package/dist/runner/claim-secrets.d.ts +27 -18
- package/dist/runner/claim-secrets.js +61 -47
- package/dist/runner/cli-run-spec.d.ts +18 -0
- package/dist/runner/cli-run-spec.js +93 -46
- package/dist/runner/compare-end.d.ts +2 -1
- package/dist/runner/compare-end.js +25 -10
- package/dist/runner/conformance/harness.js +2 -3
- package/dist/runner/conformance/subject.d.ts +4 -1
- package/dist/runner/harness-loops.js +3 -3
- package/dist/runner/held.d.ts +19 -4
- package/dist/runner/journal-kinds.d.ts +4 -1
- package/dist/runner/journal-kinds.js +22 -4
- package/dist/runner/learned-first.js +20 -4
- package/dist/runner/learning-end.d.ts +2 -8
- package/dist/runner/learning-end.js +11 -19
- package/dist/runner/live-ticker.js +7 -5
- package/dist/runner/loop-contract.d.ts +0 -2
- package/dist/runner/loop.d.ts +7 -0
- package/dist/runner/loop.js +1 -0
- package/dist/runner/main.d.ts +11 -6
- package/dist/runner/main.js +24 -18
- package/dist/runner/mcp-claim.js +24 -7
- package/dist/runner/mcp-run.d.ts +3 -6
- package/dist/runner/mcp-run.js +3 -4
- package/dist/runner/meta-tools.js +3 -2
- package/dist/runner/metrics.d.ts +7 -0
- package/dist/runner/metrics.js +19 -0
- package/dist/runner/model-route.d.ts +10 -7
- package/dist/runner/model-route.js +79 -15
- package/dist/runner/native-loop.js +10 -8
- package/dist/runner/presence.d.ts +11 -4
- package/dist/runner/presence.js +11 -6
- package/dist/runner/promotion.d.ts +25 -13
- package/dist/runner/promotion.js +125 -50
- package/dist/runner/redact.d.ts +3 -1
- package/dist/runner/redact.js +5 -3
- package/dist/runner/reflect-hook.js +1 -1
- package/dist/runner/responses-fetch.d.ts +36 -0
- package/dist/runner/responses-fetch.js +511 -0
- package/dist/runner/run-child-host.d.ts +38 -12
- package/dist/runner/run-child-host.js +231 -83
- package/dist/runner/run-child.js +11 -4
- package/dist/runner/runner-check.js +5 -1
- package/dist/runner/runner.d.ts +5 -3
- package/dist/runner/runner.js +14 -10
- package/dist/runner/save-slots.js +2 -1
- package/dist/runner/sdk-loop.js +8 -8
- package/dist/runner/spec-holds.d.ts +8 -1
- package/dist/runner/spec-holds.js +9 -4
- package/dist/runner/subagent.d.ts +11 -0
- package/dist/runner/subagent.js +17 -3
- package/dist/runner/workflow-calls.d.ts +9 -0
- package/dist/runner/workflow-calls.js +150 -0
- package/dist/runner/workflow-first.d.ts +138 -37
- package/dist/runner/workflow-first.js +230 -99
- package/dist/runner/workflow-spec.js +2 -2
- package/dist/runs-over-store.js +8 -7
- package/dist/save-once.d.ts +14 -0
- package/dist/save-once.js +31 -0
- package/dist/scrub-command.d.ts +34 -31
- package/dist/scrub-command.js +116 -147
- package/dist/sdk/runs.d.ts +6 -0
- package/dist/sdk/runs.js +89 -10
- package/dist/seal-key.js +4 -4
- package/dist/secret-cut.d.ts +3 -0
- package/dist/secret-cut.js +7 -1
- package/dist/secret-rules.d.ts +8 -1
- package/dist/secret-rules.js +482 -53
- package/dist/secrets.d.ts +51 -9
- package/dist/secrets.js +311 -21
- package/dist/server-keys.d.ts +4 -3
- package/dist/server-keys.js +4 -3
- package/dist/server-secrets-store.js +2 -4
- package/dist/server.d.ts +33 -10
- package/dist/server.js +454 -136
- package/dist/share-context.d.ts +22 -0
- package/dist/share-context.js +76 -0
- package/dist/shell-lex.d.ts +105 -0
- package/dist/shell-lex.js +646 -0
- package/dist/sign-ins-store.d.ts +5 -7
- package/dist/sign-ins-store.js +12 -16
- package/dist/sign-ins.d.ts +7 -11
- package/dist/sign-ins.js +40 -41
- package/dist/skills/agentrun-serve/SKILL.md +5 -2
- package/dist/slots.d.ts +9 -0
- package/dist/slots.js +45 -0
- package/dist/start-switches.d.ts +6 -5
- package/dist/start-switches.js +8 -4
- package/dist/stats.d.ts +5 -1
- package/dist/stats.js +1 -1
- package/dist/store/agent-body.js +2 -2
- package/dist/store/dialect.d.ts +4 -0
- package/dist/store/dialect.js +1 -0
- package/dist/store/index.d.ts +2 -2
- package/dist/store/index.js +1 -1
- package/dist/store/mcp-record-keys.d.ts +10 -0
- package/dist/store/mcp-record-keys.js +13 -0
- package/dist/store/postgres/dialect.js +2 -0
- package/dist/store/postgres/migrations/0028_learning_ledger.sql +44 -0
- package/dist/store/postgres/migrations/0029_run_launch_census_settle.sql +28 -0
- package/dist/store/postgres/migrations/0030_learning_ledger_epoch.sql +40 -0
- package/dist/store/postgres/migrations/0031_learning_ledger_calls.sql +12 -0
- package/dist/store/postgres/store.js +4 -0
- package/dist/store/schema.d.ts +44 -4
- package/dist/store/schema.js +111 -11
- package/dist/store/seal.d.ts +4 -1
- package/dist/store/sqlite/run-launch.d.ts +3 -10
- package/dist/store/sqlite/run-launch.js +12 -23
- package/dist/store/sqlite/run-patch.d.ts +19 -2
- package/dist/store/sqlite/run-patch.js +67 -2
- package/dist/store/sqlite/store.d.ts +3 -0
- package/dist/store/sqlite/store.js +177 -32
- package/dist/store/store-schema.js +3 -4
- package/dist/store/store.d.ts +74 -25
- package/dist/store/store.js +14 -11
- package/dist/store-reads/analytics.d.ts +2 -1
- package/dist/store-reads/analytics.js +7 -5
- package/dist/store-reads/learning.d.ts +102 -136
- package/dist/store-reads/learning.js +251 -302
- package/dist/store-reads/stats.d.ts +2 -2
- package/dist/store-reads/stats.js +13 -7
- package/dist/store-view.js +10 -7
- package/dist/suggestions.d.ts +1 -1
- package/dist/suggestions.js +29 -13
- package/dist/template-eval.d.ts +91 -9
- package/dist/template-eval.js +448 -105
- package/dist/template-import.d.ts +0 -10
- package/dist/template-import.js +5 -10
- package/dist/timeline/labels.d.ts +1 -1
- package/dist/timeline/labels.js +4 -3
- package/dist/timeline/timeline.d.ts +23 -11
- package/dist/timeline/timeline.js +115 -31
- package/dist/timeline/web-calls.d.ts +14 -14
- package/dist/timeline/web-calls.js +18 -30
- package/dist/tool-gate.d.ts +13 -1
- package/dist/tool-gate.js +43 -3
- package/dist/tool-keys-store.js +2 -4
- package/dist/tool-keys.d.ts +11 -0
- package/dist/tool-keys.js +16 -0
- package/dist/tool-plane.d.ts +50 -11
- package/dist/tool-plane.js +94 -30
- package/dist/tools.d.ts +5 -1
- package/dist/tools.js +7 -7
- package/dist/trigger-email.js +12 -6
- package/dist/triggers.d.ts +15 -34
- package/dist/triggers.js +119 -126
- package/dist/validate.d.ts +8 -1
- package/dist/validate.js +163 -23
- package/dist/web-fake.d.ts +2 -1
- package/dist/web-fake.js +8 -6
- package/dist/web-fetch.d.ts +8 -6
- package/dist/web-fetch.js +13 -11
- package/dist/web-holds.d.ts +32 -0
- package/dist/web-holds.js +86 -0
- package/dist/web-run.d.ts +32 -5
- package/dist/web-run.js +75 -28
- package/dist/web-save.d.ts +4 -9
- package/dist/web-save.js +27 -55
- package/dist/web-search.js +14 -25
- package/dist/wires.d.ts +4 -3
- package/dist/wires.js +5 -4
- package/dist/workspace/archil-claim.d.ts +12 -5
- package/dist/workspace/archil-claim.js +45 -5
- package/dist/workspace/attach.js +52 -19
- package/dist/workspace/attached-computers.d.ts +38 -11
- package/dist/workspace/attached-computers.js +81 -16
- package/dist/workspace/computer-deps.d.ts +29 -7
- package/dist/workspace/computer-deps.js +36 -18
- package/dist/workspace/computer-for-claim.d.ts +21 -4
- package/dist/workspace/computer-for-claim.js +166 -57
- package/dist/workspace/computer-intervals.d.ts +2 -0
- package/dist/workspace/computer-intervals.js +1 -1
- package/dist/workspace/computer-janitor.d.ts +48 -14
- package/dist/workspace/computer-janitor.js +153 -44
- package/dist/workspace/computer-kept.d.ts +158 -32
- package/dist/workspace/computer-kept.js +288 -63
- package/dist/workspace/computer-providers.d.ts +8 -3
- package/dist/workspace/computer-providers.js +12 -5
- package/dist/workspace/index.d.ts +1 -1
- package/dist/workspace/index.js +1 -1
- package/dist/workspace/local.js +41 -1
- package/dist/workspace/mount-revoke-left.d.ts +31 -0
- package/dist/workspace/mount-revoke-left.js +72 -0
- package/dist/workspace/paired-route.d.ts +91 -0
- package/dist/workspace/paired-route.js +152 -0
- package/dist/workspace/resolve-computer.d.ts +5 -2
- package/dist/workspace/resolve-computer.js +9 -3
- package/dist/workspace/run-end-computers.d.ts +11 -5
- package/dist/workspace/run-end-computers.js +153 -28
- package/dist/workspace/run-tools.d.ts +22 -3
- package/dist/workspace/run-tools.js +17 -5
- package/dist/workspace/run-workspace.d.ts +14 -1
- package/dist/workspace/run-workspace.js +34 -1
- package/dist/workspace/workspace.d.ts +6 -0
- package/dist/wrapped.d.ts +8 -2
- package/dist/wrapped.js +21 -6
- package/package.json +12 -13
- package/skills/agentrun-serve/SKILL.md +5 -2
- package/templates/README.md +25 -9
- package/dist/console/assets/backend-DVhHzJX2.js +0 -166
- package/dist/console/assets/index-Bwn1oTem.css +0 -1
- package/dist/console/assets/index-okP-y8PK.js +0 -747
|
@@ -0,0 +1,797 @@
|
|
|
1
|
+
// Claude Code's login on this machine, as a runner hands it to a run that is a user of its own (run-child-host.ts
|
|
2
|
+
// staysInRunner): the runner, the server's user, reads the login's access token from AgentRun's own login folder, and
|
|
3
|
+
// the run's process is handed that token alone (held.ts claudeLogin), never the folder or its refresh token.
|
|
4
|
+
//
|
|
5
|
+
// The runner reads the login's file again at every ask, so a renewal written there by anyone is taken at once, and it
|
|
6
|
+
// renews the login itself, with the pinned CLI's own request (renewLogin; the Claude adapter's login-refresh.ts says what
|
|
7
|
+
// that request is and where in the CLI it was read): at an ask that finds less than LOGIN_MARGIN_MS left, and at the ask
|
|
8
|
+
// after Anthropic refused the token it handed (`refused`, the CLI's 401). One ask posts once at most: one renewal is in
|
|
9
|
+
// flight per refresh token in this process, and across processes the renewer holds the CLI's own refresh lock on the
|
|
10
|
+
// folder and reads the file again once it holds it, so a token another holder (the CLI, another runner) renewed is
|
|
11
|
+
// taken and nothing is posted. It holds that lock as the CLI's lock library does, by the directory it made and the mtime
|
|
12
|
+
// it set (within 10 µs, or the start of the second that mtime falls in, which is how a filesystem that keeps whole
|
|
13
|
+
// seconds alone shows it and how the CLI's library reads its own there; that second is taken on every filesystem), and
|
|
14
|
+
// a lock another holder took over is never touched, removed or posted under once a check reads it. A read that fails
|
|
15
|
+
// for a reason other than the lock being gone is no takeover: the lock is read once more before a release gives up on
|
|
16
|
+
// it. Runners make or take over a lock one at a time, under a takeover mark beside it, so between runners one holder at
|
|
17
|
+
// a time holds it, unless a runner stalls past the 60 s stale time inside a takeover or its release, or a runner crashes
|
|
18
|
+
// holding the mark and two runners then take that dead mark over at once (one's late removal lands in the mark the
|
|
19
|
+
// other made). The CLI never sees the mark: between a runner and the CLI the lock is as safe as the CLI's own (proper-lockfile), and the
|
|
20
|
+
// CLI's second lock, beside the folder, keeps a takeover's late removal (or, on such a filesystem, a lock made in the
|
|
21
|
+
// runner's second) from letting both post where that lock can be made. The answer is written back only to the file it
|
|
22
|
+
// came from, atomically (a temp file at mode 0600 in the same folder before any byte is in it, synced, then renamed over
|
|
23
|
+
// it), every other field kept as it was. A
|
|
24
|
+
// pair whose write fails is held in this process's memory until it is saved: every ask hands its token and tries the
|
|
25
|
+
// write again, under the same refresh lock with the file read again under it, so it never lands over a newer pair, and
|
|
26
|
+
// one whose token nears its own end still unsaved is refused in LOGIN_NOT_SAVED's words. A refresh
|
|
27
|
+
// token Anthropic took (a 200 that rotated it) or refused for good (`invalid_grant`) is never posted again by this
|
|
28
|
+
// process. A renewal that fails is refused after one more read of the file (another holder may have renewed meanwhile),
|
|
29
|
+
// in LOGIN_REFUSED_NOT_RENEWED's words when Anthropic refused the token, else LOGIN_RUNNING_OUT's, and nothing retries
|
|
30
|
+
// it. No token is in a log field, an error or an event: a failure is told by its status and
|
|
31
|
+
// its OAuth error code alone, never a response body or a thrown error's words. Each value read or answered joins this
|
|
32
|
+
// process's redaction (secrets.ts holdSecret), and each token handed joins every watcher's.
|
|
33
|
+
//
|
|
34
|
+
// A runner whose runs on the login stay in its own process (`process` isolation, or none) has its CLI read and renew the
|
|
35
|
+
// same folder. Each runner says on the data folder which it is (sayLoginRunner), and a run under a user of its own is
|
|
36
|
+
// refused while such a runner is there (loginRunnerInProcess).
|
|
37
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
38
|
+
import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
39
|
+
import { lstat, mkdir, open, readFile, realpath, rename, rm, stat, utimes } from "node:fs/promises";
|
|
40
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
41
|
+
import { dirname, join } from "node:path";
|
|
42
|
+
import { loginRefresh } from "@parcha/agentrun-harness-claude/facts";
|
|
43
|
+
import { agentRunLoginDir, LOGIN_SIGNED_OUT } from "./claude-login.js";
|
|
44
|
+
import { holdSecret } from "./secrets.js";
|
|
45
|
+
import { RUNNER_STALE_MS } from "./store/index.js";
|
|
46
|
+
/** The pinned CLI's credentials file in its credentials directory (CLAUDE_SECURESTORAGE_CONFIG_DIR). */
|
|
47
|
+
export const LOGIN_FILE = ".credentials.json";
|
|
48
|
+
/** The least a token handed to a run has left: the pinned CLI's own margin before it calls a token expired (its
|
|
49
|
+
* `n+300000>=e`), and when the runner renews it. */
|
|
50
|
+
export const LOGIN_MARGIN_MS = 5 * 60_000;
|
|
51
|
+
/** The longest one renewal request may take: the runner gives it up then (chatgpt-plan.ts's own). */
|
|
52
|
+
export const REFRESH_CALL_MS = 15_000;
|
|
53
|
+
/** How long an ask waits while another holder (the CLI, another runner) holds the login's refresh lock: the CLI's own
|
|
54
|
+
* request timeout (30 s) and its write back. Then it refuses, having posted nothing. */
|
|
55
|
+
export const LOCK_WAIT_MS = 35_000;
|
|
56
|
+
/** How often a waiting ask reads the file and tries the lock again. */
|
|
57
|
+
const LOCK_POLL_MS = 200;
|
|
58
|
+
/** The words a run gets when the login's token has less than the margin left and the runner could not renew it. */
|
|
59
|
+
export const LOGIN_RUNNING_OUT = "Claude Code's login on this machine runs out in less than 5 minutes, and the runner could not renew it: open Claude Code on this login once to renew it, or sign in again under Settings → Model keys, then start the run again.";
|
|
60
|
+
/** The words a run gets when Anthropic refused the login's token (the run's CLI's 401), whatever time it had left, and
|
|
61
|
+
* the runner could not renew it. */
|
|
62
|
+
export const LOGIN_REFUSED_NOT_RENEWED = "Claude refused this login and it could not be renewed; open Claude Code once to sign in again.";
|
|
63
|
+
/** The words a run gets when the runner renewed the login but could not write the renewal to the login's file, and the
|
|
64
|
+
* renewed token it holds in memory has less than the margin left: Anthropic took the file's refresh token, so only that
|
|
65
|
+
* held pair can be renewed, and the runner renews only from the file. */
|
|
66
|
+
export const LOGIN_NOT_SAVED = "Claude Code's login on this machine was renewed, but the runner could not save the renewal to the login's file, and the renewed token runs out in less than 5 minutes: make room on the disk (or fix the login folder's permissions) and start the run again; if the runner restarted meanwhile, sign in again under Settings → Model keys.";
|
|
67
|
+
/** A renewal that holds a pair it could not save, whose token nears its end (LOGIN_NOT_SAVED). */
|
|
68
|
+
class LoginNotSaved extends Error {
|
|
69
|
+
constructor() {
|
|
70
|
+
super(LOGIN_NOT_SAVED);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/** The words a run gets when the login is kept in a form this runner does not read (not the pinned CLI's plaintext file). */
|
|
74
|
+
export const LOGIN_SEALED = "Claude Code's login on this machine is kept in a form this runner cannot hand to a run of its own user: set AGENTRUN_RUN_USER=same, or give the run a model_key.";
|
|
75
|
+
const strings = (values) => values.filter((value) => typeof value === "string");
|
|
76
|
+
/** The runner's reader of one login's access token, and its renewer. */
|
|
77
|
+
export class LoginTokens {
|
|
78
|
+
#file;
|
|
79
|
+
#login;
|
|
80
|
+
#now;
|
|
81
|
+
#renew;
|
|
82
|
+
#watchers = new Set();
|
|
83
|
+
/** An access token Anthropic refused (refused): the next ask renews rather than hand it again. */
|
|
84
|
+
#refusedAccess;
|
|
85
|
+
constructor(options) {
|
|
86
|
+
this.#login = options.login;
|
|
87
|
+
this.#file = join(options.login.dir, LOGIN_FILE);
|
|
88
|
+
this.#now = options.now ?? Date.now;
|
|
89
|
+
this.#renew = options.renew ?? renewLogin({ ...(options.fetch ? { fetch: options.fetch } : {}), now: this.#now, ...(options.log ? { log: options.log } : {}) });
|
|
90
|
+
}
|
|
91
|
+
/** Tells `listener` each token as it is handed, for a redactor. */
|
|
92
|
+
watch(listener) {
|
|
93
|
+
this.#watchers.add(listener);
|
|
94
|
+
}
|
|
95
|
+
/** The login's access token, read from its file now, with at least LOGIN_MARGIN_MS left: renewed first (once) when
|
|
96
|
+
* it has less, or when Anthropic refused it (refused). Else it throws in words (signed out, a form not read here, or
|
|
97
|
+
* near its end and not renewed), never with a value of the file in them. */
|
|
98
|
+
async token() {
|
|
99
|
+
let read = await this.#read();
|
|
100
|
+
// A pair a renewal could not save yet (heldPairs) is the renewal's to hand, and to save, at every ask.
|
|
101
|
+
if (!("refused" in read) && (read.access === this.#refusedAccess || read.expiresAt - this.#now() < LOGIN_MARGIN_MS || heldPairs.has(this.#file))) {
|
|
102
|
+
const seen = read.access;
|
|
103
|
+
let renewed;
|
|
104
|
+
let notSaved = false;
|
|
105
|
+
try {
|
|
106
|
+
renewed = await this.#renew(this.#login, seen, this.#refusedAccess);
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
// Refused below in LOGIN_NOT_SAVED's, LOGIN_REFUSED_NOT_RENEWED's or LOGIN_RUNNING_OUT's words: a renewal's
|
|
110
|
+
// own never reach a run.
|
|
111
|
+
notSaved = error instanceof LoginNotSaved;
|
|
112
|
+
}
|
|
113
|
+
// The one read after it: the renewal's write, or another holder's that renewed meanwhile (a failed post included).
|
|
114
|
+
read = await this.#read();
|
|
115
|
+
if (!("refused" in read) && read.access === seen) {
|
|
116
|
+
if (notSaved)
|
|
117
|
+
throw new Error(LOGIN_NOT_SAVED);
|
|
118
|
+
// A held pair, still unsaved, whose token Anthropic refused: its refresh token is not the file's, and the runner
|
|
119
|
+
// renews only from the file, so it is refused in those words rather than the file's old token handed.
|
|
120
|
+
if (!renewed && this.#refusedAccess !== undefined && heldPairs.get(this.#file)?.renewed.access === this.#refusedAccess)
|
|
121
|
+
throw new Error(LOGIN_REFUSED_NOT_RENEWED);
|
|
122
|
+
if (renewed)
|
|
123
|
+
read = renewed;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
if ("refused" in read)
|
|
127
|
+
throw new Error(read.refused);
|
|
128
|
+
// A token Anthropic refused is said so, whatever time it had left: "runs out in less than 5 minutes" would not be true.
|
|
129
|
+
if (read.access === this.#refusedAccess)
|
|
130
|
+
throw new Error(LOGIN_REFUSED_NOT_RENEWED);
|
|
131
|
+
if (read.expiresAt - this.#now() < LOGIN_MARGIN_MS)
|
|
132
|
+
throw new Error(LOGIN_RUNNING_OUT);
|
|
133
|
+
for (const listener of this.#watchers)
|
|
134
|
+
listener([read.access]);
|
|
135
|
+
return read.access;
|
|
136
|
+
}
|
|
137
|
+
/** Anthropic refused `sent` (the run's CLI's 401): the next ask renews it, unless the file holds another token by
|
|
138
|
+
* then (another holder renewed it, and that one is handed). */
|
|
139
|
+
async refused(sent) {
|
|
140
|
+
const read = await this.#read();
|
|
141
|
+
// The token of a pair held unsaved is the one handed while the file still holds the old one.
|
|
142
|
+
if (!("refused" in read) && (read.access === sent || heldPairs.get(this.#file)?.renewed.access === sent))
|
|
143
|
+
this.#refusedAccess = sent;
|
|
144
|
+
}
|
|
145
|
+
/** The login's access token and its end, as its file holds them now (credentialsRead). No file, no `claudeAiOauth`, or
|
|
146
|
+
* one the CLI cleared (an empty token), is signed out; anything else, a file the runner may not open included, is a
|
|
147
|
+
* form this runner does not read. */
|
|
148
|
+
async #read() {
|
|
149
|
+
const read = await credentialsRead(this.#file);
|
|
150
|
+
if (read === "gone")
|
|
151
|
+
return { refused: LOGIN_SIGNED_OUT };
|
|
152
|
+
if (typeof read === "string")
|
|
153
|
+
return { refused: LOGIN_SEALED };
|
|
154
|
+
const { accessToken, expiresAt } = read.oauth;
|
|
155
|
+
if (accessToken === "")
|
|
156
|
+
return { refused: LOGIN_SIGNED_OUT };
|
|
157
|
+
if (typeof accessToken !== "string" || typeof expiresAt !== "number" || !Number.isFinite(expiresAt))
|
|
158
|
+
return { refused: LOGIN_SEALED };
|
|
159
|
+
return { access: accessToken, expiresAt };
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
/** Refresh tokens this process never posts again: one Anthropic refused for good (`invalid_grant`), and one it took (a
|
|
163
|
+
* 200 that answered another refresh token: the one posted is spent). */
|
|
164
|
+
const dead = new Set();
|
|
165
|
+
/** The renewals in flight in this process, by the refresh token they spend: two asks on one login share one. */
|
|
166
|
+
const flights = new Map();
|
|
167
|
+
/** The pairs this process renewed and could not save yet, by the file they belong in: every ask on that login hands the
|
|
168
|
+
* held token and tries the write again (saveHeld), until it lands, another holder writes the file, or the process ends. */
|
|
169
|
+
const heldPairs = new Map();
|
|
170
|
+
/** `held` written into `file` as the pinned CLI writes a renewal back (login-refresh.ts): only while the file still holds
|
|
171
|
+
* the refresh token it spent (or one the CLI cleared), the fields it gives over the file's, the rest kept as they are.
|
|
172
|
+
* "saved" once written (or found written: another ask saved it), "held" while the write or the read before it fails
|
|
173
|
+
* (kept in heldPairs), and "dropped" when the file holds another holder's pair (or is gone, or holds no login the
|
|
174
|
+
* runner reads): the file wins, as the CLI's own check lets it. */
|
|
175
|
+
async function saveHeld(file, held, options, owned) {
|
|
176
|
+
const say = options.log ?? (() => undefined);
|
|
177
|
+
const forget = () => {
|
|
178
|
+
if (heldPairs.get(file) === held)
|
|
179
|
+
heldPairs.delete(file);
|
|
180
|
+
};
|
|
181
|
+
const current = await credentialsRead(file, fsOf(options).readFile);
|
|
182
|
+
// A read that failed says nothing of which pair the file holds, and the held pair's refresh token may be the only one
|
|
183
|
+
// left that renews the login (Anthropic rotated it): the pair stays held, and a later ask reads the file again. It is
|
|
184
|
+
// dropped only once a read shows the file gone or holding another pair.
|
|
185
|
+
if (current === "unread") {
|
|
186
|
+
heldPairs.set(file, held);
|
|
187
|
+
say({ claude_login: "renewed", saved: "no", reason: "file_unread" });
|
|
188
|
+
return "held";
|
|
189
|
+
}
|
|
190
|
+
// The file holds this very pair: another ask of this process saved it since this one took it from heldPairs. Saved,
|
|
191
|
+
// and said so, never as a newer pair, which reads as another holder's takeover.
|
|
192
|
+
if (typeof current !== "string" && current.oauth.accessToken === held.fields.accessToken && current.oauth.refreshToken === held.fields.refreshToken) {
|
|
193
|
+
forget();
|
|
194
|
+
say({ claude_login: "renewed", saved: "yes", reason: "already_saved" });
|
|
195
|
+
return "saved";
|
|
196
|
+
}
|
|
197
|
+
if (typeof current === "string" || (current.oauth.refreshToken !== held.posted && current.oauth.refreshToken !== "")) {
|
|
198
|
+
forget();
|
|
199
|
+
say({ claude_login: "renewed", saved: "no", reason: "newer" });
|
|
200
|
+
return "dropped";
|
|
201
|
+
}
|
|
202
|
+
// `owned`: the refresh lock this save holds, asked after the read and before the write. One lost since (taken over)
|
|
203
|
+
// means another holder may write now, and one whose read failed may be: the pair stays held, and a later ask tries
|
|
204
|
+
// again.
|
|
205
|
+
const lock = owned ? await owned() : "own";
|
|
206
|
+
if (lock !== "own") {
|
|
207
|
+
heldPairs.set(file, held);
|
|
208
|
+
say({ claude_login: "renewed", saved: "no", reason: lockWord(lock) });
|
|
209
|
+
return "held";
|
|
210
|
+
}
|
|
211
|
+
try {
|
|
212
|
+
await replaceFile(file, JSON.stringify({ ...current.json, claudeAiOauth: { ...current.oauth, ...held.fields } }));
|
|
213
|
+
}
|
|
214
|
+
catch {
|
|
215
|
+
heldPairs.set(file, held);
|
|
216
|
+
say({ claude_login: "renewed", saved: "no", reason: "held" });
|
|
217
|
+
return "held";
|
|
218
|
+
}
|
|
219
|
+
forget();
|
|
220
|
+
say({ claude_login: "renewed", saved: "yes" });
|
|
221
|
+
return "saved";
|
|
222
|
+
}
|
|
223
|
+
/** A held pair's save as renewLogin makes it at an ask: under the CLI's refresh locks on the login's folder, as a
|
|
224
|
+
* renewal is, so it takes its turn with every renewal of that file (the CLI's, another runner's, this process's own),
|
|
225
|
+
* and saveHeld's read and check are made while it holds them. A save that read the file before a renewal wrote a newer
|
|
226
|
+
* pair, and writes after, would put the held pair back over it, its refresh token spent. While another holder has the
|
|
227
|
+
* locks it waits, as a renewal does, then the pair stays held for a later ask; so it does when the locks cannot be
|
|
228
|
+
* made at all (a full disk refuses a mkdir too). */
|
|
229
|
+
async function saveHeldUnderLock(dir, file, held, options) {
|
|
230
|
+
const say = options.log ?? (() => undefined);
|
|
231
|
+
const fs = fsOf(options);
|
|
232
|
+
const updateMs = options.lockUpdateMs ?? loginRefresh.lockUpdateMs;
|
|
233
|
+
const giveUp = Date.now() + (options.lockWaitMs ?? LOCK_WAIT_MS);
|
|
234
|
+
for (;;) {
|
|
235
|
+
let locks;
|
|
236
|
+
try {
|
|
237
|
+
locks = await takeRefreshLocks(dir, fs, updateMs);
|
|
238
|
+
}
|
|
239
|
+
catch {
|
|
240
|
+
say({ claude_login: "renewed", saved: "no", reason: "held" });
|
|
241
|
+
return "held";
|
|
242
|
+
}
|
|
243
|
+
if (locks) {
|
|
244
|
+
try {
|
|
245
|
+
return await saveHeld(file, held, options, locks.owned);
|
|
246
|
+
}
|
|
247
|
+
finally {
|
|
248
|
+
await locks.release().catch(() => undefined);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
// Another holder renews now: its write lands first, and the check under the locks then drops the held pair.
|
|
252
|
+
if (Date.now() > giveUp) {
|
|
253
|
+
say({ claude_login: "renewed", saved: "no", reason: "locked" });
|
|
254
|
+
return "held";
|
|
255
|
+
}
|
|
256
|
+
await sleep(LOCK_POLL_MS);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
const readText = (path) => readFile(path, "utf8");
|
|
260
|
+
/** The login's credentials file as it is now, in the pinned CLI's shape: its parsed object and its `claudeAiOauth`,
|
|
261
|
+
* every token in it held for redaction; the one reader of the file, the runner's asks' (LoginTokens) and its
|
|
262
|
+
* renewals' (read with LockFs.readFile). Else a word, never a value of the file: "gone" when it is not there or holds
|
|
263
|
+
* no `claudeAiOauth` (signed out); "unread" when the read fails another way (an I/O error) or its text is not JSON,
|
|
264
|
+
* which says nothing of which pair it holds; "sealed" when it is JSON in another shape, a form this runner does not
|
|
265
|
+
* read. A renewal takes any word as no pair to renew from. */
|
|
266
|
+
async function credentialsRead(file, read = readText) {
|
|
267
|
+
let json;
|
|
268
|
+
try {
|
|
269
|
+
json = JSON.parse(await read(file));
|
|
270
|
+
}
|
|
271
|
+
catch (error) {
|
|
272
|
+
return error?.code === "ENOENT" ? "gone" : "unread";
|
|
273
|
+
}
|
|
274
|
+
if (json === null || typeof json !== "object" || Array.isArray(json))
|
|
275
|
+
return "sealed";
|
|
276
|
+
const oauth = json.claudeAiOauth;
|
|
277
|
+
if (oauth === undefined || oauth === null)
|
|
278
|
+
return "gone";
|
|
279
|
+
if (typeof oauth !== "object" || Array.isArray(oauth))
|
|
280
|
+
return "sealed";
|
|
281
|
+
const fields = oauth;
|
|
282
|
+
holdSecret(...strings([fields.accessToken, fields.refreshToken]));
|
|
283
|
+
return { json: json, oauth: fields };
|
|
284
|
+
}
|
|
285
|
+
/** The pinned CLI's renewal of a login (the adapter's login-refresh.ts), as the runner does it in the CLI's place. */
|
|
286
|
+
export function renewLogin(options = {}) {
|
|
287
|
+
const now = options.now ?? Date.now;
|
|
288
|
+
const renew = async (login, seen, refusedAccess) => {
|
|
289
|
+
const file = join(login.dir, LOGIN_FILE);
|
|
290
|
+
// A pair renewed here and not saved yet: its token is handed and its write tried again (under the refresh locks, read
|
|
291
|
+
// again there: saveHeldUnderLock), and nothing is posted, for the file's refresh token is spent. Once saved, a token
|
|
292
|
+
// near its own end, or one Anthropic refused (refusedAccess), is renewed from the file as any other.
|
|
293
|
+
const held = heldPairs.get(file);
|
|
294
|
+
if (held) {
|
|
295
|
+
const kept = await saveHeldUnderLock(login.dir, file, held, options);
|
|
296
|
+
if (kept === "dropped")
|
|
297
|
+
return undefined;
|
|
298
|
+
const refusedHeld = held.renewed.access === refusedAccess;
|
|
299
|
+
if (!refusedHeld && held.renewed.expiresAt - now() >= LOGIN_MARGIN_MS)
|
|
300
|
+
return held.renewed;
|
|
301
|
+
if (kept === "held") {
|
|
302
|
+
// Unsaved, nothing can renew it here: refused (LoginTokens.token says which words), never handed again.
|
|
303
|
+
if (refusedHeld)
|
|
304
|
+
throw new Error("Anthropic refused the held token, and its pair is not saved");
|
|
305
|
+
throw new LoginNotSaved();
|
|
306
|
+
}
|
|
307
|
+
seen = held.renewed.access;
|
|
308
|
+
}
|
|
309
|
+
const read = await credentialsRead(file, fsOf(options).readFile);
|
|
310
|
+
// Another holder renewed it since it was read, or it changed (no pair read: the caller reads it again too).
|
|
311
|
+
if (typeof read === "string" || read.oauth.accessToken !== seen)
|
|
312
|
+
return undefined;
|
|
313
|
+
const refresh = read.oauth.refreshToken;
|
|
314
|
+
if (typeof refresh !== "string" || refresh === "")
|
|
315
|
+
throw new Error("the login holds no refresh token");
|
|
316
|
+
// A renewal in flight on this refresh token is joined first: one Anthropic answered with a new refresh token has
|
|
317
|
+
// marked this one spent (postRefresh) before its save writes the new pair, and an ask that read the file in between
|
|
318
|
+
// is handed that pair. The spent check stops only a new request.
|
|
319
|
+
let flight = flights.get(refresh);
|
|
320
|
+
if (!flight) {
|
|
321
|
+
if (dead.has(refresh)) {
|
|
322
|
+
// The renewal that spent it may have held its pair unsaved and settled while this read was out, after the check
|
|
323
|
+
// of heldPairs above: that pair is this ask's, through the held branch, never a refusal.
|
|
324
|
+
if (heldPairs.get(file)?.posted === refresh)
|
|
325
|
+
return renew(login, seen, refusedAccess);
|
|
326
|
+
throw new Error("the login's refresh token is spent or was refused for good");
|
|
327
|
+
}
|
|
328
|
+
flight = renewUnderLock(login.dir, file, seen, refresh, options).finally(() => flights.delete(refresh));
|
|
329
|
+
flights.set(refresh, flight);
|
|
330
|
+
}
|
|
331
|
+
return flight;
|
|
332
|
+
};
|
|
333
|
+
return renew;
|
|
334
|
+
}
|
|
335
|
+
const LOCK_FS = { mkdir: (path) => mkdir(path), stat: (path) => stat(path), utimes: (path, atime, mtime) => utimes(path, atime, mtime), rm: (path, options) => rm(path, options), readFile: (path) => readText(path) };
|
|
336
|
+
/** A renewal's file operations: those `options` gives, fs/promises' own for the rest. */
|
|
337
|
+
const fsOf = (options) => ({ ...LOCK_FS, ...options.lockFs });
|
|
338
|
+
/** Whether two reads are of one directory with one mtime, exactly: what a takeover removes is only the lock it read. */
|
|
339
|
+
const sameLock = (read, kept) => read.dev === kept.dev && read.ino === kept.ino && read.mtimeMs === kept.mtimeMs;
|
|
340
|
+
/** Whether `read` is this holder's own lock: the directory it made (`kept`, once known) with the mtime it set (`set`)
|
|
341
|
+
* as the filesystem keeps it: within 10 µs (libuv keeps whole microseconds, and the round trip through a double is
|
|
342
|
+
* under one more), or the start of the second `set` falls in, as a filesystem that keeps whole seconds alone shows
|
|
343
|
+
* it. That second is the CLI's lock library's own rule there, and it is taken on every filesystem: another holder's
|
|
344
|
+
* mtime of exactly that whole second reads as this holder's too. Between runners the takeover mark keeps a second
|
|
345
|
+
* holder out. */
|
|
346
|
+
const ownRead = (read, kept, set) => (kept === undefined || (read.dev === kept.dev && read.ino === kept.ino)) &&
|
|
347
|
+
(Math.abs(read.mtimeMs - set) < 0.01 || read.mtimeMs === Math.floor(set / 1000) * 1000);
|
|
348
|
+
/** The log word for a lock not read as its holder's own. */
|
|
349
|
+
const lockWord = (state) => (state === "lost" ? "lock_lost" : "lock_unread");
|
|
350
|
+
/** `path` read for the removal of a lock or mark this holder made: a read that fails for a reason other than the path
|
|
351
|
+
* being gone is made once more, so one transient failure never leaves it standing for the stale time; none when it is
|
|
352
|
+
* gone or both reads fail. */
|
|
353
|
+
async function readForRemoval(path, fs) {
|
|
354
|
+
try {
|
|
355
|
+
return await fs.stat(path);
|
|
356
|
+
}
|
|
357
|
+
catch (error) {
|
|
358
|
+
if (error?.code === "ENOENT")
|
|
359
|
+
return undefined;
|
|
360
|
+
return fs.stat(path).catch(() => undefined);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
/** Beside each lock, the runners' takeover mark: a directory `<lock>.takeover`, never inside the lock, made, taken over
|
|
364
|
+
* when dead and released as a lock of its own (makeLock, ownRead). It is held for a few file operations, so a mark
|
|
365
|
+
* older than lockStaleMs is a crashed (or 60 s stalled) runner's. */
|
|
366
|
+
const TAKEOVER_MARK = ".takeover";
|
|
367
|
+
/** Lock `path` made, or a dead one (older than lockStaleMs) taken over, its mtime set and read back: this holder's own
|
|
368
|
+
* directory and mtime, or none while another holds it. A dead lock is removed only while a read right before the
|
|
369
|
+
* removal shows the same directory with the same mtime, so none touched or made again since. One this holder made and
|
|
370
|
+
* could not touch or read back is removed only while it can still be its own: never once a touch finds it gone (what
|
|
371
|
+
* is at the path then may be another holder's, which the ask waits for as for any other), and after a failed read only
|
|
372
|
+
* while a second read shows the mtime this holder set. The takeover mark is taken with it, and a lock only under the
|
|
373
|
+
* mark. */
|
|
374
|
+
async function makeLock(path, fs) {
|
|
375
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
376
|
+
try {
|
|
377
|
+
await fs.mkdir(path);
|
|
378
|
+
}
|
|
379
|
+
catch (error) {
|
|
380
|
+
if (error?.code !== "EEXIST")
|
|
381
|
+
throw error;
|
|
382
|
+
const seen = await fs.stat(path).catch(() => undefined);
|
|
383
|
+
// Released since: try again.
|
|
384
|
+
if (!seen)
|
|
385
|
+
continue;
|
|
386
|
+
if (Date.now() - seen.mtimeMs <= loginRefresh.lockStaleMs)
|
|
387
|
+
return undefined;
|
|
388
|
+
// The same directory with the same mtime is still the stale one read above.
|
|
389
|
+
const again = await fs.stat(path).catch(() => undefined);
|
|
390
|
+
if (!again || !sameLock(again, seen))
|
|
391
|
+
continue;
|
|
392
|
+
await fs.rm(path, { recursive: true, force: true });
|
|
393
|
+
continue;
|
|
394
|
+
}
|
|
395
|
+
const set = Date.now();
|
|
396
|
+
try {
|
|
397
|
+
await fs.utimes(path, new Date(set), new Date(set));
|
|
398
|
+
}
|
|
399
|
+
catch (error) {
|
|
400
|
+
if (error?.code === "ENOENT")
|
|
401
|
+
return undefined;
|
|
402
|
+
await fs.rm(path, { recursive: true, force: true }).catch(() => undefined);
|
|
403
|
+
throw error;
|
|
404
|
+
}
|
|
405
|
+
let made;
|
|
406
|
+
try {
|
|
407
|
+
made = await fs.stat(path);
|
|
408
|
+
}
|
|
409
|
+
catch (error) {
|
|
410
|
+
if (error?.code !== "ENOENT") {
|
|
411
|
+
const again = await fs.stat(path).catch(() => undefined);
|
|
412
|
+
if (again && ownRead(again, undefined, set))
|
|
413
|
+
await fs.rm(path, { recursive: true, force: true }).catch(() => undefined);
|
|
414
|
+
}
|
|
415
|
+
return undefined;
|
|
416
|
+
}
|
|
417
|
+
// Another's (an mtime this holder did not set): not this holder's to touch or remove.
|
|
418
|
+
return ownRead(made, undefined, set) ? { dev: made.dev, ino: made.ino, set } : undefined;
|
|
419
|
+
}
|
|
420
|
+
return undefined;
|
|
421
|
+
}
|
|
422
|
+
/** A lock in proper-lockfile's form, as the pinned CLI takes it (login-refresh.ts): a directory made with mkdir, its
|
|
423
|
+
* mtime touched every `updateMs` while it is held, taken over once older than lockStaleMs. Nothing is ever put inside
|
|
424
|
+
* it: proper-lockfile removes a lock with rmdir. It is this holder's while a read shows the directory it made with the
|
|
425
|
+
* mtime it last set (ownRead); any other read (another directory, another mtime, the lock gone) marks it lost for
|
|
426
|
+
* good, the CLI's "compromised", and it is never touched or removed again. A read that fails while it is there is
|
|
427
|
+
* neither: the next read decides, and its release reads it once more. None while another holds it.
|
|
428
|
+
* Runners make, take over and read back a lock only under the takeover mark beside it, one runner at a time, so
|
|
429
|
+
* between runners one holder at a time holds it. Left open, as in every lease lock: a runner stalled past the stale
|
|
430
|
+
* time inside a takeover (its mark taken over as dead, its removal then lands in another's lock), or between its
|
|
431
|
+
* release's check and its removal; and a runner that crashed holding the mark, whose dead mark two runners then take
|
|
432
|
+
* over at once (one's late removal lands in the mark the other made). The pinned CLI never sees the mark: against the
|
|
433
|
+
* CLI the lock keeps proper-lockfile's rules, a takeover's late removal included (the second lock, beside the folder,
|
|
434
|
+
* keeps the two from both posting where it can be made). */
|
|
435
|
+
async function lockDirectory(path, fs, updateMs) {
|
|
436
|
+
const markPath = `${path}${TAKEOVER_MARK}`;
|
|
437
|
+
const mark = await makeLock(markPath, fs);
|
|
438
|
+
// Another runner makes, takes over or reads back this lock now: as good as held.
|
|
439
|
+
if (!mark)
|
|
440
|
+
return undefined;
|
|
441
|
+
let made;
|
|
442
|
+
try {
|
|
443
|
+
made = await makeLock(path, fs);
|
|
444
|
+
}
|
|
445
|
+
finally {
|
|
446
|
+
// Only the mark made here: one another runner made after taking this one over as dead (this runner stalled past the
|
|
447
|
+
// stale time) is that runner's. A mark left standing holds every runner on the login for the stale time.
|
|
448
|
+
const still = await readForRemoval(markPath, fs);
|
|
449
|
+
if (still && ownRead(still, mark, mark.set))
|
|
450
|
+
await fs.rm(markPath, { recursive: true, force: true }).catch(() => undefined);
|
|
451
|
+
}
|
|
452
|
+
if (!made)
|
|
453
|
+
return undefined;
|
|
454
|
+
let mine = made;
|
|
455
|
+
let lost = false;
|
|
456
|
+
let timer;
|
|
457
|
+
/** Every read of the lock (owned), the heartbeat's read and touch, and the release run one at a time, in order: a
|
|
458
|
+
* read never meets a touch half done (the mtime on disk new, `mine` still the old one, or the other way round), so
|
|
459
|
+
* this holder never takes its own live lock for another's. */
|
|
460
|
+
let turn = Promise.resolve();
|
|
461
|
+
const inTurn = (step) => {
|
|
462
|
+
const run = turn.then(step, step);
|
|
463
|
+
turn = run.catch(() => undefined);
|
|
464
|
+
return run;
|
|
465
|
+
};
|
|
466
|
+
/** A heartbeat waiting or running: the next tick adds none. */
|
|
467
|
+
let beating = false;
|
|
468
|
+
const check = async () => {
|
|
469
|
+
if (lost)
|
|
470
|
+
return "lost";
|
|
471
|
+
try {
|
|
472
|
+
if (ownRead(await fs.stat(path), mine, mine.set))
|
|
473
|
+
return "own";
|
|
474
|
+
}
|
|
475
|
+
catch (error) {
|
|
476
|
+
// Unread but not gone (a transient failure): not touched or removed at this read, and read again at the next, as
|
|
477
|
+
// proper-lockfile does.
|
|
478
|
+
if (error?.code !== "ENOENT")
|
|
479
|
+
return "unread";
|
|
480
|
+
}
|
|
481
|
+
// Gone, or another's: lost.
|
|
482
|
+
lost = true;
|
|
483
|
+
clearInterval(timer);
|
|
484
|
+
return "lost";
|
|
485
|
+
};
|
|
486
|
+
const owned = () => inTurn(check);
|
|
487
|
+
timer = setInterval(() => {
|
|
488
|
+
if (lost || beating)
|
|
489
|
+
return;
|
|
490
|
+
beating = true;
|
|
491
|
+
void inTurn(async () => {
|
|
492
|
+
if ((await check()) !== "own")
|
|
493
|
+
return;
|
|
494
|
+
const at = Date.now();
|
|
495
|
+
try {
|
|
496
|
+
await fs.utimes(path, new Date(at), new Date(at));
|
|
497
|
+
}
|
|
498
|
+
catch (error) {
|
|
499
|
+
// Gone since it was read: lost. Another failure is tried again at the next beat, as proper-lockfile does.
|
|
500
|
+
if (error?.code === "ENOENT") {
|
|
501
|
+
lost = true;
|
|
502
|
+
clearInterval(timer);
|
|
503
|
+
}
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
// The mtime it set, kept in the same turn: the next read must show exactly that (ownRead), on the same directory.
|
|
507
|
+
mine = { dev: mine.dev, ino: mine.ino, set: at };
|
|
508
|
+
}).finally(() => {
|
|
509
|
+
beating = false;
|
|
510
|
+
});
|
|
511
|
+
}, updateMs);
|
|
512
|
+
timer.unref();
|
|
513
|
+
return {
|
|
514
|
+
owned,
|
|
515
|
+
release: async () => {
|
|
516
|
+
clearInterval(timer);
|
|
517
|
+
await inTurn(async () => {
|
|
518
|
+
// A read that fails while the lock is there is made once more (readForRemoval's rule): one transient failure
|
|
519
|
+
// never leaves the lock standing for the stale time.
|
|
520
|
+
let state = await check();
|
|
521
|
+
if (state === "unread")
|
|
522
|
+
state = await check();
|
|
523
|
+
if (state === "own")
|
|
524
|
+
await fs.rm(path, { recursive: true, force: true });
|
|
525
|
+
lost = true;
|
|
526
|
+
});
|
|
527
|
+
},
|
|
528
|
+
};
|
|
529
|
+
}
|
|
530
|
+
/** The CLI's two refresh locks on credentials directory `dir`, in its order (the lock in the folder, then the older one
|
|
531
|
+
* beside the folder's real path; that one taken where it can be, as the CLI does): whether both are still this
|
|
532
|
+
* holder's, and their release; or none while another holder has either. */
|
|
533
|
+
async function takeRefreshLocks(dir, fs, updateMs) {
|
|
534
|
+
const current = await lockDirectory(join(dir, loginRefresh.lockName), fs, updateMs);
|
|
535
|
+
if (!current)
|
|
536
|
+
return undefined;
|
|
537
|
+
// null: the older lock could not be made, and the CLI goes on without it then (only another holder of it stops it).
|
|
538
|
+
let legacy;
|
|
539
|
+
try {
|
|
540
|
+
legacy = await lockDirectory(`${await realpath(dir).catch(() => dir)}${loginRefresh.legacyLockSuffix}`, fs, updateMs);
|
|
541
|
+
}
|
|
542
|
+
catch {
|
|
543
|
+
legacy = null;
|
|
544
|
+
}
|
|
545
|
+
if (legacy === undefined) {
|
|
546
|
+
await current.release();
|
|
547
|
+
return undefined;
|
|
548
|
+
}
|
|
549
|
+
const older = legacy;
|
|
550
|
+
return {
|
|
551
|
+
// Both asked each time: each one's own lost mark is set by its own read.
|
|
552
|
+
owned: async () => {
|
|
553
|
+
const first = await current.owned();
|
|
554
|
+
return first !== "own" || older === null ? first : older.owned();
|
|
555
|
+
},
|
|
556
|
+
release: async () => {
|
|
557
|
+
await older?.release().catch(() => undefined);
|
|
558
|
+
await current.release();
|
|
559
|
+
},
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
/** One renewal of the login in file `file` whose access token was `seen` and refresh token `refresh`: under the CLI's
|
|
563
|
+
* refresh locks, the file read again, one post, and the answer written back. A lock lost before the post (taken over
|
|
564
|
+
* while this holder was paused) is never posted under: the holder waits for the new one's write as for any other's,
|
|
565
|
+
* the pinned CLI's own check before its post (`tengu_oauth_token_refresh_lock_compromised_pre_post`). One lost after
|
|
566
|
+
* the post keeps the answer: the refresh token posted is spent, so the pair is written back by the same check the CLI
|
|
567
|
+
* makes (the file still holds the refresh token posted, or a cleared one), without the lock, as the CLI writes it then
|
|
568
|
+
* (`tengu_oauth_refresh_compromised_cas_saved`), and held in memory if that write fails (saveHeld). */
|
|
569
|
+
async function renewUnderLock(dir, file, seen, refresh, options) {
|
|
570
|
+
const say = options.log ?? (() => undefined);
|
|
571
|
+
const fs = fsOf(options);
|
|
572
|
+
const updateMs = options.lockUpdateMs ?? loginRefresh.lockUpdateMs;
|
|
573
|
+
const giveUp = Date.now() + (options.lockWaitMs ?? LOCK_WAIT_MS);
|
|
574
|
+
for (;;) {
|
|
575
|
+
const locks = await takeRefreshLocks(dir, fs, updateMs);
|
|
576
|
+
if (locks) {
|
|
577
|
+
try {
|
|
578
|
+
// Read again under the lock: a holder that renewed before it was taken has written its pair, which is taken.
|
|
579
|
+
const held = await credentialsRead(file, fs.readFile);
|
|
580
|
+
if (typeof held === "string" || held.oauth.accessToken !== seen || held.oauth.refreshToken !== refresh)
|
|
581
|
+
return undefined;
|
|
582
|
+
// A lock read as another's is said as lost; one whose read failed, as unread: no takeover is said that did not
|
|
583
|
+
// happen. Either way nothing is posted under it, and the next try reads it again.
|
|
584
|
+
const before = await locks.owned();
|
|
585
|
+
if (before === "own") {
|
|
586
|
+
const answer = await postRefresh(held.oauth, refresh, options);
|
|
587
|
+
const after = await locks.owned();
|
|
588
|
+
// Written back (or held) before the line is said: a log that throws never loses the pair the post rotated.
|
|
589
|
+
const renewed = await writeBack(file, refresh, answer, options);
|
|
590
|
+
if (after !== "own")
|
|
591
|
+
say({ claude_login: lockWord(after), at: "after_post" });
|
|
592
|
+
return renewed;
|
|
593
|
+
}
|
|
594
|
+
say({ claude_login: lockWord(before), at: "before_post" });
|
|
595
|
+
}
|
|
596
|
+
finally {
|
|
597
|
+
await locks.release().catch(() => undefined);
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
// Another holder renews it now: its write is taken when it lands, never a second post of the same refresh token.
|
|
601
|
+
const now = await credentialsRead(file, fs.readFile);
|
|
602
|
+
if (typeof now === "string" || now.oauth.accessToken !== seen)
|
|
603
|
+
return undefined;
|
|
604
|
+
if (Date.now() > giveUp) {
|
|
605
|
+
say({ claude_login: "renew_failed", reason: "locked" });
|
|
606
|
+
throw new Error("another holder kept the login's refresh lock");
|
|
607
|
+
}
|
|
608
|
+
await sleep(LOCK_POLL_MS);
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
/** The pinned CLI's refresh request for the login whose fields are `oauth` (login-refresh.ts), posted once. Every token
|
|
612
|
+
* in its answer is held for redaction before anything else reads it. A failure throws words with no value of the
|
|
613
|
+
* request or the answer in them, and is told to the log by its status and OAuth error code alone. */
|
|
614
|
+
async function postRefresh(oauth, refresh, options) {
|
|
615
|
+
const say = options.log ?? (() => undefined);
|
|
616
|
+
const scopes = Array.isArray(oauth.scopes) && oauth.scopes.length > 0 && oauth.scopes.every((scope) => typeof scope === "string") ? oauth.scopes : loginRefresh.scopes;
|
|
617
|
+
const body = {
|
|
618
|
+
grant_type: "refresh_token",
|
|
619
|
+
refresh_token: refresh,
|
|
620
|
+
client_id: typeof oauth.clientId === "string" && oauth.clientId !== "" ? oauth.clientId : loginRefresh.clientId,
|
|
621
|
+
scope: scopes.join(" "),
|
|
622
|
+
};
|
|
623
|
+
let response;
|
|
624
|
+
try {
|
|
625
|
+
// Never followed: a 307 or 308 would post the same body, refresh token included, to the Location's host. A redirect
|
|
626
|
+
// rejects as fetch's network error, a failed post like any other: nothing saved, the refresh token not taken as refused.
|
|
627
|
+
response = await (options.fetch ?? globalThis.fetch)(loginRefresh.tokenUrl, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), redirect: "error", signal: AbortSignal.timeout(options.callMs ?? REFRESH_CALL_MS) });
|
|
628
|
+
}
|
|
629
|
+
catch (error) {
|
|
630
|
+
say({ claude_login: "renew_failed", reason: error?.name === "TimeoutError" ? "timeout" : "network" });
|
|
631
|
+
throw new Error("the login's renewal request got no answer");
|
|
632
|
+
}
|
|
633
|
+
let parsed;
|
|
634
|
+
try {
|
|
635
|
+
parsed = await response.json();
|
|
636
|
+
}
|
|
637
|
+
catch {
|
|
638
|
+
parsed = undefined;
|
|
639
|
+
}
|
|
640
|
+
const answer = (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {});
|
|
641
|
+
holdSecret(...strings([answer.access_token, answer.refresh_token]));
|
|
642
|
+
if (response.status !== 200) {
|
|
643
|
+
const code = typeof answer.error === "string" && /^[a-z_]{1,40}$/.test(answer.error) ? answer.error : undefined;
|
|
644
|
+
// The CLI's own: a refresh token refused as invalid_grant is dead, and never sent again.
|
|
645
|
+
if (code === "invalid_grant")
|
|
646
|
+
dead.add(refresh);
|
|
647
|
+
say({ claude_login: "renew_refused", status: String(response.status), ...(code ? { error: code } : {}) });
|
|
648
|
+
throw new Error(`the login's renewal was answered ${response.status}${code ? ` (${code})` : ""}`);
|
|
649
|
+
}
|
|
650
|
+
const { access_token: access, refresh_token: next, expires_in: expiresIn, refresh_token_expires_in: refreshExpiresIn, scope } = answer;
|
|
651
|
+
if (typeof access !== "string" || access === "" || typeof expiresIn !== "number" || !(expiresIn > 0)) {
|
|
652
|
+
say({ claude_login: "renew_failed", reason: "answer" });
|
|
653
|
+
throw new Error("the login's renewal answer held no token");
|
|
654
|
+
}
|
|
655
|
+
// Anthropic took the refresh token and answered another: the one posted is spent, and never posted again, whatever
|
|
656
|
+
// becomes of the answer's write. One answered with no new refresh token is the CLI's `refresh_token:K=e`: still the
|
|
657
|
+
// login's, kept.
|
|
658
|
+
if (typeof next === "string" && next !== "" && next !== refresh)
|
|
659
|
+
dead.add(refresh);
|
|
660
|
+
return {
|
|
661
|
+
access,
|
|
662
|
+
refresh: typeof next === "string" && next !== "" ? next : undefined,
|
|
663
|
+
expiresIn,
|
|
664
|
+
refreshExpiresIn: typeof refreshExpiresIn === "number" && Number.isFinite(refreshExpiresIn) ? refreshExpiresIn : undefined,
|
|
665
|
+
scope: typeof scope === "string" ? scope : undefined,
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
/** The renewal's answer written into `file`, the one it came from (saveHeld): the token it got, whether the write landed
|
|
669
|
+
* or not. One that did not land is held in this process's memory (heldPairs) and written at a later ask; one the file
|
|
670
|
+
* holds another holder's pair in place of is dropped, its token handed to this ask alone. */
|
|
671
|
+
async function writeBack(file, posted, answer, options) {
|
|
672
|
+
const now = (options.now ?? Date.now)();
|
|
673
|
+
const renewed = { access: answer.access, expiresAt: now + answer.expiresIn * 1000 };
|
|
674
|
+
const fields = {
|
|
675
|
+
accessToken: answer.access,
|
|
676
|
+
refreshToken: answer.refresh ?? posted,
|
|
677
|
+
expiresAt: renewed.expiresAt,
|
|
678
|
+
...(answer.refreshExpiresIn === undefined ? {} : { refreshTokenExpiresAt: now + answer.refreshExpiresIn * 1000 }),
|
|
679
|
+
...(answer.scope === undefined ? {} : { scopes: answer.scope.split(" ").filter(Boolean) }),
|
|
680
|
+
};
|
|
681
|
+
await saveHeld(file, { posted, fields, renewed }, options);
|
|
682
|
+
return renewed;
|
|
683
|
+
}
|
|
684
|
+
/** `file` replaced by `text` atomically: a new file beside it, at mode 0600 before any byte is written to it, synced,
|
|
685
|
+
* then renamed over it, and its folder synced. A `file` that is no plain file (a link, say) is never written. */
|
|
686
|
+
async function replaceFile(file, text) {
|
|
687
|
+
if (!(await lstat(file)).isFile())
|
|
688
|
+
throw new Error("the login's file is not a plain file");
|
|
689
|
+
const dir = dirname(file);
|
|
690
|
+
const temp = join(dir, `${LOGIN_FILE}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
|
|
691
|
+
// O_CREAT | O_EXCL: a new file of this process's alone, never one that was there.
|
|
692
|
+
const handle = await open(temp, "wx", 0o600);
|
|
693
|
+
try {
|
|
694
|
+
// Exactly 0600 (a umask only narrows the mode open was given), before a byte of a token is in it.
|
|
695
|
+
await handle.chmod(0o600);
|
|
696
|
+
await handle.writeFile(text, "utf8");
|
|
697
|
+
await handle.sync();
|
|
698
|
+
}
|
|
699
|
+
catch (error) {
|
|
700
|
+
await handle.close().catch(() => undefined);
|
|
701
|
+
await rm(temp, { force: true });
|
|
702
|
+
throw error;
|
|
703
|
+
}
|
|
704
|
+
await handle.close();
|
|
705
|
+
try {
|
|
706
|
+
await rename(temp, file);
|
|
707
|
+
}
|
|
708
|
+
catch (error) {
|
|
709
|
+
await rm(temp, { force: true });
|
|
710
|
+
throw error;
|
|
711
|
+
}
|
|
712
|
+
const folder = await open(dir, "r");
|
|
713
|
+
try {
|
|
714
|
+
await folder.sync();
|
|
715
|
+
}
|
|
716
|
+
catch {
|
|
717
|
+
// A folder some filesystems cannot sync still holds the rename.
|
|
718
|
+
}
|
|
719
|
+
finally {
|
|
720
|
+
await folder.close();
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
/** Whether `login` is AgentRun's own login folder in `data` (claude-login.ts agentRunLoginDir), the one login a run
|
|
724
|
+
* under a user of its own is handed a token of; this machine's own Claude Code login is not. */
|
|
725
|
+
export const agentRunLogin = (login, data) => login.dir === agentRunLoginDir(data);
|
|
726
|
+
/** One reader per login folder in this process, so every claim on it holds the same watchers' tokens and the same
|
|
727
|
+
* refused token; each renews with the pinned CLI's own request (renewLogin), and says each renewal's outcome to `log`
|
|
728
|
+
* in fields that hold no token. The reader keeps the `log` of the claim that first asks for its folder, for as long as
|
|
729
|
+
* the process runs: a later claim's `log` is not used. Every claim in a runner hands the same one (the runner's own log),
|
|
730
|
+
* so a renewal is said once, on that log, whichever claim's ask set it off. */
|
|
731
|
+
const readers = new Map();
|
|
732
|
+
export function loginTokensFor(login, log) {
|
|
733
|
+
let reader = readers.get(login.dir);
|
|
734
|
+
if (!reader)
|
|
735
|
+
readers.set(login.dir, (reader = new LoginTokens({ login, log })));
|
|
736
|
+
return reader;
|
|
737
|
+
}
|
|
738
|
+
/** The words a run's start is refused in by its runner (held.ts claudeLogin) when its claim read Claude Code's login and
|
|
739
|
+
* the runner's second read of the setting, at the start, names none or another folder: the run is put on no login its
|
|
740
|
+
* start did not read, and never falls to a model key it was not claimed on. They name no folder. */
|
|
741
|
+
export const LOGIN_CHANGED_SINCE_CLAIM = "This run's runner handed it no Claude Code login: the login was turned off or moved to another folder since this run's claim, and a run claimed on the login does not fall back to the model keys. Start the run again to run it as the login is now, or give it a model_key.";
|
|
742
|
+
/** A run's own process's login (held.ts claudeLogin's reader): each token it reads held by `hold` (the run's redactors)
|
|
743
|
+
* and this process's own (secrets.ts holdSecret) before the run's CLI is handed it, and a token Anthropic refused told
|
|
744
|
+
* to the runner, which renews it at the next ask. A process its runner hands no reader runs on no login (cli-run-spec.ts):
|
|
745
|
+
* its claim read the login as off for it, or its run brought its own model key. */
|
|
746
|
+
export function heldTokenLogin(reader, hold) {
|
|
747
|
+
return {
|
|
748
|
+
token: async () => {
|
|
749
|
+
const token = await reader.token();
|
|
750
|
+
holdSecret(token);
|
|
751
|
+
hold([token]);
|
|
752
|
+
return token;
|
|
753
|
+
},
|
|
754
|
+
refused: async (sent) => {
|
|
755
|
+
await reader.refused?.(sent);
|
|
756
|
+
},
|
|
757
|
+
};
|
|
758
|
+
}
|
|
759
|
+
/** Where the runners on a data folder say whether their runs on the login stay in their own process: one file per
|
|
760
|
+
* runner, named by the sha256 of its whole name, so two names never share a file and no name is a folder (`.`,
|
|
761
|
+
* `..`). The file holds the name itself, which loginRunnerInProcess reads. */
|
|
762
|
+
export const loginRunnersDir = (data) => join(data, "claude-login-runners");
|
|
763
|
+
const runnerFile = (data, runner) => join(loginRunnersDir(data), createHash("sha256").update(runner, "utf8").digest("hex"));
|
|
764
|
+
/** Runner `runner` says, at its start, how its runs on the login run: `process` (in its own process, its CLI on the
|
|
765
|
+
* login folder), or `uid` (each a user of its own, on a token), which takes back what an earlier start of that name said. */
|
|
766
|
+
export function sayLoginRunner(data, runner, isolation) {
|
|
767
|
+
const file = runnerFile(data, runner);
|
|
768
|
+
if (isolation === "uid")
|
|
769
|
+
return void rmSync(file, { force: true });
|
|
770
|
+
mkdirSync(loginRunnersDir(data), { recursive: true, mode: 0o700 });
|
|
771
|
+
writeFileSync(file, `${runner}\n`, { mode: 0o600 });
|
|
772
|
+
}
|
|
773
|
+
/** The name of a runner on data folder `data` whose runs on the login stay in its own process, and whose word in the
|
|
774
|
+
* store is fresh (presence.ts); none when there is no such runner. */
|
|
775
|
+
export async function loginRunnerInProcess(data, runners) {
|
|
776
|
+
const dir = loginRunnersDir(data);
|
|
777
|
+
let files;
|
|
778
|
+
try {
|
|
779
|
+
files = readdirSync(dir);
|
|
780
|
+
}
|
|
781
|
+
catch {
|
|
782
|
+
return undefined;
|
|
783
|
+
}
|
|
784
|
+
const said = new Set(files.flatMap((file) => {
|
|
785
|
+
try {
|
|
786
|
+
const name = readFileSync(join(dir, file), "utf8").trim();
|
|
787
|
+
return name ? [name] : [];
|
|
788
|
+
}
|
|
789
|
+
catch {
|
|
790
|
+
// Taken back since the list was read.
|
|
791
|
+
return [];
|
|
792
|
+
}
|
|
793
|
+
}));
|
|
794
|
+
if (said.size === 0)
|
|
795
|
+
return undefined;
|
|
796
|
+
return (await runners.live(RUNNER_STALE_MS)).find((row) => said.has(row.runner))?.runner;
|
|
797
|
+
}
|