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

opened this

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

  • Merged. scout/18457-one-versioned-agent-protocol-heartbeat-c was merged into main as 9a6d9b3.

Review

Sign in to review this change.
23 files changed +762 −244
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

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/:id and heartbeat routes record nothing, so a deployed runner still on them is invisible to lastUse. 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.

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
378378 export { route as postApiV1AdminRunnersIdResume } from "./postApiV1AdminRunnersIdResume.ts";
379379 export { route as postApiV1AdminRunnersIdRevoke } from "./postApiV1AdminRunnersIdRevoke.ts";
380380 export { route as postApiV1AdminRunnersIdTrust } from "./postApiV1AdminRunnersIdTrust.ts";
381 export { route as postApiV1AgentV1Message } from "./postApiV1AgentV1Message.ts";
381382 export { route as postApiV1Agents } from "./postApiV1Agents.ts";
382383 export { route as postApiV1Apps } from "./postApiV1Apps.ts";
383384 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
@@ -60,6 +60,7 @@ const ALIAS: Readonly<Record<string, string>> = {
6060 sessions: "tokens",
6161 "first-admin": "admin",
6262 runner: "meta",
63 agent: "meta",
6364 health: "meta",
6465 version: "meta",
6566 releases: "meta",
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 @@
11 #!/usr/bin/env bash
22 # forge-game-agent (forge games, 2026-11-30): keeps a game box's Docker Compose project as the forge
33 # 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:
55 # writes compose.yml and the secret env files beside it and brings the project up when the compose
66 # sha (or an env file) changes, and runs the queued commands. Nothing dials in to the box. A failed
77 # sync waits 5 s and tries again, forever. The token is read from the environment (systemd's
@@ -101,7 +101,7 @@ boot_status() {
101101 # One word to the forge with a body built without jq; never fails the caller.
102102 say_boot() {
103103 curl -fsS -m 20 -H "@$AUTH" -H 'content-type: application/json' \
104 --data-binary "{\"agent\":1,\"boot\":$(json_str "$1")}" "${FORGE_URL%/}/api/v1/games/agent/sync" >/dev/null 2>&1 || true
104 --data-binary "{\"agent\":1,\"v\":1,\"boot\":$(json_str "$1")}" "${FORGE_URL%/}/api/v1/agent/v1/heartbeat" >/dev/null 2>&1 || true
105105 }
106106
107107 # ---- 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() {
17421742 else [.[0]] + (.[1:] | codes) end;
17431743 (if . == "" then ["0"] else split(";") end) | [codes[] | $t[.] // empty | "\u00a7" + .] | join("");
17441744 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: $sha, services: $services[0], logs: $logs[0], results: $results[0], host: $host[0], diag: $diag[0], people: $people[0], metrics: $metrics[0], snapshots: $snapshots[0], chat: $chat[0].lines, chatId: $chat[0].id, lend: $lend, lendWhy: $lendWhy, retry: $retry, jars: true, got: $got}
1745 {agent: 1, v: 1, composeSha: $sha, services: $services[0], logs: $logs[0], results: $results[0], host: $host[0], diag: $diag[0], people: $people[0], metrics: $metrics[0], snapshots: $snapshots[0], chat: $chat[0].lines, chatId: $chat[0].id, lend: $lend, lendWhy: $lendWhy, retry: $retry, jars: true, got: $got}
17461746 + (if $tokenSha == "" then {} else {tokenSha: $tokenSha} end)
17471747 + (if $ask[0] == [] then {} else {ask: $ask[0]} end)
17481748 | walk(if type == "string" then plain else . end)' >"$DIR/.sync.body" || return 1
17491749 # 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 "@$AUTH" -H 'content-type: application/json' --data-binary "@$DIR/.sync.body" -w '\n%{http_code}' "${FORGE_URL%/}/api/v1/games/agent/sync")" || answer=$'\nnothing'
1750 answer="$(curl -sS -m 20 -H "@$AUTH" -H 'content-type: application/json' --data-binary "@$DIR/.sync.body" -w '\n%{http_code}' "${FORGE_URL%/}/api/v1/agent/v1/heartbeat")" || answer=$'\nnothing'
17511751 code="${answer##*$'\n'}"
17521752 answer="${answer%$'\n'*}"
17531753 if [[ "$code" != 2?? ]]; then
@@ -2232,8 +2232,8 @@ light_sync() {
22322232 if [ -f "$DIR/.desk.due" ] && desk_here; then desk_take; else rm -f "$DIR/.desk.due"; echo '[]' >"$DIR/.sync.ask"; fi
22332233 json_or '[]' <"$DIR/.results" >"$DIR/.sync.results"
22342234 jq -cn --slurpfile ask "$DIR/.sync.ask" --arg sha "$(cat "$DIR/.compose-sha" 2>/dev/null)" --slurpfile results "$DIR/.sync.results" --argjson told "$(desk_here && echo true || echo false)" --argjson got "$(desk_got)" --arg deskv "$(cat "$DIR/.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)' >"$DIR/.sync.light" || return 1
2236 answer="$(curl -fsS -m 5 -H "@$AUTH" -H 'content-type: application/json' --data-binary "@$DIR/.sync.light" "${FORGE_URL%/}/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)' >"$DIR/.sync.light" || return 1
2236 answer="$(curl -fsS -m 5 -H "@$AUTH" -H 'content-type: application/json' --data-binary "@$DIR/.sync.light" "${FORGE_URL%/}/api/v1/agent/v1/heartbeat")" || { desk_again; return 1; }
22372237 echo '[]' >"$DIR/.results"
22382238 desk_heard "$DIR/.sync.light"
22392239 desk_told "$answer"
src/generated/marks.ts +214 −212
@@ -8,218 +8,219 @@ import k3 from "../http/marks/api-project-envelope.json";
88 import k4 from "../http/marks/api-project-otlp.json";
99 import k5 from "../http/marks/api-traces.json";
1010 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";
223224
224225 /** Each file of `http/marks/`, parsed, in name order. */
225226 export const MARK_FILES: readonly unknown[] = [
@@ -442,4 +443,5 @@ export const MARK_FILES: readonly unknown[] = [
442443 k216,
443444 k217,
444445 k218,
446 k219,
445447 ];
src/http/api.ts +2
@@ -349,6 +349,7 @@ import { tokenRoutes } from "./api/tokens.ts";
349349 import { accountAdmin, adminRoutes } from "./api/admin.ts";
350350 import { arcadeRoutes } from "./api/arcade.ts";
351351 import { runnerRoutes } from "./api/runners.ts";
352 import { agentV1Routes } from "./api/agent_v1.ts";
352353 import { environmentRoutes } from "./api/environments.ts";
353354 import { maintenanceRoutes } from "./api/maintenance.ts";
354355 import { maintenanceRunsRoutes } from "./api/maintenance_runs.ts";
@@ -1297,6 +1298,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
12971298 forgeOriginRoutes(router);
12981299 adminRoutes(router);
12991300 runnerRoutes(router);
1301 agentV1Routes(router);
13001302 environmentRoutes(router);
13011303 arcadeRoutes(router);
13021304 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 @@
99 * stranger's header: no page, no API route and no git door knows them.
1010 */
1111
12 import { noteUse } from "../../machines/agent_use.ts";
1213 import { dropHands, takeHand } from "../../checks/runner_hands.ts";
1314 import { HAND_BYTES_MAX } from "../../checks/hand_files.ts";
1415 import { listLending, offerLending, resumeLending, stopLending } from "../../actions/lending.ts";
@@ -60,7 +61,7 @@ import { accountAdmin } from "./admin.ts";
6061 /** The longest a claim waits for a job, in seconds: under every proxy's own patience. */
6162 export const CLAIM_WAIT_MAX_S = 25;
6263 /** 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;
6465 const LINES_MAX = 5_000;
6566
6667 const bearer = (request: Request): string =>
@@ -124,7 +125,25 @@ function packShareOf(app: App): PackShare {
124125 return share;
125126 }
126127
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;
128147 router.add("POST", "/api/v1/admin/runners", async (ctx) => {
129148 const denied = accountAdmin(ctx, "admin");
130149 if (denied) return denied;
@@ -235,7 +254,7 @@ export function runnerRoutes(router: Router<Handler>): void {
235254
236255 // A runner says it is here, in what state, and which labels it holds (#18037). Silence past
237256 // `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) => {
239258 const runner = runnerByToken(ctx.app.db, bearer(ctx.request), Date.now());
240259 if (runner === undefined) return unauthorized();
241260 const input = await boundedBody(ctx.request, STRANGER_MAX);
@@ -246,10 +265,10 @@ export function runnerRoutes(router: Router<Handler>): void {
246265 noteHeartbeat(ctx.app.db, runner.id, { state });
247266 wakeClaimers(ctx.app);
248267 return new Response(null, { status: 204 });
249 });
268 }, false));
250269
251270 // 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) => {
253272 const runner = runnerByToken(ctx.app.db, bearer(ctx.request), Date.now());
254273 if (runner === undefined) return unauthorized();
255274 const input = await boundedBody(ctx.request, STRANGER_MAX);
@@ -288,7 +307,7 @@ export function runnerRoutes(router: Router<Handler>): void {
288307 // (`perf/in_flight.ts`).
289308 await inFlight.rest(ctx.request, () => nextOffer(ctx.app, left, stop));
290309 }
291 });
310 }, false));
292311
293312 /** The job this request's token holds, with the check waiting on it here; else nothing. */
294313 const held = (ctx: Ctx) => {
@@ -304,7 +323,7 @@ export function runnerRoutes(router: Router<Handler>): void {
304323 };
305324
306325 // 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) => {
308327 const mine = held(ctx);
309328 if (mine === undefined) {
310329 // 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 {
367386 }
368387 if (!renewJob(ctx.app.db, mine.job.id, token, Date.now())) return notFound();
369388 return json({ lease });
370 });
389 }, true));
371390
372391 // The job's seed door: the files the forge seeded its checkout with, by the path, size and hash
373392 // 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 @@
33 * bearer), the signed jar download, and the `/games` pages (`web/pages/games.ts`).
44 */
55
6 import { noteUse } from "../machines/agent_use.ts";
67 import { applyWhenQuiet } from "../games/when_quiet.ts";
78 import { composeServices, readCompose } from "../games/compose.ts";
89 import { watchAgent } from "../games/agent_watch.ts";
@@ -168,7 +169,13 @@ export function gameAgentScript(ctx: Ctx): Response {
168169 }
169170
170171 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 });
172179 router.add("GET", "/api/v1/games/agent/script", gameAgentScript);
173180 }
174181
src/http/lazy_lists.ts +1
@@ -1361,6 +1361,7 @@ export const API_ROUTES = [
13611361 ["POST", "/api/v1/runner/jobs/:id/hand"],
13621362 ["GET", "/api/v1/runner/jobs/:id/git/info/refs"],
13631363 ["POST", "/api/v1/runner/jobs/:id/git/git-upload-pack"],
1364 ["POST", "/api/v1/agent/v1/:message"],
13641365 ["GET", "/api/v1/repos/:owner/:name/environments"],
13651366 ["PUT", "/api/v1/repos/:owner/:name/environments/:env/:entry"],
13661367 ["DELETE", "/api/v1/repos/:owner/:name/environments/:env/:entry"],
src/http/marks/api-v1-agent.json added +4
@@ -0,0 +1,4 @@
1 {
2 "head": "/api/v1/agent",
3 "mark": "open"
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";
5757 import { isSafeOid } from "../git/guard.ts";
5858 import { background } from "../perf/jobs.ts";
5959 import { BuildWatch, exitOnUpgrade, RUNNER_VERSION_HEADER } from "./upgrade.ts";
60 import { PROTOCOL_VERSION, splitReport } from "../machines/protocol.ts";
6061
6162 /**
6263 * 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;
7172 */
7273 export const jobReporter =
7374 (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 };
8189
8290 /** How often a job's lines go to the forge; each report renews the lease. */
8391 const REPORT_MS = 1_000;
@@ -707,9 +715,9 @@ export async function runRunner(options: RunnerOptions): Promise<RunnerEnd> {
707715 let res: Response;
708716 try {
709717 res = await post(
710 "/api/v1/runner/claim",
718 "/api/v1/agent/v1/claim",
711719 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 },
713721 AbortSignal.any([asking, yielding.signal]),
714722 );
715723 } 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", () => {
8484 expect(await p.exited).toBe(0);
8585 const said = await new Response(p.stderr).text();
8686 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" ' });
8888 expect(said).toContain("missing jq; saying so and checking again in 30s");
8989 } finally {
9090 forge.stop();
@@ -104,7 +104,7 @@ describe("the agent, missing a tool", () => {
104104 });
105105 const p = Bun.spawn(["bash", AGENT, "--boot-report"], { env: { PATH: bin, FORGE_GAME_DIR: dir }, stdout: "pipe", stderr: "pipe" });
106106 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 " }]);
108108 } finally {
109109 forge.stop();
110110 await rm(box, { recursive: true, force: true });
test/game-lend-box.test.ts +2 −2
@@ -6,6 +6,7 @@
66 * stand-ins for what needs root (systemd-run, bwrap, systemctl, docker, git) that record what
77 * they were asked.
88 */
9 import { legacyOf } from "./helpers/agent-v1.ts";
910 import { $ } from "bun";
1011 import { afterEach, describe, expect, test } from "bun:test";
1112 import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs";
@@ -92,10 +93,9 @@ exit 0`,
9293 port: 0,
9394 hostname: "127.0.0.1",
9495 async fetch(req) {
95 const path = new URL(req.url).pathname;
9696 const auth = req.headers.get("authorization") ?? "";
9797 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>));
9999 seen.push({ method: req.method, path, auth, body });
100100 if (path === "/api/v1/games/agent/sync")
101101 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
117117 const server = Bun.serve({
118118 port: 0,
119119 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
121121 ? new Promise<Response>(() => {})
122122 : new Response(null, { status: 200 }),
123123 });
test/runner-upgrade.test.ts +4 −3
@@ -3,6 +3,7 @@
33 * forge names its build in every claim answer, and when it changes the runner takes no new job,
44 * reports the one in hand, and ends for its host to start it from the current image.
55 */
6 import { legacyOf } from "./helpers/agent-v1.ts";
67 import { afterAll, beforeAll, expect, test } from "bun:test";
78 import { mkdtemp, rm } from "node:fs/promises";
89 import { tmpdir } from "node:os";
@@ -25,7 +26,7 @@ function fakeForge(answer: (n: number) => { build: string; job?: boolean }, onRe
2526 const server = Bun.serve({
2627 port: 0,
2728 async fetch(req) {
28 const path = new URL(req.url).pathname;
29 const path = legacyOf(new URL(req.url).pathname, {}).path;
2930 if (path === "/api/v1/runner/claim") {
3031 const a = answer(++claims);
3132 events.push(`claim ${a.build}${a.job === true ? " job" : ""}`);
@@ -49,8 +50,8 @@ function fakeForge(answer: (n: number) => { build: string; job?: boolean }, onRe
4950 };
5051 return Response.json({ job, token: "forge_job_x", lease: 30 }, { headers });
5152 }
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 };
5455 if (body.abandon === undefined) return new Response(null, { status: 200 });
5556 await onReport?.();
5657 events.push("reported");

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs