podster 0.0.0-stage → 0.0.1-test.2

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 (53) hide show
  1. package/README.md +116 -2
  2. package/build/core/adapter.js +1 -0
  3. package/build/core/broker.js +461 -0
  4. package/build/core/capabilities.js +49 -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 +1207 -0
  10. package/build/core/nudge.js +340 -0
  11. package/build/core/pairing.js +285 -0
  12. package/build/core/policy.js +741 -0
  13. package/build/core/poller.js +261 -0
  14. package/build/core/prompt.js +93 -0
  15. package/build/core/record.js +106 -0
  16. package/build/core/repository.js +272 -0
  17. package/build/core/results.js +149 -0
  18. package/build/core/run-interface.js +464 -0
  19. package/build/core/runs.js +172 -0
  20. package/build/core/runtime.js +38 -0
  21. package/build/core/state.js +41 -0
  22. package/build/core/storage.js +125 -0
  23. package/build/core/thumbprint.js +15 -0
  24. package/build/core/tool-policy.js +130 -0
  25. package/build/node/broker-listener.js +183 -0
  26. package/build/node/child-env.js +26 -0
  27. package/build/node/claude-driver.js +741 -0
  28. package/build/node/claude-engine.js +196 -0
  29. package/build/node/cli.js +273 -0
  30. package/build/node/docker-sandbox.js +465 -0
  31. package/build/node/file-runs.js +63 -0
  32. package/build/node/file-state.js +73 -0
  33. package/build/node/git.js +124 -0
  34. package/build/node/github-api.js +79 -0
  35. package/build/node/hidden-input.js +47 -0
  36. package/build/node/key-store.js +150 -0
  37. package/build/node/keychain.js +160 -0
  38. package/build/node/local-stop.js +67 -0
  39. package/build/node/lock.js +155 -0
  40. package/build/node/nudge-command.js +132 -0
  41. package/build/node/nudge-listener.js +137 -0
  42. package/build/node/platform.js +127 -0
  43. package/build/node/policy-file.js +13 -0
  44. package/build/node/prompter.js +166 -0
  45. package/build/node/provider-transport.js +181 -0
  46. package/build/node/repo-path.js +370 -0
  47. package/build/node/run-command.js +59 -0
  48. package/build/node/safe-fs.js +244 -0
  49. package/claude-image/Dockerfile +29 -0
  50. package/git/credential-helper +23 -0
  51. package/npm-shrinkwrap.json +3173 -0
  52. package/package.json +47 -4
  53. package/sandbox/Dockerfile +17 -0
@@ -0,0 +1,272 @@
1
+ /**
2
+ * The repository path's rules (M7 step 10; RUNNER.md "Workroom repository and local task copy" and "Proposed GitHub
3
+ * access"; ADR 0009). Pure: the node side (`src/node/repo-path.ts`) does the I/O and asks these functions what to accept.
4
+ *
5
+ * **Decision 230's own rules for `get_repo_access`.** Runner names the capability again only under these, since a
6
+ * token with contents write can commit straight to a default branch that no ruleset protects:
7
+ *
8
+ * 1. **The owner scopes it.** A room has a repository only when the machine's owner named it in Runner's local
9
+ * configuration, by full name and GitHub's numeric ID (L4 on #455). Nothing Podster or the task sends selects or
10
+ * widens it: `get_repo_access`'s answer must name exactly that repository and its canonical clone URL, and GitHub's
11
+ * own answer for it must carry that ID.
12
+ * 2. **Protected or nothing.** Before Runner fetches, pushes or opens anything, GitHub must say the default branch is
13
+ * under the three rules ADR 0009's rulesets put there (`pull_request`, `required_status_checks` and `update`). A
14
+ * repository without them, such as a private one on GitHub's Free plan, is refused (`repository_unprotected`).
15
+ * 3. **One branch, never the default.** Runner pushes exactly one refspec, `refs/heads/podster/<task>` to itself, with
16
+ * no `+`, never a tag, and refuses a default branch that is, or sits under, `podster/`.
17
+ * 4. **A fixed set of GitHub calls.** Read the repository, its branch rules and a ref; open, list and read a pull
18
+ * request. Never a merge, a ref update through the API, a review, a status or anything administrative.
19
+ * 5. **The token stays on the host.** It is held in Runner's memory by the broker, handed to host Git only through the
20
+ * credential helper's inherited descriptor, and never reaches a container, a file, an argument, an environment
21
+ * variable, a URL, Git's configuration or a log.
22
+ *
23
+ * Agent content is data: nothing here reads task text; a pull request's title and body are fixed words and the task's ID.
24
+ */
25
+ import { isFullName } from "./policy.js";
26
+ export { isFullName };
27
+ /** Why the repository path refused or failed, as a fixed code. Never text from GitHub, Git or Podster. */
28
+ export class RepoPathError extends Error {
29
+ code;
30
+ /** Worth trying again later: the network, a rate limit, a branch that moved while read. */
31
+ transient;
32
+ constructor(code, transient = false) {
33
+ super(`repository path: ${code}`);
34
+ this.code = /^[a-z][a-z0-9_]{0,63}$/.test(code) ? code : "unknown";
35
+ this.transient = transient;
36
+ }
37
+ }
38
+ /** Where the owner's configured repository lives, and the one origin Runner's GitHub calls reach. */
39
+ export const GIT_HOST = "github.com";
40
+ export const API_ORIGIN = "https://api.github.com";
41
+ /** The rules ADR 0009's two rulesets put on the default branch. All three must be there. */
42
+ export const REQUIRED_RULES = ["pull_request", "required_status_checks", "update"];
43
+ /**
44
+ * When Runner asks for a held token again. Every `get_repo_access` call reruns the server's whole decision
45
+ * (`decide_access`), but the server answers the token it holds while more than 5 minutes of it are left
46
+ * (`TOKEN_RENEW_BEFORE_MS` in `crates/core/src/repo_access.rs`), and mints a new one only after that. At 6 minutes, as
47
+ * this was first set, a renewal got the same token back. At 4 minutes it is inside the server's window, so a renewal is
48
+ * a new token, minted after that full recheck (#462's review, item 9).
49
+ */
50
+ export const RENEW_BEFORE_MS = 4 * 60 * 1000;
51
+ /** The prefix of every task branch. */
52
+ export const BRANCH_PREFIX = "podster/";
53
+ /** The fixed identity of a commit Runner makes, so no name or address from anywhere else is ever used. */
54
+ export const COMMIT_IDENTITY = { name: "Podster Runner", email: "runner@podster.invalid" };
55
+ const TOKEN = /^[A-Za-z0-9_]{20,255}$/;
56
+ const COMMIT = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
57
+ const TASK = /^[a-z0-9_-]{1,128}$/;
58
+ /** A branch name Runner will use or accept as a default branch: plain segments, no ref syntax. */
59
+ const BRANCH = /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/;
60
+ const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
61
+ const isCount = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
62
+ export const isCommit = (v) => typeof v === "string" && COMMIT.test(v);
63
+ /** GitHub compares names without case; so does Runner, and never by anything else. */
64
+ export const sameName = (a, b) => a.toLowerCase() === b.toLowerCase();
65
+ /** A branch name that is safe on Git's command line and in a refspec: no `..`, `@{`, leading `-` or `.`, or `.lock`. */
66
+ export function isBranch(v) {
67
+ if (typeof v !== "string" || v.length < 1 || v.length > 200 || !BRANCH.test(v))
68
+ return false;
69
+ return v.split("/").every((s) => s !== "" && !s.startsWith(".") && !s.startsWith("-") && !s.endsWith(".lock") && !s.endsWith(".")) && !v.includes("..");
70
+ }
71
+ /** The one task branch for a task. Its ID is already lower case and path-safe (`policy.ts`). */
72
+ export function taskBranch(task_id) {
73
+ if (!TASK.test(task_id))
74
+ throw new RepoPathError("task_invalid");
75
+ return `${BRANCH_PREFIX}${task_id}`;
76
+ }
77
+ /** The only URL Runner gives Git: GitHub's canonical HTTPS address for the scoped repository, with no credentials. */
78
+ export const cloneUrl = (full_name) => `https://${GIT_HOST}/${full_name}.git`;
79
+ /** The pull request's address, for a submission's link (M7 step 11): the scoped repository and Runner's own number. */
80
+ export const pullRequestUrl = (full_name, number) => `https://${GIT_HOST}/${full_name}/pull/${number}`;
81
+ /**
82
+ * `get_repo_access`'s answer, checked against the contract's `RepoAccess` and the owner's scope. Any other field, a
83
+ * permission other than the three the contract fixes, another repository or a clone URL other than the canonical one
84
+ * refuses it.
85
+ */
86
+ export function readAccess(answer, scope, now) {
87
+ if (!isObj(answer))
88
+ throw new RepoPathError("access_invalid");
89
+ const keys = ["token", "expires_at", "repository", "clone_url", "permissions", "authority_ends_at"];
90
+ if (Object.keys(answer).length !== keys.length || !keys.every((k) => Object.hasOwn(answer, k)))
91
+ throw new RepoPathError("access_invalid");
92
+ const { token, expires_at, repository, clone_url, permissions, authority_ends_at } = answer;
93
+ if (typeof token !== "string" || !TOKEN.test(token))
94
+ throw new RepoPathError("access_invalid");
95
+ if (!isCount(expires_at) || expires_at <= now)
96
+ throw new RepoPathError("access_expired");
97
+ if (!(authority_ends_at === null || isCount(authority_ends_at)))
98
+ throw new RepoPathError("access_invalid");
99
+ if (!isObj(permissions) || Object.keys(permissions).length !== 3 || permissions.contents !== "write" || permissions.pull_requests !== "write" || permissions.metadata !== "read")
100
+ throw new RepoPathError("access_permissions");
101
+ if (!isFullName(repository) || !sameName(repository, scope.full_name))
102
+ throw new RepoPathError("repository_out_of_scope");
103
+ if (typeof clone_url !== "string" || !sameName(clone_url, cloneUrl(scope.full_name)))
104
+ throw new RepoPathError("clone_url_unexpected");
105
+ return { token, expires_at, repository, clone_url, authority_ends_at };
106
+ }
107
+ /** Whether a held token should be asked for again: near its expiry, or past the task's authority. */
108
+ export function renewDue(access, now) {
109
+ if (access.authority_ends_at !== null && now >= access.authority_ends_at)
110
+ return true;
111
+ return now >= access.expires_at - RENEW_BEFORE_MS;
112
+ }
113
+ /** GitHub's own answer for the repository, held to the owner's scope by its numeric ID. Answers its default branch. */
114
+ export function readRepository(answer, scope, task_id) {
115
+ if (!isObj(answer))
116
+ throw new RepoPathError("repository_unreadable");
117
+ if (answer.id !== scope.provider_repo_id)
118
+ throw new RepoPathError("repository_id_mismatch");
119
+ if (!isFullName(answer.full_name) || !sameName(answer.full_name, scope.full_name))
120
+ throw new RepoPathError("repository_renamed");
121
+ if (answer.archived !== false || answer.disabled === true)
122
+ throw new RepoPathError("repository_archived");
123
+ const branch = answer.default_branch;
124
+ if (!isBranch(branch))
125
+ throw new RepoPathError("default_branch_invalid");
126
+ // The task branch can never be the default branch, or sit beside it under Runner's prefix.
127
+ if (branch === taskBranch(task_id) || branch.startsWith(BRANCH_PREFIX) || `${branch}/`.startsWith(BRANCH_PREFIX))
128
+ throw new RepoPathError("default_branch_invalid");
129
+ return { default_branch: branch };
130
+ }
131
+ /**
132
+ * GitHub's rules for the default branch (`GET /repos/{repo}/rules/branches/{branch}`): every rule ADR 0009's rulesets
133
+ * put there must be listed. A list missing one, or one Runner can't read, refuses: Runner never pushes where a
134
+ * contents-write token could reach the default branch (decision 230).
135
+ */
136
+ export function checkProtected(answer) {
137
+ if (!Array.isArray(answer))
138
+ throw new RepoPathError("repository_unprotected");
139
+ const types = new Set(answer.filter(isObj).map((rule) => rule.type));
140
+ for (const rule of REQUIRED_RULES)
141
+ if (!types.has(rule))
142
+ throw new RepoPathError("repository_unprotected");
143
+ }
144
+ /** A ref as `GET /repos/{repo}/git/ref/heads/{branch}` answers it: the commit it points at. */
145
+ export function readRef(answer, branch) {
146
+ if (!isObj(answer) || answer.ref !== `refs/heads/${branch}` || !isObj(answer.object) || answer.object.type !== "commit" || !isCommit(answer.object.sha))
147
+ throw new RepoPathError("ref_unreadable");
148
+ return answer.object.sha;
149
+ }
150
+ /**
151
+ * A pull request as GitHub answers it, held to exactly what Runner opened: in the scoped repository, from the task
152
+ * branch of that same repository (never a fork), to the default branch, open, not a draft, with the pushed commit as its
153
+ * head. Answers its number.
154
+ */
155
+ export function readPullRequest(answer, want) {
156
+ if (!isObj(answer) || !isCount(answer.number) || answer.number < 1)
157
+ throw new RepoPathError("pull_request_unreadable");
158
+ const head = answer.head;
159
+ const base = answer.base;
160
+ if (!isObj(head) || !isObj(base) || !isObj(head.repo) || !isObj(base.repo))
161
+ throw new RepoPathError("pull_request_unreadable");
162
+ if (base.repo.id !== want.scope.provider_repo_id || head.repo.id !== want.scope.provider_repo_id)
163
+ throw new RepoPathError("pull_request_wrong_repository");
164
+ if (base.ref !== want.default_branch)
165
+ throw new RepoPathError("pull_request_wrong_base");
166
+ if (head.ref !== want.branch)
167
+ throw new RepoPathError("pull_request_wrong_head");
168
+ if (head.sha !== want.commit)
169
+ throw new RepoPathError("pull_request_commit_changed");
170
+ if (answer.state !== "open" || answer.draft === true)
171
+ throw new RepoPathError("pull_request_not_open");
172
+ return answer.number;
173
+ }
174
+ /** The pull request Runner opens: fixed words and the task's ID, never the task's text or the agent's. */
175
+ export function pullRequestBody(task_id, branch, default_branch) {
176
+ return {
177
+ title: `Podster task ${task_id}`,
178
+ head: branch,
179
+ base: default_branch,
180
+ body: `Opened by Podster Runner for task ${task_id}. Review it in Podster; Runner never merges.`,
181
+ draft: false,
182
+ maintainer_can_modify: false,
183
+ };
184
+ }
185
+ /**
186
+ * The settings every host Git command Runner runs starts with (L2 on #459). With `--git-dir` and `--work-tree` named,
187
+ * Git never looks for a `.git` in the task's folder, which the task can write; the Git folder itself is in Runner's home,
188
+ * never mounted into a container. Hooks are off, `core.fsmonitor` is off, no system or global configuration is read
189
+ * (`git-env`), only HTTPS reaches a remote, no redirect is followed, nothing recurses into submodules, and no credential
190
+ * helper is used but Runner's own, and that only for a command that reaches GitHub.
191
+ */
192
+ export function hardening(helper) {
193
+ const settings = [
194
+ "core.hooksPath=/dev/null",
195
+ "core.fsmonitor=false",
196
+ "core.untrackedCache=false",
197
+ "core.symlinks=false",
198
+ "core.autocrlf=false",
199
+ "core.sshCommand=false",
200
+ "core.askPass=",
201
+ "protocol.allow=never",
202
+ "protocol.https.allow=always",
203
+ "http.followRedirects=false",
204
+ "http.sslVerify=true",
205
+ "http.proxy=",
206
+ "submodule.recurse=false",
207
+ "fetch.recurseSubmodules=false",
208
+ "push.recurseSubmodules=no",
209
+ "gc.auto=0",
210
+ "maintenance.auto=false",
211
+ "commit.gpgSign=false",
212
+ "tag.gpgSign=false",
213
+ "credential.useHttpPath=false",
214
+ // An empty value clears every helper named before it, so only Runner's own (or none) is left.
215
+ "credential.helper=",
216
+ ];
217
+ // Through `/bin/sh` by its path, so the helper needs no execute bit (the ruling on #470). The path is plain (`isPlainPath`).
218
+ if (helper !== null)
219
+ settings.push(`credential.helper=!/bin/sh ${helper}`);
220
+ return settings.flatMap((s) => ["-c", s]);
221
+ }
222
+ /** A path Runner gives Git on its command line or in a setting: absolute, plain characters only, so no shell reads it. */
223
+ export function isPlainPath(v) {
224
+ return typeof v === "string" && v.length > 1 && v.length < 1024 && /^\/[A-Za-z0-9/._-]+$/.test(v) && !v.split("/").includes("..");
225
+ }
226
+ /**
227
+ * The location arguments of every Git command for one task: its Git folder and its work tree, both named, so Git never
228
+ * looks for a `.git` in the work tree, which a task's shell can write (#461's finding), and trusts only that work tree.
229
+ */
230
+ export function locate(git_dir, work_tree) {
231
+ if (!isPlainPath(git_dir) || !isPlainPath(work_tree))
232
+ throw new RepoPathError("path_unsafe");
233
+ // `safe.directory` names only this work tree, on the command line, which Git counts as protected configuration.
234
+ return ["-c", `safe.directory=${work_tree}`, `--git-dir=${git_dir}`, `--work-tree=${work_tree}`];
235
+ }
236
+ /** Fetches exactly one branch into one local ref: no tags, no submodules, no other refs. */
237
+ export function fetchArgs(full_name, branch, into) {
238
+ if (!isFullName(full_name) || !isBranch(branch) || !/^refs\/runner\/[a-z]+$/.test(into))
239
+ throw new RepoPathError("fetch_invalid");
240
+ return ["fetch", "--quiet", "--no-tags", "--no-recurse-submodules", "--no-write-fetch-head", cloneUrl(full_name), `refs/heads/${branch}:${into}`];
241
+ }
242
+ /**
243
+ * Pushes exactly the task branch to itself: no `+`, no tag, no other ref, never the default branch. A push the remote
244
+ * can't fast-forward is refused by Git, so nothing Runner pushes rewrites a branch.
245
+ */
246
+ export function pushArgs(full_name, branch, default_branch) {
247
+ if (!isFullName(full_name) || !isBranch(branch) || !branch.startsWith(BRANCH_PREFIX) || branch === default_branch)
248
+ throw new RepoPathError("push_invalid");
249
+ return ["push", "--porcelain", "--no-verify", "--no-follow-tags", "--recurse-submodules=no", cloneUrl(full_name), `refs/heads/${branch}:refs/heads/${branch}`];
250
+ }
251
+ function checked(full_name, branch) {
252
+ if (!isFullName(full_name) || (branch !== undefined && !isBranch(branch)))
253
+ throw new RepoPathError("request_invalid");
254
+ }
255
+ /**
256
+ * Every GitHub call Runner makes, and no other (decision 230's rule 4): read the repository, its default branch's rules
257
+ * and a branch's ref; open a pull request, and find one already open from the task branch. Nothing here can merge,
258
+ * update a ref, review, set a status or change a setting.
259
+ */
260
+ export const GITHUB = {
261
+ repository: (full_name) => (checked(full_name), { method: "GET", path: `/repos/${full_name}` }),
262
+ rules: (full_name, branch) => (checked(full_name, branch), { method: "GET", path: `/repos/${full_name}/rules/branches/${branch}` }),
263
+ ref: (full_name, branch) => (checked(full_name, branch), { method: "GET", path: `/repos/${full_name}/git/ref/heads/${branch}` }),
264
+ openPull: (full_name, task_id, branch, default_branch) => (checked(full_name, branch), checked(full_name, default_branch), { method: "POST", path: `/repos/${full_name}/pulls`, body: pullRequestBody(task_id, branch, default_branch) }),
265
+ findPull: (full_name, branch, default_branch) => {
266
+ checked(full_name, branch);
267
+ checked(full_name, default_branch);
268
+ const owner = full_name.split("/")[0];
269
+ const query = `state=open&head=${encodeURIComponent(`${owner}:${branch}`)}&base=${encodeURIComponent(default_branch)}&per_page=2`;
270
+ return { method: "GET", path: `/repos/${full_name}/pulls?${query}` };
271
+ },
272
+ };
@@ -0,0 +1,149 @@
1
+ /** The server's limit on a submission's note (`crates/core` `MAX_NOTE_BYTES`). */
2
+ export const MAX_NOTE_BYTES = 16 * 1024;
3
+ /** The most of the agent's words, marked and redacted, a note carries. **Proposed** figure. */
4
+ export const NOTE_WORDS_BYTES = 12 * 1024;
5
+ const byteLength = (text) => new TextEncoder().encode(text).byteLength;
6
+ const HIDDEN = /[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Cn}\p{Z}\p{Mn}\p{Me}\p{Default_Ignorable_Code_Point}\u2800]/u;
7
+ /** Whether a character is written as a mark: every one in `HIDDEN` but the line feed and the plain space. */
8
+ const hidden = (ch) => ch !== "\n" && ch !== " " && HIDDEN.test(ch);
9
+ const mark = (cp) => `⟨U+${cp.toString(16).toUpperCase().padStart(4, "0")}⟩`;
10
+ /** The text with every character that would draw nothing, or would reorder its neighbours, written as a mark. */
11
+ export function markHidden(text) {
12
+ let out = "";
13
+ for (const ch of text) {
14
+ if (hidden(ch))
15
+ out += mark(ch.codePointAt(0));
16
+ else
17
+ out += ch;
18
+ }
19
+ return out;
20
+ }
21
+ /** The text with the hidden characters taken out, as a reader who doesn't see them would read it. */
22
+ const stripHidden = (text) => [...text].filter((ch) => !hidden(ch)).join("");
23
+ const hasHidden = (text) => [...text].some(hidden);
24
+ const REDACTED = "[redacted]";
25
+ /**
26
+ * Secrets by their fixed shapes. Each is replaced whole; a `key = value` one keeps its name. Distinctive prefixes need no
27
+ * boundary at all, so `key_sk-ant-…` or `xghp_…` can't hide one; the others need only no letter or digit before them,
28
+ * since `\b` treats `_` as part of a word (review 3 on #465). No pattern matches `[redacted]` (review 2).
29
+ */
30
+ const SECRETS = [
31
+ { pattern: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$)/g },
32
+ { pattern: /sk-ant-[A-Za-z0-9_-]{8,}/g },
33
+ { pattern: /gh[pousr]_[A-Za-z0-9]{20,}/g },
34
+ { pattern: /github_pat_[A-Za-z0-9_]{20,}/g },
35
+ { pattern: /(?<![A-Za-z0-9])sk-[A-Za-z0-9_-]{20,}/g },
36
+ { pattern: /(?<![A-Za-z0-9])(?:AKIA|ASIA)[0-9A-Z]{16}(?![A-Za-z0-9])/g },
37
+ { pattern: /(?<![A-Za-z0-9])xox[abposr]-[A-Za-z0-9-]{10,}/g },
38
+ { pattern: /(?<![A-Za-z0-9])AIza[0-9A-Za-z_-]{30,}/g },
39
+ { pattern: /(?<![A-Za-z0-9])[rs]k_(?:live|test)_[0-9A-Za-z]{16,}/g },
40
+ { pattern: /(?<![A-Za-z0-9])eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g },
41
+ { pattern: /(?<![A-Za-z0-9])(?:bearer|token)\s+[A-Za-z0-9._~+/=-]{20,}/gi },
42
+ { pattern: /(?<![A-Za-z0-9])((?:api[_-]?key|secret|token|password|passwd|private[_-]?key|access[_-]?key)["']?\s*[:=]\s*["']?)(?!\[redacted\])[^\s"'[\]]{8,}/gi, keep: true },
43
+ ];
44
+ /** The text with every secret Runner recognises replaced by `[redacted]`, and how many were. */
45
+ export function redactSecrets(text) {
46
+ let count = 0;
47
+ let out = text;
48
+ for (const { pattern, keep } of SECRETS) {
49
+ out = out.replace(pattern, (_whole, name) => {
50
+ count++;
51
+ return keep && typeof name === "string" ? `${name}${REDACTED}` : REDACTED;
52
+ });
53
+ }
54
+ return { text: out, count };
55
+ }
56
+ const holdsSecret = (text) => SECRETS.some(({ pattern }) => text.search(pattern) >= 0);
57
+ /**
58
+ * The result's words as they may be shown and sent: withheld whole when the raw text hides characters and a secret shows
59
+ * once they're taken out; otherwise redacted, then marked, then cut as the note lays them out (review 2 on #465).
60
+ */
61
+ export function cleanResult(result) {
62
+ let redactions = 0;
63
+ const clean = (raw) => {
64
+ if (hasHidden(raw) && holdsSecret(stripHidden(raw)))
65
+ return null;
66
+ const redacted = redactSecrets(raw);
67
+ redactions += redacted.count;
68
+ return markHidden(redacted.text);
69
+ };
70
+ const summary = clean(result.summary);
71
+ const files = result.files.map(clean);
72
+ if (summary === null || files.some((f) => f === null))
73
+ return { ok: false, reason: "secret_hidden" };
74
+ return { ok: true, ...cutAgentWords(summary, files), redactions };
75
+ }
76
+ const WHY_NOT_SHARED = {
77
+ withheld: "The agent's words aren't shared: this room's output policy holds them for the machine's owner, who chose not to share them.",
78
+ lost: "The agent's words aren't shared: Runner restarted before sending them, and it never stores them.",
79
+ secret_hidden: "The agent's words aren't shared: they held what looked like a secret hidden among characters that don't show.",
80
+ };
81
+ const CUT = "⟨cut by Runner⟩";
82
+ /** Each line of the agent's words in the note starts with this, as the terminal fences them; nothing of Runner's does. */
83
+ const FENCE = "| ";
84
+ const FILES_DIVIDER = "--- files the agent named ---";
85
+ const TOKENS = /⟨U\+[0-9A-F]{4,6}⟩|[\s\S]/gu;
86
+ /**
87
+ * The agent's words, marked, cut so that their part of the note, as `agentSection` lays it out (each line fenced, the
88
+ * files after Runner's divider), is at most `NOTE_WORDS_BYTES`, on a character's edge and never inside a mark, with `CUT`
89
+ * at the end when cut. Words that fit come back as they are, so cutting twice changes nothing.
90
+ */
91
+ export function cutAgentWords(summary, files) {
92
+ if (byteLength(agentSection(summary, files)) <= NOTE_WORDS_BYTES)
93
+ return { summary, files };
94
+ const room = NOTE_WORDS_BYTES - byteLength(CUT);
95
+ let size = byteLength(FENCE);
96
+ let out = "";
97
+ for (const token of summary.match(TOKENS) ?? []) {
98
+ const n = token === "\n" ? 1 + byteLength(FENCE) : byteLength(token);
99
+ if (size + n > room)
100
+ return { summary: `${out}${CUT}`, files: [] };
101
+ out += token;
102
+ size += n;
103
+ }
104
+ const kept = [];
105
+ if (files.length > 0)
106
+ size += 1 + byteLength(FILES_DIVIDER);
107
+ for (const file of files) {
108
+ let line = "";
109
+ size += 1 + byteLength(`${FENCE}- `);
110
+ for (const token of file.match(TOKENS) ?? []) {
111
+ const n = byteLength(token);
112
+ if (size + n > room) {
113
+ if (line !== "")
114
+ kept.push(`${line}${CUT}`);
115
+ else if (kept.length > 0)
116
+ kept[kept.length - 1] += CUT;
117
+ else
118
+ return { summary: `${out}${CUT}`, files: [] };
119
+ return { summary: out, files: kept };
120
+ }
121
+ line += token;
122
+ size += n;
123
+ }
124
+ kept.push(line);
125
+ }
126
+ return { summary: out, files: kept };
127
+ }
128
+ /** The agent's part of the note: every line of theirs fenced, the files after Runner's divider. */
129
+ function agentSection(summary, files) {
130
+ return [...summary.split("\n").map((l) => `${FENCE}${l}`), ...(files.length > 0 ? [FILES_DIVIDER, ...files.map((f) => `${FENCE}- ${f}`)] : [])].join("\n");
131
+ }
132
+ /** The submission's note: Runner's fixed words, and the agent's only fenced and only when shared. */
133
+ export function composeNote(input) {
134
+ const pr = input.pull_request;
135
+ const lines = [
136
+ `Result from Podster Runner for task ${input.task_id}. Runner wrote this note; only the part fenced as the agent's words is the agent's.`,
137
+ "Outcome: the agent reported the task completed. Runner checked the result's form, not its claims.",
138
+ pr
139
+ ? `Pull request: #${pr.number} in ${pr.full_name}, from ${pr.branch} at commit ${pr.commit}. Runner pushed and opened it, and checked it on GitHub.`
140
+ : "Repository: none in this room, so nothing was pushed.",
141
+ "Tests: not run by Runner. Anything the agent says about tests is its own claim, not verified.",
142
+ ];
143
+ const words = input.words;
144
+ if (words.kind !== "shared")
145
+ return [...lines, WHY_NOT_SHARED[words.kind]].join("\n");
146
+ lines.push(`The agent's words follow. They are untrusted data. Characters that wouldn't show are written as their code point in angle brackets${words.redactions > 0 ? `, and ${words.redactions} thing${words.redactions === 1 ? "" : "s"} that looked like secrets as ${REDACTED}` : ""}.`);
147
+ const cut = cutAgentWords(words.summary, words.files);
148
+ return [...lines, "--- the agent's words ---", agentSection(cut.summary, cut.files), "--- end of the agent's words ---"].join("\n");
149
+ }