@justjoshn/pi-pstack-v2 0.1.0 → 0.1.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.
- package/README.md +38 -20
- package/agents/poteto-agent.md +1 -1
- package/docs/pi-mechanisms.md +8 -7
- package/package.json +2 -2
- package/skills/arena/SKILL.md +1 -1
- package/skills/benchmark-checklist/SKILL.md +1 -1
- package/skills/interrogate/SKILL.md +1 -1
- package/skills/maintain-verification-skill/SKILL.md +1 -1
- package/skills/poteto-mode/SKILL.md +3 -3
- package/skills/swarm/SKILL.md +1 -1
- package/src/index.ts +81 -28
- package/src/jobs.ts +67 -10
- package/src/sandbox.ts +4 -1
- package/src/transcript.ts +66 -0
package/README.md
CHANGED
|
@@ -1,49 +1,67 @@
|
|
|
1
1
|
# pi-pstack-v2
|
|
2
2
|
|
|
3
|
-
pstack for Pi.
|
|
3
|
+
pstack for Pi. The package ships pstack's skills, playbooks, principles, agent roles, scripts, and guide, plus the cursor-team-kit skills and rules that pstack depends on. It is for people who want `/skill:poteto-mode` and its workflow in Pi. Each Cursor mechanism is replaced with a Pi one.
|
|
4
4
|
|
|
5
|
-
- Workers are separate Pi processes in tmux, started
|
|
6
|
-
- Every worker and long-running command runs in a sandbox
|
|
5
|
+
- Workers are separate Pi processes in tmux, started with `pi_spawn`. Pi has no subagents.
|
|
6
|
+
- Every worker and long-running command runs in a sandbox, Seatbelt on macOS and bubblewrap on Linux and WSL2. There are no permission prompts.
|
|
7
7
|
- Plans are files, and checklists live in `TODO.md`.
|
|
8
8
|
- Watchers, dev servers, and heartbeat ticks run through `tmux_run`, never as background shell jobs.
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
Read [how pstack maps onto Pi](https://github.com/just-joshn/pi-customizations/blob/main/extensions/pi-pstack-v2/docs/pi-mechanisms.md) for the full mapping, and [the guide](https://github.com/just-joshn/pi-customizations/blob/main/extensions/pi-pstack-v2/docs/guide/README.md) to learn the workflow. Both also ship in the package under `docs/`.
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
pi install npm:@justjoshn/pi-pstack-v2
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Built and tested against Pi 1.5.2. Do not install another pstack package alongside it. Skill names collide, and Pi keeps only the first it finds.
|
|
11
19
|
|
|
12
20
|
## Requirements
|
|
13
21
|
|
|
14
|
-
- Pi 1.5 or newer.
|
|
15
22
|
- tmux. Pi's `docs/tmux.md` covers the extended-keys setup.
|
|
16
23
|
- A sandbox. macOS has Seatbelt built in. On Linux and WSL2, install bubblewrap (`bwrap`). Jobs refuse to start without one.
|
|
17
|
-
- bun and `gh
|
|
18
|
-
- `jq` and `rg` (ripgrep) for `worktree-audit.sh` and the `pr-review-canvas` skill.
|
|
24
|
+
- bun and `gh`, for the scripts some skills run, such as `watch-pr` and `statechart`.
|
|
25
|
+
- `jq` and `rg` (ripgrep), for `worktree-audit.sh` and the `pr-review-canvas` skill.
|
|
19
26
|
|
|
20
|
-
##
|
|
27
|
+
## First use
|
|
21
28
|
|
|
22
|
-
|
|
23
|
-
|
|
29
|
+
Run `/skill:setup-pstack` to choose a model and thinking level per role. It writes `pstack-v2-models.md` in your Pi agent directory, and the extension shows those role lines to the model in every session. Then start a task:
|
|
30
|
+
|
|
31
|
+
```text
|
|
32
|
+
/skill:poteto-mode <task>
|
|
24
33
|
```
|
|
25
34
|
|
|
26
|
-
|
|
35
|
+
Type `/skill:poteto-help` with a question if you are unsure which skill fits.
|
|
27
36
|
|
|
28
|
-
|
|
37
|
+
## What it adds
|
|
29
38
|
|
|
30
|
-
|
|
39
|
+
The package adds three tools for the model to call, and no slash commands. Every skill runs as `/skill:<name>`.
|
|
31
40
|
|
|
32
41
|
| Tool | Does |
|
|
33
42
|
| --- | --- |
|
|
34
|
-
| `pi_spawn` | Starts a sandboxed `pi -p` worker in its own tmux session with a standalone brief
|
|
35
|
-
| `tmux_run` | Runs a sandboxed shell command in tmux. Optionally wakes
|
|
43
|
+
| `pi_spawn` | Starts a sandboxed `pi -p` worker in its own tmux session with a standalone brief. Takes an optional role from `agents/`, model, thinking level, git worktree, or readonly mode. Wakes your session with the worker's report when it exits. |
|
|
44
|
+
| `tmux_run` | Runs a sandboxed shell command in tmux. Optionally wakes your session when it exits, or repeats it as a heartbeat. |
|
|
36
45
|
| `tmux_jobs` | Lists, tails, waits on, or stops this session's jobs. |
|
|
37
46
|
|
|
38
|
-
|
|
47
|
+
## Notes
|
|
48
|
+
|
|
49
|
+
- The extension appends two cursor-team-kit rules to the system prompt, no inline imports and exhaustive switches.
|
|
50
|
+
- Jobs never write your Pi agent directory. Each top-level job's Pi gets its own, with a copy of your credentials. The extension syncs refreshed OAuth tokens back to your login.
|
|
51
|
+
- A job may write only its own directory, its worktree or working directory, the repository's git directory, and temp directories.
|
|
52
|
+
|
|
53
|
+
## Replaces `@justjoshn/pi-pstack`
|
|
54
|
+
|
|
55
|
+
```sh
|
|
56
|
+
pi install npm:@justjoshn/pi-pstack-v2
|
|
57
|
+
pi remove npm:@justjoshn/pi-pstack
|
|
58
|
+
```
|
|
39
59
|
|
|
40
60
|
## Develop
|
|
41
61
|
|
|
42
|
-
```
|
|
62
|
+
```sh
|
|
43
63
|
bun run --filter @justjoshn/pi-pstack-v2 test
|
|
44
64
|
bun run --filter @justjoshn/pi-pstack-v2 typecheck
|
|
45
65
|
```
|
|
46
66
|
|
|
47
|
-
`
|
|
48
|
-
|
|
49
|
-
License: MIT, from upstream pstack.
|
|
67
|
+
`upstream.lock.json` pins the pstack and cursor-team-kit source that the package copies. MIT license, from upstream pstack.
|
package/agents/poteto-agent.md
CHANGED
|
@@ -5,4 +5,4 @@ description: Worker for code-writing and helper tasks that a `/skill:poteto-mode
|
|
|
5
5
|
|
|
6
6
|
# Poteto worker
|
|
7
7
|
|
|
8
|
-
You are operating as poteto-mode's full agent style. The session that receives `/skill:poteto-mode` owns the playbook, `TODO.md`, and every `pi_spawn`. You are one of its workers. Read the `poteto-mode` skill's `SKILL.md` in full before doing any work, including its inline Principles index. Use the absolute path your brief gave you. With no path, before any other work, find `skills/poteto-mode/SKILL.md` in the pi-pstack-v2 package. Run `pi list` to see where the package is installed, or search under `~/.pi/agent/`. If more than one file matches, use the copy in the package `pi list` reports. Your skill catalog hides this skill, so a missing catalog entry does not mean pstack is absent. If no such file exists, stop and tell your parent. Navigate to a leaf `principle-*` skill whenever you apply that principle.
|
|
8
|
+
You are operating as poteto-mode's full agent style. The session that receives `/skill:poteto-mode` owns the playbook, `TODO.md`, and every `pi_spawn`. You are one of its workers. Read the `poteto-mode` skill's `SKILL.md` in full before doing any work, including its inline Principles index. Use the absolute path your brief gave you. With no path, before any other work, find `skills/poteto-mode/SKILL.md` in the pi-pstack-v2 package. Run `pi list` to see where the package is installed, or search under `~/.pi/agent/`. If more than one file matches, use the copy in the package `pi list` reports. Your skill catalog hides this skill, so a missing catalog entry does not mean pstack is absent. If no such file exists, stop and tell your parent. Navigate to a leaf `principle-*` skill whenever you apply that principle. When something fails only in your sandbox (a browser that will not launch, a download that never lands, a permission error), report it as a sandbox suspect with the exact error. Do not mark it a product defect, a skip, or a fixme.
|
package/docs/pi-mechanisms.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# How pstack maps onto Pi
|
|
2
2
|
|
|
3
|
-
pstack 0.15.
|
|
3
|
+
pstack 0.15.42 and cursor-team-kit 1.2.0 were written for Cursor. `upstream.lock.json` pins the exact upstream commit. This package keeps every skill, playbook, principle, agent, rule, script, and guide chapter, and replaces each Cursor or Claude Code mechanism with the Pi mechanism that does the same job. The skills name Pi mechanisms directly. There is no adapter to read at run time.
|
|
4
4
|
|
|
5
5
|
Pi skips sub-agents, permission popups, plan mode, built-in to-dos, and background bash on purpose. Each row below names what pstack does instead.
|
|
6
6
|
|
|
@@ -11,8 +11,8 @@ Pi skips sub-agents, permission popups, plan mode, built-in to-dos, and backgrou
|
|
|
11
11
|
| No sub-agents. Spawn Pi instances via tmux. | `pi_spawn` starts a separate `pi -p` process in its own tmux session with a standalone brief. It runs in parallel and wakes the spawning session with its report when it exits. |
|
|
12
12
|
| No permission popups. Run in a container. | Every `pi_spawn` and `tmux_run` job runs inside Seatbelt (`sandbox-exec`) on macOS or bubblewrap (`bwrap`) on Linux and WSL2. Writes are limited to the worker's own session directory, its worktree or working directory, the repository's git directory, and temp directories. Pi's own configuration stays read-only. No job runs unsandboxed. |
|
|
13
13
|
| No plan mode. Write plans to files. | A plan is a Markdown file, such as `plans/<slug>.md`. The human reviews the file. |
|
|
14
|
-
| No built-in to-dos. Use a TODO.md file. | Each checklist pstack used to keep in a todo tool lives in `TODO.md` at the root of the checkout you work in, as `- [ ]` and `- [x]` lines. It is working state
|
|
15
|
-
| No background bash. Use tmux. | Watchers, dev servers, long builds, and heartbeat ticks run through `tmux_run`. Nothing uses `&`, `nohup`, `setsid`, or `disown`. |
|
|
14
|
+
| No built-in to-dos. Use a TODO.md file. | Each checklist pstack used to keep in a todo tool lives in `TODO.md` at the root of the checkout you work in, as `- [ ]` and `- [x]` lines. It is working state, so never stage it. When the checkout already tracks a `TODO.md`, the checklist is `.pi/TODO.md`. |
|
|
15
|
+
| No background bash. Use tmux. Full observability, direct interaction. | Watchers, dev servers, long builds, and heartbeat ticks run through `tmux_run`. Nothing uses `&`, `nohup`, `setsid`, or `disown`. Every job is a tmux session you can attach to with the command `tmux_jobs` `list` prints. Its output shows there as it is written, and Ctrl-C there stops it. A job reads no input, so a command that needs an answer typed runs in the root session. |
|
|
16
16
|
|
|
17
17
|
Pi's design principle for customizing is to pick the least powerful mechanism that meets the need. Skills carry all workflow text. The one extension (`src/index.ts`) exists only for what a skill cannot do: start sandboxed tmux jobs, wake the session when they exit, and put the model-role lines and the two team-kit rules into the system prompt.
|
|
18
18
|
|
|
@@ -32,7 +32,7 @@ Pi's design principle for customizing is to pick the least powerful mechanism th
|
|
|
32
32
|
| Nested subagents, launched by a subagent | The same limit as Cursor. The root Pi and the workers it starts have `pi_spawn`. A worker started by another worker does not, and the root refuses a Pi request from one. Every worker keeps `tmux_run` and `tmux_jobs`. |
|
|
33
33
|
| `resume` an agent | `pi_spawn` with `resume: "<job id>"` continues that job's Pi session. |
|
|
34
34
|
| Steer or stop a running agent | `tmux_jobs` with `action: "stop"`, then a fresh `pi_spawn` with consolidated scope. A print-mode Pi takes no mid-run input. |
|
|
35
|
-
| Wait for agents | End your turn and let the wake arrive
|
|
35
|
+
| Wait for agents | End your turn and let the wake arrive. `tmux_jobs` `wait` is for a short wait on named jobs. A spawned Pi running in print mode waits for its own jobs automatically before it finishes. |
|
|
36
36
|
| `file_attachments` | List the paths in the brief. |
|
|
37
37
|
| `model` slug such as `claude-opus-5-5-xhigh` or `grok-4.7-xhigh-fast` | `pi_spawn` `model: "<provider>/<id>"` and `thinking: "<level>"`. Thinking levels are `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`. Pi has no fast variant, so a "fast" choice is dropped. |
|
|
38
38
|
| `~/.cursor/rules/pstack-models.mdc`, `~/.claude/rules/pstack-models.md` | `~/.pi/agent/pstack-v2-models.md`, written by `/skill:setup-pstack`. The extension shows its role lines to the model in a `pstack-models` system-prompt section. A role with no line, or a line of `inherit-parent` or `auto`, runs on the session model, so omit `model`. |
|
|
@@ -68,8 +68,8 @@ Pi's design principle for customizing is to pick the least powerful mechanism th
|
|
|
68
68
|
- Both sandboxes enforce the same rules, and `test/parity.test.ts` runs one table of operations inside a real job on each platform and fails on any difference beyond the Linux exceptions listed below.
|
|
69
69
|
- A job cannot add or change a git worktree or submodule, apart from the metadata of the worktree it works in, and cannot write the git directory of a nested repository. A job that needs another revision beside its own exports it into its private temp directory with `git archive <sha> | tar -x -C "$TMPDIR/<name>"`.
|
|
70
70
|
- bubblewrap can make only existing paths read-only, so before a job starts the root creates any missing `hooks/`, `info/`, `worktrees/`, and `modules/` directory and `config.worktree` file in the git directory, empty, on every platform. Git reads them as nothing.
|
|
71
|
-
- Shared temp directories and user caches are not writable, because unsandboxed programs load code cached there, such as Pi's compiled-extension cache. Each job's `TMPDIR`, `XDG_CACHE_HOME`, and npm, bun, pip, uv, Go, Yarn, and Deno caches point at its private temp directory, so installs and builds still work. Those caches are deleted when the job exits, and the rest of its temp directory is kept for the report. On Linux the job also gets a private `/tmp`.
|
|
72
|
-
- `cwd` must be inside the session's project, which is the git top level or else the session cwd,
|
|
71
|
+
- Shared temp directories and user caches are not writable, because unsandboxed programs load code cached there, such as Pi's compiled-extension cache. Each job's `TMPDIR`, `XDG_CACHE_HOME`, and npm, bun, pip, uv, Go, Yarn, and Deno caches point at its private temp directory, so installs and builds still work. Those caches are deleted when the job exits, and the rest of its temp directory is kept for the report. Chromium follows `MAC_CHROMIUM_TMPDIR` and zsh follows `TMPPREFIX`, both set to the same directory. On macOS a job finds a `mktemp` first on `PATH` that uses `$TMPDIR`, since the system one prefers the per-user temp directory. A command a worker starts shares the worker's temp directory. On Linux the job also gets a private `/tmp`.
|
|
72
|
+
- `cwd` must be inside the session's project, which is the git top level or else the session cwd, or a linked worktree of the same repository. A checkout of another repository is refused even when it sits inside the project, since the job would be handed that repository's git directory. No writable path may contain Pi's agent directory. The model cannot widen its own sandbox by naming another directory.
|
|
73
73
|
- Paths an unsandboxed process later executes from stay read-only even inside a writable checkout. Those are the git `hooks/`, `config`, `config.worktree`, and `info/` entries, a configured `core.hooksPath`, and the code entries of every `.pi` directory in the checkout at any depth: `extensions`, `settings.json`, `mcp.json`, and installed packages in `npm` and `git`. Git finds hooks through `.git`, every `.git` pointer file such as a submodule's, every linked worktree's `commondir`, `gitdir`, and `config.worktree`, and submodule git directories, so all of those stay read-only. Every existing directory above a protected path, and `.git` itself, cannot be renamed or replaced. A protected path that is a symlink is guarded at the link as well as its target.
|
|
74
74
|
- Code can still appear where none was at launch, because a job can rename a directory it built into place or link a parent elsewhere, and bubblewrap cannot bind what does not exist. At launch the root records every protected path, `.pi` code entry, and `.git` entry in the checkout. When the job exits or is stopped, the unsandboxed wrapper sweeps the checkout and moves anything new of those kinds into the job's `quarantine/` directory, and the job's output says so. The sweep never follows a link, and a `.pi` symlink you already had is left alone. Moving, not deleting, keeps a file you created yourself during the job recoverable. On macOS, Seatbelt also denies writing those paths anywhere in the checkout.
|
|
75
75
|
- Jobs never write your Pi agent directory, your `auth.json` included. Each top-level job gets its own agent directory, through Pi's `PI_CODING_AGENT_DIR`, shared by every job it starts. It links to your configuration, holds `settings.json` with its local package paths anchored to your real agent directory, and holds a copy of your credentials. In it a job may write only the contents of that copy and Pi's lock directories, so no job can change what another job's Pi loads. On Linux it is a throwaway tmpfs view, so other writes there vanish with the job.
|
|
@@ -89,6 +89,7 @@ Pi's design principle for customizing is to pick the least powerful mechanism th
|
|
|
89
89
|
- On Linux a job takes Pi's credential lock in its own throwaway view, so a job refreshing a token and the root syncing that copy at the same moment can lose that refresh. pstack refreshes a worker's credentials just before starting it, so this needs a worker to outlive its token.
|
|
90
90
|
- A job can leave a fake rebase in progress in the git directory, whose steps run if you then run `git rebase --continue`.
|
|
91
91
|
- A print-mode run waits for every job it started with a wake message, so one that never exits keeps it running.
|
|
92
|
+
- On macOS a job cannot run `ps` or `top`, so it reads the load with `uptime`. A bash here-document fails in a checkout the job cannot write, such as a readonly worker's, so the job changes to `$TMPDIR` first or writes with `printf`.
|
|
92
93
|
- Cargo and Maven caches are not redirected to the job's private temp directory, so their downloads fail inside a job.
|
|
93
94
|
- Until a job exits, a protected path it created by rename or link still exists, and an unsandboxed process started in that checkout during the job could use it.
|
|
94
95
|
- On macOS a job process that detaches into its own session with `setsid` survives `stop` and keeps its sandbox rights, still inside its sandbox. It can keep writing what the job could write, including a protected path after cleanup ran. The credential check still reverts any command key it plants. Linux has no such gap, because the PID namespace ends every process.
|
|
@@ -97,4 +98,4 @@ Pi's design principle for customizing is to pick the least powerful mechanism th
|
|
|
97
98
|
|
|
98
99
|
## Jobs on disk
|
|
99
100
|
|
|
100
|
-
Each job lives in `~/.pi/agent/pstack-v2/jobs/<id>/`: `job.json` (the spec), `brief.md`, `wrapper.sh`, `inventory.json`, `output.log`, `exit`, its private `tmp/`, a top-level job's `agent/`, any `quarantine/`, and for Pi workers `session/`, `nested/`, and `stderr.log`. The job directory is read-only to the job, so a job cannot rewrite its own spec or exit code. The unsandboxed tmux wrapper writes `output.log` and `exit`. A Pi worker can write only `session/` and `nested/`, and the jobs it starts live in `nested/`. Each spawning session runs its own tmux server on a socket in `/tmp/pstack-v2-<uid>/`, named from a hash of the session id. `tmux_jobs` `list` prints a `tail -f` command to follow each job's output. A wake is claimed once through a `woken` marker file, so restarting Pi never delivers a report twice.
|
|
101
|
+
Each job lives in `~/.pi/agent/pstack-v2/jobs/<id>/`: `job.json` (the spec), `brief.md`, `wrapper.sh`, `inventory.json`, `output.log`, `exit`, its private `tmp/`, a top-level job's `agent/`, any `quarantine/`, and for Pi workers `session/`, `nested/`, and `stderr.log`. The job directory is read-only to the job, so a job cannot rewrite its own spec or exit code. The unsandboxed tmux wrapper writes `output.log` and `exit`. A Pi worker can write only `session/` and `nested/`, and the jobs it starts live in `nested/`. Each spawning session runs its own tmux server on a socket in `/tmp/pstack-v2-<uid>/`, named from a hash of the session id. `tmux_jobs` `list` prints a `tail -f` command to follow each job's output and a `tmux attach` command for each running job. A worker's report is every answer it completed, read from its session file, so a reply to a late job notice cannot replace it. A wake is claimed once through a `woken` marker file, so restarting Pi never delivers a report twice.
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@justjoshn/pi-pstack-v2",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"description": "pstack and
|
|
3
|
+
"version": "0.1.2",
|
|
4
|
+
"description": "Use the pstack skills and workflow in Pi, with sandboxed Pi workers and shell jobs running in tmux.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"repository": {
|
package/skills/arena/SKILL.md
CHANGED
|
@@ -21,7 +21,7 @@ Every candidate gets the same prompt, so the prompt is the contract.
|
|
|
21
21
|
|
|
22
22
|
Spawn all N workers in one message with N `pi_spawn` calls, each with the task, the path to the shared grounding, its own output path, and instructions to produce the artifact and a short rationale naming the alternatives it considered and what it rejected.
|
|
23
23
|
|
|
24
|
-
Each runner wakes you with its report when it exits. End your turn and let the wakes arrive
|
|
24
|
+
Each runner wakes you with its report when it exits. End your turn and let the wakes arrive before Phase C. If a candidate produces no output, proceed with N-1 and note the dropout.
|
|
25
25
|
|
|
26
26
|
## Phase C: Cross-judge
|
|
27
27
|
|
|
@@ -14,7 +14,7 @@ For a quick ballpark the user asked for, one run is enough. Still check question
|
|
|
14
14
|
|
|
15
15
|
- Write down the claim you expect to make, in the words you would ship ("export is 30% faster at p50 on the 60k-row dataset"). The questions test that sentence.
|
|
16
16
|
- Read the measurement script. Note what it times, counts, and ignores.
|
|
17
|
-
- Check the load average with `uptime` and the core count with `nproc`. If the machine is busy, find out what is running. If you cannot stop it, interleave the sides so both see the same noise, and say so in the report.
|
|
17
|
+
- Check the load average with `uptime` and the core count with `nproc`. If the machine is busy, find out what is running. If you cannot stop it, interleave the sides so both see the same noise, and say so in the report. In the pstack sandbox `ps` and `top` are refused, so report the load from `uptime` and ask the session that started you what is running.
|
|
18
18
|
|
|
19
19
|
## The questions
|
|
20
20
|
|
|
@@ -22,7 +22,7 @@ Run Phase A steps 3 and 4 and Phase B of the **arena** skill, with four changes.
|
|
|
22
22
|
|
|
23
23
|
## Verify
|
|
24
24
|
|
|
25
|
-
Each adversary wakes you with its report when it exits. End your turn and let the wakes arrive
|
|
25
|
+
Each adversary wakes you with its report when it exits. End your turn and let the wakes arrive before you verify.
|
|
26
26
|
|
|
27
27
|
Verify each finding per arena Phase F by rerunning its command. Keep a finding when the output shows the failure and the failure breaks the intent. Drop the rest. Merge findings that share a root cause.
|
|
28
28
|
|
|
@@ -26,7 +26,7 @@ Only edit the verification skill's own directory (its SKILL.md, features/, and a
|
|
|
26
26
|
|
|
27
27
|
1. **Index hygiene.** Read the feature map README and glob its sibling files. Fix missing, extra, duplicate, or dead entries. Lightweight; no generated inventory.
|
|
28
28
|
|
|
29
|
-
2. **Source wave.** One readonly worker per feature file, started with one `pi_spawn` call each in a single message so they run concurrently. Each explains "how does this user-facing feature work?" from source, flags likely doc drift with citations, and returns one concise live-verification recipe. Workers never drive the app and never edit files. Each exits with that result as its report, which wakes you. End your turn and let the wakes arrive
|
|
29
|
+
2. **Source wave.** One readonly worker per feature file, started with one `pi_spawn` call each in a single message so they run concurrently. Each explains "how does this user-facing feature work?" from source, flags likely doc drift with citations, and returns one concise live-verification recipe. Workers never drive the app and never edit files. Each exits with that result as its report, which wakes you. End your turn and let the wakes arrive before you reconcile. Return shape: feature summary / source entry points / likely drift or none / one recipe.
|
|
30
30
|
|
|
31
31
|
3. **Reconcile.** Every feature file has a returned summary. Merge overlapping recipes into as few app states as practical. Spot-check cited drift; don't re-prove clean claims. Sweep recent churn for user-facing surfaces missing from the map — require a concrete source path before calling one missing.
|
|
32
32
|
|
|
@@ -94,11 +94,11 @@ Pi has no subagents. A worker is a separate Pi process that `pi_spawn` starts in
|
|
|
94
94
|
|
|
95
95
|
**Use `pi_spawn` with `agent: "poteto-agent"` for any worker you spawn inside a playbook step** (code-writing delegates, ad-hoc helpers). The session that receives `/skill:poteto-mode` runs the playbook. Never spawn a `poteto-agent` to run the playbook itself. Routed workflow skills (`interrogate`, `reflect`, `swarm`) set their own `agent` and model for diverse-model review. Respect what the skill prescribes, don't override to `poteto-agent`.
|
|
96
96
|
|
|
97
|
-
**Defaults for every `pi_spawn` call.** Every worker runs in parallel and wakes you with its report when it exits, so keep working or end your turn while it runs. Leave `readonly` unset unless the worker must not write. Give file pointers, not inlined context. Pass an explicit model per role (configurable via `/skill:setup-pstack`, shown to you as the `pstack-models` system-prompt section). A role with no line runs on this session's model, so omit `model`. Code delegates tier by difficulty. The hardest changes (cross-cutting design, gnarly concurrency, subtle algorithms) go to your `hardest tasks` model, whether the task needs judgment on vague intent or is a precisely specified sequence of steps to execute to the letter. Trivial mechanical edits go to your `swarm workers` model. Per-role lines in the setup-pstack file override these defaults and the model choices in the routed skills (`arena`, `swarm`, `architect`, `interrogate`, `reflect`). A role with no line keeps its default, and a role line of `inherit-parent` or `auto` runs that role on this session's model (omit `model`). Each code playbook's configured model comes from its line (`feature, refactoring`, `bug-fix`, `perf-issue`, or `hillclimb`), and the hardest changes read `hardest tasks`. Prose and judgment read `judgment and prose`. If the setup-pstack file has no `# defaults: 2` line, an older setup wrote it. Keep honoring its lines, and tell the user once per session to rerun `/skill:setup-pstack`.
|
|
97
|
+
**Defaults for every `pi_spawn` call.** Every worker runs in parallel and wakes you with its report when it exits, so keep working or end your turn while it runs. Use `tmux_jobs` `wait` only for a short, bounded wait on named job ids, never to block until a worker finishes. Give a `tmux_run` job that polls for a condition a deadline, so it exits and wakes you whether or not the condition arrives. Leave `readonly` unset unless the worker must not write. Give file pointers, not inlined context. Pass an explicit model per role (configurable via `/skill:setup-pstack`, shown to you as the `pstack-models` system-prompt section). A role with no line runs on this session's model, so omit `model`. Code delegates tier by difficulty. The hardest changes (cross-cutting design, gnarly concurrency, subtle algorithms) go to your `hardest tasks` model, whether the task needs judgment on vague intent or is a precisely specified sequence of steps to execute to the letter. Trivial mechanical edits go to your `swarm workers` model. Per-role lines in the setup-pstack file override these defaults and the model choices in the routed skills (`arena`, `swarm`, `architect`, `interrogate`, `reflect`). A role with no line keeps its default, and a role line of `inherit-parent` or `auto` runs that role on this session's model (omit `model`). Each code playbook's configured model comes from its line (`feature, refactoring`, `bug-fix`, `perf-issue`, or `hillclimb`), and the hardest changes read `hardest tasks`. Prose and judgment read `judgment and prose`. If the setup-pstack file has no `# defaults: 2` line, an older setup wrote it. Keep honoring its lines, and tell the user once per session to rerun `/skill:setup-pstack`.
|
|
98
98
|
|
|
99
99
|
**Match the model to the job.** Before each spawn, start from the role's line and pick the `thinking` level the job needs. The setup-pstack budget sets each role's starting level, `xhigh` or `high` by default, and `max` for `hardest tasks`. Raise it one step, up to `max`, for the hardest or subtlest work. Lower it one step for judgment and two or more steps for routine work. Verification is the exception and stays on the `swarm workers` model and level. Change only the thinking level and keep the model the role names, so a diverse panel stays diverse. If the model does not support that level, clamp to the nearest level it supports. A role on `auto` or `inherit-parent` stays on this session's model. A model counts as rejected once `pi_spawn` says it is not valid. Never pass a rejected model, and skip any fallback that is already rejected. If `pi_spawn` rejects an adjusted model, use the role's line and say so. When the calling skill has a fallback, follow it next. When it has none, use the nearest model of the role's provider from the error's list of valid models, or omit `model` when the list has none, and say so. When a fallback runs out of models, omit `model` too.
|
|
100
100
|
|
|
101
|
-
You own every worker's work. Review the diff and write your own summary, don't pass through what it said. A second opinion is the same brief against a different model. Agreement is high-signal.
|
|
101
|
+
You own every worker's work. Review the diff and write your own summary, don't pass through what it said. A second opinion is the same brief against a different model. Agreement is high-signal. A failure a worker sees only inside the sandbox (a browser that will not launch, a download that never lands, a permission error) is a sandbox suspect until you reproduce it outside the sandbox. Until then, do not file it as a product defect, a skip, or a fixme.
|
|
102
102
|
|
|
103
103
|
**Fresh workers by default.** Give new work to a fresh `pi_spawn` with consolidated scope, meaning the original brief, every later directive, and the prior worker's report and branch. This holds for a fix round, a follow-up, a retry, and the next queue item. Continue an earlier worker's session (`pi_spawn` with `resume: "<job id>"`) only when the new work strictly needs state that lives in that worker and is costly to move: its worktree or its uncommitted changes. A process dies when its job exits, so restart a dev server or a babysit watcher with a fresh `tmux_run`. Stopping a running worker with `tmux_jobs` `stop` is not reuse. A role such as a PR owner outlives its worker. Once that worker exits, a fresh worker takes the role's next round. A resumed session can silently drop directives, so spawn fresh with consolidated scope rather than trusting a "done" summary.
|
|
104
104
|
|
|
@@ -122,7 +122,7 @@ Comments follow the same rule as the reply. Write them clean as you go. Keep a c
|
|
|
122
122
|
|
|
123
123
|
## Playbooks
|
|
124
124
|
|
|
125
|
-
Write `TODO.md` at the root of your checkout with the matched playbook's steps first, copied in verbatim as `- [ ]` items, before any task-specific items. Check items off as you finish them. A step you choose not to do stays in the list with a one-line `skip: <reason>`. `TODO.md` is working state, so never stage it. Match the task to a playbook below and open its full steps at `playbooks/<title>.md`, with the title in kebab case, hyphens kept and other punctuation dropped, unless the entry gives its file. Copy its steps in verbatim.
|
|
125
|
+
Write `TODO.md` at the root of your checkout with the matched playbook's steps first, copied in verbatim as `- [ ]` items, before any task-specific items. Check items off as you finish them. A step you choose not to do stays in the list with a one-line `skip: <reason>`. `TODO.md` is working state, so never stage it. If the checkout already tracks a `TODO.md`, write the checklist to `.pi/TODO.md` instead, under the same rules. This holds wherever a skill says to write `TODO.md`. Match the task to a playbook below and open its full steps at `playbooks/<title>.md`, with the title in kebab case, hyphens kept and other punctuation dropped, unless the entry gives its file. Copy its steps in verbatim.
|
|
126
126
|
|
|
127
127
|
A large or cross-cutting effort (a migration across many call sites, an ambitious multi-part change), or work the user steps away from to trust later, routes to the **figure-it-out** skill even when a narrower playbook like Feature fits. Use **figure-it-out** whenever no bundled playbook fits. It designs a bespoke, rigorous playbook for the task. A standing project-scale program (multi-day, many stacked PRs, a fleet of spawned Pi workers under one coordinator) routes to **Orchestrate** instead. figure-it-out designs one bespoke run, orchestrate runs the program.
|
|
128
128
|
|
package/skills/swarm/SKILL.md
CHANGED
|
@@ -34,7 +34,7 @@ If a worker drops out, proceed with N-1 and note it.
|
|
|
34
34
|
|
|
35
35
|
## Phase C: Aggregate
|
|
36
36
|
|
|
37
|
-
Each worker wakes you with its report when it exits. End your turn and let the wakes arrive
|
|
37
|
+
Each worker wakes you with its report when it exits. End your turn and let the wakes arrive. Then read the terminal results. Drop a result that does not record the SHAs and method its brief names, and respawn that worker once. After a second miss, record a gap. A gap does not count as a pass. For coverage, every required slice needs a result. For a race, apply the selection rule declared up front. Use first pass, rank all, or best-of. Do not paste raw worker dumps.
|
|
38
38
|
|
|
39
39
|
## Phase D: Report
|
|
40
40
|
|
package/src/index.ts
CHANGED
|
@@ -6,9 +6,10 @@ import { fileURLToPath } from 'node:url';
|
|
|
6
6
|
import { type ExtensionAPI, type ExtensionContext, getAgentDir, parseFrontmatter, stripFrontmatter } from '@earendil-works/pi-coding-agent';
|
|
7
7
|
import { Type } from 'typebox';
|
|
8
8
|
import { commandProviders, jobAgentDir, makeJobAgentDir, syncTokens } from './credentials.ts';
|
|
9
|
-
import { brokeredSession, claimWake, excerpt, exitPath, type Job, type JobSpec, launch, launchBrokered, list, newJobId, outputPath, read, readSpec, request, resultsDir, settleBrokered, stop, tail, tmuxSocket } from './jobs.ts';
|
|
9
|
+
import { brokeredSession, claimWake, clip, excerpt, exitPath, type Job, type JobSpec, launch, launchBrokered, list, newJobId, outputPath, read, readSpec, request, resultsDir, settleBrokered, stop, tail, tmuxSocket } from './jobs.ts';
|
|
10
10
|
import { JOB_DIR_ENV, SANDBOX_ENV, type SandboxPolicy, sandboxed, TOP_DIR_ENV } from './sandbox.ts';
|
|
11
11
|
import { codePaths, PI_CODE } from './sweep.ts';
|
|
12
|
+
import { workerReport } from './transcript.ts';
|
|
12
13
|
|
|
13
14
|
const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
14
15
|
const AGENTS = ['poteto-agent', 'comment-sicko', 'ci-watcher', 'thermo-nuclear-code-quality-review'] as const;
|
|
@@ -34,7 +35,8 @@ const text = (value: string) => ({ content: [{ type: 'text' as const, text: valu
|
|
|
34
35
|
|
|
35
36
|
const agentRoles = AGENTS.map((name) => `${name}: ${parseFrontmatter<{ description?: string }>(readFileSync(join(packageRoot, 'agents', `${name}.md`), 'utf8')).frontmatter.description ?? ''}`);
|
|
36
37
|
const skillsHint = `pstack skills, including ones hidden from the skill list, live at ${join(packageRoot, 'skills')}/<name>/SKILL.md. When a skill says to run another skill, read that file and follow it.`;
|
|
37
|
-
const SANDBOX_NOTE =
|
|
38
|
+
const SANDBOX_NOTE =
|
|
39
|
+
'You run in the pstack sandbox. The shared /tmp, macOS per-user temp directory, and user caches are read-only. Keep temp files in $TMPDIR, your own temp directory. Chromium uses the same private directory through MAC_CHROMIUM_TMPDIR. Tools that ignore both variables cannot write shared temp files. `ps` and `top` are refused, so read the load with `uptime`. In a checkout you cannot write, a bash here-document fails, so `cd "$TMPDIR"` first or write the file with printf.';
|
|
38
40
|
const flagValue = (command: string[], flag: string): string | undefined => (command.includes(flag) ? command[command.indexOf(flag) + 1] : undefined);
|
|
39
41
|
const rules = ['no-inline-imports', 'typescript-exhaustive-switch'].map((name) => stripFrontmatter(readFileSync(join(packageRoot, 'rules', `${name}.md`), 'utf8')).replace(/^#.*\n+/, ''));
|
|
40
42
|
|
|
@@ -54,7 +56,14 @@ function gitPath(cwd: string, flag: '--git-common-dir' | '--show-toplevel' | '--
|
|
|
54
56
|
function projectPath(ctx: ExtensionContext, path: string | undefined): string {
|
|
55
57
|
const root = realpathSync(gitPath(ctx.cwd, '--show-toplevel') ?? ctx.cwd);
|
|
56
58
|
const target = realpathSync(path === undefined ? ctx.cwd : resolve(ctx.cwd, path));
|
|
57
|
-
|
|
59
|
+
// A linked worktree of the same repository, such as a worker's checkout, is the same project on another branch.
|
|
60
|
+
const common = gitPath(ctx.cwd, '--git-common-dir');
|
|
61
|
+
const targetCommon = gitPath(target, '--git-common-dir');
|
|
62
|
+
const sameRepository = common !== undefined && targetCommon !== undefined && landing(targetCommon) === landing(common);
|
|
63
|
+
const worktree = sameRepository ? gitPath(target, '--show-toplevel') : undefined;
|
|
64
|
+
if (!within(target, [root, ...(worktree ? [worktree] : [])])) throw new Error(`cwd must be inside this project (${root}), got ${target}. To work on another branch, pass worktree and the job gets its own checkout.`);
|
|
65
|
+
// A checkout of another repository can sit inside the project, and a job there would be handed that repository's git directory.
|
|
66
|
+
if (targetCommon !== undefined && !sameRepository && !within(targetCommon, [root])) throw new Error(`cwd ${target} is a checkout of another repository (${targetCommon}). A job works only in this session's repository.`);
|
|
58
67
|
return target;
|
|
59
68
|
}
|
|
60
69
|
|
|
@@ -103,23 +112,52 @@ function addWorktree(cwd: string, path: string, branch: string, base: string | u
|
|
|
103
112
|
} catch {
|
|
104
113
|
exists = false;
|
|
105
114
|
}
|
|
106
|
-
git(cwd, exists ? ['worktree', 'add', path, branch] : ['worktree', 'add', '-b', branch, path, base
|
|
115
|
+
git(cwd, exists ? ['worktree', 'add', path, branch] : ['worktree', 'add', '-b', branch, path, base === undefined ? 'HEAD' : baseOrSoleRemoteBranch(cwd, base)]);
|
|
107
116
|
return !exists;
|
|
108
117
|
}
|
|
109
118
|
|
|
119
|
+
function baseOrSoleRemoteBranch(cwd: string, base: string): string {
|
|
120
|
+
try {
|
|
121
|
+
git(cwd, ['rev-parse', '--verify', '--quiet', `${base}^{commit}`]);
|
|
122
|
+
return base;
|
|
123
|
+
} catch {
|
|
124
|
+
const remote = git(cwd, ['for-each-ref', '--format=%(refname:short)', `refs/remotes/*/${base}`])
|
|
125
|
+
.split('\n')
|
|
126
|
+
.filter(Boolean);
|
|
127
|
+
return remote.length === 1 ? (remote[0] ?? base) : base;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
110
131
|
function report(job: Job): string {
|
|
111
132
|
const state = job.status.state === 'exited' ? `exited with code ${job.status.code}` : 'was lost (its tmux session ended without an exit code)';
|
|
112
133
|
const output = outputPath(job.spec.out);
|
|
113
|
-
const
|
|
134
|
+
const transcript = job.spec.kind === 'pi' ? workerReport(flagValue(job.spec.command, '--session-dir'), job.spec.createdAt) : undefined;
|
|
135
|
+
const answers = transcript?.answers ?? [];
|
|
136
|
+
const body =
|
|
137
|
+
answers.length && transcript
|
|
138
|
+
? clip(answers.join('\n\n[Later completed answer]\n\n'), REPORT_HEAD, REPORT_LIMIT - REPORT_HEAD, transcript.path)
|
|
139
|
+
: job.spec.kind === 'pi'
|
|
140
|
+
? excerpt(output, REPORT_HEAD, REPORT_LIMIT - REPORT_HEAD)
|
|
141
|
+
: tail(output, 60);
|
|
114
142
|
// A worker that fails at startup, such as on a bad model or credential, says why only on stderr.
|
|
115
143
|
const failed = job.status.state !== 'exited' || job.status.code !== 0 || !body.trim();
|
|
116
144
|
const errors = failed ? tail(join(job.spec.out, 'stderr.log'), 40).trim() : '';
|
|
117
|
-
return [
|
|
145
|
+
return [
|
|
146
|
+
`tmux job ${job.spec.name} (${job.spec.id}) ${state}. Raw output: ${output}`,
|
|
147
|
+
transcript ? `Transcript: ${transcript.path}` : '',
|
|
148
|
+
job.spec.wake ?? '',
|
|
149
|
+
job.spec.kind === 'pi' && !answers.length ? '[No completed transcript answers available; showing raw stdout.]' : '',
|
|
150
|
+
`<output>\n${body.trim()}\n</output>`,
|
|
151
|
+
errors ? `<stderr>\n${errors}\n</stderr>` : '',
|
|
152
|
+
]
|
|
153
|
+
.filter(Boolean)
|
|
154
|
+
.join('\n\n');
|
|
118
155
|
}
|
|
119
156
|
|
|
120
157
|
function describe(job: Job): string {
|
|
121
158
|
const state = job.status.state === 'exited' ? `exited ${job.status.code}` : job.status.state;
|
|
122
|
-
|
|
159
|
+
const attach = job.spec.socket && job.status.state === 'running' ? `\n attach: tmux -S ${job.spec.socket} attach -t ${job.spec.id}` : '';
|
|
160
|
+
return `${job.spec.id} ${job.spec.kind} ${state} ${job.spec.name}\n follow: tail -f ${outputPath(job.spec.out)}${attach}`;
|
|
123
161
|
}
|
|
124
162
|
|
|
125
163
|
function resolveModel(ctx: ExtensionContext, model: string | undefined): string | undefined {
|
|
@@ -157,11 +195,14 @@ function start(root: string, spec: JobSpec, files: Record<string, string> = {},
|
|
|
157
195
|
if (!insideJob()) makeJobAgentDir(getAgentDir(), jobAgentDir(jobDir), resolved);
|
|
158
196
|
// Every job gets a private temp directory, since the shared ones hold code unsandboxed programs load, and writes
|
|
159
197
|
// credentials only to its top-level job's copy.
|
|
160
|
-
|
|
198
|
+
// A command a worker starts shares the worker's temp directory, so a path the worker hands it under $TMPDIR exists for both.
|
|
199
|
+
const parent = process.env[JOB_DIR_ENV];
|
|
200
|
+
const tmp = insideJob() && parent && spec.kind === 'command' ? join(parent, 'tmp') : undefined;
|
|
201
|
+
const policy: SandboxPolicy = { ...spec.policy, jobDir, credentials: jobAgentDir(top), writable: [...new Set([...spec.policy.writable, join(jobDir, 'tmp'), ...(tmp ? [tmp] : [])])] };
|
|
161
202
|
// A writable path that holds Pi's agent directory would let the job rewrite Pi's own code and settings.
|
|
162
203
|
const holder = policy.writable.find((path) => within(policy.agentDir, [path]));
|
|
163
204
|
if (holder) throw new Error(`pstack will not let a job write ${holder}, because it contains Pi's agent directory ${policy.agentDir}. Run Pi from a project directory.`);
|
|
164
|
-
spec = { ...spec, sweep: sweepFor(policy) };
|
|
205
|
+
spec = { ...spec, sweep: sweepFor(policy), ...(tmp ? { tmp } : {}) };
|
|
165
206
|
policy.checkouts = spec.sweep.roots;
|
|
166
207
|
// bubblewrap binds only paths that exist, so the private temp directory exists before the sandbox is built.
|
|
167
208
|
mkdirSync(join(jobDir, 'tmp'), { recursive: true });
|
|
@@ -260,7 +301,10 @@ export function serveRequests(top: Job, socket: string, nested: string, requeste
|
|
|
260
301
|
granted.checkouts = sweepFor(granted).roots;
|
|
261
302
|
mkdirSync(out, { recursive: true });
|
|
262
303
|
writeFileSync(join(out, 'granted.json'), JSON.stringify(writable));
|
|
263
|
-
|
|
304
|
+
// The worker supplies tmp, so it is trusted only if it is one of the writable paths validated above.
|
|
305
|
+
const { tmp: asked, ...rest } = spec;
|
|
306
|
+
const tmp = typeof asked === 'string' && writable.includes(landing(asked)) ? landing(asked) : undefined;
|
|
307
|
+
launchBrokered(top.dir, dir, { ...rest, ...(tmp ? { tmp } : {}) }, sweepFor(granted), sandboxed(spec.command, granted), socket);
|
|
264
308
|
} catch {
|
|
265
309
|
// One request failing must not stop the others.
|
|
266
310
|
}
|
|
@@ -272,6 +316,8 @@ export default function pstack(pi: ExtensionAPI) {
|
|
|
272
316
|
const stoppedSeries = new Set<string>();
|
|
273
317
|
// Jobs a tmux_jobs wait call is blocking on. Their report goes back as that call's result, not as a wake.
|
|
274
318
|
const awaited = new Set<string>();
|
|
319
|
+
// While a print-mode run settles, agent_before_settle delivers the reports itself.
|
|
320
|
+
let settling = false;
|
|
275
321
|
|
|
276
322
|
// Reports a finished job whose wake was just claimed, restarting it first when it is a heartbeat that exited cleanly.
|
|
277
323
|
const finish = (job: Job): string => {
|
|
@@ -302,6 +348,7 @@ export default function pstack(pi: ExtensionAPI) {
|
|
|
302
348
|
};
|
|
303
349
|
|
|
304
350
|
const interactive = (ctx: ExtensionContext): boolean => ctx.mode === 'tui' || ctx.mode === 'rpc';
|
|
351
|
+
const deliverable = (ctx: ExtensionContext): boolean => interactive(ctx) || (!settling && !ctx.isIdle());
|
|
305
352
|
|
|
306
353
|
const serve = (ctx: ExtensionContext): void => {
|
|
307
354
|
if (brokering()) return;
|
|
@@ -321,7 +368,7 @@ export default function pstack(pi: ExtensionAPI) {
|
|
|
321
368
|
|
|
322
369
|
// Each step runs on its own, so one failing does not stop the others.
|
|
323
370
|
const tick = (ctx: ExtensionContext): void => {
|
|
324
|
-
for (const step of [() => syncCredentials(ctx), () => serve(ctx), () =>
|
|
371
|
+
for (const step of [() => syncCredentials(ctx), () => serve(ctx), () => deliverable(ctx) && deliverFinished(ctx)]) {
|
|
325
372
|
try {
|
|
326
373
|
step();
|
|
327
374
|
} catch (error) {
|
|
@@ -353,13 +400,18 @@ export default function pstack(pi: ExtensionAPI) {
|
|
|
353
400
|
const owner = ctx.sessionManager.getSessionId();
|
|
354
401
|
const pending = () => list(jobsRoot(), owner).filter((job) => job.spec.wake !== null && !job.spec.repeat && !existsSync(join(job.dir, 'woken')));
|
|
355
402
|
if (pending().length === 0) return;
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
403
|
+
settling = true;
|
|
404
|
+
try {
|
|
405
|
+
while (pending().some((job) => job.status.state === 'running')) await new Promise((done) => setTimeout(done, POLL_MS));
|
|
406
|
+
syncCredentials(ctx);
|
|
407
|
+
const finished = pending().filter(claimWake);
|
|
408
|
+
return {
|
|
409
|
+
entries: [...event.entries, ...finished.map((job) => ({ type: 'custom_message' as const, customType: 'pstack-job', content: finish(job), display: true }))],
|
|
410
|
+
continue: true,
|
|
411
|
+
};
|
|
412
|
+
} finally {
|
|
413
|
+
settling = false;
|
|
414
|
+
}
|
|
363
415
|
});
|
|
364
416
|
|
|
365
417
|
pi.on('before_agent_start', async (event, ctx) => {
|
|
@@ -379,7 +431,7 @@ export default function pstack(pi: ExtensionAPI) {
|
|
|
379
431
|
name: 'pi_spawn',
|
|
380
432
|
label: 'Spawn Pi',
|
|
381
433
|
description:
|
|
382
|
-
'Start a separate Pi process in its own tmux session, inside a Seatbelt (macOS) or bubblewrap (Linux) sandbox, with a standalone brief. It runs in parallel and does not see this conversation. When it exits you are woken with its final report. Each call starts one fresh instance; to start several, call pi_spawn several times in one message. A Pi it starts can start workers too, and those workers cannot.',
|
|
434
|
+
'Start a separate Pi process in its own tmux session, inside a Seatbelt (macOS) or bubblewrap (Linux) sandbox, with a standalone brief. It runs in parallel and does not see this conversation. When it exits you are woken with its final report. Each call starts one fresh instance; to start several, call pi_spawn several times in one message. A Pi it starts can start workers too, and those workers cannot. The shared /tmp is read-only to the worker, so a brief that names a scratch path uses $TMPDIR or the checkout.',
|
|
383
435
|
promptSnippet: 'Start a parallel Pi instance in tmux with a standalone brief, then get woken with its report',
|
|
384
436
|
promptGuidelines: [
|
|
385
437
|
'Use pi_spawn wherever a pstack skill says to spawn a worker, delegate, explorer, reviewer, or Pi instance. Pi has no subagents.',
|
|
@@ -489,7 +541,7 @@ export default function pstack(pi: ExtensionAPI) {
|
|
|
489
541
|
name: 'tmux_run',
|
|
490
542
|
label: 'Run in tmux',
|
|
491
543
|
description:
|
|
492
|
-
'Run a shell command in its own tmux session, inside the pstack sandbox, instead of a background shell. Use it for watchers, dev servers, long builds, and heartbeat timers. With wake set, you are woken with that message and the output tail when the command exits. With repeat, the command restarts each time it exits cleanly, so `sleep 3600` plus a wake message is an hourly tick. The shared /tmp is read-only to the command, so it keeps temp files in $TMPDIR, its own temp directory.',
|
|
544
|
+
'Run a shell command in its own tmux session, inside the pstack sandbox, instead of a background shell. Use it for watchers, dev servers, long builds, and heartbeat timers. With wake set, you are woken with that message and the output tail when the command exits. With repeat, the command restarts each time it exits cleanly, so `sleep 3600` plus a wake message is an hourly tick. The shared /tmp is read-only to the command, so it keeps temp files in $TMPDIR, its own temp directory. The command reads no input.',
|
|
493
545
|
promptSnippet: 'Run a long-lived or watched command in tmux and get woken when it exits',
|
|
494
546
|
promptGuidelines: ['Use tmux_run for any command that would otherwise run in the background. Never background a command with &, nohup, setsid, or disown.'],
|
|
495
547
|
parameters: Type.Object({
|
|
@@ -539,12 +591,12 @@ export default function pstack(pi: ExtensionAPI) {
|
|
|
539
591
|
name: 'tmux_jobs',
|
|
540
592
|
label: 'tmux jobs',
|
|
541
593
|
description:
|
|
542
|
-
"Inspect or control this session's pi_spawn and tmux_run jobs. list shows every job with its state and a command to
|
|
594
|
+
"Inspect or control this session's pi_spawn and tmux_run jobs. list shows every job with its state, a command to follow its output, and for a running job a command to attach to its tmux session, where the output shows live and Ctrl-C stops it. output shows an exited worker's completed answers and transcript, or the last lines of a command or running worker. wait blocks until the named jobs (default every running job with a wake) exit, the timeout passes, or the user sends a message, then returns their reports. A job with a wake reports on its own, so end your turn instead of waiting unless the wait is short. stop ends jobs, and every later run of a repeating one, and suppresses their wake.",
|
|
543
595
|
parameters: Type.Object({
|
|
544
596
|
action: stringEnum(['list', 'output', 'wait', 'stop'] as const),
|
|
545
597
|
ids: Type.Optional(Type.Array(Type.String(), { description: 'Job ids. Required for output and stop.' })),
|
|
546
|
-
lines: Type.Optional(Type.Number({ description: 'Lines for output. Default 80.' })),
|
|
547
|
-
timeout_seconds: Type.Optional(Type.Number({ description: 'Longest wait. Default
|
|
598
|
+
lines: Type.Optional(Type.Number({ description: 'Lines for raw output. Exited Pi workers show their completed answers instead. Default 80.' })),
|
|
599
|
+
timeout_seconds: Type.Optional(Type.Number({ description: 'Longest wait. Default 300.' })),
|
|
548
600
|
}),
|
|
549
601
|
async execute(_id, params, signal, update, ctx) {
|
|
550
602
|
const root = jobsRoot();
|
|
@@ -565,7 +617,7 @@ export default function pstack(pi: ExtensionAPI) {
|
|
|
565
617
|
case 'output':
|
|
566
618
|
return text(
|
|
567
619
|
named()
|
|
568
|
-
.map((job) => `${describe(job)}\n${tail(outputPath(job.spec.out), params.lines ?? 80)}`)
|
|
620
|
+
.map((job) => (job.spec.kind === 'pi' && job.status.state !== 'running' ? report(job) : `${describe(job)}\n${tail(outputPath(job.spec.out), params.lines ?? 80)}`))
|
|
569
621
|
.join('\n\n'),
|
|
570
622
|
);
|
|
571
623
|
case 'stop': {
|
|
@@ -581,14 +633,15 @@ export default function pstack(pi: ExtensionAPI) {
|
|
|
581
633
|
const ids = params.ids?.length
|
|
582
634
|
? params.ids
|
|
583
635
|
: list(root, owner)
|
|
584
|
-
// A heartbeat never stops on its own, so waiting on everything leaves
|
|
585
|
-
.filter((job) => job.status.state === 'running' && !job.spec.repeat)
|
|
636
|
+
// A heartbeat or a server never stops on its own, so waiting on everything leaves them out.
|
|
637
|
+
.filter((job) => job.status.state === 'running' && !job.spec.repeat && job.spec.wake !== null)
|
|
586
638
|
.map((job) => job.spec.id);
|
|
587
|
-
const deadline = Date.now() + (params.timeout_seconds ??
|
|
639
|
+
const deadline = Date.now() + (params.timeout_seconds ?? 300) * 1000;
|
|
588
640
|
const current = () => ids.map((id) => read(root, id, owner)).filter((job): job is Job => job !== undefined);
|
|
589
641
|
for (const id of ids) awaited.add(id);
|
|
590
642
|
try {
|
|
591
|
-
while
|
|
643
|
+
// A message the user sends while this blocks ends the wait, so they are never shut out until the timeout.
|
|
644
|
+
while (current().some((job) => job.status.state === 'running') && Date.now() < deadline && !signal?.aborted && !ctx.hasPendingMessages()) {
|
|
592
645
|
update?.(text(`Waiting on ${current().filter((job) => job.status.state === 'running').length} job(s)...`));
|
|
593
646
|
await new Promise((done) => setTimeout(done, POLL_MS));
|
|
594
647
|
}
|
package/src/jobs.ts
CHANGED
|
@@ -44,6 +44,8 @@ export interface JobSpec {
|
|
|
44
44
|
socket: string;
|
|
45
45
|
/** Protected paths and checkout roots the wrapper sweeps after the job, for code that appeared while it ran. */
|
|
46
46
|
sweep: { roots: string[]; protect: string[] };
|
|
47
|
+
/** The $TMPDIR of the worker that started this job, shared so paths it hands the job exist. Unset for a top-level job. */
|
|
48
|
+
tmp?: string;
|
|
47
49
|
createdAt: string;
|
|
48
50
|
}
|
|
49
51
|
|
|
@@ -126,17 +128,43 @@ const CACHES: Record<string, string> = {
|
|
|
126
128
|
npm_config_store_dir: 'pnpm',
|
|
127
129
|
};
|
|
128
130
|
|
|
131
|
+
// zsh writes here-documents under TMPPREFIX, which defaults to the shared /tmp.
|
|
132
|
+
const tempEnv = (tmp: string): Record<string, string> => ({ TMPDIR: tmp, TMP: tmp, TEMP: tmp, MAC_CHROMIUM_TMPDIR: tmp, TMPPREFIX: join(tmp, 'zsh') });
|
|
133
|
+
|
|
134
|
+
/** macOS mktemp prefers the per-user temp directory to $TMPDIR, and a job may not write there, so jobs find this one first on PATH. */
|
|
135
|
+
const MKTEMP = `#!/bin/sh
|
|
136
|
+
flags=
|
|
137
|
+
prefix=
|
|
138
|
+
while getopts :dqut:p: opt; do
|
|
139
|
+
case $opt in
|
|
140
|
+
d|q|u) flags="$flags -$opt" ;;
|
|
141
|
+
t) prefix=$OPTARG ;;
|
|
142
|
+
*) exec /usr/bin/mktemp "$@" ;;
|
|
143
|
+
esac
|
|
144
|
+
done
|
|
145
|
+
shift $((OPTIND - 1))
|
|
146
|
+
[ $# -gt 0 ] && [ -z "$prefix" ] && exec /usr/bin/mktemp $flags "$@"
|
|
147
|
+
exec /usr/bin/mktemp $flags "\${TMPDIR%/}/\${prefix:-tmp}.XXXXXXXXXX"
|
|
148
|
+
`;
|
|
149
|
+
|
|
129
150
|
/**
|
|
130
151
|
* A private temp directory and caches for the job. Shared temp directories and user caches hold code that unsandboxed
|
|
131
152
|
* programs later load, such as Pi's compiled-extension cache, so a job may write none of them.
|
|
132
153
|
*/
|
|
133
154
|
export const privateEnv = (tmp: string): Record<string, string> => ({
|
|
134
|
-
|
|
135
|
-
TMP: tmp,
|
|
136
|
-
TEMP: tmp,
|
|
155
|
+
...tempEnv(tmp),
|
|
137
156
|
...Object.fromEntries(Object.entries(CACHES).map(([name, dir]) => [name, join(tmp, dir)])),
|
|
138
157
|
});
|
|
139
158
|
|
|
159
|
+
/**
|
|
160
|
+
* Firefox and pnpm run their own sandbox or store-locking steps, which fail inside the job's sandbox. Firefox aborts when it
|
|
161
|
+
* cannot sandbox its child processes, and pnpm cannot lock the shared store it switches engines from.
|
|
162
|
+
*/
|
|
163
|
+
const SANDBOX_COMPAT: Record<string, string> = {
|
|
164
|
+
...Object.fromEntries(['CONTENT', 'GMP', 'RDD', 'SOCKET_PROCESS', 'GPU', 'UTILITY'].map((name) => [`MOZ_DISABLE_${name}_SANDBOX`, '1'])),
|
|
165
|
+
npm_config_manage_package_manager_versions: 'false',
|
|
166
|
+
};
|
|
167
|
+
|
|
140
168
|
interface Run {
|
|
141
169
|
kind: JobKind;
|
|
142
170
|
cwd: string;
|
|
@@ -149,6 +177,7 @@ interface Run {
|
|
|
149
177
|
/** Where output and the exit code go. */
|
|
150
178
|
out: string;
|
|
151
179
|
top: string;
|
|
180
|
+
tmp: string | undefined;
|
|
152
181
|
}
|
|
153
182
|
|
|
154
183
|
/**
|
|
@@ -160,10 +189,25 @@ interface Run {
|
|
|
160
189
|
*/
|
|
161
190
|
function run(job: Run): void {
|
|
162
191
|
// Pi's own variable points every job at its top-level job's agent directory, so no job's Pi writes your real credentials.
|
|
163
|
-
const env = Object.entries({
|
|
192
|
+
const env = Object.entries({
|
|
193
|
+
[SANDBOX_ENV]: '1',
|
|
194
|
+
[JOB_DIR_ENV]: job.dir,
|
|
195
|
+
[TOP_DIR_ENV]: job.top,
|
|
196
|
+
PI_CODING_AGENT_DIR: jobAgentDir(job.top),
|
|
197
|
+
...SANDBOX_COMPAT,
|
|
198
|
+
...privateEnv(join(job.dir, 'tmp')),
|
|
199
|
+
...(job.tmp ? tempEnv(job.tmp) : {}),
|
|
200
|
+
})
|
|
164
201
|
.map(([name, value]) => `${name}=${shellQuote(value)}`)
|
|
165
202
|
.join(' ');
|
|
166
|
-
|
|
203
|
+
// The job cannot write its results directory, so it cannot replace what it finds there on PATH.
|
|
204
|
+
const bin = join(job.out, 'bin');
|
|
205
|
+
if (process.platform === 'darwin') {
|
|
206
|
+
mkdirSync(bin, { recursive: true });
|
|
207
|
+
writeFileSync(join(bin, 'mktemp'), MKTEMP, { mode: 0o755 });
|
|
208
|
+
}
|
|
209
|
+
const path = process.platform === 'darwin' ? `PATH=${shellQuote(bin)}:"$PATH" ` : '';
|
|
210
|
+
const command = `${path}${env} ${job.argv.map(shellQuote).join(' ')} < /dev/null`;
|
|
167
211
|
const out = shellQuote(outputPath(job.out));
|
|
168
212
|
const exit = shellQuote(exitPath(job.out));
|
|
169
213
|
// Output goes straight to its file, not through a pipe, so a child the job leaves running cannot hold the job open.
|
|
@@ -182,6 +226,7 @@ function run(job: Run): void {
|
|
|
182
226
|
' [ "$finished" = 1 ] && return',
|
|
183
227
|
' finished=1',
|
|
184
228
|
' kill -KILL -- -$pid 2>/dev/null; wait $pid 2>/dev/null',
|
|
229
|
+
' kill $mirror 2>/dev/null',
|
|
185
230
|
// Off the terminal: once tmux is gone, Node reopening the terminal to report an error blocks forever and holds a pty.
|
|
186
231
|
` ${shellQuote(process.execPath)} ${shellQuote(sweepCopy)} ${shellQuote(inventoryFile(job.out))} < /dev/null >> ${out} 2>&1`,
|
|
187
232
|
// Go leaves its module cache read-only. find never follows a link the job planted, so only the job's own directories change.
|
|
@@ -191,6 +236,9 @@ function run(job: Run): void {
|
|
|
191
236
|
`trap 'kill -TERM -- -$pid 2>/dev/null; for i in $(seq 30); do kill -0 -- -$pid 2>/dev/null || break; sleep 0.1; done; finish ${STOPPED_EXIT_CODE}; exit ${STOPPED_EXIT_CODE}' HUP TERM INT`,
|
|
192
237
|
`${body} &`,
|
|
193
238
|
'pid=$!',
|
|
239
|
+
// The session's pane shows the output as it is written, so attaching to it is a live view of the job.
|
|
240
|
+
`tail -n +1 -f ${job.kind === 'pi' ? `${out} ${shellQuote(join(job.out, 'stderr.log'))}` : out} 2>/dev/null &`,
|
|
241
|
+
'mirror=$!',
|
|
194
242
|
'wait $pid',
|
|
195
243
|
'finish "$?"',
|
|
196
244
|
].join('\n');
|
|
@@ -212,7 +260,7 @@ export function launch(root: string, spec: JobSpec, files: Record<string, string
|
|
|
212
260
|
const dir = jobDir(root, spec.id);
|
|
213
261
|
const full = { ...spec, out: dir };
|
|
214
262
|
write(dir, full, files);
|
|
215
|
-
run({ kind: spec.kind, cwd: spec.cwd, argv: spec.argv, inventory: takeInventory(spec, dir), socket: spec.socket, session: spec.id, dir, out: dir, top: inheritedTop(dir) });
|
|
263
|
+
run({ kind: spec.kind, cwd: spec.cwd, argv: spec.argv, inventory: takeInventory(spec, dir), socket: spec.socket, session: spec.id, dir, out: dir, top: inheritedTop(dir), tmp: spec.tmp });
|
|
216
264
|
return { spec: full, dir, status: { state: 'running' } };
|
|
217
265
|
}
|
|
218
266
|
|
|
@@ -239,7 +287,7 @@ export function launchBrokered(top: string, dir: string, spec: JobSpec, sweepWha
|
|
|
239
287
|
const out = resultsDir(top, dir);
|
|
240
288
|
mkdirSync(out, { recursive: true });
|
|
241
289
|
try {
|
|
242
|
-
run({ kind: spec.kind, cwd: spec.cwd, argv, inventory: takeInventory({ ...spec, sweep: sweepWhat }, out), socket, session: brokeredSession(dir), dir, out, top });
|
|
290
|
+
run({ kind: spec.kind, cwd: spec.cwd, argv, inventory: takeInventory({ ...spec, sweep: sweepWhat }, out), socket, session: brokeredSession(dir), dir, out, top, tmp: spec.tmp });
|
|
243
291
|
writeFileSync(join(out, 'launched'), '');
|
|
244
292
|
} catch (error) {
|
|
245
293
|
settleBrokered(out, 127, `pstack could not launch this job: ${error instanceof Error ? error.message : String(error)}`);
|
|
@@ -289,6 +337,8 @@ export function list(root: string, owner: string): Job[] {
|
|
|
289
337
|
* with it. A brokered job is ended by the root, which sees the stop marker on its next tick.
|
|
290
338
|
*/
|
|
291
339
|
export async function stop(job: Job): Promise<void> {
|
|
340
|
+
// Claimed first, since the session is gone before the wrapper records the exit, and the watcher would report the job lost.
|
|
341
|
+
claimWake(job);
|
|
292
342
|
if (job.spec.brokered) {
|
|
293
343
|
writeFileSync(join(job.dir, 'stop'), '');
|
|
294
344
|
} else {
|
|
@@ -317,7 +367,6 @@ export async function stop(job: Job): Promise<void> {
|
|
|
317
367
|
renameSync(`${exit}.tmp`, exit);
|
|
318
368
|
}
|
|
319
369
|
}
|
|
320
|
-
claimWake(job);
|
|
321
370
|
}
|
|
322
371
|
|
|
323
372
|
/** Returns true exactly once per job, so a wake survives restarts without being delivered twice. */
|
|
@@ -359,12 +408,20 @@ export function excerpt(path: string, head: number, tailBytes: number): string {
|
|
|
359
408
|
if (!existsSync(path)) return '';
|
|
360
409
|
const size = statSync(path).size;
|
|
361
410
|
if (size <= head + tailBytes) return readEnd(path, size);
|
|
362
|
-
|
|
411
|
+
return clipRanges(readRange(path, 0, head), readRange(path, size - tailBytes, tailBytes), size, path);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
export function clip(text: string, head: number, tailBytes: number, source: string): string {
|
|
415
|
+
const buffer = Buffer.from(text);
|
|
416
|
+
if (buffer.length <= head + tailBytes) return text;
|
|
417
|
+
return clipRanges(buffer.subarray(0, head), buffer.subarray(buffer.length - tailBytes), buffer.length, source);
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function clipRanges(first: Buffer, last: Buffer, size: number, path: string): string {
|
|
363
421
|
let lead = first.length - 1;
|
|
364
422
|
while (lead > 0 && isContinuation(first[lead])) lead--;
|
|
365
423
|
const byte = first[lead] ?? 0;
|
|
366
424
|
const end = lead + (byte >= 0xf0 ? 4 : byte >= 0xe0 ? 3 : byte >= 0xc0 ? 2 : 1) > first.length ? lead : first.length;
|
|
367
|
-
const last = readRange(path, size - tailBytes, tailBytes);
|
|
368
425
|
let from = 0;
|
|
369
426
|
while (isContinuation(last[from])) from++;
|
|
370
427
|
const omitted = size - end - (last.length - from);
|
package/src/sandbox.ts
CHANGED
|
@@ -88,11 +88,14 @@ export function seatbeltProfile(policy: SandboxPolicy): string {
|
|
|
88
88
|
// Nor may it serve one, such as a tmux server of its own. Linux refuses the same through seccomp.
|
|
89
89
|
'(deny network-bind (local unix-socket))',
|
|
90
90
|
// Services that start processes on a caller's behalf would run them outside the sandbox: LaunchServices (`open`) and Apple Events.
|
|
91
|
+
// `open -a` on an app the job wrote launches it through launchd, so the lookup rules below cannot stop it, and lsopen does.
|
|
91
92
|
'(deny appleevent-send)',
|
|
93
|
+
'(deny lsopen)',
|
|
92
94
|
// A job may signal only processes in its own sandbox, never the wrapper that cleans up after it or the root Pi.
|
|
93
95
|
'(deny signal)',
|
|
94
96
|
'(allow signal (target same-sandbox))',
|
|
95
|
-
|
|
97
|
+
// launchservicesd stays reachable because Firefox checks in with it at startup and aborts without it. Opening goes through lsopen.
|
|
98
|
+
'(deny mach-lookup (global-name-regex #"^com\\.apple\\.lsd\\.") (global-name "com.apple.coreservices.appleevents"))',
|
|
96
99
|
// launchd would run a job it is handed outside the sandbox, and preference writes go through a daemon outside it.
|
|
97
100
|
'(deny mach-lookup (global-name-regex #"^com\\.apple\\.xpc\\.launchd\\."))',
|
|
98
101
|
'(deny user-preference-write)',
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { lstatSync, readdirSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
|
|
4
|
+
import { parseSessionEntries, type SessionEntry } from '@earendil-works/pi-coding-agent';
|
|
5
|
+
|
|
6
|
+
export function workerReport(sessionDir: string | undefined, since: string): { path: string; answers: string[] } | undefined {
|
|
7
|
+
if (!sessionDir) return undefined;
|
|
8
|
+
try {
|
|
9
|
+
if (!lstatSync(sessionDir).isDirectory()) return undefined;
|
|
10
|
+
const files = readdirSync(sessionDir)
|
|
11
|
+
.filter((name) => name.endsWith('.jsonl'))
|
|
12
|
+
.map((name) => ({ path: join(sessionDir, name), stat: lstatSync(join(sessionDir, name)) }))
|
|
13
|
+
.filter(({ stat }) => stat.isFile())
|
|
14
|
+
.sort((a, b) => b.stat.mtimeMs - a.stat.mtimeMs);
|
|
15
|
+
for (const { path } of files) {
|
|
16
|
+
const entries = parseSessionEntries(readFileSync(path, 'utf8'));
|
|
17
|
+
if (entries[0]?.type !== 'session') continue;
|
|
18
|
+
const turns = entries.filter((entry): entry is SessionEntry => entry.type !== 'session');
|
|
19
|
+
const byId = new Map(turns.map((entry) => [entry.id, entry]));
|
|
20
|
+
const branch: SessionEntry[] = [];
|
|
21
|
+
const seen = new Set<string>();
|
|
22
|
+
for (let entry = turns.at(-1); entry && !seen.has(entry.id); entry = entry.parentId ? byId.get(entry.parentId) : undefined) {
|
|
23
|
+
seen.add(entry.id);
|
|
24
|
+
branch.push(entry);
|
|
25
|
+
}
|
|
26
|
+
branch.reverse();
|
|
27
|
+
const prompt = branch.findLastIndex((entry) => entry.type === 'message' && entry.message.role === 'user');
|
|
28
|
+
const answers: string[] = [];
|
|
29
|
+
if (prompt >= 0 && Date.parse(branch[prompt]?.timestamp ?? '') >= Date.parse(since)) {
|
|
30
|
+
const turns = branch.slice(prompt + 1).filter((entry) => entry.type === 'message' && entry.message.role === 'assistant');
|
|
31
|
+
for (const entry of turns) {
|
|
32
|
+
if (entry.type !== 'message' || entry.message.role !== 'assistant') continue;
|
|
33
|
+
const message = entry.message;
|
|
34
|
+
const text = message.content
|
|
35
|
+
.filter((block) => block.type === 'text')
|
|
36
|
+
.map((block) => block.text)
|
|
37
|
+
.join('\n');
|
|
38
|
+
switch (message.stopReason) {
|
|
39
|
+
case 'stop':
|
|
40
|
+
if (text.trim()) answers.push(text);
|
|
41
|
+
break;
|
|
42
|
+
case 'error':
|
|
43
|
+
case 'aborted':
|
|
44
|
+
// A failed turn the worker went on from was retried, so only the one it ended on is its answer.
|
|
45
|
+
if (entry !== turns.at(-1)) break;
|
|
46
|
+
answers.push([`[Worker answer ended with ${message.stopReason}]`, text, message.errorMessage].filter(Boolean).join('\n'));
|
|
47
|
+
break;
|
|
48
|
+
case 'length':
|
|
49
|
+
answers.push([`[Worker answer ended with ${message.stopReason}]`, text, message.errorMessage].filter(Boolean).join('\n'));
|
|
50
|
+
break;
|
|
51
|
+
case 'toolUse':
|
|
52
|
+
case 'pending':
|
|
53
|
+
case 'deferred':
|
|
54
|
+
break;
|
|
55
|
+
default: {
|
|
56
|
+
const unhandled: never = message.stopReason;
|
|
57
|
+
throw new Error(`Unhandled worker stop reason: ${unhandled}`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return { path, answers };
|
|
63
|
+
}
|
|
64
|
+
} catch {}
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|