open-pstack 0.9.159 → 0.9.161

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/lib/bundle.mjs +12 -3
  2. package/lib/cli.mjs +2 -2
  3. package/package.json +1 -1
  4. package/plugin/.antigravity-plugin/plugin.json +1 -1
  5. package/plugin/.claude-plugin/plugin.json +1 -1
  6. package/plugin/.codex-plugin/plugin.json +1 -1
  7. package/plugin/.github/plugin/plugin.json +1 -1
  8. package/plugin/.grok-plugin/plugin.json +1 -1
  9. package/plugin/.muse-plugin/plugin.json +1 -1
  10. package/plugin/omp/index.mjs +2 -3
  11. package/plugin/package.json +1 -1
  12. package/plugin/pi/agent-text.ts +4 -3
  13. package/plugin/pi/agent-tools.ts +2 -2
  14. package/plugin/pi/agents.ts +75 -40
  15. package/plugin/pi/child.ts +1 -0
  16. package/plugin/pi/config.ts +6 -3
  17. package/plugin/pi/hc-child.ts +11 -7
  18. package/plugin/pi/orca-child.ts +242 -0
  19. package/plugin/pi/prompt.ts +8 -2
  20. package/plugin/pi/t3-child.ts +94 -26
  21. package/plugin/skills/babysit/SKILL.md +4 -2
  22. package/plugin/skills/poteto-mode/playbooks/babysit.md +1 -1
  23. package/plugin/skills/poteto-mode/references/cloud-session-pr-reads.md +5 -4
  24. package/plugin/skills/poteto-mode/references/codex-tools.md +3 -2
  25. package/plugin/skills/poteto-mode/references/omp-tools.md +7 -3
  26. package/plugin/skills/poteto-mode/references/pi-tools.md +5 -4
  27. package/plugin/skills/poteto-mode/scripts/watch-pr/cli.port.test.ts +41 -0
  28. package/plugin/skills/poteto-mode/scripts/watch-pr/cli.ts +18 -0
  29. package/plugin/skills/poteto-mode/scripts/watch-pr/policy.port.test.ts +132 -0
  30. package/plugin/skills/poteto-mode/scripts/watch-pr/policy.ts +17 -0
  31. package/plugin/skills/poteto-mode/scripts/watch-pr/types.ts +2 -0
package/lib/bundle.mjs CHANGED
@@ -1,9 +1,18 @@
1
- import { cpSync, existsSync, mkdirSync, renameSync, rmSync } from "node:fs";
1
+ import { cpSync, existsSync, lstatSync, mkdirSync, renameSync, rmSync } from "node:fs";
2
2
  import { dirname, join, relative, sep } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
 
5
5
  const installerRoot = join(dirname(fileURLToPath(import.meta.url)), "..");
6
6
 
7
+ const entryExists = (path) => {
8
+ try {
9
+ lstatSync(path);
10
+ return true;
11
+ } catch {
12
+ return false;
13
+ }
14
+ };
15
+
7
16
  // The tarball carries installer/plugin; a repo checkout or the tag tarball
8
17
  // carries plugins/pstack beside installer/.
9
18
  export function bundledPluginSource() {
@@ -30,10 +39,10 @@ export function stagePlugin(source, dest) {
30
39
  rmSync(fresh, { recursive: true, force: true });
31
40
  try {
32
41
  cpSync(source, fresh, { recursive: true, filter: withoutNodeModules(source) });
33
- if (existsSync(dest)) renameSync(dest, old);
42
+ if (entryExists(dest)) renameSync(dest, old);
34
43
  renameSync(fresh, dest);
35
44
  } catch (error) {
36
- if (!existsSync(dest) && existsSync(old)) renameSync(old, dest);
45
+ if (!entryExists(dest) && entryExists(old)) renameSync(old, dest);
37
46
  throw error;
38
47
  } finally {
39
48
  rmSync(fresh, { recursive: true, force: true });
package/lib/cli.mjs CHANGED
@@ -44,8 +44,8 @@ function parseArgs(argv) {
44
44
  const arg = argv[i];
45
45
  if (arg === "--only") {
46
46
  const value = argv[++i];
47
- if (!value) throw new UsageError("--only needs a comma list of ids");
48
- opts.only = idList(value);
47
+ opts.only = value ? idList(value) : [];
48
+ if (opts.only.length === 0) throw new UsageError("--only needs a comma list of ids");
49
49
  } else if (arg.startsWith("--only=")) {
50
50
  opts.only = idList(arg.slice(7));
51
51
  if (opts.only.length === 0) throw new UsageError("--only needs a comma list of ids");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "open-pstack",
3
- "version": "0.9.159",
3
+ "version": "0.9.161",
4
4
  "description": "Install pstack into the agent harnesses on this machine: Claude Code, Codex, Pi, Copilot, Muse, OMP, Kimi, Grok, MiniMax, OpenCode, Antigravity, and the shared skills directory.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pstack",
3
- "version": "0.9.159",
3
+ "version": "0.9.161",
4
4
  "description": "If you want to go fast, go deep first. pstack helps you write less, but higher quality code. rigorous agent workflows you can parallelize with confidence. Ported from cursor/plugins/pstack to Antigravity. Original pstack by Lauren Tan (poteto).",
5
5
  "author": "Michael Denyer",
6
6
  "logo": "assets/pstack-icon.png",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pstack",
3
3
  "displayName": "pstack (Claude Code port)",
4
- "version": "0.9.159",
4
+ "version": "0.9.161",
5
5
  "description": "If you want to go fast, go deep first. pstack helps you write less, but higher quality code. rigorous agent workflows you can parallelize with confidence. Ported from cursor/plugins/pstack to Claude Code. Original pstack by Lauren Tan (poteto).",
6
6
  "author": {
7
7
  "name": "Michael Denyer",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pstack",
3
- "version": "0.9.159",
3
+ "version": "0.9.161",
4
4
  "description": "If you want to go fast, go deep first. pstack helps you write less, but higher quality code. rigorous agent workflows you can parallelize with confidence. Codex port of the Claude Code plugin; skills are shared, tool names resolve via skills/poteto-mode/references/codex-tools.md. Original pstack by Lauren Tan (poteto).",
5
5
  "author": {
6
6
  "name": "Michael Denyer",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pstack",
3
3
  "displayName": "pstack (GitHub Copilot port)",
4
- "version": "0.9.159",
4
+ "version": "0.9.161",
5
5
  "description": "If you want to go fast, go deep first. pstack helps you write less, but higher quality code. rigorous agent workflows you can parallelize with confidence. Ported from cursor/plugins/pstack to GitHub Copilot CLI and app. Original pstack by Lauren Tan (poteto).",
6
6
  "author": {
7
7
  "name": "Michael Denyer",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pstack",
3
- "version": "0.9.159",
3
+ "version": "0.9.161",
4
4
  "description": "pstack workflows and skills for Grok Build",
5
5
  "skills": [
6
6
  "./skills",
@@ -2,7 +2,7 @@
2
2
  "schemaVersion": 1,
3
3
  "name": "pstack",
4
4
  "displayName": "pstack (Muse port)",
5
- "version": "0.9.159",
5
+ "version": "0.9.161",
6
6
  "description": "If you want to go fast, go deep first. pstack helps you write less, but higher quality code. Rigorous agent workflows you can parallelize with confidence. Muse port of the Claude Code plugin; skills are shared, tool names resolve via skills/poteto-mode/references/muse-tools.md. Original pstack by Lauren Tan (poteto).",
7
7
  "compat": {
8
8
  "source": "native",
@@ -4,13 +4,12 @@ import { homedir } from "node:os";
4
4
  import { fileURLToPath } from "node:url";
5
5
 
6
6
  const root = join(dirname(fileURLToPath(import.meta.url)), "..");
7
- const skills = join(root, "skills");
8
- const mapping = join(root, "skills", "poteto-mode", "references", "omp-tools.md");
9
7
  const mandate = readFileSync(join(root, "hooks", "session-start-context.md"), "utf8");
10
8
  const marker = "[pstack OMP instructions]";
9
+ const adapter = `${marker}
10
+ A pstack skill's URL is skill://pstack/<name> when OMP's skill list names pstack/<name>, and skill://<name> otherwise; read a file inside it as that URL followed by /<path>. Before following a pstack skill, read skill://poteto-mode/references/omp-tools.md, or skill://pstack/poteto-mode/references/omp-tools.md when the list names pstack/poteto-mode, for OMP tool and model mappings. Resolve every pstack:<name> skill in the following instructions by reading its URL. For example, read skill://poteto-mode for pstack:poteto-mode, or skill://pstack/poteto-mode when the list names pstack/poteto-mode. Do not read pstack skills by their absolute install path, which can sit in a folder the user restricted.`;
11
11
 
12
12
  function instructions(routed) {
13
- const adapter = `${marker}\nBefore following a pstack skill, read ${JSON.stringify(mapping)} for OMP tool and model mappings. Resolve every pstack:<name> skill in the following instructions by reading the installed plugin file at ${JSON.stringify(join(skills, "<name>", "SKILL.md"))}, substituting the named skill. For example, read ${JSON.stringify(join(skills, "poteto-mode", "SKILL.md"))} for pstack:poteto-mode. Do not resolve these names through a bare skill name, which can select a different installation.`;
14
13
  return routed ? `${adapter}\n${mandate}` : adapter;
15
14
  }
16
15
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pstack",
3
- "version": "0.9.159",
3
+ "version": "0.9.161",
4
4
  "private": true,
5
5
  "omp": {
6
6
  "extensions": ["./omp/index.mjs"]
@@ -7,7 +7,8 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
7
7
  import type { AgentRecord, EndedRecord } from "./agents.ts";
8
8
  import type { Activity } from "./child.ts";
9
9
 
10
- const NOTICE_TYPE = "pstack-agent";
10
+ export const NOTICE_TYPE = "pstack-agent";
11
+ export const AGENTS_ENTRY = "pstack-agents";
11
12
  export const OUTPUT_CAP_BYTES = 50 * 1024;
12
13
 
13
14
  export function truncateUtf8(text: string, cap: number): string {
@@ -89,11 +90,11 @@ export function agentsReport(records: AgentRecord[], { transcriptOf, activityOf
89
90
  .join("\n\n");
90
91
  }
91
92
 
92
- export function noticeOf(record: EndedRecord, transcript: string | undefined): Parameters<ExtensionAPI["sendMessage"]>[0] {
93
+ export function noticeOf(record: EndedRecord, transcript: string | undefined, triggerTurn: boolean): Parameters<ExtensionAPI["sendMessage"]>[0] {
93
94
  return {
94
95
  customType: NOTICE_TYPE,
95
96
  content: `pstack agent finished.\n${header(record, transcript)}${record.outputFile ? `\nfull output: ${record.outputFile}` : ""}\n\n${report(record)}`,
96
97
  display: true,
97
- details: { agentId: record.agent.id, status: record.status, exitCode: record.exitCode, outputFile: record.outputFile },
98
+ details: { agentId: record.agent.id, status: record.status, exitCode: record.exitCode, outputFile: record.outputFile, triggerTurn },
98
99
  };
99
100
  }
@@ -106,12 +106,12 @@ export function registerAgentTools(pi: ExtensionAPI, runner: AgentRunner, settin
106
106
  label: "Send message",
107
107
  exposure: "model-only",
108
108
  description:
109
- "Send a message to an agent this session started, by agentId or description. A running agent reads it after its current tool calls and carries on in the same run, so one completion notice follows. A finished agent resumes in the background with its earlier context and sends a completion notice.",
109
+ "Send a message to an agent this session started, by agentId or description. A running agent reads it after its current tool calls, or once its current turn ends when its host queues it, and carries on in the same run, so one completion notice follows. A finished agent resumes in the background with its earlier context and sends a completion notice.",
110
110
  parameters: sendParams,
111
111
  async execute(_id, params) {
112
112
  const { record, running } = await runner.send(params.to, params.message);
113
113
  const text = running
114
- ? `Agent ${record.agent.id} is running; it reads the message after its current tool calls.`
114
+ ? `Agent ${record.agent.id} is running; it reads the message after its current tool calls, or, when its host queues the message, once its current turn ends.`
115
115
  : JSON.stringify({ agentId: record.agent.id, status: "running" });
116
116
  return { content: [{ type: "text", text }], details: { agentId: record.agent.id, running } };
117
117
  },
@@ -6,16 +6,16 @@ import type { ExtensionAPI, ExtensionContext, SessionEntry } from "@earendil-wor
6
6
  import { type Static, Type } from "typebox";
7
7
  import { Value } from "typebox/value";
8
8
 
9
- import { noticeOf, OUTPUT_CAP_BYTES, statusText, truncateUtf8 } from "./agent-text.ts";
9
+ import { AGENTS_ENTRY, noticeOf, OUTPUT_CAP_BYTES, statusText, truncateUtf8 } from "./agent-text.ts";
10
10
  import type { AgentParams } from "./agent-tools.ts";
11
11
  import { type Activity, type AgentChild, alive, type ChildExit, type Fate, PiChild, terminateGroup } from "./child.ts";
12
12
  import { HcChild, pidOfTerminal } from "./hc-child.ts";
13
+ import { OrcaChild, opensTabs, orcaSession } from "./orca-child.ts";
13
14
  import { t3Brief, T3_ENV_REMOVED, T3Child, t3Host, t3Session, type T3Task } from "./t3-child.ts";
14
15
  import { loadAgentTypes } from "./agent-files.ts";
15
- import { checkEffort, DEPTH_FLAG, GENERAL_PURPOSE, InvalidValueError, PSTACK_STATE_DIR, readSheet, resolveModel, type Settings } from "./config.ts";
16
+ import { checkEffort, DEPTH_FLAG, GENERAL_PURPOSE, InvalidValueError, projectRoot, PSTACK_STATE_DIR, readSheet, resolveModel, type Settings } from "./config.ts";
16
17
  import { ensureWorktree, planWorktree, settleWorktree, type Worktree, worktreeSchema } from "./worktree.ts";
17
18
 
18
- const ENTRY_TYPE = "pstack-agents";
19
19
  const STATUS_KEY = "pstack-agents";
20
20
  // Claude Code lets agents nest three layers below the main session and withholds
21
21
  // the Agent tool at the third.
@@ -27,7 +27,7 @@ const PARENT_SESSION_ENV = "PI_SUBAGENT_PARENT_SESSION";
27
27
  const endedStatus = Type.Union([Type.Literal("completed"), Type.Literal("failed"), Type.Literal("stopped")]);
28
28
  type EndedStatus = Static<typeof endedStatus>;
29
29
  // Absent on a record an earlier version wrote; such an agent runs as an RPC child.
30
- const hostSchema = Type.Union([Type.Literal("rpc"), Type.Literal("hc"), Type.Literal("t3")]);
30
+ const hostSchema = Type.Union([Type.Literal("rpc"), Type.Literal("hc"), Type.Literal("t3"), Type.Literal("orca")]);
31
31
  type Host = Static<typeof hostSchema>;
32
32
 
33
33
  // Fixed when the agent starts and reused by every launch of it, so a resume
@@ -60,8 +60,10 @@ const runningSchema = Type.Object({
60
60
  pidStart: Type.Optional(Type.String()),
61
61
  // The pi process that launched it. Only that process may reap it.
62
62
  parentPid: Type.Number(),
63
+ parentStart: Type.Optional(Type.String()),
63
64
  host: Type.Optional(hostSchema),
64
65
  t3TaskId: Type.Optional(Type.String()),
66
+ t3RequestId: Type.Optional(Type.String()),
65
67
  });
66
68
  const endedSchema = Type.Object({
67
69
  agent: identitySchema,
@@ -107,6 +109,7 @@ type AgentState = LocalAgent
107
109
  // there on every first run of a --session-id).
108
110
  function outcomeOf(exit: ChildExit, stopped: boolean): { status: EndedStatus; finalText: string } {
109
111
  if (stopped) return { status: "stopped", finalText: exit.finalText || "(stopped before it replied)" };
112
+ if (exit.interruption) return { status: "stopped", finalText: [exit.finalText, exit.interruption].filter(Boolean).join("\n\n") };
110
113
  if (exit.settled && exit.finalText && !exit.errorMessage) return { status: "completed", finalText: exit.finalText };
111
114
  const diagnostics = exit.errorMessage || exit.stderr.trim();
112
115
  const finalText = exit.finalText && diagnostics ? `${exit.finalText}\n\n${diagnostics}` : exit.finalText || diagnostics || "(no output)";
@@ -181,42 +184,52 @@ function inspect(pid: number): { parentPid: number; start: string } | undefined
181
184
  return m ? { parentPid: Number(m[1]), start: m[2] } : undefined;
182
185
  }
183
186
 
184
- // A process host's run is the process the record names by pid and start time. An
185
- // hc record written before its pid takes both from hc, in identifyByTerminalName.
186
- function processFate(record: RunningRecord): Fate {
187
- const { pid, pidStart, parentPid } = record;
188
- if (pid === undefined || !alive(pid)) return "gone";
189
- const info = inspect(pid);
190
- if (info && pidStart !== undefined && info.start !== pidStart) return "gone";
191
- // With no word from the system, two live pids keep the record: calling a
192
- // live agent stopped would let a message start a second process on its session.
193
- // An hc terminal's program is a child of herdr-core, not of the pi that launched it.
194
- const launcherHasIt = info && record.host !== "hc" ? info.parentPid === parentPid : alive(parentPid);
195
- if (parentPid !== process.pid && launcherHasIt) return "kept";
196
- return info && info.start === pidStart ? "orphan" : "unknown";
197
- }
198
-
199
187
  function identifyByTerminalName(record: RunningRecord): RunningRecord {
200
188
  if (record.host !== "hc" || record.pid !== undefined) return record;
201
189
  const pid = pidOfTerminal(record.agent.id);
202
190
  return pid === undefined ? record : { ...record, pid, pidStart: inspect(pid)?.start };
203
191
  }
204
192
 
205
- // Stops an orphan process, by its group so the bash command it has running goes too.
206
- // No other fate is signalled: a pid that may have been reused is not ours to hit.
207
- async function reapProcess(record: RunningRecord, killGraceMs: number): Promise<Fate> {
208
- if (record.pid !== undefined) await terminateGroup(record.pid, () => processFate(record) === "orphan", killGraceMs);
209
- return processFate(record);
210
- }
211
-
212
193
  interface HostPolicy {
213
194
  fate(record: RunningRecord): Fate;
214
195
  reap(record: RunningRecord, killGraceMs: number): Promise<Fate>;
215
196
  notEnded(record: RunningRecord): string;
216
197
  }
217
198
 
218
- const processHost: HostPolicy = { fate: processFate, reap: reapProcess, notEnded: ({ pid }) => `previous process (pid ${pid}) has not exited` };
219
- const hosts: Record<Host, HostPolicy> = { rpc: processHost, hc: processHost, t3: t3Host };
199
+ // A process host's run is the process the record names by pid and start time. An
200
+ // hc record written before its pid takes both from hc, in identifyByTerminalName.
201
+ function processPolicy(launcherHolds: (processParentPid: number, record: RunningRecord) => boolean): HostPolicy {
202
+ const fate = (record: RunningRecord): Fate => {
203
+ const { pid, pidStart, parentPid } = record;
204
+ if (pid === undefined || !alive(pid)) return "gone";
205
+ const info = inspect(pid);
206
+ if (info && pidStart !== undefined && info.start !== pidStart) return "gone";
207
+ // With no word from the system, two live pids keep the record: calling a
208
+ // live agent stopped would let a message start a second process on its session.
209
+ const launcherHasIt = info ? launcherHolds(info.parentPid, record) : alive(parentPid);
210
+ if (parentPid !== process.pid && launcherHasIt) return "kept";
211
+ return info && info.start === pidStart ? "orphan" : "unknown";
212
+ };
213
+ return {
214
+ fate,
215
+ // Stops an orphan process, by its group so the bash command it has running goes too.
216
+ // No other fate is signalled: a pid that may have been reused is not ours to hit.
217
+ async reap(record, killGraceMs) {
218
+ if (record.pid !== undefined) await terminateGroup(record.pid, () => fate(record) === "orphan", killGraceMs);
219
+ return fate(record);
220
+ },
221
+ notEnded: ({ pid }) => `previous process (pid ${pid}) has not exited`,
222
+ };
223
+ }
224
+
225
+ const processHost = processPolicy((processParentPid, { parentPid }) => processParentPid === parentPid);
226
+ // A terminal's program is a child of its terminal server (herdr-core, Orca), not of the pi that launched it.
227
+ const terminalHost = processPolicy((_, { parentPid, parentStart }) => {
228
+ // A launcher the system will not describe falls back to the alive check, as one with no recorded start does.
229
+ const launcher = parentStart === undefined ? undefined : inspect(parentPid);
230
+ return launcher ? launcher.start === parentStart : alive(parentPid);
231
+ });
232
+ const hosts: Record<Host, HostPolicy> = { rpc: processHost, hc: terminalHost, orca: terminalHost, t3: t3Host };
220
233
  const hostOf = (record: RunningRecord): HostPolicy => hosts[record.host ?? "rpc"];
221
234
 
222
235
  const now = () => new Date().toISOString();
@@ -270,7 +283,11 @@ export class AgentRunner {
270
283
  // cannot remove a thread's tools, so a read-only agent and one at the depth limit stay local, where
271
284
  // --exclude-tools enforces them.
272
285
  const t3 = sheet?.t3Host && t3Session() && !worktree && !params.readonly && this.settings.depth + 1 < MAX_SPAWN_DEPTH;
273
- const host: Host = t3 ? "t3" : sheet?.hcHost && process.env.HC_TERMINAL_ID ? "hc" : "rpc";
286
+ const orca = sheet?.orcaHost ? orcaSession(worktree?.repo ?? projectRoot(ctx.cwd)) : undefined;
287
+ const host: Host = t3 ? "t3"
288
+ : sheet?.hcHost && process.env.HC_TERMINAL_ID ? "hc"
289
+ : orca && opensTabs(orca) ? "orca"
290
+ : "rpc";
274
291
  const identity: AgentIdentity = {
275
292
  id,
276
293
  description: params.description,
@@ -292,6 +309,7 @@ export class AgentRunner {
292
309
 
293
310
  private launch(identity: AgentIdentity, prompt: string, background: boolean): RunningRecord {
294
311
  if (this.closed) throw new Error("This session is shutting down; no agent can start.");
312
+ if ((identity.host === "hc" || identity.host === "orca") && !prompt.trim()) throw new Error("The prompt is empty once trimmed, so the agent would have no task; send the task as text.");
295
313
  try {
296
314
  // First, so a failure here leaves no worktree or branch behind.
297
315
  this.ensureSystemPrompt(identity);
@@ -305,10 +323,10 @@ export class AgentRunner {
305
323
  }
306
324
  throw e;
307
325
  }
308
- const { child, host } = this.spawnChild(identity, prompt);
326
+ const { child, host, t3RequestId } = this.spawnChild(identity, prompt);
309
327
  const pidStart = child.pid === undefined ? undefined : inspect(child.pid)?.start;
310
328
  // An RPC record leaves host unset, as earlier versions wrote it, so an older pstack can still restore it.
311
- const record: RunningRecord = { agent: identity, status: "running", pid: child.pid, pidStart, parentPid: process.pid, host: host === "rpc" ? undefined : host };
329
+ const record: RunningRecord = { agent: identity, status: "running", pid: child.pid, pidStart, parentPid: process.pid, parentStart: inspect(process.pid)?.start, host: host === "rpc" ? undefined : host, t3RequestId };
312
330
  const run: Run = { child, background, done: child.exited.then((exit) => this.finish(identity, run, exit)) };
313
331
  this.agents.set(identity.id, { kind: "local", record, run });
314
332
  this.persist(record);
@@ -316,7 +334,7 @@ export class AgentRunner {
316
334
  return record;
317
335
  }
318
336
 
319
- private spawnChild(identity: AgentIdentity, prompt: string): { child: AgentChild; host: Host } {
337
+ private spawnChild(identity: AgentIdentity, prompt: string): { child: AgentChild; host: Host; t3RequestId?: string } {
320
338
  const { command, args } = this.settings.pi;
321
339
  const base = [...args, "--extension", join(this.settings.pluginRoot, "pi", "index.ts"), "--skill", join(this.settings.pluginRoot, "skills")];
322
340
  const flags = childArgs(identity, this.settings.depth);
@@ -330,13 +348,15 @@ export class AgentRunner {
330
348
  identity.t3ThreadId = threadId;
331
349
  this.track(identity.id, { t3TaskId: taskId });
332
350
  };
333
- const launch = { title: identity.description, model: identity.model, thinking: identity.thinking, threadId: identity.t3ThreadId, onStart };
334
- return { child: new T3Child(t3, launch, identity.t3ThreadId ? prompt : t3Brief(identity, prompt)), host };
351
+ const requestId = identity.t3ThreadId ? undefined : randomUUID();
352
+ const launch = { title: identity.description, model: identity.model, thinking: identity.thinking, threadId: identity.t3ThreadId, requestId, graceMs: this.settings.killGraceMs, onStart };
353
+ return { child: new T3Child(t3, launch, identity.t3ThreadId ? prompt : t3Brief(identity, prompt)), host, t3RequestId: requestId };
335
354
  }
336
- // An hc agent's session is a Pi session file, so outside herdr-core an RPC child resumes it.
355
+ // An interactive pi asks whether to trust the project before it reports any status; the parent already decided.
356
+ const interactiveArgs = [...base, ...flags, this.projectTrusted ? "--approve" : "--no-approve"];
357
+ // A terminal agent's session is a Pi session file, so outside herdr-core or Orca an RPC child resumes it.
337
358
  if (host === "hc" && process.env.HC_TERMINAL_ID) {
338
- // An interactive pi asks whether to trust the project before it reports any status; the parent already decided.
339
- const child = new HcChild(identity.id, command, [...base, ...flags, this.projectTrusted ? "--approve" : "--no-approve"], {
359
+ const child = new HcChild(identity.id, command, interactiveArgs, {
340
360
  cwd: identity.cwd,
341
361
  env: { ...env, PI_CODING_AGENT_DIR: this.settings.agentDir },
342
362
  envFile: join(identity.sessionDir, `${identity.id}.env`),
@@ -346,6 +366,20 @@ export class AgentRunner {
346
366
  }, prompt);
347
367
  return { child, host };
348
368
  }
369
+ const orca = host === "orca" ? orcaSession(identity.worktree?.repo ?? projectRoot(identity.cwd)) : undefined;
370
+ if (orca) {
371
+ const child = new OrcaChild(command, interactiveArgs, {
372
+ session: orca,
373
+ title: `${identity.description} (${identity.id})`,
374
+ cwd: identity.cwd,
375
+ env: { ...env, PI_CODING_AGENT_DIR: this.settings.agentDir },
376
+ files: join(identity.sessionDir, identity.id),
377
+ graceMs: this.settings.killGraceMs,
378
+ transcript: () => sessionFile(identity),
379
+ onStart: (pid) => this.track(identity.id, { pid, pidStart: inspect(pid)?.start }),
380
+ }, prompt);
381
+ return { child, host: "orca" };
382
+ }
349
383
  const child = new PiChild(command, [...base, "--mode", "rpc", ...flags], { cwd: identity.cwd, env, exitGraceMs: this.settings.exitGraceMs, onActivity: () => this.showStatus() }, prompt);
350
384
  return { child, host: "rpc" };
351
385
  }
@@ -404,7 +438,8 @@ export class AgentRunner {
404
438
  // The model that called stop_agent already has the result, so a stop's
405
439
  // notice joins the context without starting another turn.
406
440
  if (run.background && run.ending !== "teardown") {
407
- this.pi.sendMessage(noticeOf(record, sessionFile(identity)), status !== "stopped" ? { triggerTurn: true, deliverAs: "steer" } : { triggerTurn: false });
441
+ const triggerTurn = run.ending === undefined;
442
+ this.pi.sendMessage(noticeOf(record, sessionFile(identity), triggerTurn), triggerTurn ? { triggerTurn, deliverAs: "steer" } : { triggerTurn });
408
443
  }
409
444
  return record;
410
445
  }
@@ -502,7 +537,7 @@ export class AgentRunner {
502
537
  }
503
538
 
504
539
  private persist(record: AgentRecord): void {
505
- this.pi.appendEntry(ENTRY_TYPE, record);
540
+ this.pi.appendEntry(AGENTS_ENTRY, record);
506
541
  }
507
542
 
508
543
  private refreshRestored(state: AgentState): AgentState {
@@ -544,7 +579,7 @@ export class AgentRunner {
544
579
  // its host identifies as the record's is stopped.
545
580
  restore(entries: readonly SessionEntry[]): void {
546
581
  for (const entry of entries) {
547
- if (entry.type !== "custom" || entry.customType !== ENTRY_TYPE || !Value.Check(recordSchema, entry.data)) continue;
582
+ if (entry.type !== "custom" || entry.customType !== AGENTS_ENTRY || !Value.Check(recordSchema, entry.data)) continue;
548
583
  const { id } = entry.data.agent;
549
584
  if (this.agents.get(id)?.kind === "local") continue;
550
585
  this.agents.set(id, entry.data.status === "running" ? { kind: "remote", record: entry.data } : { kind: "ended", record: entry.data });
@@ -40,6 +40,7 @@ export interface ChildExit {
40
40
  // "" when the run ended cleanly.
41
41
  errorMessage: string;
42
42
  stderr: string;
43
+ interruption?: string;
43
44
  }
44
45
 
45
46
  // What a running child is doing, last event wins. It lives only in this
@@ -82,6 +82,7 @@ interface Sheet {
82
82
  agentToolsOff: boolean;
83
83
  hcHost: boolean;
84
84
  t3Host: boolean;
85
+ orcaHost: boolean;
85
86
  piModels: Map<string, string>;
86
87
  }
87
88
 
@@ -103,6 +104,7 @@ export function parseSheet(text: string): Sheet {
103
104
  agentToolsOff: lines.some((l) => l === "pi agent tools: off"),
104
105
  hcHost: lines.some((l) => l === "pi agent host: hc"),
105
106
  t3Host: lines.some((l) => l === "pi agent host: t3"),
107
+ orcaHost: lines.some((l) => l === "pi agent host: orca"),
106
108
  piModels,
107
109
  };
108
110
  }
@@ -113,13 +115,14 @@ export function parseSheet(text: string): Sheet {
113
115
  // A directory's git root does not change within a process, so it is asked once;
114
116
  // the sheet itself is read again on every call.
115
117
  const gitRoots = new Map<string, string>();
116
- function projectRoot(cwd: string): string {
118
+ export function projectRoot(cwd: string): string {
117
119
  const cached = gitRoots.get(cwd);
118
120
  if (cached !== undefined) return cached;
119
121
  let root = cwd;
120
122
  try {
121
- root = execFileSync("git", ["rev-parse", "--show-toplevel"], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
122
- } catch {
123
+ root = execFileSync("git", ["rev-parse", "--show-toplevel"], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 10_000 }).trim();
124
+ } catch (e) {
125
+ if ((e as NodeJS.ErrnoException).code === "ETIMEDOUT") return cwd;
123
126
  // The directory itself is the root, as in the session hook.
124
127
  }
125
128
  gitRoots.set(cwd, root);
@@ -15,6 +15,7 @@ const STARTUP_POLL_MS = 500;
15
15
  const GET_TIMEOUT_MS = 2000;
16
16
  const NOT_THE_CHILD = new Set(["timeout", "message"]);
17
17
  const TERMINAL_VARS = new Set(["COLORTERM", "TERM", "TERM_PROGRAM", "PWD", "OLDPWD", "SHLVL", "_"]);
18
+ const READONLY_VARS = new Set(["BASHOPTS", "BASH_VERSINFO", "EUID", "PPID", "SHELLOPTS", "UID"]);
18
19
  const LOAD_ENV = '. "$1" && rm -- "$1" && shift && exec "$@"';
19
20
 
20
21
  const waitResult = Type.Object({
@@ -68,7 +69,7 @@ export class HcChild {
68
69
  opts: HcOptions,
69
70
  prompt: string,
70
71
  ) {
71
- writeFileSync(opts.envFile, envScript({ ...process.env, ...opts.env }), { mode: 0o600 });
72
+ writeFileSync(opts.envFile, envScript({ ...process.env, ...opts.env }, "HC_"), { mode: 0o600 });
72
73
  const run = ["run", "--json", "--bg", "--no-notify", "--name", name, "--cwd", opts.cwd, "--", "sh", "-c", LOAD_ENV, "pstack-env", opts.envFile, command, ...args];
73
74
  this.exited = this.drive(run, opts, prompt);
74
75
  }
@@ -167,17 +168,20 @@ export class HcChild {
167
168
  }
168
169
  }
169
170
 
170
- export function envScript(env: NodeJS.ProcessEnv): string {
171
+ export function envScript(env: NodeJS.ProcessEnv, terminalPrefix: string): string {
171
172
  return Object.entries(env)
172
- .filter(([name, value]) => value !== undefined && /^[A-Za-z_][A-Za-z0-9_]*$/.test(name) && !name.startsWith("HC_") && !TERMINAL_VARS.has(name))
173
+ .filter(([name, value]) => value !== undefined && /^[A-Za-z_][A-Za-z0-9_]*$/.test(name) && !name.startsWith(terminalPrefix) && !TERMINAL_VARS.has(name) && !READONLY_VARS.has(name))
173
174
  .map(([name, value]) => `export ${name}='${(value ?? "").replaceAll("'", "'\\''")}'\n`)
174
175
  .join("");
175
176
  }
176
177
 
177
178
  export function replyIn(file: string | undefined, from: number): Pick<ChildExit, "finalText" | "errorMessage"> {
179
+ return replyOf(file ? jsonLines(readFileSync(file).subarray(from).toString("utf8")) : []);
180
+ }
181
+
182
+ export function replyOf(entries: unknown[]): Pick<ChildExit, "finalText" | "errorMessage"> {
178
183
  const reply = { finalText: "", errorMessage: "" };
179
- if (!file) return reply;
180
- for (const entry of jsonLines(readFileSync(file).subarray(from).toString("utf8"))) {
184
+ for (const entry of entries) {
181
185
  if (!Value.Check(transcriptReply, entry)) continue;
182
186
  const { message } = entry;
183
187
  const text = assistantText(message.content);
@@ -215,11 +219,11 @@ function hcError(e: unknown): string {
215
219
  return (e as { stderr?: string }).stderr?.trim() || (e as Error).message;
216
220
  }
217
221
 
218
- function sizeOf(file: string | undefined): number {
222
+ export function sizeOf(file: string | undefined): number {
219
223
  return file ? statSync(file).size : 0;
220
224
  }
221
225
 
222
- function jsonLines(text: string): unknown[] {
226
+ export function jsonLines(text: string): unknown[] {
223
227
  return text.split("\n").flatMap((line) => {
224
228
  try {
225
229
  return [JSON.parse(line)];