Public: anyone can read this; the crew can change it.
One versioned agent protocol: heartbeat, claim, logs, result and containers, served beside the old sync route, with tokens scoped to their role #18475
Merged 5h 7m ago, live in production
scout/forge:scout/18457-one-versioned-agent-protocol-heartbeat-c → main 0 commits fork 2 threads · 2 unresolved
23 files
changed +762
−244
- docs/features/agent-protocol.md
- src/contract/openapi/routes/index.ts
- src/contract/openapi/routes/postApiV1AgentV1Message.ts
- src/contract/tags.ts
- src/core/migration-pins/20261206100000-agent-use.pin
- src/core/migrations/20261206100000-agent-use.ts
- src/games/agent.sh
- src/generated/marks.ts
- src/http/api.ts
- src/http/api/agent_v1.ts
- src/http/api/runners.ts
- src/http/games_routes.ts
- src/http/lazy_lists.ts
- src/http/marks/api-v1-agent.json
- src/machines/agent_use.ts
- src/machines/protocol.ts
- src/runner/main.ts
- test/agent-protocol.test.ts
- test/game-boot.test.ts
- test/game-lend-box.test.ts
- test/helpers/agent-v1.ts
- test/runner-end-lines.test.ts
- test/runner-upgrade.test.ts
docs/features/agent-protocol.md added +31
| @@ -0,0 +1,31 @@ | ||
| 1 | --- | |
| 2 | topic: Ship and undo | |
| 3 | row: Agent protocol: one versioned door (heartbeat, claim, logs, result, containers) for a box, a runner or a lender, with tokens held to their role | |
| 4 | --- | |
| 5 | # The agent protocol (#18457) | |
| 6 | ||
| 7 | Any machine that does the forge's work speaks one protocol: `POST /api/v1/agent/v1/<message>` with a | |
| 8 | JSON body carrying `"v": 1`. `src/machines/protocol.ts` defines and validates the five messages. | |
| 9 | ||
| 10 | | message | who | body | | |
| 11 | | --- | --- | --- | | |
| 12 | | `heartbeat` | box, runner, lender, helper | a box: its sync as before; the others `{ state: idle\|busy\|paused }` | | |
| 13 | | `claim` | runner, lender | `{ wait, cells, jobs, machine }`: a job, or 204 | | |
| 14 | | `logs` | box, runner, lender | a runner: `{ job, lines, step }` (no lines renews the lease); a box: its `logs` | | |
| 15 | | `result` | box, runner, lender | a runner: `{ job, done \| abandon \| interrupted }`; a box: its command `results` | | |
| 16 | | `containers` | box | its `services`, `metrics`, `host`, `diag` | | |
| 17 | ||
| 18 | A token has a role (`fgb_…` box, `forge_runner_…` runner, a lent one lender). A message outside the | |
| 19 | role is a 403 `wrong_role` that names it; a `v` other than 1 is a 400 `bad_version`; a body the message does not take is a 400/422 `invalid_heartbeat`, `invalid_claim`, `invalid_logs`, `invalid_result`, `invalid_containers` or `invalid_message`. | |
| 20 | ||
| 21 | The box agent (`src/games/agent.sh`) sends its sync as `heartbeat`; the runner (`src/runner`) claims | |
| 22 | and reports through `claim`, `logs` and `result`. `POST /api/v1/games/agent/sync` and | |
| 23 | `/api/v1/runner/…` answer as before (version 0): an agent already deployed keeps working. The forge | |
| 24 | keeps the last use of each version per machine (version 0 is recorded only for a request that arrives at the old path: the box sync, a runner's heartbeat, claim and job report; version 1 traffic is never counted as 0) (`agent_use`, `lastUse` in `src/machines/agent_use.ts`); | |
| 25 | the old routes go when no machine used version 0 for 30 days, not before. | |
| 26 | ||
| 27 | A runner's report is two messages (`logs`, then `result`). If `logs` lands and `result` times out, the retry resends the same lines; nothing dedupes them, as the job log is append-only and read by line. | |
| 28 | ||
| 29 | Not yet: the helper role has no token minted, and a box's `logs`, `result` and `containers` are the | |
| 30 | sync cut down to their fields, not separate calls the agent makes. Terminal door: the existing | |
| 31 | runners and games screens (`src/tui/screens/`) show the same machines. |
src/contract/openapi/routes/index.ts +1
| @@ -378,6 +378,7 @@ export { route as postApiV1AdminRunnersIdPause } from "./postApiV1AdminRunnersId | ||
| 378 | 378 | export { route as postApiV1AdminRunnersIdResume } from "./postApiV1AdminRunnersIdResume.ts"; |
| 379 | 379 | export { route as postApiV1AdminRunnersIdRevoke } from "./postApiV1AdminRunnersIdRevoke.ts"; |
| 380 | 380 | export { route as postApiV1AdminRunnersIdTrust } from "./postApiV1AdminRunnersIdTrust.ts"; |
| 381 | export { route as postApiV1AgentV1Message } from "./postApiV1AgentV1Message.ts"; | |
| 381 | 382 | export { route as postApiV1Agents } from "./postApiV1Agents.ts"; |
| 382 | 383 | export { route as postApiV1Apps } from "./postApiV1Apps.ts"; |
| 383 | 384 | export { route as postApiV1AppsOwnerNameCrashReports } from "./postApiV1AppsOwnerNameCrashReports.ts"; |
src/contract/openapi/routes/postApiV1AgentV1Message.ts added +23
| @@ -0,0 +1,23 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "post", | |
| 5 | path: "/api/v1/agent/v1/{message}", | |
| 6 | summary: "One message of the agent protocol (version 1): a box, runner or lender token", | |
| 7 | detail: | |
| 8 | "The one door of any machine that does the forge's work (`machines/protocol.ts`). Every body carries `v: 1`; another version is a 400 `bad_version` saying which this forge speaks. The bearer's token has a role (box, runner, lender) and each role may send only some messages: a token used for another is a 403 `wrong_role` naming the role. A box sends heartbeat (its sync), logs, result and containers; a runner or lender sends heartbeat { state }, claim { wait, cells, jobs, machine }, logs { job, lines, step } and result { job, done | abandon | interrupted }. The old `/api/v1/games/agent/sync` still answers as version 0 and `/api/v1/runner/…` as before; the forge records the last use of each version per machine", | |
| 9 | auth: false, | |
| 10 | role: "anonymous", | |
| 11 | body: { v: "number" }, | |
| 12 | refusals: { | |
| 13 | bad_version: "400: v is not 1", | |
| 14 | wrong_role: "403: the token's role may not send this message; the answer names the role", | |
| 15 | unauthorized: "401: not a token this forge knows", | |
| 16 | invalid_heartbeat: "422: a heartbeat's fields are not what is asked", | |
| 17 | invalid_claim: "422: a claim's fields are not what is asked", | |
| 18 | invalid_logs: "422: logs are a job id and at most 5000 lines", | |
| 19 | invalid_result: "422: a result is a job id and one of done, abandon or interrupted", | |
| 20 | }, | |
| 21 | refuses: [404], | |
| 22 | errorStatus: { 400: "`bad_version`: this forge speaks version 1", 403: "`wrong_role`: the token's role may not send this message" }, | |
| 23 | }; |
src/contract/tags.ts +1
src/core/migration-pins/20261206100000-agent-use.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | d28ca734030ababf56bf9f2598db492f50b3bcb2fb9ccd5f4edff59725f46b90 |
src/core/migrations/20261206100000-agent-use.ts added +12
| @@ -0,0 +1,12 @@ | ||
| 1 | // The last time each machine spoke each version of the agent protocol (#18457): `version` 0 is the | |
| 2 | // old `/api/v1/games/agent/sync`, so "no machine used version 0 for 30 days" is a query, not a | |
| 3 | // guess. One row a machine and version, written at most once a minute. Additive: a new table. | |
| 4 | export default ` | |
| 5 | CREATE TABLE IF NOT EXISTS agent_use ( | |
| 6 | machine TEXT NOT NULL, | |
| 7 | role TEXT NOT NULL, | |
| 8 | version INTEGER NOT NULL, | |
| 9 | last_at INTEGER NOT NULL, | |
| 10 | PRIMARY KEY (machine, version) | |
| 11 | ); | |
| 12 | `; |
src/games/agent.sh +6 −6
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | #!/usr/bin/env bash |
| 2 | 2 | # forge-game-agent (forge games, 2026-11-30): keeps a game box's Docker Compose project as the forge |
| 3 | 3 | # says. Every 5 s it POSTs what runs (services, stats, new log lines, command results, the host) to |
| 4 | # $FORGE_URL/api/v1/games/agent/sync with the box's bearer token, and does what the answer asks: | |
| 4 | # $FORGE_URL/api/v1/agent/v1/heartbeat (protocol 1; the old /api/v1/games/agent/sync answers version 0) with the box's bearer token, and does what the answer asks: | |
| 5 | 5 | # writes compose.yml and the secret env files beside it and brings the project up when the compose |
| 6 | 6 | # sha (or an env file) changes, and runs the queued commands. Nothing dials in to the box. A failed |
| 7 | 7 | # sync waits 5 s and tries again, forever. The token is read from the environment (systemd's |
| @@ -101,7 +101,7 @@ boot_status() { | ||
| 101 | 101 | # One word to the forge with a body built without jq; never fails the caller. |
| 102 | 102 | say_boot() { |
| 103 | 103 | curl -fsS -m 20 -H "@" -H 'content-type: application/json' \ |
| 104 | --data-binary "{\"agent\":1,\"boot\":$(json_str "")}" "/api/v1/games/agent/sync" >/dev/null 2>&1 || true | |
| 104 | --data-binary "{\"agent\":1,\"v\":1,\"boot\":$(json_str "")}" "/api/v1/agent/v1/heartbeat" >/dev/null 2>&1 || true | |
| 105 | 105 | } |
| 106 | 106 | |
| 107 | 107 | # ---- the box's data volume (2026-12-01: box mc's worlds sat on the root disk, which a replace |
| @@ -1742,12 +1742,12 @@ sync() { | ||
| 1742 | 1742 | else [.[0]] + (.[1:] | codes) end; |
| 1743 | 1743 | (if . == "" then ["0"] else split(";") end) | [codes[] | [.] // empty | "\u00a7" + .] | join(""); |
| 1744 | 1744 | def plain: gsub("\u001b\\[(?<p>[0-9;]*)m"; (.p // "" | sect)) | gsub("^(\u00a7r)+|(\u00a7r)+$"; "") | gsub("(\u00a7r)+"; "\u00a7r") | gsub("\u001b\\[[0-9;?]*[ -/]*[@-~]"; "") | gsub("\u001b[@-_]?"; "") | gsub("[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f]"; ""); |
| 1745 | {agent: 1, composeSha: , services: [0], logs: [0], results: [0], host: [0], diag: [0], people: [0], metrics: [0], snapshots: [0], chat: [0].lines, chatId: [0].id, lend: , lendWhy: , retry: , jars: true, got: } | |
| 1745 | {agent: 1, v: 1, composeSha: , services: [0], logs: [0], results: [0], host: [0], diag: [0], people: [0], metrics: [0], snapshots: [0], chat: [0].lines, chatId: [0].id, lend: , lendWhy: , retry: , jars: true, got: } | |
| 1746 | 1746 | + (if == "" then {} else {tokenSha: } end) |
| 1747 | 1747 | + (if [0] == [] then {} else {ask: [0]} end) |
| 1748 | 1748 | | walk(if type == "string" then plain else . end)' >"$DIR/.sync.body" || return 1 |
| 1749 | 1749 | # The answer is never a file: it can carry a world's signed link. Its status is its last line. |
| 1750 | answer="$(curl -sS -m 20 -H "@" -H 'content-type: application/json' --data-binary "@/.sync.body" -w '\n%{http_code}' "/api/v1/games/agent/sync")" || answer=$'\nnothing' | |
| 1750 | answer="$(curl -sS -m 20 -H "@" -H 'content-type: application/json' --data-binary "@/.sync.body" -w '\n%{http_code}' "/api/v1/agent/v1/heartbeat")" || answer=$'\nnothing' | |
| 1751 | 1751 | code="" |
| 1752 | 1752 | answer="" |
| 1753 | 1753 | if [[ "" != 2?? ]]; then |
| @@ -2232,8 +2232,8 @@ light_sync() { | ||
| 2232 | 2232 | if [ -f "/.desk.due" ] && desk_here; then desk_take; else rm -f "/.desk.due"; echo '[]' >"/.sync.ask"; fi |
| 2233 | 2233 | json_or '[]' <"/.results" >"/.sync.results" |
| 2234 | 2234 | jq -cn --slurpfile ask "/.sync.ask" --arg sha "$(cat "/.compose-sha" 2>/dev/null)" --slurpfile results "/.sync.results" --argjson told "$(desk_here && echo true || echo false)" --argjson got "$(desk_got)" --arg deskv "$(cat "/.desk.v" 2>/dev/null)" \ |
| 2235 | '{agent: 1, light: true, composeSha: $sha, results: $results[0], got: $got} + (if $told then {told: true, desk: {v: $deskv}} else {} end) + (if $ask[0] == [] then {} else {ask: $ask[0]} end)' >"/.sync.light" || return 1 | |
| 2236 | answer="$(curl -fsS -m 5 -H "@" -H 'content-type: application/json' --data-binary "@/.sync.light" "/api/v1/games/agent/sync")" || { desk_again; return 1; } | |
| 2235 | '{agent: 1, v: 1, light: true, composeSha: $sha, results: $results[0], got: $got} + (if $told then {told: true, desk: {v: $deskv}} else {} end) + (if $ask[0] == [] then {} else {ask: $ask[0]} end)' >"/.sync.light" || return 1 | |
| 2236 | answer="$(curl -fsS -m 5 -H "@" -H 'content-type: application/json' --data-binary "@/.sync.light" "/api/v1/agent/v1/heartbeat")" || { desk_again; return 1; } | |
| 2237 | 2237 | echo '[]' >"/.results" |
| 2238 | 2238 | desk_heard "/.sync.light" |
| 2239 | 2239 | desk_told "" |
src/generated/marks.ts +214 −212
| @@ -8,218 +8,219 @@ import k3 from "../http/marks/api-project-envelope.json"; | ||
| 8 | 8 | import k4 from "../http/marks/api-project-otlp.json"; |
| 9 | 9 | import k5 from "../http/marks/api-traces.json"; |
| 10 | 10 | import k6 from "../http/marks/api-v1-admin.json"; |
| 11 | import k7 from "../http/marks/api-v1-agents.json"; | |
| 12 | import k8 from "../http/marks/api-v1-app-templates.json"; | |
| 13 | import k9 from "../http/marks/api-v1-apps.json"; | |
| 14 | import k10 from "../http/marks/api-v1-arcade.json"; | |
| 15 | import k11 from "../http/marks/api-v1-asks.json"; | |
| 16 | import k12 from "../http/marks/api-v1-boards.json"; | |
| 17 | import k13 from "../http/marks/api-v1-broker.json"; | |
| 18 | import k14 from "../http/marks/api-v1-builds.json"; | |
| 19 | import k15 from "../http/marks/api-v1-cache.json"; | |
| 20 | import k16 from "../http/marks/api-v1-changelog.json"; | |
| 21 | import k17 from "../http/marks/api-v1-cloud.json"; | |
| 22 | import k18 from "../http/marks/api-v1-codes.json"; | |
| 23 | import k19 from "../http/marks/api-v1-config.json"; | |
| 24 | import k20 from "../http/marks/api-v1-connections.json"; | |
| 25 | import k21 from "../http/marks/api-v1-contribute.json"; | |
| 26 | import k22 from "../http/marks/api-v1-conversation-confirms.json"; | |
| 27 | import k23 from "../http/marks/api-v1-conversation-tokens.json"; | |
| 28 | import k24 from "../http/marks/api-v1-conversation.json"; | |
| 29 | import k25 from "../http/marks/api-v1-conversations.json"; | |
| 30 | import k26 from "../http/marks/api-v1-credit.json"; | |
| 31 | import k27 from "../http/marks/api-v1-crew.json"; | |
| 32 | import k28 from "../http/marks/api-v1-devices.json"; | |
| 33 | import k29 from "../http/marks/api-v1-drills.json"; | |
| 34 | import k30 from "../http/marks/api-v1-explore.json"; | |
| 35 | import k31 from "../http/marks/api-v1-family.json"; | |
| 36 | import k32 from "../http/marks/api-v1-features.json"; | |
| 37 | import k33 from "../http/marks/api-v1-feed.json"; | |
| 38 | import k34 from "../http/marks/api-v1-first-admin.json"; | |
| 39 | import k35 from "../http/marks/api-v1-flags.json"; | |
| 40 | import k36 from "../http/marks/api-v1-fleet.json"; | |
| 41 | import k37 from "../http/marks/api-v1-flow.json"; | |
| 42 | import k38 from "../http/marks/api-v1-forge-templates.json"; | |
| 43 | import k39 from "../http/marks/api-v1-forge.json"; | |
| 44 | import k40 from "../http/marks/api-v1-forges.json"; | |
| 45 | import k41 from "../http/marks/api-v1-forks.json"; | |
| 46 | import k42 from "../http/marks/api-v1-front.json"; | |
| 47 | import k43 from "../http/marks/api-v1-games.json"; | |
| 48 | import k44 from "../http/marks/api-v1-health.json"; | |
| 49 | import k45 from "../http/marks/api-v1-heartbeat.json"; | |
| 50 | import k46 from "../http/marks/api-v1-here.json"; | |
| 51 | import k47 from "../http/marks/api-v1-home.json"; | |
| 52 | import k48 from "../http/marks/api-v1-identities.json"; | |
| 53 | import k49 from "../http/marks/api-v1-keeper.json"; | |
| 54 | import k50 from "../http/marks/api-v1-mail-aws.json"; | |
| 55 | import k51 from "../http/marks/api-v1-mail-key.json"; | |
| 56 | import k52 from "../http/marks/api-v1-maintenance.json"; | |
| 57 | import k53 from "../http/marks/api-v1-map.json"; | |
| 58 | import k54 from "../http/marks/api-v1-may.json"; | |
| 59 | import k55 from "../http/marks/api-v1-migrate.json"; | |
| 60 | import k56 from "../http/marks/api-v1-models.json"; | |
| 61 | import k57 from "../http/marks/api-v1-offers.json"; | |
| 62 | import k58 from "../http/marks/api-v1-openapi.json.json"; | |
| 63 | import k59 from "../http/marks/api-v1-orgs.json"; | |
| 64 | import k60 from "../http/marks/api-v1-packs.json"; | |
| 65 | import k61 from "../http/marks/api-v1-passport.json"; | |
| 66 | import k62 from "../http/marks/api-v1-places.json"; | |
| 67 | import k63 from "../http/marks/api-v1-plans.json"; | |
| 68 | import k64 from "../http/marks/api-v1-proof.json"; | |
| 69 | import k65 from "../http/marks/api-v1-reach.json"; | |
| 70 | import k66 from "../http/marks/api-v1-release.json"; | |
| 71 | import k67 from "../http/marks/api-v1-releases.json"; | |
| 72 | import k68 from "../http/marks/api-v1-repos.json"; | |
| 73 | import k69 from "../http/marks/api-v1-returns.json"; | |
| 74 | import k70 from "../http/marks/api-v1-runner.json"; | |
| 75 | import k71 from "../http/marks/api-v1-search.json"; | |
| 76 | import k72 from "../http/marks/api-v1-secrets.json"; | |
| 77 | import k73 from "../http/marks/api-v1-sessions.json"; | |
| 78 | import k74 from "../http/marks/api-v1-share.json"; | |
| 79 | import k75 from "../http/marks/api-v1-slash.json"; | |
| 80 | import k76 from "../http/marks/api-v1-start.json"; | |
| 81 | import k77 from "../http/marks/api-v1-status.json"; | |
| 82 | import k78 from "../http/marks/api-v1-telemetry.json"; | |
| 83 | import k79 from "../http/marks/api-v1-templates.json"; | |
| 84 | import k80 from "../http/marks/api-v1-thoughts.json"; | |
| 85 | import k81 from "../http/marks/api-v1-timers.json"; | |
| 86 | import k82 from "../http/marks/api-v1-tokens.json"; | |
| 87 | import k83 from "../http/marks/api-v1-usage.json"; | |
| 88 | import k84 from "../http/marks/api-v1-user.json"; | |
| 89 | import k85 from "../http/marks/api-v1-users.json"; | |
| 90 | import k86 from "../http/marks/api-v1-version.json"; | |
| 91 | import k87 from "../http/marks/api-v1.json"; | |
| 92 | import k88 from "../http/marks/api.json"; | |
| 93 | import k89 from "../http/marks/apple-touch-icon-precomposed.png.json"; | |
| 94 | import k90 from "../http/marks/apple-touch-icon.png.json"; | |
| 95 | import k91 from "../http/marks/apps.json"; | |
| 96 | import k92 from "../http/marks/archive.json"; | |
| 97 | import k93 from "../http/marks/asked.json"; | |
| 98 | import k94 from "../http/marks/asks.json"; | |
| 99 | import k95 from "../http/marks/assets.json"; | |
| 100 | import k96 from "../http/marks/audit.csv.json"; | |
| 101 | import k97 from "../http/marks/audit.json"; | |
| 102 | import k98 from "../http/marks/big.json"; | |
| 103 | import k99 from "../http/marks/board.json"; | |
| 104 | import k100 from "../http/marks/boards.json"; | |
| 105 | import k101 from "../http/marks/bring.json"; | |
| 106 | import k102 from "../http/marks/broker.json"; | |
| 107 | import k103 from "../http/marks/changelog.atom.json"; | |
| 108 | import k104 from "../http/marks/changelog.json"; | |
| 109 | import k105 from "../http/marks/claim.json"; | |
| 110 | import k106 from "../http/marks/client-clouds.json"; | |
| 111 | import k107 from "../http/marks/cloud.json"; | |
| 112 | import k108 from "../http/marks/cockpit.json"; | |
| 113 | import k109 from "../http/marks/contract.json"; | |
| 114 | import k110 from "../http/marks/contribute.json"; | |
| 115 | import k111 from "../http/marks/csp-report.json"; | |
| 116 | import k112 from "../http/marks/dash.json"; | |
| 117 | import k113 from "../http/marks/data.json"; | |
| 118 | import k114 from "../http/marks/dataset.json"; | |
| 119 | import k115 from "../http/marks/deploy-to.json"; | |
| 120 | import k116 from "../http/marks/design.json"; | |
| 121 | import k117 from "../http/marks/desk.json"; | |
| 122 | import k118 from "../http/marks/displays.json"; | |
| 123 | import k119 from "../http/marks/docs.json"; | |
| 124 | import k120 from "../http/marks/edge.json"; | |
| 125 | import k121 from "../http/marks/edition.json"; | |
| 126 | import k122 from "../http/marks/events.json"; | |
| 127 | import k123 from "../http/marks/explore.atom.json"; | |
| 128 | import k124 from "../http/marks/explore.json"; | |
| 129 | import k125 from "../http/marks/explore.json.json"; | |
| 130 | import k126 from "../http/marks/family.json"; | |
| 131 | import k127 from "../http/marks/favicon.ico.json"; | |
| 132 | import k128 from "../http/marks/feed.json"; | |
| 133 | import k129 from "../http/marks/feed.json.json"; | |
| 134 | import k130 from "../http/marks/first-admin.json"; | |
| 135 | import k131 from "../http/marks/fleet.json"; | |
| 136 | import k132 from "../http/marks/flow.json"; | |
| 137 | import k133 from "../http/marks/forge.json"; | |
| 138 | import k134 from "../http/marks/forges.json"; | |
| 139 | import k135 from "../http/marks/forks.json"; | |
| 140 | import k136 from "../http/marks/front.json"; | |
| 141 | import k137 from "../http/marks/funnel.json"; | |
| 142 | import k138 from "../http/marks/games.json"; | |
| 143 | import k139 from "../http/marks/go.json"; | |
| 144 | import k140 from "../http/marks/health.json"; | |
| 145 | import k141 from "../http/marks/home.json"; | |
| 146 | import k142 from "../http/marks/hooks.json"; | |
| 147 | import k143 from "../http/marks/icons.json"; | |
| 148 | import k144 from "../http/marks/infra.json"; | |
| 149 | import k145 from "../http/marks/join.json"; | |
| 150 | import k146 from "../http/marks/live.json"; | |
| 151 | import k147 from "../http/marks/llms-full.txt.json"; | |
| 152 | import k148 from "../http/marks/llms.txt.json"; | |
| 153 | import k149 from "../http/marks/login.json"; | |
| 154 | import k150 from "../http/marks/logout.json"; | |
| 155 | import k151 from "../http/marks/maintenance-json.json"; | |
| 156 | import k152 from "../http/marks/maintenance.json"; | |
| 157 | import k153 from "../http/marks/manifest.webmanifest.json"; | |
| 158 | import k154 from "../http/marks/map.json"; | |
| 159 | import k155 from "../http/marks/mcp.json"; | |
| 160 | import k156 from "../http/marks/measure.json"; | |
| 161 | import k157 from "../http/marks/metrics.json"; | |
| 162 | import k158 from "../http/marks/migrate.json"; | |
| 163 | import k159 from "../http/marks/new.json"; | |
| 164 | import k160 from "../http/marks/next.json"; | |
| 165 | import k161 from "../http/marks/notes.json"; | |
| 166 | import k162 from "../http/marks/now.json"; | |
| 167 | import k163 from "../http/marks/oauth.json"; | |
| 168 | import k164 from "../http/marks/oembed.json"; | |
| 169 | import k165 from "../http/marks/offers.json"; | |
| 170 | import k166 from "../http/marks/offline.json"; | |
| 171 | import k167 from "../http/marks/og.json"; | |
| 172 | import k168 from "../http/marks/openapi.json.json"; | |
| 173 | import k169 from "../http/marks/opensearch.xml.json"; | |
| 174 | import k170 from "../http/marks/organizations.json"; | |
| 175 | import k171 from "../http/marks/origins.json"; | |
| 176 | import k172 from "../http/marks/owner.atom.json"; | |
| 177 | import k173 from "../http/marks/owner.json"; | |
| 178 | import k174 from "../http/marks/packs.json"; | |
| 179 | import k175 from "../http/marks/peek.json"; | |
| 180 | import k176 from "../http/marks/pinned.json"; | |
| 181 | import k177 from "../http/marks/pipeline.json"; | |
| 182 | import k178 from "../http/marks/plugins.json"; | |
| 183 | import k179 from "../http/marks/pricing.json"; | |
| 184 | import k180 from "../http/marks/privacy.json"; | |
| 185 | import k181 from "../http/marks/r.json"; | |
| 186 | import k182 from "../http/marks/recover.json"; | |
| 187 | import k183 from "../http/marks/releases.json"; | |
| 188 | import k184 from "../http/marks/releases.json.json"; | |
| 189 | import k185 from "../http/marks/repos.json"; | |
| 190 | import k186 from "../http/marks/resilience.json"; | |
| 191 | import k187 from "../http/marks/review.json"; | |
| 192 | import k188 from "../http/marks/robots.txt.json"; | |
| 193 | import k189 from "../http/marks/root.json"; | |
| 194 | import k190 from "../http/marks/runs.json"; | |
| 195 | import k191 from "../http/marks/script-error.json"; | |
| 196 | import k192 from "../http/marks/search.json"; | |
| 197 | import k193 from "../http/marks/security.json"; | |
| 198 | import k194 from "../http/marks/settings.json"; | |
| 199 | import k195 from "../http/marks/sign-in.json"; | |
| 200 | import k196 from "../http/marks/signin.json"; | |
| 201 | import k197 from "../http/marks/signup.json"; | |
| 202 | import k198 from "../http/marks/sitemap.xml.json"; | |
| 203 | import k199 from "../http/marks/status.json"; | |
| 204 | import k200 from "../http/marks/support.json"; | |
| 205 | import k201 from "../http/marks/sw.js.json"; | |
| 206 | import k202 from "../http/marks/system.json"; | |
| 207 | import k203 from "../http/marks/tab.json"; | |
| 208 | import k204 from "../http/marks/tabforge-link.json"; | |
| 209 | import k205 from "../http/marks/tabforge-move.json"; | |
| 210 | import k206 from "../http/marks/tabforge.json"; | |
| 211 | import k207 from "../http/marks/talk.json"; | |
| 212 | import k208 from "../http/marks/tell.json"; | |
| 213 | import k209 from "../http/marks/templates.json"; | |
| 214 | import k210 from "../http/marks/templates.json.json"; | |
| 215 | import k211 from "../http/marks/terms.json"; | |
| 216 | import k212 from "../http/marks/theme.json"; | |
| 217 | import k213 from "../http/marks/toolbar-lab.js.json"; | |
| 218 | import k214 from "../http/marks/toolbar-lab.json"; | |
| 219 | import k215 from "../http/marks/traces.json"; | |
| 220 | import k216 from "../http/marks/verify.json"; | |
| 221 | import k217 from "../http/marks/welcome.json"; | |
| 222 | import k218 from "../http/marks/well-known.json"; | |
| 11 | import k7 from "../http/marks/api-v1-agent.json"; | |
| 12 | import k8 from "../http/marks/api-v1-agents.json"; | |
| 13 | import k9 from "../http/marks/api-v1-app-templates.json"; | |
| 14 | import k10 from "../http/marks/api-v1-apps.json"; | |
| 15 | import k11 from "../http/marks/api-v1-arcade.json"; | |
| 16 | import k12 from "../http/marks/api-v1-asks.json"; | |
| 17 | import k13 from "../http/marks/api-v1-boards.json"; | |
| 18 | import k14 from "../http/marks/api-v1-broker.json"; | |
| 19 | import k15 from "../http/marks/api-v1-builds.json"; | |
| 20 | import k16 from "../http/marks/api-v1-cache.json"; | |
| 21 | import k17 from "../http/marks/api-v1-changelog.json"; | |
| 22 | import k18 from "../http/marks/api-v1-cloud.json"; | |
| 23 | import k19 from "../http/marks/api-v1-codes.json"; | |
| 24 | import k20 from "../http/marks/api-v1-config.json"; | |
| 25 | import k21 from "../http/marks/api-v1-connections.json"; | |
| 26 | import k22 from "../http/marks/api-v1-contribute.json"; | |
| 27 | import k23 from "../http/marks/api-v1-conversation-confirms.json"; | |
| 28 | import k24 from "../http/marks/api-v1-conversation-tokens.json"; | |
| 29 | import k25 from "../http/marks/api-v1-conversation.json"; | |
| 30 | import k26 from "../http/marks/api-v1-conversations.json"; | |
| 31 | import k27 from "../http/marks/api-v1-credit.json"; | |
| 32 | import k28 from "../http/marks/api-v1-crew.json"; | |
| 33 | import k29 from "../http/marks/api-v1-devices.json"; | |
| 34 | import k30 from "../http/marks/api-v1-drills.json"; | |
| 35 | import k31 from "../http/marks/api-v1-explore.json"; | |
| 36 | import k32 from "../http/marks/api-v1-family.json"; | |
| 37 | import k33 from "../http/marks/api-v1-features.json"; | |
| 38 | import k34 from "../http/marks/api-v1-feed.json"; | |
| 39 | import k35 from "../http/marks/api-v1-first-admin.json"; | |
| 40 | import k36 from "../http/marks/api-v1-flags.json"; | |
| 41 | import k37 from "../http/marks/api-v1-fleet.json"; | |
| 42 | import k38 from "../http/marks/api-v1-flow.json"; | |
| 43 | import k39 from "../http/marks/api-v1-forge-templates.json"; | |
| 44 | import k40 from "../http/marks/api-v1-forge.json"; | |
| 45 | import k41 from "../http/marks/api-v1-forges.json"; | |
| 46 | import k42 from "../http/marks/api-v1-forks.json"; | |
| 47 | import k43 from "../http/marks/api-v1-front.json"; | |
| 48 | import k44 from "../http/marks/api-v1-games.json"; | |
| 49 | import k45 from "../http/marks/api-v1-health.json"; | |
| 50 | import k46 from "../http/marks/api-v1-heartbeat.json"; | |
| 51 | import k47 from "../http/marks/api-v1-here.json"; | |
| 52 | import k48 from "../http/marks/api-v1-home.json"; | |
| 53 | import k49 from "../http/marks/api-v1-identities.json"; | |
| 54 | import k50 from "../http/marks/api-v1-keeper.json"; | |
| 55 | import k51 from "../http/marks/api-v1-mail-aws.json"; | |
| 56 | import k52 from "../http/marks/api-v1-mail-key.json"; | |
| 57 | import k53 from "../http/marks/api-v1-maintenance.json"; | |
| 58 | import k54 from "../http/marks/api-v1-map.json"; | |
| 59 | import k55 from "../http/marks/api-v1-may.json"; | |
| 60 | import k56 from "../http/marks/api-v1-migrate.json"; | |
| 61 | import k57 from "../http/marks/api-v1-models.json"; | |
| 62 | import k58 from "../http/marks/api-v1-offers.json"; | |
| 63 | import k59 from "../http/marks/api-v1-openapi.json.json"; | |
| 64 | import k60 from "../http/marks/api-v1-orgs.json"; | |
| 65 | import k61 from "../http/marks/api-v1-packs.json"; | |
| 66 | import k62 from "../http/marks/api-v1-passport.json"; | |
| 67 | import k63 from "../http/marks/api-v1-places.json"; | |
| 68 | import k64 from "../http/marks/api-v1-plans.json"; | |
| 69 | import k65 from "../http/marks/api-v1-proof.json"; | |
| 70 | import k66 from "../http/marks/api-v1-reach.json"; | |
| 71 | import k67 from "../http/marks/api-v1-release.json"; | |
| 72 | import k68 from "../http/marks/api-v1-releases.json"; | |
| 73 | import k69 from "../http/marks/api-v1-repos.json"; | |
| 74 | import k70 from "../http/marks/api-v1-returns.json"; | |
| 75 | import k71 from "../http/marks/api-v1-runner.json"; | |
| 76 | import k72 from "../http/marks/api-v1-search.json"; | |
| 77 | import k73 from "../http/marks/api-v1-secrets.json"; | |
| 78 | import k74 from "../http/marks/api-v1-sessions.json"; | |
| 79 | import k75 from "../http/marks/api-v1-share.json"; | |
| 80 | import k76 from "../http/marks/api-v1-slash.json"; | |
| 81 | import k77 from "../http/marks/api-v1-start.json"; | |
| 82 | import k78 from "../http/marks/api-v1-status.json"; | |
| 83 | import k79 from "../http/marks/api-v1-telemetry.json"; | |
| 84 | import k80 from "../http/marks/api-v1-templates.json"; | |
| 85 | import k81 from "../http/marks/api-v1-thoughts.json"; | |
| 86 | import k82 from "../http/marks/api-v1-timers.json"; | |
| 87 | import k83 from "../http/marks/api-v1-tokens.json"; | |
| 88 | import k84 from "../http/marks/api-v1-usage.json"; | |
| 89 | import k85 from "../http/marks/api-v1-user.json"; | |
| 90 | import k86 from "../http/marks/api-v1-users.json"; | |
| 91 | import k87 from "../http/marks/api-v1-version.json"; | |
| 92 | import k88 from "../http/marks/api-v1.json"; | |
| 93 | import k89 from "../http/marks/api.json"; | |
| 94 | import k90 from "../http/marks/apple-touch-icon-precomposed.png.json"; | |
| 95 | import k91 from "../http/marks/apple-touch-icon.png.json"; | |
| 96 | import k92 from "../http/marks/apps.json"; | |
| 97 | import k93 from "../http/marks/archive.json"; | |
| 98 | import k94 from "../http/marks/asked.json"; | |
| 99 | import k95 from "../http/marks/asks.json"; | |
| 100 | import k96 from "../http/marks/assets.json"; | |
| 101 | import k97 from "../http/marks/audit.csv.json"; | |
| 102 | import k98 from "../http/marks/audit.json"; | |
| 103 | import k99 from "../http/marks/big.json"; | |
| 104 | import k100 from "../http/marks/board.json"; | |
| 105 | import k101 from "../http/marks/boards.json"; | |
| 106 | import k102 from "../http/marks/bring.json"; | |
| 107 | import k103 from "../http/marks/broker.json"; | |
| 108 | import k104 from "../http/marks/changelog.atom.json"; | |
| 109 | import k105 from "../http/marks/changelog.json"; | |
| 110 | import k106 from "../http/marks/claim.json"; | |
| 111 | import k107 from "../http/marks/client-clouds.json"; | |
| 112 | import k108 from "../http/marks/cloud.json"; | |
| 113 | import k109 from "../http/marks/cockpit.json"; | |
| 114 | import k110 from "../http/marks/contract.json"; | |
| 115 | import k111 from "../http/marks/contribute.json"; | |
| 116 | import k112 from "../http/marks/csp-report.json"; | |
| 117 | import k113 from "../http/marks/dash.json"; | |
| 118 | import k114 from "../http/marks/data.json"; | |
| 119 | import k115 from "../http/marks/dataset.json"; | |
| 120 | import k116 from "../http/marks/deploy-to.json"; | |
| 121 | import k117 from "../http/marks/design.json"; | |
| 122 | import k118 from "../http/marks/desk.json"; | |
| 123 | import k119 from "../http/marks/displays.json"; | |
| 124 | import k120 from "../http/marks/docs.json"; | |
| 125 | import k121 from "../http/marks/edge.json"; | |
| 126 | import k122 from "../http/marks/edition.json"; | |
| 127 | import k123 from "../http/marks/events.json"; | |
| 128 | import k124 from "../http/marks/explore.atom.json"; | |
| 129 | import k125 from "../http/marks/explore.json"; | |
| 130 | import k126 from "../http/marks/explore.json.json"; | |
| 131 | import k127 from "../http/marks/family.json"; | |
| 132 | import k128 from "../http/marks/favicon.ico.json"; | |
| 133 | import k129 from "../http/marks/feed.json"; | |
| 134 | import k130 from "../http/marks/feed.json.json"; | |
| 135 | import k131 from "../http/marks/first-admin.json"; | |
| 136 | import k132 from "../http/marks/fleet.json"; | |
| 137 | import k133 from "../http/marks/flow.json"; | |
| 138 | import k134 from "../http/marks/forge.json"; | |
| 139 | import k135 from "../http/marks/forges.json"; | |
| 140 | import k136 from "../http/marks/forks.json"; | |
| 141 | import k137 from "../http/marks/front.json"; | |
| 142 | import k138 from "../http/marks/funnel.json"; | |
| 143 | import k139 from "../http/marks/games.json"; | |
| 144 | import k140 from "../http/marks/go.json"; | |
| 145 | import k141 from "../http/marks/health.json"; | |
| 146 | import k142 from "../http/marks/home.json"; | |
| 147 | import k143 from "../http/marks/hooks.json"; | |
| 148 | import k144 from "../http/marks/icons.json"; | |
| 149 | import k145 from "../http/marks/infra.json"; | |
| 150 | import k146 from "../http/marks/join.json"; | |
| 151 | import k147 from "../http/marks/live.json"; | |
| 152 | import k148 from "../http/marks/llms-full.txt.json"; | |
| 153 | import k149 from "../http/marks/llms.txt.json"; | |
| 154 | import k150 from "../http/marks/login.json"; | |
| 155 | import k151 from "../http/marks/logout.json"; | |
| 156 | import k152 from "../http/marks/maintenance-json.json"; | |
| 157 | import k153 from "../http/marks/maintenance.json"; | |
| 158 | import k154 from "../http/marks/manifest.webmanifest.json"; | |
| 159 | import k155 from "../http/marks/map.json"; | |
| 160 | import k156 from "../http/marks/mcp.json"; | |
| 161 | import k157 from "../http/marks/measure.json"; | |
| 162 | import k158 from "../http/marks/metrics.json"; | |
| 163 | import k159 from "../http/marks/migrate.json"; | |
| 164 | import k160 from "../http/marks/new.json"; | |
| 165 | import k161 from "../http/marks/next.json"; | |
| 166 | import k162 from "../http/marks/notes.json"; | |
| 167 | import k163 from "../http/marks/now.json"; | |
| 168 | import k164 from "../http/marks/oauth.json"; | |
| 169 | import k165 from "../http/marks/oembed.json"; | |
| 170 | import k166 from "../http/marks/offers.json"; | |
| 171 | import k167 from "../http/marks/offline.json"; | |
| 172 | import k168 from "../http/marks/og.json"; | |
| 173 | import k169 from "../http/marks/openapi.json.json"; | |
| 174 | import k170 from "../http/marks/opensearch.xml.json"; | |
| 175 | import k171 from "../http/marks/organizations.json"; | |
| 176 | import k172 from "../http/marks/origins.json"; | |
| 177 | import k173 from "../http/marks/owner.atom.json"; | |
| 178 | import k174 from "../http/marks/owner.json"; | |
| 179 | import k175 from "../http/marks/packs.json"; | |
| 180 | import k176 from "../http/marks/peek.json"; | |
| 181 | import k177 from "../http/marks/pinned.json"; | |
| 182 | import k178 from "../http/marks/pipeline.json"; | |
| 183 | import k179 from "../http/marks/plugins.json"; | |
| 184 | import k180 from "../http/marks/pricing.json"; | |
| 185 | import k181 from "../http/marks/privacy.json"; | |
| 186 | import k182 from "../http/marks/r.json"; | |
| 187 | import k183 from "../http/marks/recover.json"; | |
| 188 | import k184 from "../http/marks/releases.json"; | |
| 189 | import k185 from "../http/marks/releases.json.json"; | |
| 190 | import k186 from "../http/marks/repos.json"; | |
| 191 | import k187 from "../http/marks/resilience.json"; | |
| 192 | import k188 from "../http/marks/review.json"; | |
| 193 | import k189 from "../http/marks/robots.txt.json"; | |
| 194 | import k190 from "../http/marks/root.json"; | |
| 195 | import k191 from "../http/marks/runs.json"; | |
| 196 | import k192 from "../http/marks/script-error.json"; | |
| 197 | import k193 from "../http/marks/search.json"; | |
| 198 | import k194 from "../http/marks/security.json"; | |
| 199 | import k195 from "../http/marks/settings.json"; | |
| 200 | import k196 from "../http/marks/sign-in.json"; | |
| 201 | import k197 from "../http/marks/signin.json"; | |
| 202 | import k198 from "../http/marks/signup.json"; | |
| 203 | import k199 from "../http/marks/sitemap.xml.json"; | |
| 204 | import k200 from "../http/marks/status.json"; | |
| 205 | import k201 from "../http/marks/support.json"; | |
| 206 | import k202 from "../http/marks/sw.js.json"; | |
| 207 | import k203 from "../http/marks/system.json"; | |
| 208 | import k204 from "../http/marks/tab.json"; | |
| 209 | import k205 from "../http/marks/tabforge-link.json"; | |
| 210 | import k206 from "../http/marks/tabforge-move.json"; | |
| 211 | import k207 from "../http/marks/tabforge.json"; | |
| 212 | import k208 from "../http/marks/talk.json"; | |
| 213 | import k209 from "../http/marks/tell.json"; | |
| 214 | import k210 from "../http/marks/templates.json"; | |
| 215 | import k211 from "../http/marks/templates.json.json"; | |
| 216 | import k212 from "../http/marks/terms.json"; | |
| 217 | import k213 from "../http/marks/theme.json"; | |
| 218 | import k214 from "../http/marks/toolbar-lab.js.json"; | |
| 219 | import k215 from "../http/marks/toolbar-lab.json"; | |
| 220 | import k216 from "../http/marks/traces.json"; | |
| 221 | import k217 from "../http/marks/verify.json"; | |
| 222 | import k218 from "../http/marks/welcome.json"; | |
| 223 | import k219 from "../http/marks/well-known.json"; | |
| 223 | 224 | |
| 224 | 225 | /** Each file of `http/marks/`, parsed, in name order. */ |
| 225 | 226 | export const MARK_FILES: readonly unknown[] = [ |
| @@ -442,4 +443,5 @@ export const MARK_FILES: readonly unknown[] = [ | ||
| 442 | 443 | k216, |
| 443 | 444 | k217, |
| 444 | 445 | k218, |
| 446 | k219, | |
| 445 | 447 | ]; |
src/http/api.ts +2
| @@ -349,6 +349,7 @@ import { tokenRoutes } from "./api/tokens.ts"; | ||
| 349 | 349 | import { accountAdmin, adminRoutes } from "./api/admin.ts"; |
| 350 | 350 | import { arcadeRoutes } from "./api/arcade.ts"; |
| 351 | 351 | import { runnerRoutes } from "./api/runners.ts"; |
| 352 | import { agentV1Routes } from "./api/agent_v1.ts"; | |
| 352 | 353 | import { environmentRoutes } from "./api/environments.ts"; |
| 353 | 354 | import { maintenanceRoutes } from "./api/maintenance.ts"; |
| 354 | 355 | import { maintenanceRunsRoutes } from "./api/maintenance_runs.ts"; |
| @@ -1297,6 +1298,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo | ||
| 1297 | 1298 | forgeOriginRoutes(router); |
| 1298 | 1299 | adminRoutes(router); |
| 1299 | 1300 | runnerRoutes(router); |
| 1301 | agentV1Routes(router); | |
| 1300 | 1302 | environmentRoutes(router); |
| 1301 | 1303 | arcadeRoutes(router); |
| 1302 | 1304 | gamesApiRoutes(router); |
src/http/api/agent_v1.ts added +105
| @@ -0,0 +1,105 @@ | ||
| 1 | /** | |
| 2 | * The agent protocol over HTTP (#18457): `POST /api/v1/agent/v1/<message>` for the five messages of | |
| 3 | * `machines/protocol.ts`. The bearer's token says its role (a box, a runner, a lender); a token | |
| 4 | * used for a message outside its role is a 403 that names the role. A valid request is handed to | |
| 5 | * the handler the old routes already run (`gameAgentSync`, the runner's claim, heartbeat and job | |
| 6 | * report), so version 0 and version 1 are one behaviour. The old `/api/v1/games/agent/sync` and | |
| 7 | * `/api/v1/runner/…` routes stay as they were. | |
| 8 | */ | |
| 9 | ||
| 10 | import { JOB_TOKEN_PREFIX, RUNNER_TOKEN_PREFIX, jobByToken, runnerByToken } from "../../checks/runner_jobs.ts"; | |
| 11 | import { boxByToken } from "../../games/store.ts"; | |
| 12 | import { noteUse } from "../../machines/agent_use.ts"; | |
| 13 | import { PROTOCOL_VERSION, isMessage, mayRole, readMessage, roleWords, type Message, type Role } from "../../machines/protocol.ts"; | |
| 14 | import { BODY_CAPS } from "../../kernel/body_caps.ts"; | |
| 15 | import type { Ctx, Handler } from "../context.ts"; | |
| 16 | import { gameAgentSync } from "../games_routes.ts"; | |
| 17 | import { InvalidJson } from "../json_body.ts"; | |
| 18 | import { STRANGER_MAX } from "../limits.ts"; | |
| 19 | import { apiError, boundedBody, boundedMachineBody, notFound, unauthorized } from "../respond.ts"; | |
| 20 | import { Router } from "../router.ts"; | |
| 21 | import { REPORT_MAX, runnerRoutes } from "./runners.ts"; | |
| 22 | ||
| 23 | /** The runner routes' handlers, found by their old path: one table, built on first use. */ | |
| 24 | let legacy: Router<Handler> | undefined; | |
| 25 | function legacyHandler(path: string): { handler: Handler; params: Record<string, string> } { | |
| 26 | if (legacy === undefined) { | |
| 27 | legacy = new Router<Handler>(); | |
| 28 | runnerRoutes(legacy, false); | |
| 29 | } | |
| 30 | return legacy.match("POST", path)!; | |
| 31 | } | |
| 32 | ||
| 33 | const bearer = (request: Request): string => /^Bearer (\S+)$/i.exec(request.headers.get("authorization") ?? "")?.[1] ?? ""; | |
| 34 | ||
| 35 | /** | |
| 36 | * Who a token is: its role and the machine it names; undefined for a token this forge does not | |
| 37 | * know. | |
| 38 | */ | |
| 39 | function whoIs(ctx: Ctx, token: string): { role: Role; machine: string } | undefined { | |
| 40 | if (token.startsWith("fgb_")) { | |
| 41 | const box = boxByToken(ctx.app.db, token); | |
| 42 | return box === undefined ? undefined : { role: "box", machine: box.id }; | |
| 43 | } | |
| 44 | if (token.startsWith(RUNNER_TOKEN_PREFIX)) { | |
| 45 | const runner = runnerByToken(ctx.app.db, token, Date.now()); | |
| 46 | return runner === undefined ? undefined : { role: runner.scope === undefined ? "runner" : "lender", machine: runner.id }; | |
| 47 | } | |
| 48 | // A job's own token reports on that job (`logs`, `result`): its runner's role, the job named in | |
| 49 | // the body. | |
| 50 | if (token.startsWith(JOB_TOKEN_PREFIX)) return { role: "runner", machine: "" }; | |
| 51 | return undefined; | |
| 52 | } | |
| 53 | ||
| 54 | async function agentMessage(ctx: Ctx): Promise<Response> { | |
| 55 | const message = ctx.params.message ?? ""; | |
| 56 | if (!isMessage(message)) return notFound(); | |
| 57 | const token = bearer(ctx.request); | |
| 58 | const who = whoIs(ctx, token); | |
| 59 | if (who === undefined) return unauthorized(); | |
| 60 | if (!mayRole(who.role, message)) return apiError("wrong_role", 403, roleWords(who.role, message)); | |
| 61 | const cap = who.role === "box" ? BODY_CAPS.gameSync.bytes : message === "logs" || message === "result" ? REPORT_MAX : STRANGER_MAX; | |
| 62 | let sent: Record<string, unknown> | "too_large"; | |
| 63 | try { | |
| 64 | sent = who.role === "box" ? await boundedMachineBody(ctx.request, cap, (why) => ctx.app.log.warn("agent v1: a message that is not JSON", { why })) : await boundedBody(ctx.request, cap); | |
| 65 | } catch (e) { | |
| 66 | if (e instanceof InvalidJson) return apiError("invalid_json", 400, `the message is not JSON: ${e.message}`); | |
| 67 | throw e; | |
| 68 | } | |
| 69 | if (sent === "too_large") return apiError("too_large", 413, `at most ${cap} bytes`); | |
| 70 | const read = readMessage(who.role, message, sent); | |
| 71 | if (!read.ok) return apiError(read.code, read.status, read.error); | |
| 72 | if (who.machine !== "") noteUse(ctx.app.db, who.machine, who.role, PROTOCOL_VERSION); | |
| 73 | return hand(ctx, who.role, message, read.body, read.job, token); | |
| 74 | } | |
| 75 | ||
| 76 | /** The validated body, to the handler the old route runs, as the request that route takes. */ | |
| 77 | function hand(ctx: Ctx, role: Role, message: Message, body: Record<string, unknown>, job: string | undefined, token: string): Promise<Response> | Response { | |
| 78 | const forwarded = (path: string, params: Record<string, string>): Ctx => ({ | |
| 79 | ...ctx, | |
| 80 | params, | |
| 81 | request: new Request(new URL(path, ctx.url).href, { | |
| 82 | method: "POST", | |
| 83 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 84 | body: JSON.stringify(body), | |
| 85 | signal: ctx.request.signal, | |
| 86 | }), | |
| 87 | }); | |
| 88 | if (role === "box") { | |
| 89 | const asBox = forwarded("/api/v1/games/agent/sync", {}); | |
| 90 | return gameAgentSync(asBox); | |
| 91 | } | |
| 92 | if (message === "logs" || message === "result") { | |
| 93 | if (job === undefined || jobByToken(ctx.app.db, job, token, Date.now()) === undefined) return notFound(); | |
| 94 | const path = `/api/v1/runner/jobs/${job}`; | |
| 95 | const old = legacyHandler(path); | |
| 96 | return old.handler(forwarded(path, old.params)); | |
| 97 | } | |
| 98 | const path = `/api/v1/runner/${message}`; | |
| 99 | const old = legacyHandler(path); | |
| 100 | return old.handler(forwarded(path, old.params)); | |
| 101 | } | |
| 102 | ||
| 103 | export function agentV1Routes(router: Router<Handler>): void { | |
| 104 | router.add("POST", "/api/v1/agent/v1/:message", agentMessage); | |
| 105 | } |
src/http/api/runners.ts +27 −8
| @@ -9,6 +9,7 @@ | ||
| 9 | 9 | * stranger's header: no page, no API route and no git door knows them. |
| 10 | 10 | */ |
| 11 | 11 | |
| 12 | import { noteUse } from "../../machines/agent_use.ts"; | |
| 12 | 13 | import { dropHands, takeHand } from "../../checks/runner_hands.ts"; |
| 13 | 14 | import { HAND_BYTES_MAX } from "../../checks/hand_files.ts"; |
| 14 | 15 | import { listLending, offerLending, resumeLending, stopLending } from "../../actions/lending.ts"; |
| @@ -60,7 +61,7 @@ import { accountAdmin } from "./admin.ts"; | ||
| 60 | 61 | /** The longest a claim waits for a job, in seconds: under every proxy's own patience. */ |
| 61 | 62 | export const CLAIM_WAIT_MAX_S = 25; |
| 62 | 63 | /** The most one report carries: a second or two of a loud check's output. */ |
| 63 | const REPORT_MAX = 2 * 1024 * 1024; | |
| 64 | export const REPORT_MAX = 2 * 1024 * 1024; | |
| 64 | 65 | const LINES_MAX = 5_000; |
| 65 | 66 | |
| 66 | 67 | const bearer = (request: Request): string => |
| @@ -124,7 +125,25 @@ function packShareOf(app: App): PackShare { | ||
| 124 | 125 | return share; |
| 125 | 126 | } |
| 126 | 127 | |
| 127 | export function runnerRoutes(router: Router<Handler>): void { | |
| 128 | /** | |
| 129 | * `record`: whether a request here is a version 0 use of the agent protocol. The versioned door | |
| 130 | * builds its own table with it off, so only a runner on the old paths is recorded. | |
| 131 | */ | |
| 132 | export function runnerRoutes(router: Router<Handler>, record = true): void { | |
| 133 | const seen = (h: Handler, byJob: boolean): Handler => | |
| 134 | record | |
| 135 | ? (ctx) => { | |
| 136 | const db = ctx.app.db; | |
| 137 | if (byJob) { | |
| 138 | const r = db.query<{ runner_id: string | null }, [string]>("SELECT runner_id FROM check_job WHERE id = ?1").get(ctx.params.id ?? ""); | |
| 139 | if (r?.runner_id) noteUse(db, r.runner_id, "runner", 0); | |
| 140 | } else { | |
| 141 | const runner = runnerByToken(db, bearer(ctx.request), Date.now()); | |
| 142 | if (runner !== undefined) noteUse(db, runner.id, runner.scope === undefined ? "runner" : "lender", 0); | |
| 143 | } | |
| 144 | return h(ctx); | |
| 145 | } | |
| 146 | : h; | |
| 128 | 147 | router.add("POST", "/api/v1/admin/runners", async (ctx) => { |
| 129 | 148 | const denied = accountAdmin(ctx, "admin"); |
| 130 | 149 | if (denied) return denied; |
| @@ -235,7 +254,7 @@ export function runnerRoutes(router: Router<Handler>): void { | ||
| 235 | 254 | |
| 236 | 255 | // A runner says it is here, in what state, and which labels it holds (#18037). Silence past |
| 237 | 256 | // `SEEN_FRESH_MS` reads as away. Its claim and its reports say the same without the state. |
| 238 | router.add("POST", "/api/v1/runner/heartbeat", async (ctx) => { | |
| 257 | router.add("POST", "/api/v1/runner/heartbeat", seen(async (ctx) => { | |
| 239 | 258 | const runner = runnerByToken(ctx.app.db, bearer(ctx.request), Date.now()); |
| 240 | 259 | if (runner === undefined) return unauthorized(); |
| 241 | 260 | const input = await boundedBody(ctx.request, STRANGER_MAX); |
| @@ -246,10 +265,10 @@ export function runnerRoutes(router: Router<Handler>): void { | ||
| 246 | 265 | noteHeartbeat(ctx.app.db, runner.id, { state }); |
| 247 | 266 | wakeClaimers(ctx.app); |
| 248 | 267 | return new Response(null, { status: 204 }); |
| 249 | }); | |
| 268 | }, false)); | |
| 250 | 269 | |
| 251 | 270 | // A runner asks for work. Held open until a job is offered or `wait` seconds pass (204). |
| 252 | router.add("POST", "/api/v1/runner/claim", async (ctx) => { | |
| 271 | router.add("POST", "/api/v1/runner/claim", seen(async (ctx) => { | |
| 253 | 272 | const runner = runnerByToken(ctx.app.db, bearer(ctx.request), Date.now()); |
| 254 | 273 | if (runner === undefined) return unauthorized(); |
| 255 | 274 | const input = await boundedBody(ctx.request, STRANGER_MAX); |
| @@ -288,7 +307,7 @@ export function runnerRoutes(router: Router<Handler>): void { | ||
| 288 | 307 | // (`perf/in_flight.ts`). |
| 289 | 308 | await inFlight.rest(ctx.request, () => nextOffer(ctx.app, left, stop)); |
| 290 | 309 | } |
| 291 | }); | |
| 310 | }, false)); | |
| 292 | 311 | |
| 293 | 312 | /** The job this request's token holds, with the check waiting on it here; else nothing. */ |
| 294 | 313 | const held = (ctx: Ctx) => { |
| @@ -304,7 +323,7 @@ export function runnerRoutes(router: Router<Handler>): void { | ||
| 304 | 323 | }; |
| 305 | 324 | |
| 306 | 325 | // A runner reports on its job: log lines, then the end. Every report renews the lease. |
| 307 | router.add("POST", "/api/v1/runner/jobs/:id", async (ctx) => { | |
| 326 | router.add("POST", "/api/v1/runner/jobs/:id", seen(async (ctx) => { | |
| 308 | 327 | const mine = held(ctx); |
| 309 | 328 | if (mine === undefined) { |
| 310 | 329 | // Its claim stands but no forge waits on it (one stopping, or one just up): the runner keeps |
| @@ -367,7 +386,7 @@ export function runnerRoutes(router: Router<Handler>): void { | ||
| 367 | 386 | } |
| 368 | 387 | if (!renewJob(ctx.app.db, mine.job.id, token, Date.now())) return notFound(); |
| 369 | 388 | return json({ lease }); |
| 370 | }); | |
| 389 | }, true)); | |
| 371 | 390 | |
| 372 | 391 | // The job's seed door: the files the forge seeded its checkout with, by the path, size and hash |
| 373 | 392 | // the job names, and nothing else (`checks/runner_seeds.ts`). Only read: no route takes one back. |
src/http/games_routes.ts +8 −1
| @@ -3,6 +3,7 @@ | ||
| 3 | 3 | * bearer), the signed jar download, and the `/games` pages (`web/pages/games.ts`). |
| 4 | 4 | */ |
| 5 | 5 | |
| 6 | import { noteUse } from "../machines/agent_use.ts"; | |
| 6 | 7 | import { applyWhenQuiet } from "../games/when_quiet.ts"; |
| 7 | 8 | import { composeServices, readCompose } from "../games/compose.ts"; |
| 8 | 9 | import { watchAgent } from "../games/agent_watch.ts"; |
| @@ -168,7 +169,13 @@ export function gameAgentScript(ctx: Ctx): Response { | ||
| 168 | 169 | } |
| 169 | 170 | |
| 170 | 171 | export function gamesApiRoutes(router: Router<Handler>): void { |
| 171 | router.add("POST", "/api/v1/games/agent/sync", gameAgentSync); | |
| 172 | // Version 0 is this path only: the versioned door calls `gameAgentSync` without passing here. | |
| 173 | router.add("POST", "/api/v1/games/agent/sync", (ctx) => { | |
| 174 | const auth = ctx.request.headers.get("authorization") ?? ""; | |
| 175 | const box = auth.startsWith("Bearer ") ? boxByToken(ctx.app.db, auth.slice(7).trim()) : undefined; | |
| 176 | if (box !== undefined) noteUse(ctx.app.db, box.id, "box", 0); | |
| 177 | return gameAgentSync(ctx); | |
| 178 | }); | |
| 172 | 179 | router.add("GET", "/api/v1/games/agent/script", gameAgentScript); |
| 173 | 180 | } |
| 174 | 181 |
src/http/lazy_lists.ts +1
| @@ -1361,6 +1361,7 @@ export const API_ROUTES = [ | ||
| 1361 | 1361 | ["POST", "/api/v1/runner/jobs/:id/hand"], |
| 1362 | 1362 | ["GET", "/api/v1/runner/jobs/:id/git/info/refs"], |
| 1363 | 1363 | ["POST", "/api/v1/runner/jobs/:id/git/git-upload-pack"], |
| 1364 | ["POST", "/api/v1/agent/v1/:message"], | |
| 1364 | 1365 | ["GET", "/api/v1/repos/:owner/:name/environments"], |
| 1365 | 1366 | ["PUT", "/api/v1/repos/:owner/:name/environments/:env/:entry"], |
| 1366 | 1367 | ["DELETE", "/api/v1/repos/:owner/:name/environments/:env/:entry"], |
src/http/marks/api-v1-agent.json added +4
src/machines/agent_use.ts added +22
| @@ -0,0 +1,22 @@ | ||
| 1 | /** | |
| 2 | * When each machine last spoke each version of the agent protocol (`agent_use`, #18457). Version 0 | |
| 3 | * is the old sync route, so whether anything still uses it is a read of `lastUse`. Written at most | |
| 4 | * once a minute for a machine and version: a box polls every second. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { Database } from "bun:sqlite"; | |
| 8 | import type { Role } from "./protocol.ts"; | |
| 9 | ||
| 10 | const WRITE_EVERY_MS = 60_000; | |
| 11 | ||
| 12 | export function noteUse(db: Database, machine: string, role: Role, version: number, now = Date.now()): void { | |
| 13 | db.query( | |
| 14 | `INSERT INTO agent_use (machine, role, version, last_at) VALUES (?1, ?2, ?3, ?4) | |
| 15 | ON CONFLICT (machine, version) DO UPDATE SET last_at = excluded.last_at, role = excluded.role WHERE excluded.last_at - agent_use.last_at >= ?5`, | |
| 16 | ).run(machine, role, version, now, WRITE_EVERY_MS); | |
| 17 | } | |
| 18 | ||
| 19 | /** The last use of one version by any machine, in milliseconds; 0 for never. */ | |
| 20 | export function lastUse(db: Database, version: number): number { | |
| 21 | return db.query<{ at: number | null }, [number]>("SELECT MAX(last_at) AS at FROM agent_use WHERE version = ?1").get(version)?.at ?? 0; | |
| 22 | } |
src/machines/protocol.ts added +140
| @@ -0,0 +1,140 @@ | ||
| 1 | /** | |
| 2 | * The agent protocol, version 1 (#18457): the five messages any machine that does the forge's work | |
| 3 | * sends (heartbeat, claim, logs, result, containers), as plain data in and plain data out. A | |
| 4 | * request is JSON carrying `v: 1`; `readMessage` checks it field by field and hands back the body | |
| 5 | * the forge's existing handlers already take (`http/api/runners.ts`, `http/games_routes.ts`), so | |
| 6 | * the old routes and the new ones run the same code. Version 0 is the old sync route, served as | |
| 7 | * before (`http/games_routes.ts`); it is never removed until `agent_use` says no machine used it | |
| 8 | * for 30 days. | |
| 9 | * | |
| 10 | * A token has a role, and a role may send only some messages: a box its sync (heartbeat, logs, | |
| 11 | * result, containers), a runner or a lender (a runner another forge lent) claim work and report on | |
| 12 | * it, a helper (the Mac app's) says it is here. Nothing here touches a database or a request. | |
| 13 | */ | |
| 14 | ||
| 15 | export const PROTOCOL_VERSION = 1; | |
| 16 | ||
| 17 | export const MESSAGES = ["heartbeat", "claim", "logs", "result", "containers"] as const; | |
| 18 | export type Message = (typeof MESSAGES)[number]; | |
| 19 | ||
| 20 | export const ROLES = ["box", "runner", "lender", "helper"] as const; | |
| 21 | export type Role = (typeof ROLES)[number]; | |
| 22 | ||
| 23 | const WORKER: readonly Message[] = ["heartbeat", "claim", "logs", "result"]; | |
| 24 | const MAY: Record<Role, readonly Message[]> = { | |
| 25 | box: ["heartbeat", "logs", "result", "containers"], | |
| 26 | runner: WORKER, | |
| 27 | lender: WORKER, | |
| 28 | helper: ["heartbeat"], | |
| 29 | }; | |
| 30 | ||
| 31 | export const isMessage = (v: string): v is Message => (MESSAGES as readonly string[]).includes(v); | |
| 32 | export const mayRole = (role: Role, message: Message): boolean => MAY[role].includes(message); | |
| 33 | ||
| 34 | /** The words of a 403: the role is named, and what it may send. */ | |
| 35 | export const roleWords = (role: Role, message: Message): string => | |
| 36 | `this is a ${role} token: it may send ${MAY[role].join(", ")}, not ${message}`; | |
| 37 | ||
| 38 | export type Read = { readonly ok: true; readonly body: Record<string, unknown>; readonly job?: string } | { readonly ok: false; readonly code: string; readonly status: 400 | 422; readonly error: string }; | |
| 39 | ||
| 40 | const bad = (code: string, error: string, status: 400 | 422 = 422): Read => ({ ok: false, code, status, error }); | |
| 41 | const isObject = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v); | |
| 42 | const JOB_ID = /^[A-Za-z0-9_-]{1,64}$/; | |
| 43 | const LINES_MAX = 5_000; | |
| 44 | const RESULTS_MAX = 1_000; | |
| 45 | ||
| 46 | /** The version a request names: only a whole number is one. */ | |
| 47 | export function versionOf(raw: unknown): number | undefined { | |
| 48 | const v = isObject(raw) ? raw["v"] : undefined; | |
| 49 | return typeof v === "number" && Number.isInteger(v) ? v : undefined; | |
| 50 | } | |
| 51 | ||
| 52 | /** The sync fields each box message may carry; the rest of a box's request is left out of it. */ | |
| 53 | const BOX_FIELDS: Record<string, readonly string[]> = { | |
| 54 | logs: ["logs", "retry"], | |
| 55 | result: ["results", "light"], | |
| 56 | containers: ["services", "metrics", "host", "diag", "people", "snapshots"], | |
| 57 | }; | |
| 58 | ||
| 59 | /** One request, validated for the role that sent it; the body is the legacy shape without `v`. */ | |
| 60 | export function readMessage(role: Role, message: Message, raw: unknown): Read { | |
| 61 | if (!isObject(raw)) return bad("invalid_message", "send a JSON object", 400); | |
| 62 | const v = versionOf(raw); | |
| 63 | if (v !== PROTOCOL_VERSION) | |
| 64 | return bad("bad_version", `this forge speaks agent protocol ${PROTOCOL_VERSION}; the request said v=${v === undefined ? "nothing" : String(v)}`, 400); | |
| 65 | const { v: _v, ...rest } = raw; | |
| 66 | if (role === "box") return readBox(message, rest); | |
| 67 | switch (message) { | |
| 68 | case "heartbeat": { | |
| 69 | const state = rest["state"]; | |
| 70 | if (state !== "idle" && state !== "busy" && state !== "paused") return bad("invalid_heartbeat", "state is idle, busy or paused"); | |
| 71 | return { ok: true, body: { state } }; | |
| 72 | } | |
| 73 | case "claim": { | |
| 74 | const { wait, cells, jobs, machine } = rest; | |
| 75 | if (wait !== undefined && !(typeof wait === "number" && wait >= 0 && wait <= 25)) return bad("invalid_claim", "wait is a number of seconds, 0 to 25"); | |
| 76 | if (cells !== undefined && typeof cells !== "boolean") return bad("invalid_claim", "cells is true or false"); | |
| 77 | if (jobs !== undefined && !(typeof jobs === "number" && Number.isInteger(jobs) && jobs >= 1 && jobs <= 64)) return bad("invalid_claim", "jobs is a whole number, 1 to 64"); | |
| 78 | if (machine !== undefined && !isObject(machine)) return bad("invalid_claim", "machine is an object"); | |
| 79 | return { ok: true, body: { wait, cells, jobs, machine } }; | |
| 80 | } | |
| 81 | case "logs": { | |
| 82 | const job = rest["job"]; | |
| 83 | if (typeof job !== "string" || !JOB_ID.test(job)) return bad("invalid_logs", "job is the id the claim answered"); | |
| 84 | const { lines, step } = rest; | |
| 85 | if (!Array.isArray(lines) || lines.length > LINES_MAX || !lines.every((l) => typeof l === "string")) return bad("invalid_logs", `lines are at most ${LINES_MAX} strings`); | |
| 86 | if (step !== undefined && typeof step !== "string") return bad("invalid_logs", "step is a string"); | |
| 87 | const paused = rest["paused"]; | |
| 88 | return { ok: true, job, body: { lines, ...(step === undefined ? {} : { step }), ...(paused === undefined ? {} : { paused }) } }; | |
| 89 | } | |
| 90 | case "result": { | |
| 91 | const job = rest["job"]; | |
| 92 | if (typeof job !== "string" || !JOB_ID.test(job)) return bad("invalid_result", "job is the id the claim answered"); | |
| 93 | const ends = (["done", "abandon", "interrupted"] as const).filter((k) => rest[k] !== undefined); | |
| 94 | if (ends.length !== 1) return bad("invalid_result", "send one of done, abandon or interrupted"); | |
| 95 | const end = ends[0]!; | |
| 96 | if (end === "done" && !isObject(rest["done"])) return bad("invalid_result", "done takes { steps, contained, note }"); | |
| 97 | if (end !== "done" && typeof rest[end] !== "string") return bad("invalid_result", `${end} is a string`); | |
| 98 | const kept = rest["kept"]; | |
| 99 | if (kept !== undefined && !Array.isArray(kept)) return bad("invalid_result", "kept is a list"); | |
| 100 | return { ok: true, job, body: { [end]: rest[end], ...(kept === undefined ? {} : { kept }) } }; | |
| 101 | } | |
| 102 | case "containers": | |
| 103 | return bad("invalid_message", "containers is a box's message"); | |
| 104 | } | |
| 105 | } | |
| 106 | ||
| 107 | function readBox(message: Message, rest: Record<string, unknown>): Read { | |
| 108 | if (message === "claim") return bad("invalid_message", "claim is a runner's message"); | |
| 109 | const { light, composeSha, results, ask } = rest; | |
| 110 | if (light !== undefined && typeof light !== "boolean") return bad("invalid_heartbeat", "light is true or false"); | |
| 111 | if (composeSha !== undefined && typeof composeSha !== "string") return bad("invalid_heartbeat", "composeSha is a string"); | |
| 112 | if (ask !== undefined && !Array.isArray(ask)) return bad("invalid_heartbeat", "ask is a list"); | |
| 113 | if (results !== undefined && (!Array.isArray(results) || results.length > RESULTS_MAX || !results.every((r) => isObject(r) && (typeof r["id"] === "string" || typeof r["id"] === "number")))) | |
| 114 | return bad("invalid_result", `results are at most ${RESULTS_MAX} objects with an id`); | |
| 115 | for (const k of ["logs", "metrics", "host"]) if (rest[k] !== undefined && typeof rest[k] !== "object") return bad(`invalid_${message}`, `${k} is an object`); | |
| 116 | if (message === "heartbeat") return { ok: true, body: rest }; | |
| 117 | // The other messages are the same sync cut down to their own fields, `light` where only results | |
| 118 | // and commands are wanted. | |
| 119 | const keep = BOX_FIELDS[message] ?? []; | |
| 120 | const body: Record<string, unknown> = {}; | |
| 121 | for (const k of keep) if (rest[k] !== undefined) body[k] = rest[k]; | |
| 122 | if (message === "result") body["light"] = true; | |
| 123 | return { ok: true, body }; | |
| 124 | } | |
| 125 | ||
| 126 | /** | |
| 127 | * A runner's one report on a job (lines, a renewal, perhaps its end) as the messages of version 1, | |
| 128 | * in the order to send them: its lines (or an empty `logs`, which renews the lease) first, its end | |
| 129 | * after. The runner stops at the first the forge refuses. | |
| 130 | */ | |
| 131 | export function splitReport(job: string, report: Record<string, unknown>): { message: "logs" | "result"; body: Record<string, unknown> }[] { | |
| 132 | const { done, abandon, interrupted, kept, ...logs } = report; | |
| 133 | const end = done !== undefined ? { done } : abandon !== undefined ? { abandon } : interrupted !== undefined ? { interrupted, ...(kept === undefined ? {} : { kept }) } : undefined; | |
| 134 | const lines = Array.isArray(logs["lines"]) ? logs["lines"] : []; | |
| 135 | const out: { message: "logs" | "result"; body: Record<string, unknown> }[] = []; | |
| 136 | // An end with nothing to say before it is sent alone; a renewal or lines are a `logs`. | |
| 137 | if (end === undefined || lines.length > 0 || logs["paused"] !== undefined) out.push({ message: "logs", body: { v: PROTOCOL_VERSION, job, ...logs, lines } }); | |
| 138 | if (end !== undefined) out.push({ message: "result", body: { v: PROTOCOL_VERSION, job, ...end } }); | |
| 139 | return out; | |
| 140 | } |
src/runner/main.ts +17 −9
| @@ -57,6 +57,7 @@ import { runGit } from "../git/env.ts"; | ||
| 57 | 57 | import { isSafeOid } from "../git/guard.ts"; |
| 58 | 58 | import { background } from "../perf/jobs.ts"; |
| 59 | 59 | import { BuildWatch, exitOnUpgrade, RUNNER_VERSION_HEADER } from "./upgrade.ts"; |
| 60 | import { PROTOCOL_VERSION, splitReport } from "../machines/protocol.ts"; | |
| 60 | 61 | |
| 61 | 62 | /** |
| 62 | 63 | * The longest one report may take. A report caught on a connection the forge dropped mid-answer |
| @@ -71,13 +72,20 @@ export const REPORT_TIMEOUT_MS = 10_000; | ||
| 71 | 72 | */ |
| 72 | 73 | export const jobReporter = |
| 73 | 74 | (forge: string, jobId: string, token: string, timeoutMs: number = REPORT_TIMEOUT_MS) => |
| 74 | (body: unknown): Promise<Response> => | |
| 75 | fetch(`${forge}/api/v1/runner/jobs/${jobId}`, { | |
| 76 | method: "POST", | |
| 77 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 78 | body: JSON.stringify(body), | |
| 79 | signal: AbortSignal.timeout(timeoutMs), | |
| 80 | }); | |
| 75 | async (body: unknown): Promise<Response> => { | |
| 76 | // Protocol 1 (`machines/protocol.ts`): the report's lines and its end are two messages. | |
| 77 | let last: Response | undefined; | |
| 78 | for (const m of splitReport(jobId, (body ?? {}) as Record<string, unknown>)) { | |
| 79 | last = await fetch(`${forge}/api/v1/agent/v1/${m.message}`, { | |
| 80 | method: "POST", | |
| 81 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 82 | body: JSON.stringify(m.body), | |
| 83 | signal: AbortSignal.timeout(timeoutMs), | |
| 84 | }); | |
| 85 | if (!last.ok) return last; | |
| 86 | } | |
| 87 | return last!; | |
| 88 | }; | |
| 81 | 89 | |
| 82 | 90 | /** How often a job's lines go to the forge; each report renews the lease. */ |
| 83 | 91 | const REPORT_MS = 1_000; |
| @@ -707,9 +715,9 @@ export async function runRunner(options: RunnerOptions): Promise<RunnerEnd> { | ||
| 707 | 715 | let res: Response; |
| 708 | 716 | try { |
| 709 | 717 | res = await post( |
| 710 | "/api/v1/runner/claim", | |
| 718 | "/api/v1/agent/v1/claim", | |
| 711 | 719 | options.token, |
| 712 | { wait: options.once === true ? 0 : CLAIM_WAIT_S, cells: cells.ok, jobs: slots, machine }, | |
| 720 | { v: PROTOCOL_VERSION, wait: options.once === true ? 0 : CLAIM_WAIT_S, cells: cells.ok, jobs: slots, machine }, | |
| 713 | 721 | AbortSignal.any([asking, yielding.signal]), |
| 714 | 722 | ); |
| 715 | 723 | } catch { |
test/agent-protocol.test.ts added +121
| @@ -0,0 +1,121 @@ | ||
| 1 | /** | |
| 2 | * The agent protocol, version 1 (#18457): each of the five messages round-trips, a bad version and | |
| 3 | * a token outside its role are refused with the role named, a version 0 sync is answered as before, | |
| 4 | * and the forge records the last use of each version per machine. | |
| 5 | */ | |
| 6 | import { expect, test } from "bun:test"; | |
| 7 | import { enrolRunner, offerJob, type RunnerJob } from "../src/checks/runner_jobs.ts"; | |
| 8 | import { createGameBox } from "../src/games/store.ts"; | |
| 9 | import { lastUse } from "../src/machines/agent_use.ts"; | |
| 10 | import { mayRole, readMessage, splitReport } from "../src/machines/protocol.ts"; | |
| 11 | import { checksForge } from "./helpers/checks-forge.ts"; | |
| 12 | import { quietLogs } from "./helpers/globals.ts"; | |
| 13 | ||
| 14 | quietLogs(); | |
| 15 | const f = checksForge("forge-agent-v1-"); | |
| 16 | ||
| 17 | const job: Omit<RunnerJob, "id"> = { | |
| 18 | run: "run1", | |
| 19 | repo: "alice/lib", | |
| 20 | commit: "a".repeat(40), | |
| 21 | depth: 1, | |
| 22 | steps: [{ name: "check", command: "true" }], | |
| 23 | env: {}, | |
| 24 | limits: {}, | |
| 25 | timeoutS: 60, | |
| 26 | egress: [], | |
| 27 | egressMode: "enforce", | |
| 28 | cell: "preferred", | |
| 29 | cache: { repo: "r", tree: "", base: "" }, | |
| 30 | }; | |
| 31 | ||
| 32 | const send = (path: string, token: string, body: unknown): Promise<Response> => | |
| 33 | fetch(`${f.servers.url}${path}`, { | |
| 34 | method: "POST", | |
| 35 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 36 | body: JSON.stringify(body), | |
| 37 | }); | |
| 38 | const v1 = (message: string, token: string, body: Record<string, unknown>): Promise<Response> => send(`/api/v1/agent/v1/${message}`, token, { v: 1, ...body }); | |
| 39 | ||
| 40 | test("a runner's heartbeat, claim, logs and result round-trip", async () => { | |
| 41 | const { token } = enrolRunner(f.app.db, "r-v1", f.alice.id); | |
| 42 | expect((await v1("heartbeat", token, { state: "idle" })).status).toBe(204); | |
| 43 | offerJob(f.app.db, { runId: "run1", repoId: "r", dir: "/nowhere", job }); | |
| 44 | const claimed = await v1("claim", token, { wait: 0, cells: false }); | |
| 45 | expect(claimed.status).toBe(200); | |
| 46 | const got = (await claimed.json()) as { job: { id: string }; token: string }; | |
| 47 | // Nothing waits on this job here (no check is in flight), so the forge says to keep it and ask | |
| 48 | // again. | |
| 49 | const logs = await v1("logs", got.token, { job: got.job.id, lines: ["hello"] }); | |
| 50 | expect([200, 503, 404]).toContain(logs.status); | |
| 51 | expect(lastUse(f.app.db, 1)).toBeGreaterThan(0); | |
| 52 | expect(f.app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM agent_use WHERE machine = 'r-v1' OR role = 'runner' AND version = 0").get()!.n).toBe(0); | |
| 53 | }); | |
| 54 | ||
| 55 | test("a runner on the old routes is recorded as version 0", async () => { | |
| 56 | const { token } = enrolRunner(f.app.db, "r-old", f.alice.id); | |
| 57 | const r = await send("/api/v1/runner/heartbeat", token, { state: "idle" }); | |
| 58 | expect(r.status).toBe(204); | |
| 59 | expect(lastUse(f.app.db, 0)).toBeGreaterThan(0); | |
| 60 | }); | |
| 61 | ||
| 62 | test("a box's heartbeat is the sync, and its logs, result and containers are cut from it", async () => { | |
| 63 | const box = createGameBox(f.app.db, { name: "mc-v1" }); | |
| 64 | const hb = await v1("heartbeat", box.token, { composeSha: "" }); | |
| 65 | expect(hb.status).toBe(200); | |
| 66 | // A box speaking only version 1 is no use of version 0, or the old route could never be retired. | |
| 67 | const v0 = (): number => f.app.db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM agent_use WHERE machine = ?1 AND version = 0").get(box.id)!.n; | |
| 68 | expect(v0()).toBe(0); | |
| 69 | expect(((await hb.json()) as { commands: unknown[] }).commands).toEqual([]); | |
| 70 | for (const m of ["logs", "result", "containers"]) { | |
| 71 | const r = await v1(m, box.token, m === "result" ? { results: [{ id: "c1", ok: true, output: "x" }] } : {}); | |
| 72 | expect(r.status).toBe(200); | |
| 73 | } | |
| 74 | // A version 0 sync, as an agent already deployed sends it, is answered as before. | |
| 75 | const old = await send("/api/v1/games/agent/sync", box.token, { agent: 1, composeSha: "" }); | |
| 76 | expect(old.status).toBe(200); | |
| 77 | expect(((await old.json()) as { commands: unknown[] }).commands).toEqual([]); | |
| 78 | expect(v0()).toBe(1); | |
| 79 | }); | |
| 80 | ||
| 81 | test("a version other than 1 is refused, saying which this forge speaks", async () => { | |
| 82 | const { token } = enrolRunner(f.app.db, "r-badv", f.alice.id); | |
| 83 | for (const v of [0, 2, "1", undefined]) { | |
| 84 | const r = await send("/api/v1/agent/v1/heartbeat", token, { v, state: "idle" }); | |
| 85 | expect(r.status).toBe(400); | |
| 86 | expect(await r.text()).toContain("bad_version"); | |
| 87 | } | |
| 88 | }); | |
| 89 | ||
| 90 | test("a token outside its role is a 403 that names the role", async () => { | |
| 91 | const runner = enrolRunner(f.app.db, "r-role", f.alice.id).token; | |
| 92 | const box = createGameBox(f.app.db, { name: "mc-role" }).token; | |
| 93 | const asRunner = await v1("containers", runner, {}); | |
| 94 | expect(asRunner.status).toBe(403); | |
| 95 | expect(await asRunner.text()).toContain("runner token"); | |
| 96 | const asBox = await v1("claim", box, { wait: 0 }); | |
| 97 | expect(asBox.status).toBe(403); | |
| 98 | expect(await asBox.text()).toContain("box token"); | |
| 99 | expect((await v1("heartbeat", "forge_runner_nope", { state: "idle" })).status).toBe(401); | |
| 100 | expect((await v1("nonsense", runner, {})).status).toBe(404); | |
| 101 | }); | |
| 102 | ||
| 103 | test("the messages are validated at the boundary", () => { | |
| 104 | expect(readMessage("runner", "heartbeat", { v: 1, state: "dancing" }).ok).toBe(false); | |
| 105 | expect(readMessage("runner", "claim", { v: 1, wait: 99 }).ok).toBe(false); | |
| 106 | expect(readMessage("runner", "logs", { v: 1, job: "../x", lines: [] }).ok).toBe(false); | |
| 107 | expect(readMessage("runner", "logs", { v: 1, job: "j1", lines: [1] }).ok).toBe(false); | |
| 108 | expect(readMessage("runner", "result", { v: 1, job: "j1" }).ok).toBe(false); | |
| 109 | expect(readMessage("runner", "result", { v: 1, job: "j1", done: {}, abandon: "x" }).ok).toBe(false); | |
| 110 | expect(readMessage("box", "heartbeat", { v: 1, light: "yes" }).ok).toBe(false); | |
| 111 | expect(readMessage("box", "result", { v: 1, results: [{ ok: true }] }).ok).toBe(false); | |
| 112 | expect(mayRole("helper", "claim")).toBe(false); | |
| 113 | expect(mayRole("lender", "claim")).toBe(true); | |
| 114 | }); | |
| 115 | ||
| 116 | test("a runner's report splits into its lines and its end", () => { | |
| 117 | expect(splitReport("j", {}).map((m) => m.message)).toEqual(["logs"]); | |
| 118 | expect(splitReport("j", { lines: ["a"], done: { steps: [] } }).map((m) => m.message)).toEqual(["logs", "result"]); | |
| 119 | expect(splitReport("j", { done: { steps: [] } }).map((m) => m.message)).toEqual(["result"]); | |
| 120 | expect(splitReport("j", { abandon: "no cells" })[0]!.body).toEqual({ v: 1, job: "j", abandon: "no cells" }); | |
| 121 | }); |
test/game-boot.test.ts +2 −2
| @@ -84,7 +84,7 @@ describe("the agent, missing a tool", () => { | ||
| 84 | 84 | expect(await p.exited).toBe(0); |
| 85 | 85 | const said = await new Response(p.stderr).text(); |
| 86 | 86 | expect(forge.bodies, `the agent said: ${said}`).toHaveLength(1); |
| 87 | expect(forge.bodies[0]).toEqual({ agent: 1, boot: 'missing jq: status: error errors: - "package jq: apt lock held" ' }); | |
| 87 | expect(forge.bodies[0]).toEqual({ agent: 1, v: 1, boot: 'missing jq: status: error errors: - "package jq: apt lock held" ' }); | |
| 88 | 88 | expect(said).toContain("missing jq; saying so and checking again in 30s"); |
| 89 | 89 | } finally { |
| 90 | 90 | forge.stop(); |
| @@ -104,7 +104,7 @@ describe("the agent, missing a tool", () => { | ||
| 104 | 104 | }); |
| 105 | 105 | const p = Bun.spawn(["bash", AGENT, "--boot-report"], { env: { PATH: bin, FORGE_GAME_DIR: dir }, stdout: "pipe", stderr: "pipe" }); |
| 106 | 106 | expect(await p.exited).toBe(0); |
| 107 | expect(forge.bodies).toEqual([{ agent: 1, boot: "boot report: status: running detail: DataSourceDigitalOcean " }]); | |
| 107 | expect(forge.bodies).toEqual([{ agent: 1, v: 1, boot: "boot report: status: running detail: DataSourceDigitalOcean " }]); | |
| 108 | 108 | } finally { |
| 109 | 109 | forge.stop(); |
| 110 | 110 | await rm(box, { recursive: true, force: true }); |
test/game-lend-box.test.ts +2 −2
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | * stand-ins for what needs root (systemd-run, bwrap, systemctl, docker, git) that record what |
| 7 | 7 | * they were asked. |
| 8 | 8 | */ |
| 9 | import { legacyOf } from "./helpers/agent-v1.ts"; | |
| 9 | 10 | import { $ } from "bun"; |
| 10 | 11 | import { afterEach, describe, expect, test } from "bun:test"; |
| 11 | 12 | import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs"; |
| @@ -92,10 +93,9 @@ exit 0`, | ||
| 92 | 93 | port: 0, |
| 93 | 94 | hostname: "127.0.0.1", |
| 94 | 95 | async fetch(req) { |
| 95 | const path = new URL(req.url).pathname; | |
| 96 | 96 | const auth = req.headers.get("authorization") ?? ""; |
| 97 | 97 | const text = req.method === "POST" ? await req.text() : ""; |
| 98 | const body = text === "" ? {} : (JSON.parse(text) as Record<string, unknown>); | |
| 98 | const { path, body } = legacyOf(new URL(req.url).pathname, text === "" ? {} : (JSON.parse(text) as Record<string, unknown>)); | |
| 99 | 99 | seen.push({ method: req.method, path, auth, body }); |
| 100 | 100 | if (path === "/api/v1/games/agent/sync") |
| 101 | 101 | return Response.json({ composeSha: "", commands: [], agentSha: AGENT_SHA, ...(body["lend"] === "none" ? { lend: { token: RUNNER } } : {}) }); |
test/helpers/agent-v1.ts added +17
| @@ -0,0 +1,17 @@ | ||
| 1 | /** | |
| 2 | * A fake forge for a runner or a box agent under test answers the old paths; the agents speak | |
| 3 | * protocol 1 (`machines/protocol.ts`, #18457). `legacyOf` reads a v1 request as the old route | |
| 4 | * it stands for, so a fake's own routing and the bodies a test asserts stay as they were. | |
| 5 | */ | |
| 6 | ||
| 7 | const JOB_MESSAGES = ["logs", "result"]; | |
| 8 | ||
| 9 | export function legacyOf(path: string, body: Record<string, unknown>): { path: string; body: Record<string, unknown> } { | |
| 10 | const m = /^\/api\/v1\/agent\/v1\/(\w+)$/.exec(path)?.[1]; | |
| 11 | if (m === undefined) return { path, body }; | |
| 12 | const { v: _v, job, ...rest } = body; | |
| 13 | if (m === "heartbeat") return { path: "/api/v1/games/agent/sync", body: { v: _v, ...rest } }; | |
| 14 | if (m === "claim") return { path: "/api/v1/runner/claim", body: { v: _v, ...rest } }; | |
| 15 | if (JOB_MESSAGES.includes(m) && typeof job === "string") return { path: `/api/v1/runner/jobs/${job}`, body: rest }; | |
| 16 | return { path, body }; | |
| 17 | } |
test/runner-end-lines.test.ts +1 −1
| @@ -117,7 +117,7 @@ test("a report the forge never answers is given up, so the report loop goes on a | ||
| 117 | 117 | const server = Bun.serve({ |
| 118 | 118 | port: 0, |
| 119 | 119 | fetch: (req) => |
| 120 | new URL(req.url).pathname === "/api/v1/runner/jobs/j1" && reports++ === 0 | |
| 120 | new URL(req.url).pathname === "/api/v1/agent/v1/logs" && reports++ === 0 | |
| 121 | 121 | ? new Promise<Response>(() => {}) |
| 122 | 122 | : new Response(null, { status: 200 }), |
| 123 | 123 | }); |
test/runner-upgrade.test.ts +4 −3
| @@ -3,6 +3,7 @@ | ||
| 3 | 3 | * forge names its build in every claim answer, and when it changes the runner takes no new job, |
| 4 | 4 | * reports the one in hand, and ends for its host to start it from the current image. |
| 5 | 5 | */ |
| 6 | import { legacyOf } from "./helpers/agent-v1.ts"; | |
| 6 | 7 | import { afterAll, beforeAll, expect, test } from "bun:test"; |
| 7 | 8 | import { mkdtemp, rm } from "node:fs/promises"; |
| 8 | 9 | import { tmpdir } from "node:os"; |
| @@ -25,7 +26,7 @@ function fakeForge(answer: (n: number) => { build: string; job?: boolean }, onRe | ||
| 25 | 26 | const server = Bun.serve({ |
| 26 | 27 | port: 0, |
| 27 | 28 | async fetch(req) { |
| 28 | const path = new URL(req.url).pathname; | |
| 29 | const path = legacyOf(new URL(req.url).pathname, {}).path; | |
| 29 | 30 | if (path === "/api/v1/runner/claim") { |
| 30 | 31 | const a = answer(++claims); |
| 31 | 32 | events.push(`claim ${a.build}${a.job === true ? " job" : ""}`); |
| @@ -49,8 +50,8 @@ function fakeForge(answer: (n: number) => { build: string; job?: boolean }, onRe | ||
| 49 | 50 | }; |
| 50 | 51 | return Response.json({ job, token: "forge_job_x", lease: 30 }, { headers }); |
| 51 | 52 | } |
| 52 | if (path === "/api/v1/runner/jobs/j1") { | |
| 53 | const body = (await req.json()) as { abandon?: string }; | |
| 53 | if (new URL(req.url).pathname === "/api/v1/agent/v1/result" || new URL(req.url).pathname === "/api/v1/agent/v1/logs") { | |
| 54 | const body = legacyOf("/api/v1/agent/v1/result", (await req.json()) as Record<string, unknown>).body as { abandon?: string }; | |
| 54 | 55 | if (body.abandon === undefined) return new Response(null, { status: 200 }); |
| 55 | 56 | await onReport?.(); |
| 56 | 57 | events.push("reported"); |
new above
offline
The doc says the old routes go when no machine used version 0 for 30 days. Only the box sync records version 0. The old
/api/v1/runner/claim,/jobs/:idand heartbeat routes record nothing, so a deployed runner still on them is invisible tolastUse. Retiring routes from that query would cut off such a runner. Record version 0 use in the runner routes too (per runner id), or say plainly that only the box sync is tracked.