@parcha/agentrun-serve 0.1.0-beta.38 → 0.1.0-beta.39
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 +418 -0
- package/README.md +325 -124
- package/dist/adapters.d.ts +4 -1
- package/dist/adapters.js +4 -2
- package/dist/agent-rows.d.ts +0 -2
- package/dist/agents-store.d.ts +5 -5
- package/dist/agents-store.js +14 -14
- package/dist/bash-read-only.js +2 -1
- package/dist/cap-short.d.ts +12 -0
- package/dist/cap-short.js +60 -0
- package/dist/cap.d.ts +3 -10
- package/dist/cap.js +2 -5
- package/dist/catalog.d.ts +0 -5
- package/dist/catalog.js +1 -5
- package/dist/chatgpt-plan.d.ts +163 -0
- package/dist/chatgpt-plan.js +549 -0
- package/dist/cli.js +26 -6
- package/dist/composio-preset.d.ts +8 -0
- package/dist/composio-preset.js +8 -7
- package/dist/composio-triggers.d.ts +113 -0
- package/dist/composio-triggers.js +411 -0
- package/dist/computer-calls.js +2 -2
- package/dist/computer-commands.d.ts +2 -0
- package/dist/computer-commands.js +7 -3
- package/dist/computer-live.d.ts +7 -2
- package/dist/computer-live.js +9 -5
- package/dist/computer-routes.d.ts +2 -2
- package/dist/computer-routes.js +2 -2
- package/dist/computer-setting.d.ts +3 -3
- package/dist/computer-setting.js +5 -5
- package/dist/computer-view.d.ts +15 -0
- package/dist/computer-view.js +16 -2
- package/dist/computer-viewer.js +14 -1
- package/dist/computers.d.ts +5 -2
- package/dist/computers.js +9 -5
- package/dist/console/assets/index-BNhZs-jp.css +1 -0
- package/dist/console/assets/index-BQv5aOGB.js +700 -0
- package/dist/console/index.html +2 -2
- package/dist/console-links.js +3 -3
- package/dist/decision-cap.d.ts +2 -5
- package/dist/decision-cap.js +3 -6
- package/dist/decision-rows.js +11 -11
- package/dist/email/account.d.ts +84 -0
- package/dist/email/account.js +159 -0
- package/dist/email/answer.d.ts +10 -0
- package/dist/email/answer.js +182 -0
- package/dist/email/email-faux.d.ts +95 -0
- package/dist/email/email-faux.js +849 -0
- package/dist/email/labels.d.ts +1 -0
- package/dist/email/labels.js +84 -0
- package/dist/email/mail.d.ts +186 -0
- package/dist/email/mail.js +380 -0
- package/dist/email/names.d.ts +20 -0
- package/dist/email/names.js +40 -0
- package/dist/email/routes.d.ts +9 -0
- package/dist/email/routes.js +50 -0
- package/dist/email/tools.d.ts +20 -0
- package/dist/email/tools.js +517 -0
- package/dist/environment.d.ts +17 -2
- package/dist/environment.js +36 -8
- package/dist/errors.d.ts +6 -0
- package/dist/errors.js +12 -0
- package/dist/eval-mailbox.d.ts +103 -0
- package/dist/eval-mailbox.js +236 -0
- package/dist/graph-view.d.ts +9 -2
- package/dist/graph-view.js +6 -2
- package/dist/harness-install.d.ts +28 -2
- package/dist/harness-install.js +147 -59
- package/dist/harness-opencode/adapter.js +2 -26
- package/dist/harness-opencode/facts.js +5 -2
- package/dist/harness-opencode/host/policy.d.ts +2 -0
- package/dist/harness-opencode/host/policy.js +10 -5
- package/dist/harness-opencode/index.d.ts +1 -1
- package/dist/harness-opencode/index.js +1 -1
- package/dist/harness-opencode/versions.d.ts +6 -0
- package/dist/harness-opencode/versions.js +6 -0
- package/dist/harness-table.js +8 -5
- package/dist/harness.d.ts +12 -0
- package/dist/harness.js +15 -3
- package/dist/hosted-search.d.ts +3 -1
- package/dist/hosted-search.js +51 -11
- package/dist/import-sources.d.ts +1 -1
- package/dist/import-sources.js +3 -3
- package/dist/import.d.ts +21 -0
- package/dist/import.js +186 -1
- package/dist/key-check.d.ts +0 -2
- package/dist/key-check.js +3 -4
- package/dist/key-refusal.d.ts +8 -2
- package/dist/key-refusal.js +16 -13
- package/dist/learn/check.d.ts +18 -3
- package/dist/learn/check.js +328 -3
- package/dist/learn/compile.d.ts +9 -2
- package/dist/learn/compile.js +52 -16
- package/dist/learn/grade.d.ts +4 -0
- package/dist/learn/grade.js +4 -1
- package/dist/learn/promote.d.ts +106 -51
- package/dist/learn/promote.js +82 -189
- package/dist/learn/refit.d.ts +21 -12
- package/dist/learn/refit.js +51 -23
- package/dist/learn/replay-calls.js +1 -1
- package/dist/learn/skills.d.ts +2 -7
- package/dist/learn/skills.js +28 -14
- package/dist/learned-nodes.d.ts +15 -7
- package/dist/learned-nodes.js +29 -5
- package/dist/learned-workflow.d.ts +41 -31
- package/dist/learned-workflow.js +122 -63
- package/dist/learning-batch.js +3 -3
- package/dist/learning-cost.d.ts +26 -8
- package/dist/learning-cost.js +17 -7
- package/dist/learning-routes.d.ts +2 -4
- package/dist/learning-routes.js +20 -3
- package/dist/learning-words.d.ts +1 -1
- package/dist/learning-words.js +4 -1
- package/dist/learning.d.ts +5 -5
- package/dist/link-check.d.ts +27 -0
- package/dist/link-check.js +164 -0
- package/dist/local-models.d.ts +33 -2
- package/dist/local-models.js +43 -5
- package/dist/mcp-pin-first.js +6 -0
- package/dist/mcp-secret-writes.js +3 -0
- package/dist/mcp-servers-store.d.ts +25 -16
- package/dist/mcp-servers-store.js +23 -3
- package/dist/model-form.d.ts +11 -0
- package/dist/model-form.js +17 -1
- package/dist/model.d.ts +26 -6
- package/dist/model.js +126 -18
- package/dist/monid.d.ts +26 -31
- package/dist/monid.js +84 -79
- package/dist/native/binding.d.ts +13 -0
- package/dist/native/binding.js +57 -0
- package/dist/native/cli.d.ts +2 -0
- package/dist/native/cli.js +48 -0
- package/dist/native/connection.d.ts +8 -0
- package/dist/native/connection.js +94 -0
- package/dist/native/context.d.ts +6 -0
- package/dist/native/context.js +22 -0
- package/dist/native/discovery.d.ts +27 -0
- package/dist/native/discovery.js +404 -0
- package/dist/native/environment.d.ts +4 -0
- package/dist/native/environment.js +18 -0
- package/dist/native/history.d.ts +20 -0
- package/dist/native/history.js +147 -0
- package/dist/native/instructions.d.ts +21 -0
- package/dist/native/instructions.js +173 -0
- package/dist/native/remote-worker-bridge.d.ts +3 -0
- package/dist/native/remote-worker-bridge.js +278 -0
- package/dist/native/remote.d.ts +187 -0
- package/dist/native/remote.js +492 -0
- package/dist/native/runtime.d.ts +17 -0
- package/dist/native/runtime.js +316 -0
- package/dist/native/runtimes.d.ts +66 -0
- package/dist/native/runtimes.js +41 -0
- package/dist/native/schema.d.ts +46 -0
- package/dist/native/schema.js +41 -0
- package/dist/native/types.d.ts +87 -0
- package/dist/native/types.js +1 -0
- package/dist/observation/http.d.ts +4 -0
- package/dist/observation/http.js +140 -0
- package/dist/observation/observer.d.ts +301 -0
- package/dist/observation/observer.js +919 -0
- package/dist/observation/schema.d.ts +52 -0
- package/dist/observation/schema.js +154 -0
- package/dist/openapi.d.ts +1 -0
- package/dist/openapi.js +394 -85
- package/dist/paid-calls.d.ts +8 -3
- package/dist/paid-calls.js +6 -2
- package/dist/place-offers.d.ts +4 -8
- package/dist/place-offers.js +4 -9
- package/dist/port-models.d.ts +7 -2
- package/dist/port-models.js +5 -2
- package/dist/print.d.ts +4 -2
- package/dist/print.js +4 -3
- package/dist/propose.d.ts +1 -2
- package/dist/propose.js +10 -1
- package/dist/provider.d.ts +5 -1
- package/dist/provider.js +8 -0
- package/dist/push-handler.d.ts +3 -2
- package/dist/push-handler.js +20 -6
- package/dist/refusal-words.d.ts +11 -0
- package/dist/refusal-words.js +13 -2
- package/dist/run-launch.d.ts +10 -1
- package/dist/run-launch.js +11 -4
- package/dist/run-learning-served.d.ts +75 -2
- package/dist/run-manifest.d.ts +3 -0
- package/dist/run-manifest.js +13 -1
- package/dist/run-reads-over-store.d.ts +3 -3
- package/dist/run-reads-over-store.js +13 -10
- package/dist/run-timeline-served.d.ts +3 -2
- package/dist/run-timeline-served.js +8 -9
- package/dist/run-view.d.ts +42 -35
- package/dist/run-view.js +79 -44
- package/dist/runnable.d.ts +13 -5
- package/dist/runnable.js +69 -60
- package/dist/runner/adapter-loop.d.ts +42 -11
- package/dist/runner/adapter-loop.js +651 -247
- package/dist/runner/adapter-run-spec.d.ts +37 -12
- package/dist/runner/adapter-run-spec.js +139 -106
- package/dist/runner/adapters/pi.d.ts +24 -0
- package/dist/runner/adapters/pi.js +59 -9
- package/dist/runner/beside.d.ts +3 -1
- package/dist/runner/beside.js +24 -8
- package/dist/runner/claim-secrets.d.ts +3 -1
- package/dist/runner/claim-secrets.js +28 -4
- package/dist/runner/cli-run-spec.d.ts +30 -0
- package/dist/runner/cli-run-spec.js +94 -50
- package/dist/runner/computer-channel.d.ts +5 -2
- package/dist/runner/computer-channel.js +3 -2
- package/dist/runner/computer-journal.d.ts +6 -0
- package/dist/runner/computer-journal.js +8 -10
- package/dist/runner/conformance/harness.js +6 -3
- package/dist/runner/end-of-run.d.ts +2 -0
- package/dist/runner/end-of-run.js +3 -1
- package/dist/runner/feedback-round.d.ts +40 -13
- package/dist/runner/feedback-round.js +64 -16
- package/dist/runner/harness-loops.js +17 -0
- package/dist/runner/journal-kinds.d.ts +37 -13
- package/dist/runner/journal-kinds.js +9 -5
- package/dist/runner/learning-dispatch.d.ts +3 -2
- package/dist/runner/learning-dispatch.js +6 -6
- package/dist/runner/learning-end.d.ts +4 -0
- package/dist/runner/learning-end.js +64 -36
- package/dist/runner/learning-factory.d.ts +3 -0
- package/dist/runner/learning-factory.js +8 -2
- package/dist/runner/learning-loop.d.ts +2 -0
- package/dist/runner/learning-loop.js +19 -4
- package/dist/runner/loop.d.ts +18 -0
- package/dist/runner/loop.js +34 -0
- package/dist/runner/main.d.ts +6 -1
- package/dist/runner/main.js +26 -4
- package/dist/runner/mcp-run.d.ts +4 -1
- package/dist/runner/mcp-run.js +11 -5
- package/dist/runner/meta-tools.d.ts +10 -3
- package/dist/runner/meta-tools.js +112 -36
- package/dist/runner/metrics.d.ts +80 -21
- package/dist/runner/metrics.js +114 -39
- package/dist/runner/model-route.d.ts +12 -3
- package/dist/runner/model-route.js +139 -18
- package/dist/runner/monid-run.d.ts +8 -6
- package/dist/runner/monid-run.js +117 -43
- package/dist/runner/native-loop.d.ts +11 -0
- package/dist/runner/native-loop.js +438 -0
- package/dist/runner/promotion.d.ts +74 -8
- package/dist/runner/promotion.js +365 -124
- package/dist/runner/redact.js +3 -0
- package/dist/runner/reflect-hook.js +9 -0
- package/dist/runner/runner.d.ts +7 -1
- package/dist/runner/runner.js +8 -4
- package/dist/runner/sdk-loop.d.ts +7 -0
- package/dist/runner/sdk-loop.js +470 -0
- package/dist/runner/spec-holds.d.ts +16 -2
- package/dist/runner/spec-holds.js +42 -14
- package/dist/runner/store-secrets.js +17 -2
- package/dist/runner/workflow-first.d.ts +30 -20
- package/dist/runner/workflow-first.js +22 -32
- package/dist/runner/workflow-loop.d.ts +1 -1
- package/dist/runner/workflow-loop.js +18 -12
- package/dist/runner/workflow-spec.d.ts +4 -1
- package/dist/runner/workflow-spec.js +56 -45
- package/dist/runs-over-store.d.ts +30 -2
- package/dist/runs-over-store.js +46 -14
- package/dist/sdk/runs.d.ts +115 -0
- package/dist/sdk/runs.js +422 -0
- package/dist/sdk/schema.d.ts +175 -0
- package/dist/sdk/schema.js +138 -0
- package/dist/sdk/workflows.d.ts +22 -0
- package/dist/sdk/workflows.js +39 -0
- package/dist/secrets.d.ts +2 -0
- package/dist/secrets.js +19 -1
- package/dist/server.d.ts +48 -32
- package/dist/server.js +554 -130
- package/dist/skill-route.d.ts +3 -0
- package/dist/skill-route.js +16 -0
- package/dist/skills/agentrun-serve/SKILL.md +368 -0
- package/dist/stats.d.ts +10 -10
- package/dist/store/agent-body.d.ts +12 -8
- package/dist/store/agent-body.js +9 -4
- package/dist/store/index.d.ts +1 -1
- package/dist/store/native-command-owner.d.ts +10 -0
- package/dist/store/native-command-owner.js +47 -0
- package/dist/store/postgres/migrations/0012_revision_monid_pin.sql +4 -0
- package/dist/store/postgres/migrations/0013_native_command_owner.sql +6 -0
- package/dist/store/postgres/migrations/0014_run_cost_upper_bound.sql +6 -0
- package/dist/store/postgres/store.js +3 -0
- package/dist/store/schema.d.ts +7 -0
- package/dist/store/schema.js +20 -1
- package/dist/store/sqlite/run-patch.d.ts +8 -1
- package/dist/store/sqlite/run-patch.js +14 -3
- package/dist/store/sqlite/store.js +133 -18
- package/dist/store/store.d.ts +52 -7
- package/dist/store-reads/analytics.d.ts +7 -7
- package/dist/store-reads/analytics.js +23 -5
- package/dist/store-reads/cap.js +8 -6
- package/dist/store-reads/journal.d.ts +5 -0
- package/dist/store-reads/journal.js +85 -41
- package/dist/store-reads/learning.d.ts +85 -5
- package/dist/store-reads/learning.js +45 -17
- package/dist/store-reads/runs.d.ts +5 -0
- package/dist/store-reads/runs.js +3 -2
- package/dist/store-view.js +75 -21
- package/dist/template-eval.d.ts +73 -11
- package/dist/template-eval.js +535 -75
- package/dist/templates.d.ts +70 -20
- package/dist/templates.js +191 -34
- package/dist/text-urls.d.ts +38 -0
- package/dist/text-urls.js +170 -0
- package/dist/timeline/index.d.ts +3 -2
- package/dist/timeline/index.js +3 -2
- package/dist/timeline/labels.d.ts +5 -2
- package/dist/timeline/labels.js +29 -6
- package/dist/timeline/origin.d.ts +1 -1
- package/dist/timeline/origin.js +2 -2
- package/dist/timeline/render-text.js +1 -1
- package/dist/timeline/timeline.d.ts +66 -4
- package/dist/timeline/timeline.js +160 -30
- package/dist/timeline/util.d.ts +5 -0
- package/dist/timeline/util.js +44 -8
- package/dist/timeline/web-calls.d.ts +17 -0
- package/dist/timeline/web-calls.js +106 -0
- package/dist/tool-gate.d.ts +42 -42
- package/dist/tool-gate.js +97 -91
- package/dist/tool-list.d.ts +4 -1
- package/dist/tool-list.js +8 -1
- package/dist/tool-names.d.ts +18 -13
- package/dist/tool-names.js +19 -17
- package/dist/tool-plane.d.ts +17 -13
- package/dist/tool-plane.js +12 -5
- package/dist/tools.d.ts +44 -16
- package/dist/tools.js +28 -28
- package/dist/trigger-adapter.d.ts +85 -5
- package/dist/trigger-adapter.js +6 -0
- package/dist/trigger-adapters.js +3 -1
- package/dist/trigger-composio.d.ts +10 -0
- package/dist/trigger-composio.js +122 -0
- package/dist/trigger-email.d.ts +4 -0
- package/dist/trigger-email.js +228 -0
- package/dist/trigger-signatures.d.ts +6 -10
- package/dist/trigger-signatures.js +16 -16
- package/dist/trigger-targets.d.ts +1 -1
- package/dist/trigger-targets.js +4 -3
- package/dist/trigger-webhook.js +6 -4
- package/dist/triggers.d.ts +94 -9
- package/dist/triggers.js +263 -62
- package/dist/uploads.d.ts +9 -0
- package/dist/uploads.js +27 -0
- package/dist/validate.js +1 -7
- package/dist/web-fake.d.ts +56 -0
- package/dist/web-fake.js +102 -0
- package/dist/web-fetch-direct.d.ts +3 -0
- package/dist/web-fetch-direct.js +4 -1
- package/dist/web-fetch.d.ts +5 -1
- package/dist/web-fetch.js +8 -31
- package/dist/web-search.d.ts +51 -2
- package/dist/web-search.js +116 -18
- package/dist/webhooks.d.ts +2 -1
- package/dist/webhooks.js +5 -1
- package/dist/workflow/node-runner.js +10 -2
- package/dist/workspace/archil-claim.d.ts +3 -0
- package/dist/workspace/archil-claim.js +9 -2
- package/dist/workspace/computer-deps.d.ts +22 -9
- package/dist/workspace/computer-deps.js +78 -37
- package/dist/workspace/computer-for-claim.d.ts +54 -4
- package/dist/workspace/computer-for-claim.js +179 -39
- package/dist/workspace/computer-janitor.d.ts +10 -3
- package/dist/workspace/computer-janitor.js +96 -29
- package/dist/workspace/computer-kept.d.ts +82 -0
- package/dist/workspace/computer-kept.js +147 -0
- package/dist/workspace/computer-mcp.js +4 -3
- package/dist/workspace/computer-ports.d.ts +23 -3
- package/dist/workspace/computer-ports.js +115 -5
- package/dist/workspace/index.d.ts +1 -2
- package/dist/workspace/index.js +1 -2
- package/dist/workspace/kind-skills/desktop/SKILL.md +25 -18
- package/dist/workspace/kind-skills/phone/SKILL.md +28 -17
- package/dist/workspace/resolve-computer.d.ts +15 -3
- package/dist/workspace/resolve-computer.js +10 -7
- package/dist/workspace/revision-skills.d.ts +6 -2
- package/dist/workspace/revision-skills.js +12 -5
- package/dist/workspace/run-end-computers.d.ts +30 -0
- package/dist/workspace/run-end-computers.js +137 -0
- package/dist/workspace/run-tools.d.ts +28 -29
- package/dist/workspace/run-tools.js +29 -30
- package/dist/wrap-up.d.ts +19 -5
- package/dist/wrap-up.js +31 -4
- package/package.json +13 -9
- package/skills/agentrun-serve/SKILL.md +248 -10
- package/templates/README.md +117 -23
- package/templates/TOOLS.md +168 -0
- package/templates/code-review/agent.md +18 -4
- package/templates/code-review/evals/mentions-defused/case.yaml +1 -1
- package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +2 -1
- package/templates/code-review/evals/other-repo/case.yaml +1 -1
- package/templates/code-review/evals/pasted-by-reference/case.yaml +5 -0
- package/templates/code-review/evals/pasted-by-reference/graders/by-reference.md +15 -0
- package/templates/code-review/evals/pasted-by-reference/graders/head-sha.md +6 -0
- package/templates/code-review/evals/pasted-by-reference/prompt.md +31 -0
- package/templates/code-review/skills/review/DEEP.md +2 -2
- package/templates/code-review/skills/review/REVIEWER.md +2 -2
- package/templates/code-review/skills/review/SKILL.md +7 -3
- package/templates/release-notes/evals/draft-not-publish/case.yaml +1 -1
- package/templates/release-notes/evals/issue-write-refused/case.yaml +1 -1
- package/templates/release-notes/evals/late-arrival/case.yaml +1 -1
- package/templates/release-notes/evals/other-repo/case.yaml +1 -1
- package/dist/console/assets/index-CjqQirbo.css +0 -1
- package/dist/console/assets/index-b6-XY5A9.js +0 -576
- package/dist/host-calls.d.ts +0 -20
- package/dist/host-calls.js +0 -12
- package/dist/runner/adapters/pi-computer.d.ts +0 -9
- package/dist/runner/adapters/pi-computer.js +0 -51
- package/dist/workspace/computer-script.d.ts +0 -53
- package/dist/workspace/computer-script.js +0 -172
|
@@ -0,0 +1,549 @@
|
|
|
1
|
+
// A person's ChatGPT plan as this server's model source for codex and pi: OpenAI's Sign in with ChatGPT, through pi-ai's
|
|
2
|
+
// own flow (its `openai` provider's OAuth: a loopback callback on 127.0.0.1:1455, or the final redirect URL pasted back),
|
|
3
|
+
// never one of ours. One sign-in per server: its credential is sealed whole in one row (CHATGPT_PLAN_ROW), and its access
|
|
4
|
+
// token goes to api.openai.com/v1/responses as a bearer, billed to the plan. Whoever holds the store and the seal key reads
|
|
5
|
+
// it per request (the server, its runners, in their own processes or containers); a token within REFRESH_MARGIN_MS of its
|
|
6
|
+
// end is renewed once across all of them: one renewal per refresh token in a process, and one holder at a time across
|
|
7
|
+
// processes, by a lease on the row taken with a compare-and-set on its sealed bytes and judged on the store's clock
|
|
8
|
+
// (ChatGPTPlan.renew). A refusal of the renewal (a refresh token spent or revoked) marks the sign-in expired: nothing
|
|
9
|
+
// retries it. No token outlives the sign-in it belongs to: a sign-out, a new sign-in, or a renewal that loses its write
|
|
10
|
+
// back revokes the pair it leaves behind at OpenAI (ChatGPTPlan.revoke). No token value is logged, journaled, put in a
|
|
11
|
+
// view or an error, or printed with the reader: each one read joins the redaction list (secrets.ts holdSecret).
|
|
12
|
+
import { randomUUID } from "node:crypto";
|
|
13
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
14
|
+
import { inspect } from "node:util";
|
|
15
|
+
import { CredentialUnavailable } from "@parcha/agentrun-kernel/host";
|
|
16
|
+
import { holdSecret } from "./secrets.js";
|
|
17
|
+
import { registerSecretWrite } from "./secret-writes.js";
|
|
18
|
+
import { putSealedKey } from "./server-keys.js";
|
|
19
|
+
import { sealColumn, sealedAt, STORE_WRITE_DEADLINE_MS, unsealColumn } from "./store/index.js";
|
|
20
|
+
// Every operation of the sign-in is the owner's session's alone (secret-writes.ts), the token in none of them: its view
|
|
21
|
+
// holds no token, but a pending sign-in's link is the owner's to open.
|
|
22
|
+
for (const operation of ["getChatGPTSignIn", "startChatGPTSignIn", "finishChatGPTSignIn", "signOutChatGPT"])
|
|
23
|
+
registerSecretWrite(operation, () => true);
|
|
24
|
+
/** The sealed row that holds the sign-in. */
|
|
25
|
+
export const CHATGPT_PLAN_ROW = "chatgpt:plan";
|
|
26
|
+
/** The model provider a plan model is named under (`chatgpt/<model-id>`), so a run's billing is never chosen silently. */
|
|
27
|
+
export const PLAN_PROVIDER = "chatgpt";
|
|
28
|
+
/** Where plan requests go. */
|
|
29
|
+
export const PLAN_ORIGIN = "https://api.openai.com";
|
|
30
|
+
/** The models listed when OpenAI's list can't be read at sign-in. */
|
|
31
|
+
export const PLAN_FALLBACK_MODELS = Object.freeze(["gpt-6.1-sol", "gpt-6.1-terra", "gpt-6-luna"]);
|
|
32
|
+
/** The model a run on the plan gets when it names none. */
|
|
33
|
+
export const PLAN_DEFAULT_MODEL = "gpt-6.1-sol";
|
|
34
|
+
const OPENID_CONFIGURATION = "https://auth.openai.com/.well-known/openid-configuration";
|
|
35
|
+
const DIRECT_SCOPE = "chatgpt.tokens.use.direct";
|
|
36
|
+
const AGENT_NAME = "AgentRun";
|
|
37
|
+
const HOST_ID_SETTING = "chatgpt_host_id";
|
|
38
|
+
const PENDING_MS = 10 * 60_000;
|
|
39
|
+
const REFRESH_MARGIN_MS = 5 * 60_000;
|
|
40
|
+
/** The longest one refresh call at OpenAI may take: its holder gives it up by then. */
|
|
41
|
+
const REFRESH_CALL_MS = 15_000;
|
|
42
|
+
/** A refresh lease's length (60 s): the call, the write back (STORE_WRITE_DEADLINE_MS) and 35 s spare, so a lease never lapses
|
|
43
|
+
* while its holder may still spend the token. Its end is stamped and judged on the store's clock (SealedKeys.clock: the
|
|
44
|
+
* database's on Postgres), never a process's own, so a reader whose clock runs ahead of the holder's never takes a lease
|
|
45
|
+
* still live and sends a refresh token the holder may be spending (which OpenAI answers by revoking the sign-in). A
|
|
46
|
+
* holder that dies holds the others up for the lease's length at most. */
|
|
47
|
+
const REFRESH_LEASE_MS = REFRESH_CALL_MS + STORE_WRITE_DEADLINE_MS + 35_000;
|
|
48
|
+
/** How often a reader waiting on a peer's renewal reads the row again. */
|
|
49
|
+
const LEASE_WAIT_MS = 200;
|
|
50
|
+
const RENEW_LATER = "OpenAI could not renew the ChatGPT sign-in just now: try again in a moment.";
|
|
51
|
+
/** Where pi-ai's flow sends the browser at its end: the address a person pastes back from a remote server. */
|
|
52
|
+
/** OpenAI's fixed callback for this flow, built from its parts: a packed package carries no loopback URL as one string. */
|
|
53
|
+
const REDIRECT = Object.assign(new URL("http://callback.invalid/auth/callback"), { hostname: "127.0.0.1", port: "1455" });
|
|
54
|
+
/** The words a run or a request gets when there is no plan token to send. */
|
|
55
|
+
export const SIGNED_OUT = "This server is not signed in to ChatGPT: sign in under Settings → Model keys, or name a model on a key.";
|
|
56
|
+
export const EXPIRED = "This server's ChatGPT sign-in expired: sign in again under Settings → Model keys.";
|
|
57
|
+
/** What a sign-out answers beside `revoked: false`: the sign-in is gone here, and the person ends it at OpenAI. */
|
|
58
|
+
export const SIGN_OUT_UNCONFIRMED = "Signed out here. OpenAI didn't confirm the revocation: remove AgentRun in your ChatGPT settings.";
|
|
59
|
+
/** A sign-in step refused, in words a person acts on (the routes' 400). */
|
|
60
|
+
export class PlanSignInRefused extends Error {
|
|
61
|
+
}
|
|
62
|
+
/** No plan token can be had now (signed out, expired, or OpenAI could not renew it), in plain words: a model proxy
|
|
63
|
+
* refuses the request in these words (CredentialUnavailable). */
|
|
64
|
+
export class PlanUnavailable extends CredentialUnavailable {
|
|
65
|
+
}
|
|
66
|
+
/** Where an environment object carries the plan's reader: a symbol, so no spawn, spread into an env list or JSON of it
|
|
67
|
+
* carries it (Node builds a child's environment from its string keys alone). */
|
|
68
|
+
const PLAN = Symbol.for("agentrun.chatgpt-plan");
|
|
69
|
+
/** `env`'s plan reader, if it has one. */
|
|
70
|
+
export const planOf = (env) => env[PLAN];
|
|
71
|
+
/** `env` carrying `plan`, in place: an enumerable symbol property, so an object spread of it keeps it. */
|
|
72
|
+
export function withPlan(env, plan) {
|
|
73
|
+
if (plan)
|
|
74
|
+
Object.defineProperty(env, PLAN, { value: plan, enumerable: true, configurable: true, writable: true });
|
|
75
|
+
return env;
|
|
76
|
+
}
|
|
77
|
+
/** Whether `env` runs on the plan now. */
|
|
78
|
+
export const signedIn = (env) => planOf(env)?.state === "signed_in";
|
|
79
|
+
/** The claims of a JWT's payload, read without checking its signature (only for what a view shows), or none. */
|
|
80
|
+
function claimsOf(token) {
|
|
81
|
+
try {
|
|
82
|
+
const parsed = JSON.parse(Buffer.from(token.split(".")[1] ?? "", "base64url").toString("utf8"));
|
|
83
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
return {};
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/** The email and plan a token names (OpenAI's profile and auth claims), for display alone. pi-ai keeps no ID token, so the
|
|
90
|
+
* access token's claims, which carry the same, are read. */
|
|
91
|
+
function whoOf(token) {
|
|
92
|
+
const claims = claimsOf(token);
|
|
93
|
+
const profile = claims["https://api.openai.com/profile"];
|
|
94
|
+
const auth = claims["https://api.openai.com/auth"];
|
|
95
|
+
const email = typeof profile?.email === "string" ? profile.email : typeof claims.email === "string" ? claims.email : undefined;
|
|
96
|
+
const plan = typeof auth?.chatgpt_plan_type === "string" ? auth.chatgpt_plan_type : undefined;
|
|
97
|
+
return { ...(email ? { email } : {}), ...(plan ? { plan } : {}) };
|
|
98
|
+
}
|
|
99
|
+
/** Whether a renewal's refusal is for good: the refresh token spent, expired or revoked (a 400 or 401 from the token
|
|
100
|
+
* endpoint, as pi-ai words it), not a network fault or a 5xx. */
|
|
101
|
+
const refusedForGood = (error) => /\((400|401)\)|invalid_grant|refresh_token_(reused|expired|invalidated)/.test(String(error?.message ?? ""));
|
|
102
|
+
/** Whether a renewal that failed surely left its refresh token unspent: OpenAI answered with a fault (a 5xx, a 429), or
|
|
103
|
+
* the request never reached it (no address, no connection). A timeout, or a fault once it was sent, may have spent it. */
|
|
104
|
+
function unspent(error) {
|
|
105
|
+
if (/token request failed \((?!400|401)\d{3}\)/.test(String(error?.message ?? "")))
|
|
106
|
+
return true;
|
|
107
|
+
const code = error?.cause?.code;
|
|
108
|
+
return code === "ECONNREFUSED" || code === "ENOTFOUND" || code === "EAI_AGAIN";
|
|
109
|
+
}
|
|
110
|
+
/** The renewals in flight in this process, by the refresh token they spend: two readers of one sign-in share one. */
|
|
111
|
+
const flights = new Map();
|
|
112
|
+
/** The plan over one store: a server's (sign-in, sign-out, its reading) or a runner's (the token, per request). Its
|
|
113
|
+
* fields are #private and it prints as its state alone (util.inspect, JSON), so an environment that carries it (withPlan)
|
|
114
|
+
* never shows a token when logged. */
|
|
115
|
+
export class ChatGPTPlan {
|
|
116
|
+
#snapshot;
|
|
117
|
+
#pending;
|
|
118
|
+
/** An access token OpenAI refused (refused): token() renews rather than send it again. */
|
|
119
|
+
#refusedAccess;
|
|
120
|
+
/** Moved on by each sign-in started and each sign-out: a sign-in keeps its credential only while it is unmoved since it
|
|
121
|
+
* started, so a sign-out (or a newer sign-in) while it finishes wins. */
|
|
122
|
+
#epoch = 0;
|
|
123
|
+
/** Set when a sign-in dropped by a sign-out (keep) could not have its revocation confirmed by OpenAI: that sign-out
|
|
124
|
+
* answers revoked false. Cleared at each sign-out's start. */
|
|
125
|
+
#droppedUnconfirmed = false;
|
|
126
|
+
#watchers = new Set();
|
|
127
|
+
#deps;
|
|
128
|
+
constructor(deps) {
|
|
129
|
+
this.#deps = deps;
|
|
130
|
+
}
|
|
131
|
+
[inspect.custom]() {
|
|
132
|
+
return `ChatGPTPlan { state: '${this.state}' }`;
|
|
133
|
+
}
|
|
134
|
+
toJSON() {
|
|
135
|
+
return { state: this.state };
|
|
136
|
+
}
|
|
137
|
+
watch(listener) {
|
|
138
|
+
this.#watchers.add(listener);
|
|
139
|
+
if (this.#snapshot)
|
|
140
|
+
listener([this.#snapshot.credential.access, this.#snapshot.credential.refresh]);
|
|
141
|
+
}
|
|
142
|
+
/** Each token of `credential` joins this process's redaction, and every watcher's. */
|
|
143
|
+
hold(credential) {
|
|
144
|
+
holdSecret(credential.access, credential.refresh);
|
|
145
|
+
for (const listener of this.#watchers)
|
|
146
|
+
listener([credential.access, credential.refresh]);
|
|
147
|
+
}
|
|
148
|
+
/** This process's clock: what a token's own end (OpenAI's `expires_in`, counted here) is judged by. */
|
|
149
|
+
now() {
|
|
150
|
+
return (this.#deps.now ?? Date.now)();
|
|
151
|
+
}
|
|
152
|
+
/** The store's clock: what a renewal lease is stamped and judged by, the same for every process on the store. */
|
|
153
|
+
storeNow() {
|
|
154
|
+
return this.#deps.store.sealedKeys.clock();
|
|
155
|
+
}
|
|
156
|
+
get state() {
|
|
157
|
+
return this.#snapshot?.state ?? "signed_out";
|
|
158
|
+
}
|
|
159
|
+
get models() {
|
|
160
|
+
return this.#snapshot?.models ?? [];
|
|
161
|
+
}
|
|
162
|
+
/** The row as sealed now, opened; none with none saved or one that does not open. */
|
|
163
|
+
async read() {
|
|
164
|
+
return (await this.readSealed())?.row;
|
|
165
|
+
}
|
|
166
|
+
/** The row as sealed now, opened, with the bytes it was read as (what a compare-and-set on it compares). */
|
|
167
|
+
async readSealed() {
|
|
168
|
+
const bytes = await this.#deps.store.sealedKeys.get(CHATGPT_PLAN_ROW);
|
|
169
|
+
if (bytes === undefined)
|
|
170
|
+
return undefined;
|
|
171
|
+
const row = this.open(bytes);
|
|
172
|
+
return row ? { row, bytes } : undefined;
|
|
173
|
+
}
|
|
174
|
+
/** The row sealed as `bytes`, opened (its tokens held for redaction); none when they do not open. */
|
|
175
|
+
open(bytes) {
|
|
176
|
+
try {
|
|
177
|
+
const row = JSON.parse(unsealColumn(this.#deps.sealKey, sealedAt.sealedKey(CHATGPT_PLAN_ROW), bytes).toString("utf8"));
|
|
178
|
+
if (row?.v !== 1 || !row.credential?.access || !row.credential.refresh)
|
|
179
|
+
return undefined;
|
|
180
|
+
this.hold(row.credential);
|
|
181
|
+
return row;
|
|
182
|
+
}
|
|
183
|
+
catch {
|
|
184
|
+
return undefined;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
/** `row` sealed as the store keeps it: fresh bytes at each seal. */
|
|
188
|
+
seal(row) {
|
|
189
|
+
return sealColumn(this.#deps.sealKey, sealedAt.sealedKey(CHATGPT_PLAN_ROW), JSON.stringify(row));
|
|
190
|
+
}
|
|
191
|
+
/** `row` saved only while the store still holds `was` (SealedKeys.replaceIf): the bytes it was saved as, or none when
|
|
192
|
+
* the row had changed. */
|
|
193
|
+
async swap(was, row) {
|
|
194
|
+
const bytes = this.seal(row);
|
|
195
|
+
return (await this.#deps.store.sealedKeys.replaceIf(CHATGPT_PLAN_ROW, was, bytes)) ? bytes : undefined;
|
|
196
|
+
}
|
|
197
|
+
/** Reads the sealed row into the state a reader sees. Returns this. */
|
|
198
|
+
async load() {
|
|
199
|
+
this.#snapshot = await this.read();
|
|
200
|
+
return this;
|
|
201
|
+
}
|
|
202
|
+
view() {
|
|
203
|
+
if (this.#pending && this.#pending.expiresAt <= this.now())
|
|
204
|
+
this.cancel();
|
|
205
|
+
const row = this.#snapshot;
|
|
206
|
+
const who = row ? { ...(row.email ? { email: row.email } : {}), ...(row.plan ? { plan: row.plan } : {}) } : {};
|
|
207
|
+
if (this.#pending)
|
|
208
|
+
return { state: "pending", authorize_url: this.#pending.authorizeUrl, expires_at: new Date(this.#pending.expiresAt).toISOString(), ...who };
|
|
209
|
+
if (!row)
|
|
210
|
+
return { state: "signed_out" };
|
|
211
|
+
return { state: row.state, ...who, ...(row.state === "signed_in" ? { models: [...row.models] } : {}) };
|
|
212
|
+
}
|
|
213
|
+
/** This server's id at OpenAI (its agent host id): a UUID made once and kept in the store's settings. Not a credential. */
|
|
214
|
+
async hostId() {
|
|
215
|
+
if (!this.#deps.store.settings)
|
|
216
|
+
throw new Error("a ChatGPT sign-in starts on the server, which keeps its host id");
|
|
217
|
+
const kept = await this.#deps.store.settings.putIfAbsent(HOST_ID_SETTING, randomUUID());
|
|
218
|
+
if (typeof kept !== "string")
|
|
219
|
+
throw new Error("this server's ChatGPT host id is not a UUID in its settings");
|
|
220
|
+
return kept;
|
|
221
|
+
}
|
|
222
|
+
cancel() {
|
|
223
|
+
const pending = this.#pending;
|
|
224
|
+
if (!pending)
|
|
225
|
+
return;
|
|
226
|
+
this.#pending = undefined;
|
|
227
|
+
clearTimeout(pending.timer);
|
|
228
|
+
pending.abort.abort();
|
|
229
|
+
}
|
|
230
|
+
/** Starts a sign-in (one at a time: a new start cancels the one waiting) and gives the address to open. It lasts 10
|
|
231
|
+
* minutes: the loopback callback finishes it where the browser runs on this machine; elsewhere finishSignIn does. */
|
|
232
|
+
async startSignIn() {
|
|
233
|
+
// A sign-in still finishing drops its credential (keep): this one is the person's latest.
|
|
234
|
+
const epoch = ++this.#epoch;
|
|
235
|
+
const before = this.#pending;
|
|
236
|
+
this.cancel();
|
|
237
|
+
// pi-ai's callback listener on :1455 closes as its login ends: the one cancelled ends before this one listens.
|
|
238
|
+
if (before)
|
|
239
|
+
await before.result.catch(() => undefined);
|
|
240
|
+
const { openaiProvider } = await import("@earendil-works/pi-ai/providers/openai");
|
|
241
|
+
const oauth = openaiProvider().auth.oauth;
|
|
242
|
+
const hostId = await this.hostId();
|
|
243
|
+
const abort = new AbortController();
|
|
244
|
+
let paste;
|
|
245
|
+
const pasted = new Promise((resolve) => (paste = resolve));
|
|
246
|
+
let linked;
|
|
247
|
+
const link = new Promise((resolve) => (linked = resolve));
|
|
248
|
+
const login = oauth.login({
|
|
249
|
+
signal: abort.signal,
|
|
250
|
+
notify: (event) => void (event.type === "auth_url" ? linked(event.url) : undefined),
|
|
251
|
+
prompt: (prompt) => (prompt.type === "manual_code" ? Promise.race([pasted, new Promise((_, reject) => prompt.signal?.addEventListener("abort", () => reject(new Error("closed")), { once: true }))]) : Promise.reject(new Error("not asked here"))),
|
|
252
|
+
}, { getDeviceId: () => hostId, agentName: AGENT_NAME });
|
|
253
|
+
const settle = () => {
|
|
254
|
+
if (this.#pending?.abort !== abort)
|
|
255
|
+
return;
|
|
256
|
+
clearTimeout(this.#pending.timer);
|
|
257
|
+
this.#pending = undefined;
|
|
258
|
+
};
|
|
259
|
+
// Pending until the credential is kept or dropped, so a sign-out meanwhile cancels it (keep's epoch).
|
|
260
|
+
const result = login.then((credential) => this.keep(credential, epoch)).finally(settle);
|
|
261
|
+
result.catch(() => undefined);
|
|
262
|
+
const authorizeUrl = await Promise.race([link, result.then(() => undefined, (error) => {
|
|
263
|
+
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.");
|
|
264
|
+
})]);
|
|
265
|
+
if (!authorizeUrl)
|
|
266
|
+
throw new PlanSignInRefused("The sign-in could not start: try again.");
|
|
267
|
+
const expiresAt = this.now() + PENDING_MS;
|
|
268
|
+
const timer = setTimeout(() => (this.#pending?.abort === abort ? this.cancel() : undefined), PENDING_MS);
|
|
269
|
+
timer.unref();
|
|
270
|
+
this.#pending = { abort, state: new URL(authorizeUrl).searchParams.get("state") ?? "", authorizeUrl, expiresAt, paste, result, timer };
|
|
271
|
+
return { authorize_url: authorizeUrl, expires_at: new Date(expiresAt).toISOString() };
|
|
272
|
+
}
|
|
273
|
+
/** Finishes the sign-in waiting with the address its browser tab ended on, pasted. A URL that is not that sign-in's end
|
|
274
|
+
* is refused in words and the sign-in keeps waiting; one OpenAI refuses ends it. */
|
|
275
|
+
async finishSignIn(redirectUrl) {
|
|
276
|
+
const pending = this.#pending && this.#pending.expiresAt > this.now() ? this.#pending : undefined;
|
|
277
|
+
if (!pending)
|
|
278
|
+
throw new PlanSignInRefused("No ChatGPT sign-in is waiting (one lasts 10 minutes): start the sign-in again.");
|
|
279
|
+
const shape = `Paste the whole address the sign-in tab ended on: it starts with ${REDIRECT.href}.`;
|
|
280
|
+
let url;
|
|
281
|
+
try {
|
|
282
|
+
url = new URL(String(redirectUrl ?? "").trim());
|
|
283
|
+
}
|
|
284
|
+
catch {
|
|
285
|
+
throw new PlanSignInRefused(shape);
|
|
286
|
+
}
|
|
287
|
+
if (url.origin !== REDIRECT.origin || url.pathname !== REDIRECT.pathname)
|
|
288
|
+
throw new PlanSignInRefused(shape);
|
|
289
|
+
const error = url.searchParams.get("error");
|
|
290
|
+
if (error)
|
|
291
|
+
throw new PlanSignInRefused(`ChatGPT did not sign you in (${error.replace(/[^a-z_]/gi, "").slice(0, 40)}): start the sign-in again.`);
|
|
292
|
+
if (url.searchParams.get("state") !== pending.state)
|
|
293
|
+
throw new PlanSignInRefused("That address is from another sign-in: paste the one from the sign-in you started last, or start again.");
|
|
294
|
+
if (!url.searchParams.get("code") || !url.searchParams.get("client_id"))
|
|
295
|
+
throw new PlanSignInRefused(`That address has no sign-in code in it. ${shape}`);
|
|
296
|
+
pending.paste(url.href);
|
|
297
|
+
try {
|
|
298
|
+
await pending.result;
|
|
299
|
+
}
|
|
300
|
+
catch (error) {
|
|
301
|
+
const words = String(error?.message ?? "");
|
|
302
|
+
if (words.includes(DIRECT_SCOPE))
|
|
303
|
+
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.");
|
|
304
|
+
throw new PlanSignInRefused("OpenAI refused the sign-in: start it again.");
|
|
305
|
+
}
|
|
306
|
+
return this.view();
|
|
307
|
+
}
|
|
308
|
+
/** A credential from the sign-in started at `epoch`, checked and sealed with what a view shows. A sign-out or a newer
|
|
309
|
+
* sign-in since then wins: the credential is dropped, never written, and revoked at OpenAI. A sign-in it takes the place
|
|
310
|
+
* of is revoked first, then replaced only while the row still holds it (a renewal of it that wrote back meanwhile is
|
|
311
|
+
* read, revoked and replaced in turn), so no earlier pair is left alive. */
|
|
312
|
+
async keep(credential, epoch) {
|
|
313
|
+
if (credential.scopes && !credential.scopes.includes(DIRECT_SCOPE))
|
|
314
|
+
throw new Error(`the grant did not include ${DIRECT_SCOPE}`);
|
|
315
|
+
this.hold(credential);
|
|
316
|
+
const models = await this.listModels(credential.access);
|
|
317
|
+
const row = { v: 1, state: "signed_in", credential, ...whoOf(credential.access), models };
|
|
318
|
+
let previousRevoked;
|
|
319
|
+
for (;;) {
|
|
320
|
+
if (epoch !== this.#epoch) {
|
|
321
|
+
if (!(await this.revoke(credential)))
|
|
322
|
+
this.#droppedUnconfirmed = true;
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
const was = await this.#deps.store.sealedKeys.get(CHATGPT_PLAN_ROW);
|
|
326
|
+
if (was === undefined) {
|
|
327
|
+
// No row to compare against: only the server signs in, and nothing else makes the row (a runner's renewal
|
|
328
|
+
// replaces one only while it holds its lease), so a plain write.
|
|
329
|
+
await putSealedKey(this.#deps.store, this.#deps.sealKey, CHATGPT_PLAN_ROW, JSON.stringify(row));
|
|
330
|
+
break;
|
|
331
|
+
}
|
|
332
|
+
const previous = this.open(was);
|
|
333
|
+
if (previous && previous.credential.refresh !== credential.refresh)
|
|
334
|
+
previousRevoked = await this.revoke(previous.credential);
|
|
335
|
+
if (epoch !== this.#epoch)
|
|
336
|
+
continue;
|
|
337
|
+
if (await this.swap(was, row))
|
|
338
|
+
break;
|
|
339
|
+
}
|
|
340
|
+
this.#snapshot = row;
|
|
341
|
+
this.#deps.log?.({ chatgpt: "signed_in", ...(previousRevoked === undefined ? {} : { previous_revoked: String(previousRevoked) }) });
|
|
342
|
+
await this.#deps.changed?.();
|
|
343
|
+
}
|
|
344
|
+
/** The plan's models from OpenAI's list (GET /v1/models with the token), those of the current families; the fallback
|
|
345
|
+
* list when it can't be read. */
|
|
346
|
+
async listModels(token) {
|
|
347
|
+
try {
|
|
348
|
+
const response = await fetch(`${PLAN_ORIGIN}/v1/models`, { headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(5_000) });
|
|
349
|
+
if (!response.ok)
|
|
350
|
+
return [...PLAN_FALLBACK_MODELS];
|
|
351
|
+
const body = (await response.json());
|
|
352
|
+
const ids = (body.data ?? []).map((model) => model.id).filter((id) => typeof id === "string" && /^gpt-6(?:[.-]|$)/.test(id));
|
|
353
|
+
return ids.length ? [...new Set(ids)] : [...PLAN_FALLBACK_MODELS];
|
|
354
|
+
}
|
|
355
|
+
catch {
|
|
356
|
+
return [...PLAN_FALLBACK_MODELS];
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
/** The access token to send now: the sealed one, renewed first when it ends within 5 minutes. Throws PlanUnavailable,
|
|
360
|
+
* in words, when there is none. */
|
|
361
|
+
async token() {
|
|
362
|
+
const row = await this.read();
|
|
363
|
+
this.#snapshot = row;
|
|
364
|
+
if (!row)
|
|
365
|
+
throw new PlanUnavailable(SIGNED_OUT);
|
|
366
|
+
if (row.state === "expired")
|
|
367
|
+
throw new PlanUnavailable(EXPIRED);
|
|
368
|
+
if (this.fresh(row))
|
|
369
|
+
return row.credential.access;
|
|
370
|
+
// One renewal per refresh token in this process; across processes, the row's lease (renew).
|
|
371
|
+
const key = row.credential.refresh;
|
|
372
|
+
let flight = flights.get(key);
|
|
373
|
+
if (!flight) {
|
|
374
|
+
flight = this.renew(key).finally(() => flights.delete(key));
|
|
375
|
+
flights.set(key, flight);
|
|
376
|
+
}
|
|
377
|
+
return flight;
|
|
378
|
+
}
|
|
379
|
+
/** Whether `row`'s access token may be sent as it is: OpenAI has not refused it here, and it has more than 5 minutes left. */
|
|
380
|
+
fresh(row) {
|
|
381
|
+
return row.credential.access !== this.#refusedAccess && row.credential.expires - this.now() > REFRESH_MARGIN_MS;
|
|
382
|
+
}
|
|
383
|
+
/** OpenAI answered 401 to `sent`: the row read again, and the next token() renews it only when the row still holds
|
|
384
|
+
* `sent` (another holder that renewed already has put a new one there, which is sent instead). */
|
|
385
|
+
async refused(sent) {
|
|
386
|
+
const row = await this.read();
|
|
387
|
+
if (row?.state === "signed_in" && row.credential.access === sent)
|
|
388
|
+
this.#refusedAccess = sent;
|
|
389
|
+
}
|
|
390
|
+
/** Renews the sign-in whose refresh token is `seen`, for any process that holds the store and the seal key (the server,
|
|
391
|
+
* each runner). A refresh token is spent at its use, and one used twice makes OpenAI revoke the whole sign-in, so one
|
|
392
|
+
* holder at a time takes a lease on the row (a compare-and-set on its sealed bytes) before it spends the token. The
|
|
393
|
+
* others adopt the pair it writes back: meanwhile they send the current token while it has not ended, and wait for the
|
|
394
|
+
* new pair once it has. A lease whose holder died lapses after REFRESH_LEASE_MS, and the next reader takes it. The
|
|
395
|
+
* lease's end is stamped and judged on the store's clock, so a process whose own clock runs ahead never takes one
|
|
396
|
+
* still live. */
|
|
397
|
+
async renew(seen) {
|
|
398
|
+
const holder = randomUUID();
|
|
399
|
+
const giveUp = this.now() + REFRESH_LEASE_MS + REFRESH_CALL_MS;
|
|
400
|
+
for (;;) {
|
|
401
|
+
const read = await this.readSealed();
|
|
402
|
+
if (!read)
|
|
403
|
+
throw new PlanUnavailable(SIGNED_OUT);
|
|
404
|
+
const { row, bytes } = read;
|
|
405
|
+
this.#snapshot = row;
|
|
406
|
+
if (row.state === "expired")
|
|
407
|
+
throw new PlanUnavailable(EXPIRED);
|
|
408
|
+
// A peer renewed it since: its pair is the row's now.
|
|
409
|
+
if (row.credential.refresh !== seen && this.fresh(row))
|
|
410
|
+
return row.credential.access;
|
|
411
|
+
const at = await this.storeNow();
|
|
412
|
+
if (row.lease && row.lease.until > at) {
|
|
413
|
+
if (row.credential.access !== this.#refusedAccess && row.credential.expires > this.now())
|
|
414
|
+
return row.credential.access;
|
|
415
|
+
if (this.now() > giveUp)
|
|
416
|
+
throw new PlanUnavailable(RENEW_LATER);
|
|
417
|
+
await sleep(LEASE_WAIT_MS);
|
|
418
|
+
continue;
|
|
419
|
+
}
|
|
420
|
+
const leased = { ...row, lease: { holder, until: at + REFRESH_LEASE_MS } };
|
|
421
|
+
// Changed since it was read (a peer leased or renewed it, or the owner signed in again): read it again.
|
|
422
|
+
const mine = await this.swap(bytes, leased);
|
|
423
|
+
if (!mine)
|
|
424
|
+
continue;
|
|
425
|
+
return this.renewUnder(leased, mine);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
/** The renewal itself, under this holder's lease on `row` (sealed as `bytes`). Every write back is a compare-and-set
|
|
429
|
+
* against the leased row, so a sign-out or a new sign-in meanwhile is never overwritten: ours is dropped. */
|
|
430
|
+
async renewUnder(row, bytes) {
|
|
431
|
+
const { lease: _, ...bare } = row;
|
|
432
|
+
const { openaiProvider } = await import("@earendil-works/pi-ai/providers/openai");
|
|
433
|
+
let next;
|
|
434
|
+
try {
|
|
435
|
+
next = (await openaiProvider().auth.oauth.refresh(bare.credential, AbortSignal.timeout(REFRESH_CALL_MS)));
|
|
436
|
+
}
|
|
437
|
+
catch (error) {
|
|
438
|
+
if (!refusedForGood(error)) {
|
|
439
|
+
// A fault at OpenAI, or none reached: the token is unspent, so the lease is given back for the next try. Sent
|
|
440
|
+
// with no answer read (a timeout, a lost connection): it may be spent, so the lease is held to its end, and no
|
|
441
|
+
// one sends it again sooner.
|
|
442
|
+
if (unspent(error))
|
|
443
|
+
await this.swap(bytes, bare).catch(() => undefined);
|
|
444
|
+
throw new PlanUnavailable(RENEW_LATER);
|
|
445
|
+
}
|
|
446
|
+
const expired = { ...bare, state: "expired" };
|
|
447
|
+
if (await this.swap(bytes, expired)) {
|
|
448
|
+
this.#snapshot = expired;
|
|
449
|
+
this.#deps.log?.({ chatgpt: "expired" });
|
|
450
|
+
await this.#deps.changed?.();
|
|
451
|
+
throw new PlanUnavailable(EXPIRED);
|
|
452
|
+
}
|
|
453
|
+
return this.adopt();
|
|
454
|
+
}
|
|
455
|
+
const renewed = { ...bare, credential: { ...bare.credential, ...next } };
|
|
456
|
+
this.hold(renewed.credential);
|
|
457
|
+
if (await this.swap(bytes, renewed)) {
|
|
458
|
+
this.#snapshot = renewed;
|
|
459
|
+
return renewed.credential.access;
|
|
460
|
+
}
|
|
461
|
+
// The owner signed out or in again while OpenAI renewed it: the new pair is the sign-in's no longer, and no one
|
|
462
|
+
// holds it but this renewal, so it is revoked here, never handed out.
|
|
463
|
+
await this.revoke(renewed.credential);
|
|
464
|
+
return this.adopt();
|
|
465
|
+
}
|
|
466
|
+
/** After a renewal whose write back lost its compare-and-set (the owner signed out or in again meanwhile): its result
|
|
467
|
+
* is dropped, and the row's state wins. */
|
|
468
|
+
async adopt() {
|
|
469
|
+
const now = await this.read();
|
|
470
|
+
this.#snapshot = now;
|
|
471
|
+
if (!now)
|
|
472
|
+
throw new PlanUnavailable(SIGNED_OUT);
|
|
473
|
+
if (now.state === "expired")
|
|
474
|
+
throw new PlanUnavailable(EXPIRED);
|
|
475
|
+
if (this.fresh(now))
|
|
476
|
+
return now.credential.access;
|
|
477
|
+
throw new PlanUnavailable(RENEW_LATER);
|
|
478
|
+
}
|
|
479
|
+
/** Signs out: any sign-in waiting cancelled (one past its browser step waited for: it drops and revokes its credential),
|
|
480
|
+
* then the row removed only while it still holds the bytes read (SealedKeys.removeIf; a renewal that wrote back
|
|
481
|
+
* meanwhile is read and removed in turn), and the pair it held revoked at OpenAI (its documented revocation endpoint,
|
|
482
|
+
* with the refresh token). The row goes whatever the revocation says. `revoked`: nothing of the sign-in is left alive
|
|
483
|
+
* at OpenAI as far as it can tell: none was signed in, or OpenAI confirmed the revocation and no renewal was out under
|
|
484
|
+
* a live lease (that renewal revokes the pair it gets when its write back finds the row gone, but OpenAI's word on it
|
|
485
|
+
* is not this answer's to give). */
|
|
486
|
+
async signOut() {
|
|
487
|
+
this.#droppedUnconfirmed = false;
|
|
488
|
+
this.#epoch += 1;
|
|
489
|
+
const finishing = this.#pending;
|
|
490
|
+
this.cancel();
|
|
491
|
+
await finishing?.result.catch(() => undefined);
|
|
492
|
+
// A sign-in past its browser step, dropped by this sign-out (keep), whose revocation OpenAI didn't confirm.
|
|
493
|
+
let revoked = !this.#droppedUnconfirmed;
|
|
494
|
+
for (;;) {
|
|
495
|
+
const bytes = await this.#deps.store.sealedKeys.get(CHATGPT_PLAN_ROW);
|
|
496
|
+
if (bytes === undefined)
|
|
497
|
+
break;
|
|
498
|
+
const row = this.open(bytes);
|
|
499
|
+
const renewing = row?.lease !== undefined && row.lease.until > (await this.storeNow());
|
|
500
|
+
if (!(await this.#deps.store.sealedKeys.removeIf(CHATGPT_PLAN_ROW, bytes)))
|
|
501
|
+
continue;
|
|
502
|
+
// A row that does not open (sealed under another key) is removed, its tokens beyond reach to revoke.
|
|
503
|
+
const removed = row ? (await this.revoke(row.credential)) && !renewing : false;
|
|
504
|
+
revoked = revoked && removed;
|
|
505
|
+
break;
|
|
506
|
+
}
|
|
507
|
+
this.#snapshot = undefined;
|
|
508
|
+
this.#deps.log?.({ chatgpt: "signed_out", revoked: String(revoked) });
|
|
509
|
+
await this.#deps.changed?.();
|
|
510
|
+
return { revoked };
|
|
511
|
+
}
|
|
512
|
+
/** `credential`'s session revoked at OpenAI (its documented revocation endpoint, with the refresh token): whether OpenAI
|
|
513
|
+
* confirmed it. The endpoint is taken from OpenAI's discovery document only when it is https on auth.openai.com, so a
|
|
514
|
+
* refresh token goes nowhere else. Never throws. */
|
|
515
|
+
async revoke(credential) {
|
|
516
|
+
try {
|
|
517
|
+
const config = (await (await fetch(OPENID_CONFIGURATION, { signal: AbortSignal.timeout(5_000) })).json());
|
|
518
|
+
const endpoint = typeof config.revocation_endpoint === "string" ? new URL(config.revocation_endpoint) : undefined;
|
|
519
|
+
if (endpoint?.protocol !== "https:" || endpoint.host !== new URL(OPENID_CONFIGURATION).host)
|
|
520
|
+
return false;
|
|
521
|
+
const response = await fetch(endpoint, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ token: credential.refresh, token_type_hint: "refresh_token", client_id: credential.clientId }), signal: AbortSignal.timeout(5_000) });
|
|
522
|
+
return response.ok;
|
|
523
|
+
}
|
|
524
|
+
catch {
|
|
525
|
+
return false;
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
/** Stops the sign-in waiting, at the server's close. */
|
|
529
|
+
close() {
|
|
530
|
+
this.cancel();
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
/** For a run on a plan model (`model`, the one its claim chose): the plan's token read once before anything starts, so a
|
|
534
|
+
* sign-in that is gone, or that OpenAI refuses to renew, fails the run at once, in words (PlanUnavailable). */
|
|
535
|
+
export async function planBeforeRun(env, model) {
|
|
536
|
+
if (model?.provider !== PLAN_PROVIDER)
|
|
537
|
+
return;
|
|
538
|
+
const plan = planOf(env);
|
|
539
|
+
if (!plan)
|
|
540
|
+
throw new PlanUnavailable(SIGNED_OUT);
|
|
541
|
+
await plan.token();
|
|
542
|
+
}
|
|
543
|
+
/** A runner's reader of the plan over its store, loaded now: none when the server holds no sign-in. */
|
|
544
|
+
export async function planReaderOf(store, sealKey) {
|
|
545
|
+
if (!sealKey)
|
|
546
|
+
return undefined;
|
|
547
|
+
const plan = await new ChatGPTPlan({ store, sealKey }).load();
|
|
548
|
+
return plan.state === "signed_out" ? undefined : plan;
|
|
549
|
+
}
|
package/dist/cli.js
CHANGED
|
@@ -25,7 +25,7 @@ surviveClosedPipes();
|
|
|
25
25
|
const USAGE = `usage: agentrun-serve [--data DIR] [--listen ADDR] [--port N] [--open] [--faux MODULE] [--faux-browser MODULE] [--faux-github] [--allow-host NAME ...] [--max-runs N] [--drain-timeout D] [--documents DIR] [--allow-code-nodes] [--learning on|off] [--learning-budget BYTES] [--grade-model MODEL] [--no-runner]
|
|
26
26
|
agentrun-serve reset-password [--data DIR]
|
|
27
27
|
agentrun-serve validate-template DIR
|
|
28
|
-
agentrun-serve eval-template DIR [--case NAME ...] [--runs N] [--server URL] [--grader-model PROVIDER/MODEL] [--report FILE] [--faux MODULE]
|
|
28
|
+
agentrun-serve eval-template DIR [--case NAME ...] [--runs N] [--server URL | --on-data DIR] [--grader-model PROVIDER/MODEL] [--report FILE] [--faux MODULE]
|
|
29
29
|
agentrun-serve import [--data DIR] [--from claude-code,codex,pi] [--dry-run] [--include-deleted] [--all] [--verbose] [--port N]
|
|
30
30
|
agentrun-serve runner --data DIR [--loops N] [--drain-timeout D] [--name NAME]
|
|
31
31
|
agentrun-serve runner --check --data DIR [--name NAME]
|
|
@@ -74,7 +74,9 @@ to AGENT_MODEL_FAST or AGENT_MODEL_STRONG, each falling back to AGENT_MODEL) is
|
|
|
74
74
|
keys from the environment, or, with AGENT_MODEL_BASE_URL, by that one OpenAI Responses gateway (AGENT_MODEL_API_KEY when
|
|
75
75
|
it needs a key). AGENTRUN_TOKEN, when set, is the token in place of DIR/.token's (a DIR/.token from an earlier start is removed), and is never printed; DIR/.token's is
|
|
76
76
|
printed only by the start that made it. AGENTRUN_PUBLIC_URL, when set, is the address people open (a container's
|
|
77
|
-
published port, or a proxy's URL), and the link printed uses it; with none, Render's RENDER_EXTERNAL_URL is.
|
|
77
|
+
published port, or a proxy's URL), and the link printed uses it; with none, Render's RENDER_EXTERNAL_URL is.
|
|
78
|
+
AGENTRUN_FREE_MODEL_REQUESTS (default 60) is the most requests on free models ($0 in the catalog) a run makes, capped
|
|
79
|
+
or not (ChatGPT-plan requests don't count): the next is not sent and the run fails, spend_cap_reached. stdout gets one line per request, per run start and
|
|
78
80
|
end, and per refused credential; AGENTRUN_LOG=quiet leaves out the request lines.
|
|
79
81
|
|
|
80
82
|
AGENTRUN_API_ONLY=1 serves the run routes alone, for a server behind its caller's backend: a run's launch, read, list,
|
|
@@ -105,11 +107,24 @@ session found, those imported before included, and the address to open the conso
|
|
|
105
107
|
\`agentrun-serve eval-template DIR\` runs a template package's eval cases (all, or each --case) as real runs of its agent
|
|
106
108
|
and grades each run with the case's graders (templates/README.md, "Running the evals"). By default on a server of its
|
|
107
109
|
own in this process, over a temp data directory removed at the end, so it never touches your server; --server URL runs
|
|
108
|
-
them on that server instead, its token in AGENTRUN_API_KEY, and archives the agents it made. --
|
|
110
|
+
them on that server instead, its token in AGENTRUN_API_KEY, and archives the agents it made. --on-data DIR runs its own
|
|
111
|
+
server on DIR, a stopped server's data folder, so the runs use what that server keeps (its ChatGPT sign-in) and a case's
|
|
112
|
+
fakes (its clock, its mailbox) still bind; it archives the agents it made there and leaves the folder and its settings,
|
|
113
|
+
and is refused while another server holds DIR, when DIR has enabled triggers or runs not ended, or for an email case
|
|
114
|
+
when DIR's server keeps an email account. --runs N runs each case N
|
|
109
115
|
times in place of its own count; --grader-model is the llm graders' model (default: the server's); --faux answers every
|
|
110
116
|
model request from MODULE, as the server's --faux does. Progress goes to stderr, a summary to stdout, the whole report
|
|
111
117
|
as JSON to --report FILE. Exit 0 when every case passed, 1 when one failed, 2 when the flags, the package or a case are
|
|
112
118
|
wrong and nothing ran. Real runs cost money: each case's prompt.md caps each of its runs (max_cost_usd).`;
|
|
119
|
+
if (process.argv[2] === "remote-bridge") {
|
|
120
|
+
const { runRemoteWorkerBridge } = await import("./native/remote-worker-bridge.js");
|
|
121
|
+
await runRemoteWorkerBridge();
|
|
122
|
+
process.exit(0);
|
|
123
|
+
}
|
|
124
|
+
if (process.argv[2] === "native") {
|
|
125
|
+
const { nativeMain } = await import("./native/cli.js");
|
|
126
|
+
process.exit(await nativeMain(process.argv.slice(3)));
|
|
127
|
+
}
|
|
113
128
|
if (process.argv[2] === "reset-password") {
|
|
114
129
|
let dir;
|
|
115
130
|
try {
|
|
@@ -151,12 +166,12 @@ if (process.argv[2] === "validate-template") {
|
|
|
151
166
|
// 0: every case passed; 1: one failed; 2: the flags, the package or a case is wrong, and nothing ran. --data is taken and
|
|
152
167
|
// ignored, as validate-template's is: the npx launcher hands every server command one, and an eval's store is a temp one.
|
|
153
168
|
if (process.argv[2] === "eval-template") {
|
|
154
|
-
const { CaseError, evalTemplate, exitCodeOf, markdownReport } = await import("./template-eval.js");
|
|
169
|
+
const { CaseError, evalTemplate, exitCodeOf, markdownReport, ON_DATA_WITH_SERVER } = await import("./template-eval.js");
|
|
155
170
|
const { PackageError } = await import("./templates.js");
|
|
156
171
|
const usage = (message) => (console.error(`agentrun-serve eval-template: ${message}\n\n${USAGE}`), process.exit(2));
|
|
157
172
|
const read = () => {
|
|
158
173
|
try {
|
|
159
|
-
return parseArgs({ args: process.argv.slice(3), allowPositionals: true, options: { case: { type: "string", multiple: true, default: [] }, runs: { type: "string" }, server: { type: "string" }, "grader-model": { type: "string" }, report: { type: "string" }, faux: { type: "string" }, data: { type: "string" } } });
|
|
174
|
+
return parseArgs({ args: process.argv.slice(3), allowPositionals: true, options: { case: { type: "string", multiple: true, default: [] }, runs: { type: "string" }, server: { type: "string" }, "grader-model": { type: "string" }, report: { type: "string" }, faux: { type: "string" }, data: { type: "string" }, "on-data": { type: "string" } } });
|
|
160
175
|
}
|
|
161
176
|
catch (error) {
|
|
162
177
|
return usage(error.message);
|
|
@@ -171,6 +186,10 @@ if (process.argv[2] === "eval-template") {
|
|
|
171
186
|
usage("--server takes the server's http(s) address.");
|
|
172
187
|
if (given.server !== undefined && given.faux !== undefined)
|
|
173
188
|
usage("--faux is the model of the server it starts itself, and --server names another server.");
|
|
189
|
+
if (given.server !== undefined && given["on-data"] !== undefined)
|
|
190
|
+
usage(`${ON_DATA_WITH_SERVER}.`);
|
|
191
|
+
if (given["on-data"] === "")
|
|
192
|
+
usage("--on-data takes a server's data folder.");
|
|
174
193
|
const token = given.server === undefined ? undefined : secret("AGENTRUN_API_KEY") || secret("AGENTRUN_TOKEN");
|
|
175
194
|
if (given.server !== undefined && !token)
|
|
176
195
|
usage("--server needs that server's token in AGENTRUN_API_KEY.");
|
|
@@ -214,7 +233,8 @@ if (process.argv[2] === "eval-template") {
|
|
|
214
233
|
const report = await evalTemplate({
|
|
215
234
|
dir: resolve(positionals[0]), cases: given.case, ...(given.runs !== undefined ? { runs: Number(given.runs) } : {}),
|
|
216
235
|
...(given.server !== undefined ? { server: { baseUrl: given.server, token: token } } : {}), ...(given["grader-model"] !== undefined ? { graderModel: given["grader-model"] } : {}),
|
|
217
|
-
...(given.faux !== undefined ? { serve: { faux: resolve(given.faux) } } : {}),
|
|
236
|
+
...(given.faux !== undefined ? { serve: { faux: resolve(given.faux) } } : {}), ...(given["on-data"] !== undefined ? { data: resolve(given["on-data"]) } : {}),
|
|
237
|
+
log: (line) => console.error(line), signal: stop.signal,
|
|
218
238
|
});
|
|
219
239
|
// A stop asked as the eval ended still stops it: no report, 130.
|
|
220
240
|
stop.signal.throwIfAborted();
|
|
@@ -1,13 +1,21 @@
|
|
|
1
|
+
import { type Json } from "./validate.js";
|
|
1
2
|
/** Another Composio than the real one, and its fetch: a test's fake (the same seam as `archilControl`). */
|
|
2
3
|
export type ComposioControl = {
|
|
3
4
|
readonly baseUrl?: string;
|
|
4
5
|
readonly fetch?: typeof fetch;
|
|
5
6
|
};
|
|
7
|
+
/** The one Composio user a server's actions run as, unless the owner names another. */
|
|
8
|
+
export declare const COMPOSIO_USER = "agentrun";
|
|
6
9
|
export type ComposioTool = {
|
|
7
10
|
slug: string;
|
|
8
11
|
name: string;
|
|
9
12
|
description: string;
|
|
10
13
|
};
|
|
14
|
+
/** A Composio call (asking): its JSON answer, or the refusal in words that name its step. */
|
|
15
|
+
export type Ask = (step: string, method: "GET" | "POST" | "PATCH" | "DELETE", path: string, body?: unknown, missing?: string) => Promise<Json>;
|
|
16
|
+
/** A Composio call as `key`: its JSON answer, or an error in words that name `step` and never the key, and end with
|
|
17
|
+
* `outcome`, what the failure left (a save's: nothing was saved). */
|
|
18
|
+
export declare function asking(control: ComposioControl, key: string, signal: AbortSignal | undefined, outcome?: string): Ask;
|
|
11
19
|
/** POST /settings/mcp-servers/composio/tools: a toolkit's actions, for the console's picker, and whether it needs no sign-in. */
|
|
12
20
|
export declare function composioTools(body: unknown, control: ComposioControl, signal?: AbortSignal): Promise<{
|
|
13
21
|
toolkit: string;
|