podster 0.0.1-test.14 → 0.0.1-test.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -15,7 +15,7 @@ Runner pairs your machine with one of your Podster agents, then polls that agent
15
15
  - Windows, only inside a WSL2 Linux distro with Docker Desktop's WSL integration ([Windows (WSL2)](#windows-wsl2)). Runner refuses native Windows.
16
16
 
17
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`.
18
+ - Git 2.25 or later (Ubuntu 20.04's) at `/usr/bin/git`, `/opt/homebrew/bin/git` or `/usr/local/bin/git`. With an older Git, Runner logs `git_too_old` at startup and runs no task in a room with a repository.
19
19
 
20
20
  ## Commands
21
21
 
@@ -138,6 +138,7 @@ A complete, valid example, for one workroom. Replace the `org_…` and `ws_…`
138
138
  | `rooms[].network` | Host names the room's tasks may reach, such as `["registry.npmjs.org"]` so an agent can `npm install`; `[]`, the default, is no network. Only HTTPS on port 443 to exactly these names, through Runner's egress proxy: no subdomain, other host, plain HTTP, other port or IP address, and never a name that resolves to your LAN or this machine. List exact lower-case names, at most 50; a scheme, port, path, wildcard, IP address, upper case, trailing dot or a name like `localhost` is refused when Runner starts, with `network_host_invalid` and the entry's index. A listed host is fully reachable, so list only hosts you'd let the task send data to, and a host behind a shared CDN can be used to reach other sites on that CDN (domain fronting), which an allowlist of names can't stop. Needs Docker Engine 26 or later; an older one refuses the run with `docker_engine_too_old`. Runner logs each allowed or refused host when a run ends. |
139
139
  | `rooms[].toolchains` | Optional toolchains for the room's tasks: any of `"dotnet"`, `"java"`, `"python"` and `"rust"`, such as `["rust", "python"]`. `[]`, the default, runs tasks in Runner's base image (shell tools and Node 22). `rust` adds Rust 1.100.0 (cargo, rustc, rustfmt, clippy) with gcc as its linker; `python` adds Python 3.14.10 and uv 0.13.9; `dotnet` adds the .NET 10 SDK 10.0.404; `java` adds the Temurin JDK 25.0.5.1 and Maven 3.10.1 (a Gradle project uses its own wrapper). Each needs `shell` in `tools`. Runner builds the room's image from its own pinned Dockerfiles the first time a task needs it, which takes a few minutes and counts against that run's time; after that it's reused. A toolchain adds no network: to fetch packages, list the registries in `network`, `index.crates.io` and `static.crates.io` for crates, `pypi.org` and `files.pythonhosted.org` for PyPI, `api.nuget.org` for NuGet, `repo.maven.apache.org` for Maven Central, and for a Gradle wrapper `services.gradle.org` with `github.com` and `release-assets.githubusercontent.com`, where it downloads Gradle from (plus `plugins.gradle.org` for plugins). Listing `github.com` for the wrapper opens all of GitHub to the task, not only Gradle's downloads. Toolchain rooms get larger bounds a build needs: 4 GB of memory, 1,024 processes and 10 minutes per command. An unknown or repeated name is refused when Runner starts, with `toolchain_unknown` or `toolchain_duplicate` and the entry's index, and toolchains without `shell` with `toolchain_needs_shell`. |
140
140
  | `rooms[].repository` | `null` for a task that starts in an empty folder, or `{ "full_name": "owner/name", "provider_repo_id": 123456 }` for one GitHub repository. |
141
+ | `rooms[].roles` | What Runner does when the room invites this agent to a role opening. `"ask"`, the default, asks you at your terminal: `y` claims it as this agent, `n` turns it down, anything else leaves it for later. `"accept"` claims it with no question. Runner never turns an invite down by itself, and a room not listed here always asks. Claiming accepts no task and gives no person access. A pairing made before Runner answered invites can't: Runner logs `pair_again_for_roles` once, and pairing again from Podster enables it. |
141
142
  | `rooms[].allowed_orgs` | Other organizations whose tasks you'll run in this room. Do not list `owner_org`: your own organization is always allowed, and Runner refuses a policy that lists it. An empty list is fine. |
142
143
  | `rooms[].acknowledged` | Both flags are required. Until `trust_statement` is `true`, Runner asks you at your terminal each time. Until `public_room_warning` is `true`, it also asks for a public room. |
143
144
 
@@ -14,6 +14,10 @@
14
14
  * its signing secret. Neither grants anything in a room, and the nudge sends nothing until a person who administers the
15
15
  * agent's organization switches it on in Podster. Only `src/core/nudge.ts` names them; a test holds that.
16
16
  *
17
+ * `list_role_openings`, `claim_role` and `decline_role` (issue 522) answer a role invite as this agent, under the owner's
18
+ * local policy (`roles.ts`): the room decides each call, only for the invite naming this agent, and a claim copies only
19
+ * the opening's preset. Neither accepts or declines a task. Only `src/core/roles.ts` names them; a test holds that.
20
+ *
17
21
  * Step 6 calls only the reads and the inbox. The lifecycle calls are named now so the registered agent is the one later
18
22
  * steps use: Runner registers once per pairing and never again by itself.
19
23
  */
@@ -38,6 +42,9 @@ export const RUNNER_CAPABILITIES = [
38
42
  "get_repo_access",
39
43
  "set_a2a_endpoint",
40
44
  "verify_a2a_endpoint",
45
+ "list_role_openings",
46
+ "claim_role",
47
+ "decline_role",
41
48
  ];
42
49
  /**
43
50
  * Capabilities a deployment lists only while a feature is switched on: `get_repo_access` only where managed repositories
@@ -47,3 +54,34 @@ export const RUNNER_CAPABILITIES = [
47
54
  export const SWITCHED = ["get_repo_access"];
48
55
  /** Never named by Runner, whatever a later list says (decision 230). `get_repo_access` left this list in step 10. */
49
56
  export const NEVER = ["merge_task", "deploy_release", "create_task", "assign_task", "cancel_task", "verify_task", "request_changes"];
57
+ /**
58
+ * The capability names the bitset in Runner's stored agent connection stands for, bit 0 first (issue 527, `storage.ts`).
59
+ * Append only: a name is never removed, reordered or reused, or a stored record would read as different grants; a test
60
+ * pins it. A granted name that isn't here (one added to `RUNNER_CAPABILITIES` and not appended) is stored by name
61
+ * instead, so nothing is dropped, only stored less compactly.
62
+ */
63
+ export const STORED_CAPABILITY_BITS = Object.freeze([
64
+ "get_identity",
65
+ "list_workspaces",
66
+ "get_workspace",
67
+ "get_workroom_brief",
68
+ "read_inbox",
69
+ "ack_inbox",
70
+ "list_tasks",
71
+ "get_task",
72
+ "accept_task",
73
+ "decline_task",
74
+ "release_task",
75
+ "send_message",
76
+ "list_messages",
77
+ "submit_task",
78
+ "create_upload",
79
+ "get_asset_link",
80
+ "list_assets",
81
+ "get_repo_access",
82
+ "set_a2a_endpoint",
83
+ "verify_a2a_endpoint",
84
+ "list_role_openings",
85
+ "claim_role",
86
+ "decline_role",
87
+ ]);
@@ -62,6 +62,8 @@ const TABLE = new Map([
62
62
  ...group(["call_invalid", "input_invalid", "tool_not_allowed", "shell_not_allowed", "path_outside_folder", "path_not_allowed", "run_stopped"], "Runner refused one of the agent's tool calls.", "Nothing to do unless the agent needs that tool: shell needs rooms[].tools to list shell."),
63
63
  ...group(["method_not_allowed", "query_not_allowed", "body_too_large", "body_invalid", "body_not_allowed", "model_not_allowed", "model_unpriced", "upstream_failed"], "Runner refused or couldn't send one of the agent's model requests.", SUPPORT),
64
64
  // The repository path.
65
+ ...group(["task_not_linked"], "Podster said this task isn't linked to the room's repository, so Runner ran it without one: an empty folder, no repository token, and no commit, push or pull request. Its result is submitted as text.", "Nothing to do. If the task needed the repository, ask the room to check the repository in Podster and make the task again once it's ready."),
66
+ ...group(["task_folder_unsafe"], "Runner couldn't empty the task's folder before a run without the repository: the folder or the room's folder above it is a link, or not where the run policy puts it.", "The task is released; check the folder under workspace_root in policy.json and remove any link there."),
65
67
  ...group(["repository_unavailable", "helper_unavailable", "git_unavailable"], "Runner can't work with this room's repository on this machine.", "Check that Git is installed and the room's repository is set in policy.json."),
66
68
  ...group(["repository_out_of_scope", "clone_url_unexpected", "repository_id_mismatch", "repository_renamed", "repository_archived", "repository_unprotected", "repository_unreadable"], "The room's repository isn't the one Runner's policy allows, or can't be used as it is.", "Check rooms[].repository in policy.json against the room's repository on GitHub."),
67
69
  ...group(["path_unsafe", "unsafe", "work_tree_git", "work_tree_link", "work_tree_special"], "The task's folder held something Runner won't commit or push.", "The details file names the check; the task is released."),
@@ -74,8 +76,21 @@ const TABLE = new Map([
74
76
  ...group(["access_authority_invalid", "access_expired", "access_fields", "access_invalid", "access_not_object", "access_permissions", "access_token_format", "token_revoked"], "Podster's repository access for this task wasn't usable.", "Try again later; if it keeps happening, check the room's repository settings in Podster."),
75
77
  ...group(["github_unavailable", "github_unreachable", "github_refused", "github_answer_too_large"], "GitHub couldn't be reached or refused a request.", "Check the network; Runner tries again later."),
76
78
  ...group(["checkout_failed", "checkout_moved", "checkout_unverified", "fetch_invalid", "git_init_failed", "default_branch_invalid", "ref_unreadable", "base_moved", "task_branch_moved"], "Runner couldn't prepare a clean checkout of the repository.", "Runner tries again later; the details file has more."),
79
+ // A failed fetch or push, by its cause (#520). Git's own words never reach these lines; `podster why` adds the stage
80
+ // and Git's exit code from the local diagnostics file.
81
+ ...group(["fetch_auth_failed"], "GitHub refused this task's repository token when Git fetched the repository.", "Runner asks Podster for a new token next time; if it keeps happening, check in Podster that the room's GitHub App installation is still active."),
82
+ ...group(["fetch_access_denied"], "GitHub took this task's repository token but refused it the repository when Git fetched it (HTTP 403).", "Check that the Podster GitHub App is installed on the room's repository with read access to its contents; the task is released."),
83
+ ...group(["fetch_repository_not_found", "push_repository_not_found"], "GitHub said no such repository is visible to this task's token: the Podster GitHub App isn't installed on it, or the repository was moved or deleted.", "Check the room's repository in Podster and that the Podster GitHub App is installed on it; the task is released."),
84
+ ...group(["fetch_ref_missing"], "Git found no such branch on GitHub, though GitHub's API had named it a moment before.", "Runner tries again later; if it keeps happening, check the repository's default branch on GitHub."),
85
+ ...group(["fetch_dns_failed"], "This machine couldn't look up GitHub's address when Git fetched the repository.", "Check this machine's DNS (in WSL, /etc/resolv.conf); Runner tries again later."),
86
+ ...group(["fetch_unreachable"], "Git couldn't connect to GitHub, or the fetch timed out. Runner's Git uses no proxy from the environment.", "Check this machine's network, VPN or firewall for direct HTTPS to GitHub; Runner tries again later."),
87
+ ...group(["fetch_tls_failed"], "Git couldn't make a verified TLS connection to GitHub: the certificate check or the handshake failed.", "Check this machine's CA certificates (on Debian or Ubuntu, the ca-certificates package) and any proxy or security tool that intercepts TLS; Runner tries again later."),
88
+ ...group(["git_too_old", "fetch_git_too_old", "push_git_too_old"], "This machine's Git is older than 2.25, or refused an option Runner passes, so Runner can't check out the room's repository.", "Install Git 2.25 or later at the path Runner uses (/usr/bin/git, /opt/homebrew/bin/git or /usr/local/bin/git), then restart Runner with `run`; `podster why` shows Git's exit code."),
89
+ ...group(["fetch_https_unavailable", "push_https_unavailable"], "This machine's Git can't reach GitHub over HTTPS: its git-remote-https helper is missing.", "Reinstall Git with HTTPS support (on Debian or Ubuntu, the git package), then restart Runner with `run`."),
90
+ ...group(["fetch_local_write_failed", "push_local_write_failed"], "Git couldn't write Runner's own Git folder for this task: a lock, a permission, or a full or read-only disk.", "Check free space and permissions in Runner's home (--home, by default ~/.podster-runner); the task is released."),
91
+ ...group(["fetch_failed"], "Git couldn't fetch the room's repository, for a reason Runner doesn't recognise.", `\`podster why\` shows Git's exit code. Check \`git --version\` (2.25 or later) and \`git ls-remote\` of the repository on this machine; if both work, ${SEND}`),
77
92
  ...group(["push_too_large"], "GitHub or the network refused the push as too large, or dropped the connection while it was sent.", "The task is released; check what the task's branch would add, and keep caches and large files out with .gitignore."),
78
- ...group(["commit_failed", "commit_unexpected", "push_invalid", "push_rejected", "push_unconfirmed", "repo_publish_failed", "publish_failed"], "Runner couldn't commit or push the run's work.", "Runner retries for an hour, then releases the task; check the task branch's protection on GitHub."),
93
+ ...group(["commit_failed", "commit_unexpected", "push_failed", "push_invalid", "push_rejected", "push_unconfirmed", "repo_publish_failed", "publish_failed"], "Runner couldn't commit or push the run's work.", "Runner retries for an hour, then releases the task; check the task branch's protection on GitHub."),
79
94
  ...group(["pull_request_commit_changed", "pull_request_not_found", "pull_request_not_open", "pull_request_refused", "pull_request_unreadable", "pull_request_wrong_base", "pull_request_wrong_head", "pull_request_wrong_repository", "pull_request_unread"], "The task's pull request wasn't as Runner pushed it.", "Check the pull request on GitHub; the task is released if it can't be submitted."),
80
95
  ...group(["run_no_changes"], "The run changed nothing, so there was nothing to submit.", "The task is released."),
81
96
  ...group(["record_invalid", "repo_record_invalid", "result_record_invalid"], "Runner's own record of this run was incomplete.", SUPPORT),
@@ -132,6 +147,8 @@ export const FAILURE_OUTCOMES = new Set([
132
147
  "held",
133
148
  "waiting",
134
149
  "grace_passed",
150
+ // Not a failure: a task Podster says isn't linked runs without the room's repository, and the terminal says so.
151
+ "without_repository",
135
152
  ]);
136
153
  /**
137
154
  * Whether a log line gets a plain-English line under it: a failure, or a try again whose count is a power of two (1, 2,
@@ -213,6 +213,7 @@ export class Lifecycle {
213
213
  this.busy = true;
214
214
  this.tickSignal = signal;
215
215
  try {
216
+ await this.deps.roles?.pass(signal);
216
217
  return await this.work(signal);
217
218
  }
218
219
  catch (error) {
@@ -381,7 +382,7 @@ export class Lifecycle {
381
382
  const parsed = parsePolicyConfig(config, homeOf(this.deps));
382
383
  if (parsed.ok && parsed.value.owner_org !== this.ownerOrg)
383
384
  return { outcome: "refuse", reason: "config_invalid", ...ids };
384
- return this.policy.evaluate({
385
+ const decision = this.policy.evaluate({
385
386
  config,
386
387
  provenance: detail.provenance,
387
388
  prompt: detail.prompt?.shape ?? null,
@@ -391,6 +392,10 @@ export class Lifecycle {
391
392
  ...homeOf(this.deps),
392
393
  now: this.now(),
393
394
  });
395
+ // Podster said this task has no linked repository (`task_not_linked`, the owner's ruling of 2026-11-22): it runs as a
396
+ // task in a room without one, in an empty folder, with no token, commit, push or pull request. Only a server answer
397
+ // sets this, never the task's words; everything else the room's policy says is unchanged.
398
+ return entry.unlinked === true && decision.facts && decision.facts.repository !== null ? { ...decision, facts: { ...decision.facts, repository: null } } : decision;
394
399
  }
395
400
  /** A new event for a task, or a wait that's over: a fresh read and a fresh evaluation. */
396
401
  async consider(offer, marker, counted, signal, approvedRound = false, onlyIfOffered = false) {
@@ -403,7 +408,7 @@ export class Lifecycle {
403
408
  this.log("lifecycle.decision", "waiting", known, { code: "attempts_exhausted" });
404
409
  return;
405
410
  }
406
- const entry = { ...known, marker, attempts: { day: today, count: attempts.count + (counted ? 1 : 0) }, retry_at: null, decision: null, consumed: null, reservation: null, accept_key: null, expected_version: null, run_ref: null, give_up: null, after_stop: null, submission: null };
411
+ let entry = { ...known, marker, attempts: { day: today, count: attempts.count + (counted ? 1 : 0) }, retry_at: null, decision: null, consumed: null, reservation: null, accept_key: null, expected_version: null, run_ref: null, give_up: null, after_stop: null, submission: null };
407
412
  const detail = await this.read(offer.workspace_id, offer.task_id);
408
413
  const task = detail?.task;
409
414
  if (!detail || !task || task.assignee !== this.deps.poller.agentId || (task.status !== "offered" && task.status !== "accepted")) {
@@ -411,6 +416,9 @@ export class Lifecycle {
411
416
  await this.put({ ...entry, phase: "done", outcome: task ? `task_${task.status}` : "not_readable" });
412
417
  return;
413
418
  }
419
+ // A new offer asks Podster afresh whether the task is linked: it may have been linked since.
420
+ if (task.status === "offered" && entry.unlinked)
421
+ entry = { ...entry, unlinked: null };
414
422
  if (onlyIfOffered && task.status !== "offered") {
415
423
  // An edit to a task that isn't an offer any more: nothing to evaluate. A running run's check-in sees edits itself.
416
424
  await this.put({ ...known, marker, attempts: entry.attempts });
@@ -663,6 +671,8 @@ export class Lifecycle {
663
671
  if (signal.aborted)
664
672
  return "aborted";
665
673
  }
674
+ else if (entry.unlinked === true && decision.repository_id === null && prompt && fresh.outcome !== "refuse" && !(await this.clearUnlinked(entry, fresh.facts)))
675
+ return null;
666
676
  const binding = { task_id: entry.task_id, workspace_id: entry.workspace_id, task_version: version, input_hash: prompt?.hash ?? "", repository_id: pinned.repository_id, base_commit: pinned.base_commit };
667
677
  const consumed = prompt ? this.policy.consumeRunDecision(pinned, fresh, binding, this.now()) : { ok: false, reason: "binding_changed" };
668
678
  if (!consumed.ok) {
@@ -733,6 +743,23 @@ export class Lifecycle {
733
743
  throw error;
734
744
  }
735
745
  }
746
+ /** An unlinked task's run starts in an empty folder: what an earlier run left is removed first. False when given up. */
747
+ async clearUnlinked(entry, facts) {
748
+ try {
749
+ await this.deps.repository?.clear({ workspace_id: entry.workspace_id, task_id: entry.task_id, task_folder: facts.task_folder, workspace_root: facts.workspace_root });
750
+ return true;
751
+ }
752
+ catch (error) {
753
+ if (!(error instanceof RepoPathError))
754
+ throw error;
755
+ this.log("lifecycle.repository", "refused", entry, { code: error.code });
756
+ this.diagnose("lifecycle.repository", entry, error.code, error);
757
+ const ledger = settle(this.state.ledger, entry.reservation, 0, this.now());
758
+ this.state = { ...this.state, ledger };
759
+ await this.giveUp({ ...entry, decision: null, reservation: null, expected_version: null }, "accepted", `repo_${error.code}`);
760
+ return false;
761
+ }
762
+ }
736
763
  /**
737
764
  * Step 10's checkout, inside the gate between the fresh evaluation and the consume: a fresh, verified checkout of the
738
765
  * decision's own repository, and its commit pinned into the stored decision. Answers the pinned decision, or null when
@@ -770,7 +797,18 @@ export class Lifecycle {
770
797
  return "aborted";
771
798
  if (!(error instanceof RepoPathError))
772
799
  throw error;
773
- this.log("lifecycle.repository", error.transient ? "unavailable" : "refused", entry, { code: error.code });
800
+ if (error.code === "task_not_linked" && error.detail.stage === "access") {
801
+ // Podster's own answer to `get_repo_access`: this task has no linked repository. Not released: the decision is
802
+ // dropped, and the task evaluated again at once without the repository, so it runs with no checkout.
803
+ this.log("lifecycle.repository", "without_repository", entry, { code: error.code });
804
+ this.diagnose("lifecycle.repository", entry, error.code);
805
+ path.forget(entry.workspace_id, entry.task_id);
806
+ const ledger = settle(this.state.ledger, entry.reservation, 0, this.now());
807
+ this.state = { ...this.state, ledger };
808
+ await this.put({ ...entry, phase: "waiting", outcome: error.code, unlinked: true, decision: null, reservation: null, expected_version: null, retry_at: this.now() });
809
+ return null;
810
+ }
811
+ this.log("lifecycle.repository", error.transient ? "unavailable" : "refused", entry, { code: error.code, stage: error.detail.stage });
774
812
  this.diagnose("lifecycle.repository", entry, error.code, error);
775
813
  if (error.transient) {
776
814
  // Passing: the decision is dropped and the task evaluated afresh at its next turn, with a new checkout.
@@ -1181,7 +1219,7 @@ export class Lifecycle {
1181
1219
  await this.put({ ...this.current(entry), submission: sub });
1182
1220
  }
1183
1221
  const words = !result || !cleaned ? { kind: "lost" } : !cleaned.ok ? { kind: "secret_hidden" } : sub.sharing === "share" || sub.sharing === "approved" ? { kind: "shared", ...cleaned } : { kind: "withheld" };
1184
- const note = composeNote({ task_id: entry.task_id, pull_request: pr, words });
1222
+ const note = composeNote({ task_id: entry.task_id, pull_request: pr, words, unlinked: pr === null && this.current(entry).unlinked === true });
1185
1223
  const noteHash = await sha256Hex(new TextEncoder().encode(note));
1186
1224
  if (sub.key === null || sub.note_hash !== noteHash) {
1187
1225
  // Stored before it's first sent. A different note gets a new key, so a replay never carries another body.
@@ -304,7 +304,7 @@ function parseCaps(v) {
304
304
  return { ok: true, value: { spend_micro_usd, run_time_ms, turns, output_tokens, max_tokens } };
305
305
  }
306
306
  function parseRoom(v, ownerOrg) {
307
- if (!isObj(v) || !keysAre(v, ["room_id", "allowed_orgs", "acknowledged"], ["mode", "tools", "network", "toolchains", "outputs", "repository"]))
307
+ if (!isObj(v) || !keysAre(v, ["room_id", "allowed_orgs", "acknowledged"], ["mode", "tools", "network", "toolchains", "outputs", "repository", "roles"]))
308
308
  return fail("rooms[]");
309
309
  const roomId = own(v, "room_id");
310
310
  if (!isId(roomId))
@@ -343,7 +343,10 @@ function parseRoom(v, ownerOrg) {
343
343
  const repository = given === null ? null : parseRepoScope(given);
344
344
  if (given !== null && repository === null)
345
345
  return fail("rooms[].repository");
346
- return { ok: true, value: { room_id: roomId, mode, allowed_orgs: allowed, tools, network, toolchains, outputs, acknowledged: { trust_statement: trust, public_room_warning: warning }, repository } };
346
+ const roles = Object.hasOwn(v, "roles") ? v.roles : "ask";
347
+ if (roles !== "ask" && roles !== "accept")
348
+ return fail("rooms[].roles");
349
+ return { ok: true, value: { room_id: roomId, mode, allowed_orgs: allowed, tools, network, toolchains, outputs, acknowledged: { trust_statement: trust, public_room_warning: warning }, repository, roles } };
347
350
  }
348
351
  /**
349
352
  * Whether a path is on a Windows drive as WSL2 mounts it by default (`/mnt/c`, `/mnt/d/…`): the Windows file system,
@@ -24,7 +24,7 @@ import { Connection } from "./connection.js";
24
24
  import { GatewayError, meaningOf } from "./errors.js";
25
25
  import { retire } from "./pairing.js";
26
26
  import { backoffMs } from "./retry.js";
27
- import { applyEvents, applyListing, readEvents, readTask } from "./record.js";
27
+ import { applyEvents, applyListing, markRoleCheck, readEvents, readTask } from "./record.js";
28
28
  import { isId } from "./state.js";
29
29
  import { RunnerStorage } from "./storage.js";
30
30
  /** The owner's poll interval is held between these. Podster allows each agent 120 calls a minute. */
@@ -126,6 +126,19 @@ export class Poller {
126
126
  request(capability, args = {}) {
127
127
  return this.call(capability, args);
128
128
  }
129
+ /**
130
+ * The capabilities this agent's stored credential holds, by name, as its pairing registered them. A pairing made before
131
+ * a capability was in Runner's list doesn't hold it, and calling it would read as an authority error, so a caller checks
132
+ * here first (issue 522).
133
+ */
134
+ async granted() {
135
+ const connection = await this.storage.getAgentConnection(this.state.plugin_agent_id);
136
+ return new Set((connection?.capabilityGrants ?? []).filter((grant) => grant.status === "active").map((grant) => grant.capability));
137
+ }
138
+ /** Saves a change to the record that isn't the inbox's or a listing's: the role invites' (issue 522). */
139
+ async updateRecord(change) {
140
+ await this.save(change(this.state));
141
+ }
129
142
  /** Retires the key after an authority error the lifecycle met: the same stop the loop makes for its own. */
130
143
  async endAuthority() {
131
144
  if (this.state.stopped === null)
@@ -173,6 +186,8 @@ export class Poller {
173
186
  }
174
187
  tasks += found.length;
175
188
  state = applyListing(state, this.state.agent_id, workspace, found, whole, this.deps.clock.now());
189
+ // An invite made while Runner was off, or whose event was dropped, is found by reading the room's openings (issue 522).
190
+ state = { ...state, role_checks: markRoleCheck(state.role_checks ?? {}, workspace, null, this.deps.clock.now()) };
176
191
  }
177
192
  const now = this.deps.clock.now();
178
193
  await this.save({ ...state, reconciled_at: now, last_contact_at: now });
@@ -11,6 +11,14 @@ export const OFFERS_KEPT = 5000;
11
11
  const TYPE = /^[a-z][a-z0-9_.]{0,63}$/;
12
12
  /** Event types that put a task in the record. Any other event only updates a task already there. */
13
13
  const STARTS = new Set(["task.offered", "task.changes_requested"]);
14
+ /**
15
+ * Event types with no task that Runner records (issue 522): an invite to one of a room's role openings. The event names
16
+ * only the room, so the room is recorded to be read with `list_role_openings`. Any other event with no task moves only
17
+ * the cursor, as before.
18
+ */
19
+ export const ROLE_NOTICES = new Set(["role.invited"]);
20
+ /** Most rooms kept to read for role invites. Past this, those least recently changed are dropped first. */
21
+ export const ROLE_CHECKS_KEPT = 500;
14
22
  /** Task statuses the listing reports for a task Runner may have to act on. */
15
23
  export const LISTED = new Set(["offered", "accepted"]);
16
24
  /** An inbox page's events, each checked. One with a bad sequence makes the page unusable; any other bad field drops only its IDs. */
@@ -50,11 +58,16 @@ function bounded(offers) {
50
58
  */
51
59
  export function applyEvents(state, events, now) {
52
60
  const offers = { ...state.offers };
61
+ let checks = state.role_checks ?? {};
53
62
  let cursor = state.inbox_cursor;
54
63
  for (const event of [...events].sort((a, b) => a.seq - b.seq)) {
55
64
  if (event.seq <= cursor)
56
65
  continue;
57
66
  cursor = event.seq;
67
+ // A role invite has no task: it's recorded by its room, in the same save as the cursor, so it's never acknowledged
68
+ // unrecorded (issue 522).
69
+ if (!event.task_id && event.workspace_id && ROLE_NOTICES.has(event.type))
70
+ checks = markRoleCheck(checks, event.workspace_id, event.seq, now);
58
71
  if (!event.task_id || !event.workspace_id)
59
72
  continue;
60
73
  const id = key(event.workspace_id, event.task_id);
@@ -64,7 +77,17 @@ export function applyEvents(state, events, now) {
64
77
  else if (STARTS.has(event.type))
65
78
  offers[id] = { workspace_id: event.workspace_id, task_id: event.task_id, source: "inbox", seq: event.seq, last: event.type, version: null, recorded_at: now, updated_at: now };
66
79
  }
67
- return { ...state, inbox_cursor: cursor, offers: bounded(offers) };
80
+ return { ...state, inbox_cursor: cursor, offers: bounded(offers), ...(checks === state.role_checks ? {} : { role_checks: checks }) };
81
+ }
82
+ /** The rooms to read for role invites, with this one due. Bounded: those least recently changed go first. */
83
+ export function markRoleCheck(checks, workspaceId, seq, now) {
84
+ const known = checks[workspaceId];
85
+ const next = { ...checks, [workspaceId]: { workspace_id: workspaceId, seq: seq ?? known?.seq ?? null, due: true, recorded_at: known?.recorded_at ?? now, updated_at: now } };
86
+ const entries = Object.entries(next);
87
+ if (entries.length <= ROLE_CHECKS_KEPT)
88
+ return next;
89
+ entries.sort(([, a], [, b]) => b.updated_at - a.updated_at);
90
+ return Object.fromEntries(entries.slice(0, ROLE_CHECKS_KEPT));
68
91
  }
69
92
  /** A listed task, by its IDs, status and version only. Null for anything not shaped as a task. */
70
93
  export function readTask(row) {
@@ -362,11 +362,109 @@ export function locate(git_dir, work_tree) {
362
362
  // `safe.directory` names only this work tree, on the command line, which Git counts as protected configuration.
363
363
  return ["-c", `safe.directory=${work_tree}`, `--git-dir=${git_dir}`, `--work-tree=${work_tree}`];
364
364
  }
365
- /** Fetches exactly one branch into one local ref: no tags, no submodules, no other refs. */
366
- export function fetchArgs(full_name, branch, into) {
365
+ /**
366
+ * The oldest Git Runner works with: 2.25, Ubuntu 20.04's, which WSL installs (the coordinator's ruling on #525). Checked
367
+ * on a real 2.25 in `test/old-git.test.ts`. Below it Runner refuses at startup (`git_too_old`).
368
+ */
369
+ export const MIN_GIT_VERSION = [2, 25];
370
+ /**
371
+ * The first Git with `fetch --no-write-fetch-head`. An older one is not given it, and writes `FETCH_HEAD` into the task's
372
+ * Git folder in Runner's home, which no container mounts; it names a commit and the URL, never a credential.
373
+ */
374
+ export const NO_FETCH_HEAD_VERSION = [2, 29];
375
+ /** `git --version`'s major and minor, or null when the answer isn't Git's usual `git version X.Y…` line. */
376
+ export function parseGitVersion(text) {
377
+ const m = /^git version (\d{1,4})\.(\d{1,4})(?:[.\s]|$)/.exec(text.trim());
378
+ return m ? [Number(m[1]), Number(m[2])] : null;
379
+ }
380
+ /** Whether `v` is at least `min` (by default `MIN_GIT_VERSION`). */
381
+ export const gitVersionSupported = (v, min = MIN_GIT_VERSION) => v[0] > min[0] || (v[0] === min[0] && v[1] >= min[1]);
382
+ export function gitFailureCause(result, op) {
383
+ const text = `${result.stdout}\n${result.stderr}`;
384
+ if (/Authentication failed|could not read (Username|Password)|returned error: 401|Invalid username or (password|token)/i.test(text))
385
+ return "auth";
386
+ if (/returned error: 403|Permission to \S+ denied|Write access to repository not granted/i.test(text))
387
+ return "access_denied";
388
+ if (/Repository not found|repository '[^'\n]*' not found|returned error: 404/i.test(text))
389
+ return "repository_not_found";
390
+ if (/couldn't find remote ref|could not find remote ref/i.test(text))
391
+ return "ref_missing";
392
+ if (/Could not resolve (host|proxy)|Temporary failure in name resolution|Name or service not known|nodename nor servname/i.test(text))
393
+ return "dns";
394
+ // A timeout or a connection that failed is the network's, whatever else Git said with it: `RPC failed; curl 28
395
+ // Operation timed out` is one. Runner's own time limit (124) is one too.
396
+ if (result.code === 124 || /Failed to connect|Connection (timed out|reset|refused)|Operation timed out|timed out/i.test(text))
397
+ return "network";
398
+ if (/SSL certificate problem|certificate verif|server certificate|SSL connect error|SSL_connect|SSL_ERROR|gnutls_handshake|TLS connect error|unable to get local issuer|CAfile|CApath/i.test(text))
399
+ return "tls";
400
+ // Only for a push, on a clear sign of size: an HTTP 413, a pack over a limit, or GitHub's large-file refusal; checked
401
+ // before the plain rejection, since GH001 arrives as one. A bare `RPC failed` or `remote end hung up` says neither.
402
+ if (op === "push" && /HTTP 413|returned error: 413|pack exceeds|GH001|exceeds GitHub's file size limit|this exceeds/i.test(text))
403
+ return "too_large";
404
+ if (/\[rejected\]|\[remote rejected\]|non-fast-forward|fetch first/.test(text))
405
+ return "rejected";
406
+ if (result.code === 129 || /unknown option|unknown switch|^usage: git /im.test(text))
407
+ return "git_too_old";
408
+ if (/unable to find remote helper|remote-https|transport 'https' not allowed|Protocol "?https"? not supported/i.test(text))
409
+ return "https_unavailable";
410
+ if (/cannot lock ref|unable to (write|create|append)|could not write|Permission denied|No space left|Read-only file system|insufficient permission|Disk quota/i.test(text))
411
+ return "local_write";
412
+ if (/unable to access/i.test(text))
413
+ return "network";
414
+ return "unknown";
415
+ }
416
+ /**
417
+ * The fixed code a failed fetch or push is refused with, by its cause, and whether it's tried again later. A fetch
418
+ * names its cause under `fetch_` (#520), so the release reason and `podster why` say which; a push keeps its codes from
419
+ * before (`token_revoked`, `github_unreachable`, `push_too_large`, `push_rejected`, `push_failed`) and names the causes
420
+ * it had none for under `push_`. `revoke`: the token is dropped, so the next use asks Podster again.
421
+ */
422
+ export function gitFailureCode(cause, op) {
423
+ const passing = cause === "dns" || cause === "network" || cause === "tls";
424
+ if (op === "fetch") {
425
+ const codes = {
426
+ auth: "fetch_auth_failed",
427
+ access_denied: "fetch_access_denied",
428
+ repository_not_found: "fetch_repository_not_found",
429
+ // GitHub's API named the branch a moment before: read afresh at the next turn.
430
+ ref_missing: "fetch_ref_missing",
431
+ dns: "fetch_dns_failed",
432
+ network: "fetch_unreachable",
433
+ tls: "fetch_tls_failed",
434
+ too_large: "fetch_failed",
435
+ rejected: "fetch_failed",
436
+ git_too_old: "fetch_git_too_old",
437
+ https_unavailable: "fetch_https_unavailable",
438
+ local_write: "fetch_local_write_failed",
439
+ unknown: "fetch_failed",
440
+ };
441
+ return { code: codes[cause], transient: passing || cause === "ref_missing", revoke: cause === "auth" || cause === "access_denied" };
442
+ }
443
+ const codes = {
444
+ auth: "token_revoked",
445
+ access_denied: "token_revoked",
446
+ repository_not_found: "push_repository_not_found",
447
+ ref_missing: "push_failed",
448
+ dns: "github_unreachable",
449
+ network: "github_unreachable",
450
+ tls: "github_unreachable",
451
+ too_large: "push_too_large",
452
+ rejected: "push_rejected",
453
+ git_too_old: "push_git_too_old",
454
+ https_unavailable: "push_https_unavailable",
455
+ local_write: "push_local_write_failed",
456
+ unknown: "push_failed",
457
+ };
458
+ return { code: codes[cause], transient: passing, revoke: cause === "auth" || cause === "access_denied" };
459
+ }
460
+ /**
461
+ * Fetches exactly one branch into one local ref: no tags, no submodules, no other refs. `fetch_head` false leaves out
462
+ * `--no-write-fetch-head`, for a Git older than `NO_FETCH_HEAD_VERSION`, which refuses it.
463
+ */
464
+ export function fetchArgs(full_name, branch, into, fetch_head = true) {
367
465
  if (!isFullName(full_name) || !isBranch(branch) || !/^refs\/runner\/[a-z]+$/.test(into))
368
466
  throw new RepoPathError("fetch_invalid");
369
- return ["fetch", "--quiet", "--no-tags", "--no-recurse-submodules", "--no-write-fetch-head", cloneUrl(full_name), `refs/heads/${branch}:${into}`];
467
+ return ["fetch", "--quiet", "--no-tags", "--no-recurse-submodules", ...(fetch_head ? ["--no-write-fetch-head"] : []), cloneUrl(full_name), `refs/heads/${branch}:${into}`];
370
468
  }
371
469
  /**
372
470
  * Pushes exactly the task branch to itself: no `+`, no tag, no other ref, never the default branch. A push the remote
@@ -194,7 +194,7 @@ export function composeNote(input) {
194
194
  `- Branch: ${codeSpan(pr.branch)}`,
195
195
  `- Commit: ${codeSpan(pr.commit)}`,
196
196
  ]
197
- : ["- Repository: none in this room, so nothing was pushed."]),
197
+ : [input.unlinked ? "- Repository: Podster said this task isn't linked to the room's repository, so Runner ran it without a checkout and pushed nothing." : "- Repository: none in this room, so nothing was pushed."]),
198
198
  "- Tests: not run by Runner. Anything the agent says about tests is its own claim, not verified.",
199
199
  ];
200
200
  if (words.kind === "shared" && words.redactions > 0)