podster 0.0.0-stage → 0.0.1-test.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +96 -2
  2. package/build/core/adapter.js +1 -0
  3. package/build/core/broker.js +461 -0
  4. package/build/core/capabilities.js +42 -0
  5. package/build/core/claude-profile.js +35 -0
  6. package/build/core/connection.js +106 -0
  7. package/build/core/errors.js +115 -0
  8. package/build/core/gateway.js +93 -0
  9. package/build/core/lifecycle.js +1206 -0
  10. package/build/core/pairing.js +285 -0
  11. package/build/core/policy.js +741 -0
  12. package/build/core/poller.js +253 -0
  13. package/build/core/prompt.js +93 -0
  14. package/build/core/record.js +106 -0
  15. package/build/core/repository.js +272 -0
  16. package/build/core/results.js +149 -0
  17. package/build/core/run-interface.js +464 -0
  18. package/build/core/runs.js +172 -0
  19. package/build/core/runtime.js +38 -0
  20. package/build/core/state.js +41 -0
  21. package/build/core/storage.js +105 -0
  22. package/build/core/thumbprint.js +15 -0
  23. package/build/core/tool-policy.js +130 -0
  24. package/build/node/broker-listener.js +183 -0
  25. package/build/node/child-env.js +26 -0
  26. package/build/node/claude-driver.js +741 -0
  27. package/build/node/claude-engine.js +196 -0
  28. package/build/node/cli.js +249 -0
  29. package/build/node/docker-sandbox.js +465 -0
  30. package/build/node/file-runs.js +63 -0
  31. package/build/node/file-state.js +73 -0
  32. package/build/node/git.js +124 -0
  33. package/build/node/github-api.js +79 -0
  34. package/build/node/hidden-input.js +47 -0
  35. package/build/node/key-store.js +150 -0
  36. package/build/node/keychain.js +160 -0
  37. package/build/node/local-stop.js +67 -0
  38. package/build/node/lock.js +155 -0
  39. package/build/node/platform.js +127 -0
  40. package/build/node/policy-file.js +13 -0
  41. package/build/node/prompter.js +166 -0
  42. package/build/node/provider-transport.js +181 -0
  43. package/build/node/repo-path.js +370 -0
  44. package/build/node/run-command.js +59 -0
  45. package/build/node/safe-fs.js +244 -0
  46. package/claude-image/Dockerfile +29 -0
  47. package/git/credential-helper +23 -0
  48. package/npm-shrinkwrap.json +3173 -0
  49. package/package.json +47 -4
  50. package/sandbox/Dockerfile +17 -0
package/README.md CHANGED
@@ -1,3 +1,97 @@
1
- # Temporary Holding Version
1
+ # podster (Runner, test pre-release)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Test pre-release for Podster's staging only. Not supported. Not security-reviewed (M7 step 17 pending).**
4
+
5
+ Don't use it with anything you can't lose. It talks to Podster's staging deployment, which can be reset at any time. Versions are `0.0.x-test.N`, published only under npm's `test` tag; npm may also point `latest` at the first version. The real release, once M7's gate and security review pass, replaces it.
6
+
7
+ Runner pairs your machine with one of your Podster agents, then polls that agent's inbox from your machine, outbound only. With your provider key it runs the tasks its run policy allows, in Docker containers. Unattended runs are off by default: you approve each run at your terminal unless you switch them on for a workroom in Runner's own run policy, `policy.json` in Runner's home. Nothing Podster sends can switch them on.
8
+
9
+ ## Requirements
10
+
11
+ - Node 22 or later.
12
+ - To run tasks, Docker on one of these, since Claude Code and each task run in their own containers:
13
+ - macOS, with Docker Desktop;
14
+ - Linux, with Docker Engine ([Linux](#linux));
15
+ - Windows, only inside a WSL2 Linux distro with Docker Desktop's WSL integration ([Windows (WSL2)](#windows-wsl2)). Runner refuses native Windows.
16
+
17
+ On any other system Runner refuses to run tasks (`platform_unverified`), and pairing and polling still work.
18
+ - Git at `/usr/bin/git`, `/opt/homebrew/bin/git` or `/usr/local/bin/git`.
19
+
20
+ ## Commands
21
+
22
+ Run it with install scripts off, as below: no dependency Runner uses needs one. Or set `npm_config_ignore_scripts=true` in your environment. The package ships `npm-shrinkwrap.json`, so `npx` installs exactly the dependencies Runner was tested with.
23
+
24
+ Pair this machine with the agent a pairing in Podster started. Paste the code when asked: it's never an argument.
25
+
26
+ ```bash
27
+ npx --ignore-scripts podster@test pair --agent <agt_…>
28
+ ```
29
+
30
+ The gateway is staging's, `https://gateway-staging.podster.dev`, unless you name another with `--gateway <https://…>`.
31
+
32
+ Poll the inbox until you stop it with Ctrl-C:
33
+
34
+ ```bash
35
+ npx --ignore-scripts podster@test run
36
+ npx --ignore-scripts podster@test run --provider-key-file <path>
37
+ ```
38
+
39
+ Then:
40
+
41
+ ```bash
42
+ npx --ignore-scripts podster@test status # what this Runner's record says, by IDs
43
+ npx --ignore-scripts podster@test stop # stop the Runner running from this home, and any run, at once
44
+ npx --ignore-scripts podster@test forget # delete this Runner's keys and record; disconnect the agent in Podster yourself
45
+ ```
46
+
47
+ Every command takes `--home <folder>`, Runner's own folder. The default is `~/.podster-runner`.
48
+
49
+ Running tasks needs plain paths: letters, digits, `.`, `_`, `-` and `/` only. If your home folder's path has a space or any other character, Runner refuses to run tasks (`helper_unavailable`, or `path_unsafe` for its home), since both npm's cache, where `npx` puts Runner (`<cache>/_npx`), and `~/.podster-runner` sit under it. Then point npm's cache and Runner's home at plain folders only you can write, for example `npm_config_cache=/Users/Shared/podster-npm npx --ignore-scripts podster@test run --home /Users/Shared/podster-runner …`, and use the same two on every command.
50
+
51
+ ## Your provider key
52
+
53
+ Without `--provider-key-file`, `run` records offers and accepts none.
54
+
55
+ To run tasks, put your Anthropic API key alone in a file that you own and only you can read, then pass its path:
56
+
57
+ ```bash
58
+ chmod 600 <path>
59
+ ```
60
+
61
+ Runner refuses a key file that's a link, that someone else can read, or that holds anything but one key. It reads the key once and keeps it on your machine, in its own process: never in a task's container, a log, an argument or the environment of anything it starts. Use a key with a spending limit you set at the provider.
62
+
63
+ Runner's two container images, one for each task and one for Claude Code, are pinned by image ID in Runner's home. The first time `run --provider-key-file` finds one missing, Runner builds it with Docker from the Dockerfile in this package, says so first, and pins what it built. A build takes a few minutes, and the Claude Code image downloads Claude Code from npm's registry. If a build fails, `run` stops before running anything.
64
+
65
+ ## Linux
66
+
67
+ **Validated so far only by CI's Linux job,** on GitHub's Ubuntu runner with Docker Engine (S-47). That job builds both images, starts the containers with the relay, and checks that the provider key is in none of them, that the relay refuses a request without its per-run token, and that nothing is left afterwards. It calls no provider. No task has run end to end with Claude Code on Linux yet.
68
+
69
+ You need:
70
+
71
+ - Docker Engine, which your user can reach without `sudo`: `docker version` names a server. Rootful Docker only. Rootless Docker, user-namespace remapping, and SELinux enforcing on bind mounts aren't supported yet, so Runner's check fails there.
72
+ - `docker` at `/usr/bin/docker` or `/usr/local/bin/docker`.
73
+ - Runner's home and the workspace root in the Linux file system, owned by you. On Linux, Runner's home path may be at most 51 bytes, so each run's Unix socket path fits; the default, `~/.podster-runner`, does. A longer `--home` is refused with a message saying so.
74
+
75
+ How it differs from macOS:
76
+
77
+ - **The relay.** On a Mac, Claude Code's requests reach Runner's listener over TCP through Docker Desktop's `host.docker.internal`. On Linux the listener is a Unix socket in the run's own folder, mode 600, which only the relay container mounts, read-only, and forwards to with `socat`. The relay joins no network but the run's internal one, and no TCP port opens on your machine. The per-run token is still required.
78
+ - **A check before any task.** `run --provider-key-file` first checks that Docker answers, then sends one request from a throwaway Claude Code container through the relay to a throwaway listener. If either fails, Runner refuses to run tasks (`linux_check_failed`), says which part failed, and runs nothing. Pairing and polling still work.
79
+ - **Where your keys go.** If the Secret Service answers (GNOME Keyring or KWallet, through `/usr/bin/secret-tool`), Runner keeps its keys there. Otherwise it keeps them in files under `keys/` in Runner's home: the folder mode 700 and each file mode 600, both yours, each replaced whole when written. Runner refuses a key folder or file with any other mode or owner. Anyone who can read your files can read these. Runner prints one line saying which store it uses. The choice is made once per home, in `key-store` there, so a locked keyring later shows as an error rather than a lost pairing.
80
+
81
+ ## Windows (WSL2)
82
+
83
+ **Validated only by CI's Linux job and by M7's staging run (step 16) on Long's machine.** Nothing else has run Runner under WSL2.
84
+
85
+ Runner on Windows runs inside a WSL2 Linux distro and follows the Linux path above. Native Windows is refused, with a message pointing here.
86
+
87
+ 1. Install WSL2 and a distro such as Ubuntu: `wsl --install` in PowerShell.
88
+ 2. Install Docker Desktop for Windows with its WSL2 backend.
89
+ 3. In Docker Desktop, open **Settings > Resources > WSL integration** and turn it on for your distro. Apply, then open a new terminal in the distro.
90
+ 4. In the distro, `docker version` should name a server. Install Node 22 or later in the distro, not on Windows, and run the `npx --ignore-scripts podster@test …` commands above from the distro's terminal.
91
+ 5. Keep Runner's home and your workspace root in the distro's own file system, such as `~/.podster-runner`. Runner refuses either one under `/mnt/<drive>` (the Windows file system, where Linux file modes aren't enforced and access is slow), and refuses Runner's home on any 9p or drvfs mount.
92
+
93
+ A WSL2 distro usually has no Secret Service, so Runner uses its file store there and says so.
94
+
95
+ ## Where it comes from
96
+
97
+ Each version is built and published by the `runner-prerelease` workflow on `main` of `github.com/thachp/podster`, with npm provenance. The one possible exception is the first, `0.0.1-test.1`, which the owner may publish once from that workflow's own build, without provenance (see `docs/runner-prerelease.md` in the repository). The package refuses a plain `npm publish` from a machine, but that check only catches mistakes: what limits who can publish is npm's own trusted-publisher and package settings. MIT licensed.
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,461 @@
1
+ /**
2
+ * Runner's provider broker, its pure part (M7 step 9(a); the architect's rulings 3 and 5 on spike B). The hard stop for
3
+ * spend, turns and output tokens lives here, not in any SDK (S-37, S-42):
4
+ *
5
+ * - **A fixed upstream.** A request goes only to the URL built from the provider profile's fixed parts, in the adapter's
6
+ * own code. Nothing is copied from the request: not its host, path, query or headers. It must name the profile's one
7
+ * path, with no query, by POST.
8
+ * - **`max_tokens` is rewritten on every request** to the run's bound, and never above what's left of the run's output
9
+ * tokens. The body is parsed and written again, so a duplicate key can't carry another value past the rewrite.
10
+ * - **The worst case is reserved before a request goes.** Each body byte counts as an input token at the dearest input
11
+ * price, plus a fixed margin for the provider's hidden tool prompt, and all of `max_tokens` as output. A request whose worst case would pass what's left of the spend cap, after
12
+ * every request still in flight, is refused. So spend never passes the cap on the provider's own usage.
13
+ * - **Only a known body** (M1 on #459): known top-level keys, `output_config`, adaptive `thinking`, top-level
14
+ * `cache_control` and a tool's `eager_input_streaming` only in their reviewed shapes (three reviewed widenings, all
15
+ * 2026-11-18), and a system-role message of text only (the fourth); every beta-only key and every other declared key not ruled in stays refused by name; tools only the driver's own (`custom`), never the
16
+ * provider's server tools; content blocks only text, image or document (base64 or text sources), tool use, tool results
17
+ * and thinking, with documents in plain text only (a PDF bills beyond the body's bytes); no MCP servers, container, speed or service tier, and no cache lifetime. Anything else could act or
18
+ * spend outside Runner's tools and its worst case. A profile's fixed headers may not turn on a beta.
19
+ * - **A model with no price is refused,** never counted as free. A run's model list is checked against the price table
20
+ * when the broker is made.
21
+ * - **Turns** are model requests: exactly the cap's number go, and the next is refused.
22
+ * - A refusal for spend, turns or output tokens is a hard stop: the run is cancelled (`run-interface.ts`).
23
+ *
24
+ * What it counts is Runner's own running total. Usage the provider reports is priced here; a request whose usage never
25
+ * arrives, or can't be read, counts its whole worst case. An SDK's own spend figure is never read.
26
+ *
27
+ * Pure: no clock, no network, no randomness. Step 9(b) feeds it from a loopback listener and forwards through a transport
28
+ * that adds the owner's key, outside the task's container. Logs and refusals carry codes only.
29
+ */
30
+ const HARD = new Set(["turns_exhausted", "output_tokens_exhausted", "spend_cap"]);
31
+ /** The largest request body taken: far above a run's needs, and bounded so a body can't exhaust Runner. */
32
+ export const MAX_BODY_BYTES = 8 * 1024 * 1024;
33
+ /** Input tokens added to every request's worst case for what the provider adds unseen, such as its tool-use prompt. */
34
+ export const INPUT_MARGIN_TOKENS = 4_096;
35
+ const HOST_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
36
+ const PATH = /^(?:\/[A-Za-z0-9_-][A-Za-z0-9._-]*)+$/;
37
+ const MODEL = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
38
+ const isCount = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
39
+ const isCap = (v) => isCount(v) && v > 0;
40
+ function checkProfile(profile) {
41
+ if (Object.keys(profile.headers).some((name) => name.toLowerCase() === "anthropic-beta"))
42
+ throw new Error("the provider profile's fixed headers may not turn on a beta");
43
+ const labels = profile.host.split(".");
44
+ if (profile.host.length > 253 || labels.length < 2 || !labels.every((l) => HOST_LABEL.test(l)))
45
+ throw new Error("the provider profile's host isn't a plain host name");
46
+ if (!PATH.test(profile.path) || profile.path.split("/").some((s) => s === "." || s === ".."))
47
+ throw new Error("the provider profile's path isn't a plain path");
48
+ for (const [model, price] of Object.entries(profile.prices)) {
49
+ if (!MODEL.test(model))
50
+ throw new Error("the provider profile names a model Runner can't take");
51
+ if (![price.input, price.output, price.cache_write, price.cache_read].every(isCount))
52
+ throw new Error("the provider profile has a price that isn't a whole number of micro-USD");
53
+ const long = price.long_context;
54
+ if (long !== undefined && ![long.input, long.output, long.cache_write, long.cache_read, long.above_input_tokens].every(isCount))
55
+ throw new Error("the provider profile has a price that isn't a whole number of micro-USD");
56
+ }
57
+ }
58
+ /** The one URL a request is forwarded to, from the profile's fixed parts. */
59
+ export function upstreamUrl(profile) {
60
+ checkProfile(profile);
61
+ return `https://${profile.host}${profile.path}`;
62
+ }
63
+ const priced = (tokens, perMillion) => Math.ceil((tokens * perMillion) / 1_000_000);
64
+ /** What usage costs, rounded up, at the tier its input falls in. */
65
+ export function costOf(price, usage) {
66
+ const input = usage.input_tokens + usage.cache_creation_input_tokens + usage.cache_read_input_tokens;
67
+ const r = price.long_context !== undefined && input > price.long_context.above_input_tokens ? price.long_context : price;
68
+ return priced(usage.input_tokens, r.input) + priced(usage.output_tokens, r.output) + priced(usage.cache_creation_input_tokens, r.cache_write) + priced(usage.cache_read_input_tokens, r.cache_read);
69
+ }
70
+ /**
71
+ * The most a request can cost: each body byte, plus the margin, as an input token at the dearest input price, and all
72
+ * of `max_tokens` as output. The tier is the one that bound on input falls in: the long-context tier only when it is
73
+ * above that tier's threshold (re-review item 4 on #460), since a request's input tokens can't pass its bound.
74
+ */
75
+ export function worstCaseOf(price, bodyBytes, maxTokens) {
76
+ const bound = bodyBytes + INPUT_MARGIN_TOKENS;
77
+ const r = price.long_context !== undefined && bound > price.long_context.above_input_tokens ? price.long_context : price;
78
+ return priced(bound, Math.max(r.input, r.cache_write, r.cache_read)) + priced(maxTokens, r.output);
79
+ }
80
+ function usageOf(v) {
81
+ if (typeof v !== "object" || v === null || Array.isArray(v))
82
+ return null;
83
+ const u = v;
84
+ const input = u.input_tokens;
85
+ const output = u.output_tokens;
86
+ const write = u.cache_creation_input_tokens ?? 0;
87
+ const read = u.cache_read_input_tokens ?? 0;
88
+ if (!isCount(input) || !isCount(output) || !isCount(write) || !isCount(read))
89
+ return null;
90
+ return { input_tokens: input, output_tokens: output, cache_creation_input_tokens: write, cache_read_input_tokens: read };
91
+ }
92
+ const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
93
+ const only = (o, keys) => Object.keys(o).every((k) => keys.includes(k));
94
+ const optional = (v, check) => v === undefined || check(v);
95
+ const isText = (v) => typeof v === "string";
96
+ const TOP_KEYS = ["model", "messages", "max_tokens", "system", "metadata", "stop_sequences", "stream", "temperature", "top_k", "top_p", "tools", "tool_choice", "thinking", "output_config", "cache_control"];
97
+ /** `output_config.effort`, exactly the enum the pinned SDK 0.3.327 declares (its Messages `OutputConfig` type). */
98
+ const EFFORTS = ["low", "medium", "high", "xhigh", "max"];
99
+ /**
100
+ * `output_config`, the first reviewed widening of the allowlist (the architect's ruling of 2026-11-18, after #460's
101
+ * third real run, where Claude Code sent it on every request): an object holding at most `effort`, from the SDK's
102
+ * enum, and `format`, exactly `{ type: "json_schema", schema: {…} }`. Any other key is refused by name. It touches
103
+ * neither `max_tokens` nor the worst case, which are computed the same with or without it.
104
+ */
105
+ function outputConfigRefusal(v) {
106
+ if (!isObj(v))
107
+ return "output_config";
108
+ const extra = Object.keys(v).find((k) => k !== "effort" && k !== "format");
109
+ if (extra !== undefined)
110
+ return `output_config_key:${nameCode(extra)}`;
111
+ if (v.effort !== undefined && !(typeof v.effort === "string" && EFFORTS.includes(v.effort)))
112
+ return "output_config:effort";
113
+ if (v.format !== undefined) {
114
+ const f = v.format;
115
+ if (!isObj(f) || !only(f, ["type", "schema"]) || f.type !== "json_schema" || !isObj(f.schema))
116
+ return "output_config:format";
117
+ }
118
+ return null;
119
+ }
120
+ /** Only `{ type: "ephemeral" }`: no lifetime, which would buy a longer, dearer cache. */
121
+ const cacheOk = (v) => v === undefined || (isObj(v) && only(v, ["type"]) && v.type === "ephemeral");
122
+ function sourceOk(v, kinds) {
123
+ if (!isObj(v) || typeof v.type !== "string" || !kinds.includes(v.type))
124
+ return false;
125
+ return only(v, ["type", "media_type", "data"]) && isText(v.media_type) && isText(v.data);
126
+ }
127
+ /** A content block; inside a tool result, only text, images and documents. */
128
+ function blockOk(v, inResult = false) {
129
+ if (!isObj(v) || typeof v.type !== "string" || !cacheOk(v.cache_control))
130
+ return false;
131
+ switch (v.type) {
132
+ case "text":
133
+ return only(v, ["type", "text", "cache_control"]) && isText(v.text);
134
+ case "image":
135
+ return only(v, ["type", "source", "cache_control"]) && sourceOk(v.source, ["base64"]);
136
+ case "document":
137
+ return only(v, ["type", "source", "cache_control", "title", "context"]) && sourceOk(v.source, ["base64", "text"]) && v.source.media_type === "text/plain" && optional(v.title, isText) && optional(v.context, isText);
138
+ case "tool_use":
139
+ return !inResult && only(v, ["type", "id", "name", "input", "cache_control"]) && isText(v.id) && isText(v.name) && isObj(v.input);
140
+ case "tool_result":
141
+ return !inResult && only(v, ["type", "tool_use_id", "content", "is_error", "cache_control"]) && isText(v.tool_use_id) && optional(v.is_error, (e) => typeof e === "boolean") && optional(v.content, (c) => isText(c) || (Array.isArray(c) && c.every((b) => blockOk(b, true))));
142
+ case "thinking":
143
+ return !inResult && only(v, ["type", "thinking", "signature"]) && isText(v.thinking) && optional(v.signature, isText);
144
+ case "redacted_thinking":
145
+ return !inResult && only(v, ["type", "data"]) && isText(v.data);
146
+ default:
147
+ return false;
148
+ }
149
+ }
150
+ const contentOk = (v) => isText(v) || (Array.isArray(v) && v.every((b) => blockOk(b)));
151
+ /** A tool's keys. `eager_input_streaming`, a boolean, is the third reviewed widening's (2026-11-18). */
152
+ const TOOL_KEYS = ["type", "name", "description", "input_schema", "cache_control", "eager_input_streaming"];
153
+ function toolOk(v) {
154
+ if (!isObj(v) || !only(v, TOOL_KEYS))
155
+ return false;
156
+ return (v.type === undefined || v.type === "custom") && isText(v.name) && optional(v.description, isText) && isObj(v.input_schema) && cacheOk(v.cache_control) && optional(v.eager_input_streaming, (e) => typeof e === "boolean");
157
+ }
158
+ /** A name from the request as a code: itself if it's a plain identifier, else `other`. */
159
+ const nameCode = (v) => (typeof v === "string" && /^[a-z][a-z0-9_]{0,39}$/.test(v) ? v : "other");
160
+ /** The first part of a content block outside the allowlist, as a code; null when the block is allowed. */
161
+ /** Each block type's keys, as `blockOk` takes them. */
162
+ const BLOCK_KEYS = {
163
+ text: ["type", "text", "cache_control"],
164
+ image: ["type", "source", "cache_control"],
165
+ document: ["type", "source", "cache_control", "title", "context"],
166
+ tool_use: ["type", "id", "name", "input", "cache_control"],
167
+ tool_result: ["type", "tool_use_id", "content", "is_error", "cache_control"],
168
+ thinking: ["type", "thinking", "signature"],
169
+ redacted_thinking: ["type", "data"],
170
+ };
171
+ /** Only these may sit inside a tool result's content. */
172
+ const RESULT_BLOCKS = ["text", "image", "document"];
173
+ /** A media type as a code: itself when it is a plain `kind/subtype`, else `other`. */
174
+ const mediaCode = (v) => (typeof v === "string" && /^[a-z]+\/[a-z0-9.+-]{1,40}$/.test(v) ? v : "other");
175
+ /**
176
+ * The first part of a content block outside the allowlist, as a precise code (the sixth real run of #460); null when
177
+ * the block is allowed. It refuses exactly what `blockOk` refuses: the code only says where.
178
+ */
179
+ function blockRefusal(v, inResult = false) {
180
+ if (blockOk(v, inResult))
181
+ return null;
182
+ if (!isObj(v) || typeof v.type !== "string" || !Object.hasOwn(BLOCK_KEYS, v.type))
183
+ return `${inResult ? "tool_result_content_type" : "content_type"}:${nameCode(isObj(v) ? v.type : undefined)}`;
184
+ const type = v.type;
185
+ if (inResult && !RESULT_BLOCKS.includes(type))
186
+ return `tool_result_content_type:${type}`;
187
+ const extra = Object.keys(v).find((k) => !BLOCK_KEYS[type].includes(k));
188
+ if (extra !== undefined)
189
+ return `block_key:${type}.${nameCode(extra)}`;
190
+ if (v.cache_control !== undefined && !cacheOk(v.cache_control))
191
+ return isObj(v.cache_control) && Object.hasOwn(v.cache_control, "ttl") ? "cache_control_ttl" : "cache_control";
192
+ if (type === "image" || type === "document") {
193
+ const source = v.source;
194
+ if (!isObj(source))
195
+ return `block_shape:${type}`;
196
+ const kinds = type === "image" ? ["base64"] : ["base64", "text"];
197
+ if (!kinds.includes(source.type))
198
+ return `source_type:${nameCode(source.type)}`;
199
+ if (type === "document" && source.media_type !== "text/plain")
200
+ return `media_type:${mediaCode(source.media_type)}`;
201
+ }
202
+ if (type === "tool_result" && Array.isArray(v.content)) {
203
+ for (const inner of v.content) {
204
+ const refused = blockRefusal(inner, true);
205
+ if (refused !== null)
206
+ return refused;
207
+ }
208
+ }
209
+ return `block_shape:${type}`;
210
+ }
211
+ /**
212
+ * A system-role message's content blocks: the fourth reviewed widening (the architect's ruling of 2026-11-18, after
213
+ * #460's seventh real run, where Claude Code sent one with every request). Only `text` blocks, each with at most an
214
+ * ephemeral `cache_control`, as with a string. The architect's reasoning: it is Claude Code's own system-reminder text,
215
+ * not the task's, so it gives the model nothing beyond the system prompt Runner already sends; its bytes count toward
216
+ * the worst case like any other content.
217
+ */
218
+ function systemMessageRefusal(blocks) {
219
+ for (const block of blocks) {
220
+ if (!isObj(block) || typeof block.type !== "string")
221
+ return "system_message_shape";
222
+ if (block.type !== "text")
223
+ return `system_message_type:${nameCode(block.type)}`;
224
+ const extra = Object.keys(block).find((k) => k !== "type" && k !== "text" && k !== "cache_control");
225
+ if (extra !== undefined)
226
+ return `system_message_key:${nameCode(extra)}`;
227
+ if (block.cache_control !== undefined && !cacheOk(block.cache_control))
228
+ return isObj(block.cache_control) && Object.hasOwn(block.cache_control, "ttl") ? "cache_control_ttl" : "cache_control";
229
+ if (!isText(block.text))
230
+ return "system_message_shape";
231
+ }
232
+ return null;
233
+ }
234
+ /** `thinking.display` for adaptive thinking, exactly the enum SDK 0.3.327 declares (its `ThinkingConfigAdaptive`). */
235
+ const THINKING_DISPLAYS = ["summarized", "omitted"];
236
+ /**
237
+ * `thinking`, as the allowlist takes it. The second reviewed widening (the architect's ruling of 2026-11-18, after
238
+ * #460's fourth real run, where Claude Code sent adaptive thinking on every request) adds `{ type: "adaptive" }`, with
239
+ * an optional `display` from the SDK's enum; `enabled` and `disabled`, with an optional `budget_tokens`, are taken as
240
+ * before. Any other type or inner key is refused by name. Thinking bills as output within `max_tokens`, which the
241
+ * broker rewrites and reserves in full, so the worst case covers it unchanged.
242
+ */
243
+ function thinkingRefusal(t) {
244
+ if (!isObj(t))
245
+ return "thinking";
246
+ if (t.type === "adaptive") {
247
+ const extra = Object.keys(t).find((k) => k !== "type" && k !== "display");
248
+ if (extra !== undefined)
249
+ return `thinking_key:${nameCode(extra)}`;
250
+ if (t.display !== undefined && !(typeof t.display === "string" && THINKING_DISPLAYS.includes(t.display)))
251
+ return "thinking:display";
252
+ return null;
253
+ }
254
+ if (t.type === "enabled" || t.type === "disabled") {
255
+ const extra = Object.keys(t).find((k) => k !== "type" && k !== "budget_tokens");
256
+ return extra === undefined ? null : `thinking_key:${nameCode(extra)}`;
257
+ }
258
+ return `thinking:${nameCode(t.type)}`;
259
+ }
260
+ /** The request body, by the allowlist: the first part refused, as a code, or null when the body is allowed. */
261
+ function bodyRefusal(b) {
262
+ const extra = Object.keys(b).find((k) => !TOP_KEYS.includes(k));
263
+ if (extra !== undefined)
264
+ return `top_key:${nameCode(extra)}`;
265
+ // Top-level automatic caching, exactly `{ type: "ephemeral" }`, no lifetime (the third reviewed widening). The worst
266
+ // case already prices every input byte at the dearest input-side rate, a cache write's included.
267
+ if (b.cache_control !== undefined && !(isObj(b.cache_control) && only(b.cache_control, ["type"]) && b.cache_control.type === "ephemeral"))
268
+ return "cache_control";
269
+ if (b.output_config !== undefined) {
270
+ const refused = outputConfigRefusal(b.output_config);
271
+ if (refused !== null)
272
+ return refused;
273
+ }
274
+ if (!Array.isArray(b.messages))
275
+ return "messages";
276
+ for (const m of b.messages) {
277
+ if (!isObj(m))
278
+ return "message_shape";
279
+ const key = Object.keys(m).find((k) => k !== "role" && k !== "content");
280
+ if (key !== undefined)
281
+ return `message_key:${nameCode(key)}`;
282
+ if (m.role !== "user" && m.role !== "assistant" && m.role !== "system")
283
+ return `message_role:${nameCode(m.role)}`;
284
+ if (isText(m.content))
285
+ continue;
286
+ if (!Array.isArray(m.content))
287
+ return "message_content";
288
+ if (m.role === "system") {
289
+ const refused = systemMessageRefusal(m.content);
290
+ if (refused !== null)
291
+ return refused;
292
+ continue;
293
+ }
294
+ for (const block of m.content) {
295
+ const refused = blockRefusal(block);
296
+ if (refused)
297
+ return refused;
298
+ }
299
+ }
300
+ if (!optional(b.system, (v) => isText(v) || (Array.isArray(v) && v.every((x) => isObj(x) && x.type === "text" && blockOk(x)))))
301
+ return "system";
302
+ if (b.tools !== undefined) {
303
+ if (!Array.isArray(b.tools))
304
+ return "tools";
305
+ for (const t of b.tools) {
306
+ if (!isObj(t))
307
+ return "tools";
308
+ const key = Object.keys(t).find((k) => !TOOL_KEYS.includes(k));
309
+ if (key !== undefined)
310
+ return `tool_key:${nameCode(key)}`;
311
+ if (t.type !== undefined && t.type !== "custom")
312
+ return `tool_type:${nameCode(t.type)}`;
313
+ if (!optional(t.eager_input_streaming, (e) => typeof e === "boolean"))
314
+ return "tool:eager_input_streaming";
315
+ if (!toolOk(t))
316
+ return "tool_shape";
317
+ }
318
+ }
319
+ if (!optional(b.tool_choice, (v) => isObj(v) && only(v, ["type", "name", "disable_parallel_tool_use"]) && ["auto", "any", "tool", "none"].includes(v.type)))
320
+ return "tool_choice";
321
+ if (b.thinking !== undefined) {
322
+ const refused = thinkingRefusal(b.thinking);
323
+ if (refused !== null)
324
+ return refused;
325
+ }
326
+ if (!optional(b.metadata, (v) => isObj(v) && only(v, ["user_id"])))
327
+ return "metadata";
328
+ if (!optional(b.stop_sequences, (v) => Array.isArray(v) && v.every(isText)))
329
+ return "stop_sequences";
330
+ if (!optional(b.stream, (v) => typeof v === "boolean"))
331
+ return "stream";
332
+ for (const k of ["temperature", "top_k", "top_p"])
333
+ if (!optional(b[k], (v) => typeof v === "number" && Number.isFinite(v)))
334
+ return k;
335
+ return null;
336
+ }
337
+ /** One run's broker: its caps, its allowed models, and its running total. */
338
+ export class RunBroker {
339
+ profile;
340
+ caps;
341
+ models;
342
+ url;
343
+ spent = 0;
344
+ outputUsed = 0;
345
+ turns = 0;
346
+ next = 0;
347
+ closed = false;
348
+ inFlight = new Map();
349
+ constructor(profile, caps, models) {
350
+ this.url = upstreamUrl(profile);
351
+ if (!isCap(caps.spend_micro_usd) || !isCap(caps.turns) || !isCap(caps.output_tokens) || !isCap(caps.max_tokens))
352
+ throw new Error("a run's caps must each be set, as a positive whole number");
353
+ for (const model of models)
354
+ if (!Object.hasOwn(profile.prices, model))
355
+ throw new Error("a run's model has no price in the provider profile, so Runner won't allow it");
356
+ this.profile = profile;
357
+ this.caps = { ...caps };
358
+ this.models = new Set(models);
359
+ }
360
+ /** Spend counted so far, with every request in flight at its worst case; turns; output tokens; requests in flight. */
361
+ get totals() {
362
+ let held = 0;
363
+ for (const f of this.inFlight.values())
364
+ held += f.worst;
365
+ return { spent_micro_usd: this.spent + held, turns: this.turns, output_tokens: this.outputUsed, in_flight: this.inFlight.size };
366
+ }
367
+ /** Refuses every later request. Requests in flight still settle, or count their worst case. */
368
+ close() {
369
+ this.closed = true;
370
+ }
371
+ admit(request) {
372
+ const refuse = (reason) => ({ ok: false, reason, hard_stop: HARD.has(reason) });
373
+ if (this.closed)
374
+ return refuse("run_stopped");
375
+ if (request.method !== "POST")
376
+ return refuse("method_not_allowed");
377
+ if (request.path !== this.profile.path)
378
+ return refuse("path_not_allowed");
379
+ if (request.query !== "")
380
+ return refuse("query_not_allowed");
381
+ if (request.body.byteLength > MAX_BODY_BYTES)
382
+ return refuse("body_too_large");
383
+ let body;
384
+ try {
385
+ body = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(request.body));
386
+ }
387
+ catch {
388
+ return refuse("body_invalid");
389
+ }
390
+ if (typeof body !== "object" || body === null || Array.isArray(body))
391
+ return refuse("body_invalid");
392
+ const fields = body;
393
+ const model = fields.model;
394
+ if (typeof model !== "string")
395
+ return refuse("body_invalid");
396
+ if (!Object.hasOwn(this.profile.prices, model))
397
+ return refuse("model_unpriced");
398
+ if (!this.models.has(model))
399
+ return refuse("model_not_allowed");
400
+ const refusedPart = bodyRefusal(fields);
401
+ if (refusedPart !== null)
402
+ return { ok: false, reason: "body_not_allowed", hard_stop: false, detail: refusedPart };
403
+ if (this.turns >= this.caps.turns)
404
+ return refuse("turns_exhausted");
405
+ let heldOutput = 0;
406
+ let heldSpend = 0;
407
+ for (const f of this.inFlight.values()) {
408
+ heldOutput += f.max_tokens;
409
+ heldSpend += f.worst;
410
+ }
411
+ const outputLeft = this.caps.output_tokens - this.outputUsed - heldOutput;
412
+ const asked = fields.max_tokens;
413
+ const bound = Math.min(this.caps.max_tokens, outputLeft, isCap(asked) ? asked : Number.POSITIVE_INFINITY);
414
+ if (bound <= 0)
415
+ return refuse("output_tokens_exhausted");
416
+ const rewritten = new TextEncoder().encode(JSON.stringify({ ...fields, max_tokens: bound }));
417
+ const worst = worstCaseOf(this.profile.prices[model], rewritten.byteLength, bound);
418
+ if (this.spent + heldSpend + worst > this.caps.spend_micro_usd)
419
+ return refuse("spend_cap");
420
+ const request_id = `req_${++this.next}`;
421
+ this.turns++;
422
+ this.inFlight.set(request_id, { worst, max_tokens: bound, price: this.profile.prices[model] });
423
+ return { ok: true, forward: { request_id, url: this.url, headers: { ...this.profile.headers }, body: rewritten, max_tokens: bound, worst_micro_usd: worst } };
424
+ }
425
+ /**
426
+ * Counts what a forwarded request cost, from the provider's usage, and says whether a cap is now reached. Usage that
427
+ * can't be read counts the request's worst case. A request the broker didn't admit, or already counted, changes nothing.
428
+ */
429
+ settle(request_id, usage) {
430
+ const held = this.inFlight.get(request_id);
431
+ if (!held)
432
+ return { cap_reached: this.reached() };
433
+ this.inFlight.delete(request_id);
434
+ const read = usageOf(usage);
435
+ if (read) {
436
+ this.spent += costOf(held.price, read);
437
+ this.outputUsed += read.output_tokens;
438
+ }
439
+ else {
440
+ this.spent += held.worst;
441
+ this.outputUsed += held.max_tokens;
442
+ }
443
+ return { cap_reached: this.reached() };
444
+ }
445
+ /** A request whose usage never arrived (cut, failed or lost): its whole worst case counts. */
446
+ fail(request_id) {
447
+ const held = this.inFlight.get(request_id);
448
+ if (!held)
449
+ return;
450
+ this.inFlight.delete(request_id);
451
+ this.spent += held.worst;
452
+ this.outputUsed += held.max_tokens;
453
+ }
454
+ reached() {
455
+ if (this.spent >= this.caps.spend_micro_usd)
456
+ return "spend_cap";
457
+ if (this.outputUsed >= this.caps.output_tokens)
458
+ return "output_tokens_exhausted";
459
+ return null;
460
+ }
461
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The capabilities Runner names when it registers its one agent (decision 230): what it uses, and nothing that merges,
3
+ * releases, makes, assigns or cancels work. They must lie within the gateway's `RUNNER_CAPABILITIES`, the paired host's
4
+ * defaults, or the plugin leaves the agent waiting for an approval the pairing never gives; a test reads the gateway's
5
+ * list and holds this one inside it.
6
+ *
7
+ * `get_repo_access` is back (M7 step 10), under the repository path's own rules (`repository.ts`): only for a repository
8
+ * the owner scoped locally, only where GitHub shows the default branch under ADR 0009's rules, one task branch and never
9
+ * the default one, a fixed set of GitHub calls with no merge, and the token kept in Runner's broker on the host. Only
10
+ * `src/node/repo-path.ts` calls it; a test holds that.
11
+ *
12
+ * Step 6 calls only the reads and the inbox. The lifecycle calls are named now so the registered agent is the one later
13
+ * steps use: Runner registers once per pairing and never again by itself.
14
+ */
15
+ export const RUNNER_CAPABILITIES = [
16
+ "get_identity",
17
+ "list_workspaces",
18
+ "get_workspace",
19
+ "get_workroom_brief",
20
+ "read_inbox",
21
+ "ack_inbox",
22
+ "list_tasks",
23
+ "get_task",
24
+ "accept_task",
25
+ "decline_task",
26
+ "release_task",
27
+ "send_message",
28
+ "list_messages",
29
+ "submit_task",
30
+ "create_upload",
31
+ "get_asset_link",
32
+ "list_assets",
33
+ "get_repo_access",
34
+ ];
35
+ /**
36
+ * Capabilities a deployment lists only while a feature is switched on: `get_repo_access` only where managed repositories
37
+ * are. Where the plugin refuses the whole list as naming one it doesn't have (`invalid_capabilities`), Runner registers
38
+ * once more without these, and nothing else is ever dropped or added.
39
+ */
40
+ export const SWITCHED = ["get_repo_access"];
41
+ /** Never named by Runner, whatever a later list says (decision 230). `get_repo_access` left this list in step 10. */
42
+ export const NEVER = ["merge_task", "deploy_release", "create_task", "assign_task", "cancel_task", "verify_task", "request_changes"];
@@ -0,0 +1,35 @@
1
+ /** The SDK and its bundled Claude Code, as spike B ran them. A new pair is admitted only after spike B's checks pass on it. */
2
+ export const PINNED_SDK_VERSION = "0.3.327";
3
+ export const PINNED_CLAUDE_CODE_VERSION = "2.1.327";
4
+ /** The model Runner asks for. */
5
+ export const CLAUDE_MODEL = "claude-haiku-5-5";
6
+ /**
7
+ * Micro-USD per million tokens. Input and output are Anthropic's list prices for Claude Haiku 5.5 (0.10 and 0.50 USD per
8
+ * million, read 2026-11-18 from the claude-api reference cached 2026-11-03, for prompts up to 100K tokens). Cache writes
9
+ * and reads are taken at 1.25 and 0.1 times input, as spike B assumed and the SDK's figures matched. Above 100K input
10
+ * tokens the list price rises to 0.50 and 2.50 USD; that tier is priced too, and the broker's worst case takes it.
11
+ */
12
+ const HAIKU_5_5 = {
13
+ input: 100_000,
14
+ output: 500_000,
15
+ cache_write: 125_000,
16
+ cache_read: 10_000,
17
+ // Above 100K input tokens: 0.50 and 2.50 USD per million, cache at the same 1.25 and 0.1 times (L6 on #460).
18
+ long_context: { above_input_tokens: 100_000, input: 500_000, output: 2_500_000, cache_write: 625_000, cache_read: 50_000 },
19
+ };
20
+ export const CLAUDE_PROFILE = Object.freeze({
21
+ provider: "anthropic",
22
+ host: "api.anthropic.com",
23
+ path: "/v1/messages",
24
+ headers: Object.freeze({ "anthropic-version": "2023-06-01", "content-type": "application/json" }),
25
+ prices: Object.freeze({ [CLAUDE_MODEL]: Object.freeze({ ...HAIKU_5_5, long_context: Object.freeze({ ...HAIKU_5_5.long_context }) }) }),
26
+ });
27
+ export const CLAUDE_MODELS = Object.freeze([CLAUDE_MODEL]);
28
+ /** Why the installed pair can't run, or null when it is exactly the pinned one. */
29
+ export function versionRefusal(found) {
30
+ if (found.sdk !== PINNED_SDK_VERSION)
31
+ return "sdk_version";
32
+ if (found.claude_code !== PINNED_CLAUDE_CODE_VERSION)
33
+ return "claude_code_version";
34
+ return null;
35
+ }