open-pstack 0.9.158 → 0.9.160

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "open-pstack",
3
- "version": "0.9.158",
3
+ "version": "0.9.160",
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.158",
3
+ "version": "0.9.160",
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.158",
4
+ "version": "0.9.160",
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.158",
3
+ "version": "0.9.160",
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.158",
4
+ "version": "0.9.160",
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.158",
3
+ "version": "0.9.160",
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.158",
5
+ "version": "0.9.160",
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.158",
3
+ "version": "0.9.160",
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, 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
16
  import { checkEffort, DEPTH_FLAG, GENERAL_PURPOSE, InvalidValueError, 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,10 @@ 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 host: Host = t3 ? "t3"
287
+ : sheet?.hcHost && process.env.HC_TERMINAL_ID ? "hc"
288
+ : sheet?.orcaHost && orcaSession() ? "orca"
289
+ : "rpc";
274
290
  const identity: AgentIdentity = {
275
291
  id,
276
292
  description: params.description,
@@ -292,6 +308,7 @@ export class AgentRunner {
292
308
 
293
309
  private launch(identity: AgentIdentity, prompt: string, background: boolean): RunningRecord {
294
310
  if (this.closed) throw new Error("This session is shutting down; no agent can start.");
311
+ 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
312
  try {
296
313
  // First, so a failure here leaves no worktree or branch behind.
297
314
  this.ensureSystemPrompt(identity);
@@ -305,10 +322,10 @@ export class AgentRunner {
305
322
  }
306
323
  throw e;
307
324
  }
308
- const { child, host } = this.spawnChild(identity, prompt);
325
+ const { child, host, t3RequestId } = this.spawnChild(identity, prompt);
309
326
  const pidStart = child.pid === undefined ? undefined : inspect(child.pid)?.start;
310
327
  // 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 };
328
+ 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
329
  const run: Run = { child, background, done: child.exited.then((exit) => this.finish(identity, run, exit)) };
313
330
  this.agents.set(identity.id, { kind: "local", record, run });
314
331
  this.persist(record);
@@ -316,7 +333,7 @@ export class AgentRunner {
316
333
  return record;
317
334
  }
318
335
 
319
- private spawnChild(identity: AgentIdentity, prompt: string): { child: AgentChild; host: Host } {
336
+ private spawnChild(identity: AgentIdentity, prompt: string): { child: AgentChild; host: Host; t3RequestId?: string } {
320
337
  const { command, args } = this.settings.pi;
321
338
  const base = [...args, "--extension", join(this.settings.pluginRoot, "pi", "index.ts"), "--skill", join(this.settings.pluginRoot, "skills")];
322
339
  const flags = childArgs(identity, this.settings.depth);
@@ -330,13 +347,15 @@ export class AgentRunner {
330
347
  identity.t3ThreadId = threadId;
331
348
  this.track(identity.id, { t3TaskId: taskId });
332
349
  };
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 };
350
+ const requestId = identity.t3ThreadId ? undefined : randomUUID();
351
+ const launch = { title: identity.description, model: identity.model, thinking: identity.thinking, threadId: identity.t3ThreadId, requestId, graceMs: this.settings.killGraceMs, onStart };
352
+ return { child: new T3Child(t3, launch, identity.t3ThreadId ? prompt : t3Brief(identity, prompt)), host, t3RequestId: requestId };
335
353
  }
336
- // An hc agent's session is a Pi session file, so outside herdr-core an RPC child resumes it.
354
+ // An interactive pi asks whether to trust the project before it reports any status; the parent already decided.
355
+ const interactiveArgs = [...base, ...flags, this.projectTrusted ? "--approve" : "--no-approve"];
356
+ // A terminal agent's session is a Pi session file, so outside herdr-core or Orca an RPC child resumes it.
337
357
  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"], {
358
+ const child = new HcChild(identity.id, command, interactiveArgs, {
340
359
  cwd: identity.cwd,
341
360
  env: { ...env, PI_CODING_AGENT_DIR: this.settings.agentDir },
342
361
  envFile: join(identity.sessionDir, `${identity.id}.env`),
@@ -346,6 +365,20 @@ export class AgentRunner {
346
365
  }, prompt);
347
366
  return { child, host };
348
367
  }
368
+ const orca = host === "orca" ? orcaSession() : undefined;
369
+ if (orca) {
370
+ const child = new OrcaChild(command, interactiveArgs, {
371
+ session: orca,
372
+ title: identity.description,
373
+ cwd: identity.cwd,
374
+ env: { ...env, PI_CODING_AGENT_DIR: this.settings.agentDir },
375
+ files: join(identity.sessionDir, identity.id),
376
+ graceMs: this.settings.killGraceMs,
377
+ transcript: () => sessionFile(identity),
378
+ onStart: (pid) => this.track(identity.id, { pid, pidStart: inspect(pid)?.start }),
379
+ }, prompt);
380
+ return { child, host: "orca" };
381
+ }
349
382
  const child = new PiChild(command, [...base, "--mode", "rpc", ...flags], { cwd: identity.cwd, env, exitGraceMs: this.settings.exitGraceMs, onActivity: () => this.showStatus() }, prompt);
350
383
  return { child, host: "rpc" };
351
384
  }
@@ -404,7 +437,8 @@ export class AgentRunner {
404
437
  // The model that called stop_agent already has the result, so a stop's
405
438
  // notice joins the context without starting another turn.
406
439
  if (run.background && run.ending !== "teardown") {
407
- this.pi.sendMessage(noticeOf(record, sessionFile(identity)), status !== "stopped" ? { triggerTurn: true, deliverAs: "steer" } : { triggerTurn: false });
440
+ const triggerTurn = run.ending === undefined;
441
+ this.pi.sendMessage(noticeOf(record, sessionFile(identity), triggerTurn), triggerTurn ? { triggerTurn, deliverAs: "steer" } : { triggerTurn });
408
442
  }
409
443
  return record;
410
444
  }
@@ -502,7 +536,7 @@ export class AgentRunner {
502
536
  }
503
537
 
504
538
  private persist(record: AgentRecord): void {
505
- this.pi.appendEntry(ENTRY_TYPE, record);
539
+ this.pi.appendEntry(AGENTS_ENTRY, record);
506
540
  }
507
541
 
508
542
  private refreshRestored(state: AgentState): AgentState {
@@ -544,7 +578,7 @@ export class AgentRunner {
544
578
  // its host identifies as the record's is stopped.
545
579
  restore(entries: readonly SessionEntry[]): void {
546
580
  for (const entry of entries) {
547
- if (entry.type !== "custom" || entry.customType !== ENTRY_TYPE || !Value.Check(recordSchema, entry.data)) continue;
581
+ if (entry.type !== "custom" || entry.customType !== AGENTS_ENTRY || !Value.Check(recordSchema, entry.data)) continue;
548
582
  const { id } = entry.data.agent;
549
583
  if (this.agents.get(id)?.kind === "local") continue;
550
584
  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
@@ -2,7 +2,7 @@ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { execFileSync } from "node:child_process";
3
3
  import { existsSync, readFileSync } from "node:fs";
4
4
  import { homedir } from "node:os";
5
- import { basename, dirname, join } from "node:path";
5
+ import { dirname, join, win32 } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { type Static, Type } from "typebox";
8
8
  import { Value } from "typebox/value";
@@ -32,15 +32,26 @@ export interface Settings {
32
32
  exitGraceMs: number;
33
33
  }
34
34
 
35
+ const isBunVirtualPath = (path: string, execPath: string) => {
36
+ const normalized = path.replaceAll("\\", "/");
37
+ if (normalized.startsWith("/$bunfs/")) return true;
38
+ const runtime = win32.basename(execPath).toLowerCase();
39
+ return !/^(node|bun)(\.exe)?$/.test(runtime) && /^[A-Za-z]:\/~BUN\//i.test(normalized);
40
+ };
41
+
35
42
  // Pi re-runs itself for children when it can: the same runtime and CLI script,
36
43
  // so a child never picks up a different pi from PATH.
37
- function piInvocation(): Settings["pi"] {
38
- const script = process.argv[1];
39
- if (script && !script.startsWith("/$bunfs/") && existsSync(script)) {
40
- return { command: process.execPath, args: [script] };
44
+ export function piInvocation({ execPath = process.execPath, argv = process.argv, fileExists = existsSync }: {
45
+ execPath?: string;
46
+ argv?: string[];
47
+ fileExists?: (path: string) => boolean;
48
+ } = {}): Settings["pi"] {
49
+ const script = argv[1];
50
+ if (script && !isBunVirtualPath(script, execPath) && fileExists(script)) {
51
+ return { command: execPath, args: [script] };
41
52
  }
42
- const exe = basename(process.execPath).toLowerCase();
43
- return /^(node|bun)(\.exe)?$/.test(exe) ? { command: "pi", args: [] } : { command: process.execPath, args: [] };
53
+ const exe = win32.basename(execPath).toLowerCase();
54
+ return /^(node|bun)(\.exe)?$/.test(exe) ? { command: "pi", args: [] } : { command: execPath, args: [] };
44
55
  }
45
56
 
46
57
  // readDepth is called on each use: pi parses extension flags after it loads
@@ -71,6 +82,7 @@ interface Sheet {
71
82
  agentToolsOff: boolean;
72
83
  hcHost: boolean;
73
84
  t3Host: boolean;
85
+ orcaHost: boolean;
74
86
  piModels: Map<string, string>;
75
87
  }
76
88
 
@@ -92,6 +104,7 @@ export function parseSheet(text: string): Sheet {
92
104
  agentToolsOff: lines.some((l) => l === "pi agent tools: off"),
93
105
  hcHost: lines.some((l) => l === "pi agent host: hc"),
94
106
  t3Host: lines.some((l) => l === "pi agent host: t3"),
107
+ orcaHost: lines.some((l) => l === "pi agent host: orca"),
95
108
  piModels,
96
109
  };
97
110
  }
@@ -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({
@@ -49,6 +50,10 @@ export interface HcOptions {
49
50
  onStart: (pid: number) => void;
50
51
  }
51
52
 
53
+ export function terminalTermination(platform: NodeJS.Platform, pid: number | undefined): { kind: "hc" } | { kind: "process-group"; pid: number } {
54
+ return platform === "win32" || pid === undefined ? { kind: "hc" } : { kind: "process-group", pid };
55
+ }
56
+
52
57
  export class HcChild {
53
58
  readonly pid = undefined;
54
59
  readonly activity = undefined;
@@ -64,7 +69,7 @@ export class HcChild {
64
69
  opts: HcOptions,
65
70
  prompt: string,
66
71
  ) {
67
- writeFileSync(opts.envFile, envScript({ ...process.env, ...opts.env }), { mode: 0o600 });
72
+ writeFileSync(opts.envFile, envScript({ ...process.env, ...opts.env }, "HC_"), { mode: 0o600 });
68
73
  const run = ["run", "--json", "--bg", "--no-notify", "--name", name, "--cwd", opts.cwd, "--", "sh", "-c", LOAD_ENV, "pstack-env", opts.envFile, command, ...args];
69
74
  this.exited = this.drive(run, opts, prompt);
70
75
  }
@@ -85,8 +90,9 @@ export class HcChild {
85
90
  }
86
91
 
87
92
  signal(signal: NodeJS.Signals): void {
88
- if (this.terminalPid === undefined) spawn("hc", ["kill", this.name], { detached: true, stdio: "ignore" }).unref();
89
- else signalGroup(this.terminalPid, signal);
93
+ const termination = terminalTermination(process.platform, this.terminalPid);
94
+ if (termination.kind === "hc") spawn("hc", ["kill", this.name], { detached: true, stdio: "ignore" }).unref();
95
+ else signalGroup(termination.pid, signal);
90
96
  }
91
97
 
92
98
  private async drive(run: string[], opts: HcOptions, prompt: string): Promise<ChildExit> {
@@ -115,9 +121,9 @@ export class HcChild {
115
121
  }
116
122
 
117
123
  private stop(graceMs: number): void {
118
- const pid = this.terminalPid;
119
- if (pid === undefined) void quiet(["kill", this.name]);
120
- else void terminateGroup(pid, () => alive(pid), graceMs);
124
+ const termination = terminalTermination(process.platform, this.terminalPid);
125
+ if (termination.kind === "hc") void quiet(["kill", this.name]);
126
+ else void terminateGroup(termination.pid, () => alive(termination.pid), graceMs);
121
127
  }
122
128
 
123
129
  private async turn(prompt: string): Promise<WaitResult> {
@@ -162,17 +168,20 @@ export class HcChild {
162
168
  }
163
169
  }
164
170
 
165
- export function envScript(env: NodeJS.ProcessEnv): string {
171
+ export function envScript(env: NodeJS.ProcessEnv, terminalPrefix: string): string {
166
172
  return Object.entries(env)
167
- .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))
168
174
  .map(([name, value]) => `export ${name}='${(value ?? "").replaceAll("'", "'\\''")}'\n`)
169
175
  .join("");
170
176
  }
171
177
 
172
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"> {
173
183
  const reply = { finalText: "", errorMessage: "" };
174
- if (!file) return reply;
175
- for (const entry of jsonLines(readFileSync(file).subarray(from).toString("utf8"))) {
184
+ for (const entry of entries) {
176
185
  if (!Value.Check(transcriptReply, entry)) continue;
177
186
  const { message } = entry;
178
187
  const text = assistantText(message.content);
@@ -210,11 +219,11 @@ function hcError(e: unknown): string {
210
219
  return (e as { stderr?: string }).stderr?.trim() || (e as Error).message;
211
220
  }
212
221
 
213
- function sizeOf(file: string | undefined): number {
222
+ export function sizeOf(file: string | undefined): number {
214
223
  return file ? statSync(file).size : 0;
215
224
  }
216
225
 
217
- function jsonLines(text: string): unknown[] {
226
+ export function jsonLines(text: string): unknown[] {
218
227
  return text.split("\n").flatMap((line) => {
219
228
  try {
220
229
  return [JSON.parse(line)];
@@ -0,0 +1,230 @@
1
+ import { execFile } from "node:child_process";
2
+ import { readFileSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { setTimeout as sleep } from "node:timers/promises";
4
+ import { promisify } from "node:util";
5
+ import { type Static, type TSchema, Type } from "typebox";
6
+ import { Value } from "typebox/value";
7
+
8
+ import { AGENTS_ENTRY, NOTICE_TYPE } from "./agent-text.ts";
9
+ import { alive, type ChildExit, signalGroup, terminateGroup } from "./child.ts";
10
+ import { envScript, jsonLines, replyOf, sizeOf } from "./hc-child.ts";
11
+
12
+ const execOrca = promisify(execFile);
13
+ export const SETTLE_POLL_MS = 500;
14
+ const CLOSE_POLL_MS = 200;
15
+ const CALL_TIMEOUT_MS = 10_000;
16
+
17
+ const createResult = Type.Object({ result: Type.Object({ terminal: Type.Object({ handle: Type.String(), processId: Type.Number() }) }) });
18
+ const sendResult = Type.Object({ result: Type.Object({ send: Type.Object({ accepted: Type.Boolean() }) }) });
19
+ const readResult = Type.Object({ result: Type.Object({ terminal: Type.Object({ tail: Type.Array(Type.String()) }) }) });
20
+ const failedResult = Type.Object({ error: Type.Object({ message: Type.String() }) });
21
+ const messageEntry = Type.Object({
22
+ type: Type.Literal("message"),
23
+ id: Type.Optional(Type.String()),
24
+ message: Type.Object({ role: Type.String(), stopReason: Type.Optional(Type.String()) }),
25
+ });
26
+ const droppedEntry = Type.Object({ type: Type.Literal("context_edit"), targetId: Type.String(), replacement: Type.Null() });
27
+ const agentEntry = Type.Object({ type: Type.Literal("custom"), customType: Type.Literal(AGENTS_ENTRY), data: Type.Object({ agent: Type.Object({ id: Type.String() }), status: Type.String() }) });
28
+ const noticeEntry = Type.Object({ type: Type.Literal("custom_message"), customType: Type.Literal(NOTICE_TYPE), details: Type.Object({ triggerTurn: Type.Boolean() }) });
29
+ const userMessage = (entry: unknown): boolean => Value.Check(messageEntry, entry) && entry.message.role === "user";
30
+
31
+ export interface OrcaSession {
32
+ cli: string;
33
+ workspace: string;
34
+ }
35
+
36
+ // Orca's macOS app sets no ORCA_CLI_COMMAND, and on Linux a bare orca is the screen reader.
37
+ export function orcaSession(env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform): OrcaSession | undefined {
38
+ if (platform === "win32") return undefined;
39
+ const handle = env.ORCA_TERMINAL_HANDLE;
40
+ const cli = env.ORCA_CLI_COMMAND || (platform === "darwin" ? "orca" : undefined);
41
+ const workspace = env.ORCA_WORKTREE_ID || env.ORCA_WORKSPACE_ID;
42
+ return handle && cli && workspace ? { cli, workspace } : undefined;
43
+ }
44
+
45
+ export function settledRun(entries: unknown[], steers: number): Pick<ChildExit, "interruption"> | undefined {
46
+ const last = entries.filter((entry) => Value.Check(messageEntry, entry) || (Value.Check(noticeEntry, entry) && entry.details.triggerTurn)).at(-1);
47
+ if (!Value.Check(messageEntry, last) || last.message.role !== "assistant" || last.message.stopReason === "toolUse") return undefined;
48
+ // Pi drops a failed reply it is about to retry with a context edit.
49
+ if (entries.some((entry) => Value.Check(droppedEntry, entry) && entry.targetId === last.id)) return undefined;
50
+ // Pi puts a steer still queued at an abort back in its editor, so it never arrives.
51
+ if (last.message.stopReason === "aborted") return { interruption: "stopped in Orca" };
52
+ // Counted, not matched by text: a TUI may reshape pasted text.
53
+ const users = entries.filter(userMessage).length;
54
+ if (users < 1 + steers) return undefined;
55
+ const agents = new Map(entries.filter((entry) => Value.Check(agentEntry, entry)).map(({ data }) => [data.agent.id, data.status]));
56
+ return [...agents.values()].includes("running") ? undefined : { interruption: undefined };
57
+ }
58
+
59
+ export interface OrcaOptions {
60
+ session: OrcaSession;
61
+ title: string;
62
+ cwd: string;
63
+ env: Record<string, string | undefined>;
64
+ files: string;
65
+ graceMs: number;
66
+ transcript: () => string | undefined;
67
+ onStart: (pid: number) => void;
68
+ }
69
+
70
+ export class OrcaChild {
71
+ readonly pid = undefined;
72
+ readonly activity = undefined;
73
+ readonly exited: Promise<ChildExit>;
74
+ private readonly cli: string;
75
+ private begin!: () => void;
76
+ private readonly begun = new Promise<void>((resolve) => {
77
+ this.begin = resolve;
78
+ });
79
+ private readonly files: Record<string, string>;
80
+ private handle?: string;
81
+ private terminalPid?: number;
82
+ private steers = 0;
83
+ private settled = false;
84
+ private ending = false;
85
+
86
+ constructor(command: string, args: string[], opts: OrcaOptions, prompt: string) {
87
+ this.cli = opts.session.cli;
88
+ const files = { env: `${opts.files}.env`, prompt: `${opts.files}.prompt`, script: `${opts.files}.sh`, err: `${opts.files}.err` };
89
+ this.files = files;
90
+ writeFileSync(files.env, envScript({ ...process.env, ...opts.env }, "ORCA_"), { mode: 0o600 });
91
+ // Pi reads an argument that starts with @ as a file, even after --, and one that starts with / as a command.
92
+ writeFileSync(files.prompt, /^[@/]/.test(prompt) ? ` ${prompt}` : prompt, { mode: 0o600 });
93
+ const launch = `. ${quote(files.env)} && rm -- ${quote(files.env)} && p=$(cat ${quote(files.prompt)}; printf x) && p=\${p%x} && rm -- ${quote(files.prompt)} && cd ${quote(opts.cwd)} && exec ${[command, ...args].map(quote).join(" ")} -- "$p" 2>>${quote(files.err)}\n`;
94
+ writeFileSync(files.script, launch, { mode: 0o600 });
95
+ const from = sizeOf(opts.transcript());
96
+ const created = this.orca(createResult, ["terminal", "create", `--worktree=id:${opts.session.workspace}`, `--title=${opts.title}`, `--command=exec sh ${quote(files.script)}`]);
97
+ this.exited = this.drive(created, from, opts);
98
+ }
99
+
100
+ async steer(message: string): Promise<{ response: { success: boolean; error?: string } | undefined; taken: boolean }> {
101
+ if (/^\s*[!/]/.test(message)) {
102
+ return { response: { success: false, error: "the message starts with ! or /, which pi's editor in the Orca tab would run as a shell or slash command; reword it" }, taken: false };
103
+ }
104
+ if (!message.trim()) return { response: { success: false, error: "the message is empty once pi's editor trims it, so pi would drop it" }, taken: false };
105
+ if (!this.settled) {
106
+ // Counted before the send, so the run cannot settle while the message is on its way.
107
+ this.steers++;
108
+ // Pi keeps text typed into the tab before it has started in its editor, unsubmitted.
109
+ const begun = await Promise.race([this.begun.then(() => true), this.exited.then(() => false)]);
110
+ const handle = begun && !this.settled ? this.handle : undefined;
111
+ let tooLong = false;
112
+ try {
113
+ const sent = handle && (await this.orca(sendResult, ["terminal", "send", `--terminal=${handle}`, `--text=${message}`, "--enter"]));
114
+ if (sent && sent.result.send.accepted) return { response: { success: true }, taken: true };
115
+ } catch (e) {
116
+ tooLong = (e as NodeJS.ErrnoException).code === "E2BIG";
117
+ }
118
+ this.steers--;
119
+ if (tooLong) return { response: { success: false, error: "the message is longer than one command-line argument can be; put it in a file and name the file" }, taken: false };
120
+ }
121
+ return { response: undefined, taken: false };
122
+ }
123
+
124
+ end(graceMs: number): void {
125
+ this.ending = true;
126
+ this.stop(graceMs);
127
+ }
128
+
129
+ signal(signal: NodeJS.Signals): void {
130
+ if (this.terminalPid !== undefined) signalGroup(this.terminalPid, signal);
131
+ else this.removeFiles();
132
+ }
133
+
134
+ private async drive(created: Promise<Static<typeof createResult>>, from: number, opts: OrcaOptions): Promise<ChildExit> {
135
+ const written = () => {
136
+ const file = opts.transcript();
137
+ return file ? jsonLines(readFileSync(file).subarray(from).toString("utf8")) : [];
138
+ };
139
+ try {
140
+ const { handle, processId } = (await created).result.terminal;
141
+ this.handle = handle;
142
+ this.terminalPid = processId;
143
+ opts.onStart(processId);
144
+ if (this.ending) this.stop(opts.graceMs);
145
+ let run: Pick<ChildExit, "interruption"> | undefined;
146
+ // Pi writes a failed reply before the context edit that drops it for a retry.
147
+ let seen = -1;
148
+ while (!run && alive(processId)) {
149
+ await sleep(SETTLE_POLL_MS);
150
+ if (!alive(processId)) break;
151
+ const entries = written();
152
+ if (entries.some(userMessage)) this.begin();
153
+ const ready = settledRun(entries, this.steers);
154
+ run = ready && entries.length === seen ? ready : undefined;
155
+ seen = ready ? entries.length : -1;
156
+ }
157
+ this.settled = run !== undefined;
158
+ const entries = written();
159
+ const stderr = this.settled || this.ending ? "" : readText(this.files.err) || (await this.screen());
160
+ await this.close(opts.graceMs);
161
+ return { exitCode: null, settled: this.settled, ...replyOf(entries), interruption: run?.interruption, stderr };
162
+ } catch (e) {
163
+ await this.close(opts.graceMs);
164
+ return { exitCode: null, settled: false, finalText: replyOf(written()).finalText, errorMessage: orcaError(e), stderr: "" };
165
+ } finally {
166
+ this.removeFiles();
167
+ }
168
+ }
169
+
170
+ private removeFiles(): void {
171
+ for (const file of Object.values(this.files)) {
172
+ try {
173
+ unlinkSync(file);
174
+ } catch {}
175
+ }
176
+ }
177
+
178
+ private stop(graceMs: number): void {
179
+ const pid = this.terminalPid;
180
+ if (pid !== undefined) void terminateGroup(pid, () => alive(pid), graceMs);
181
+ }
182
+
183
+ private async close(graceMs: number): Promise<void> {
184
+ this.stop(graceMs);
185
+ while (this.terminalPid !== undefined && alive(this.terminalPid)) await sleep(CLOSE_POLL_MS);
186
+ // Orca usually removes the tab itself once pi is gone, and then there is nothing to close.
187
+ if (this.handle !== undefined) await this.orca(Type.Unknown(), ["terminal", "close", `--terminal=${this.handle}`]).catch(() => undefined);
188
+ }
189
+
190
+ private screen(): Promise<string> {
191
+ return this.orca(readResult, ["terminal", "read", `--terminal=${this.handle}`, "--screen"]).then(
192
+ ({ result }) => result.terminal.tail.join("\n"),
193
+ () => "",
194
+ );
195
+ }
196
+
197
+ private async orca<T extends TSchema>(schema: T, args: string[]): Promise<Static<T>> {
198
+ const { stdout } = await execOrca(this.cli, [...args, "--json"], { timeout: CALL_TIMEOUT_MS }).catch((e: { killed?: boolean }) => {
199
+ throw e.killed ? new Error(`orca ${args[0]} ${args[1]} did not answer within ${CALL_TIMEOUT_MS / 1000} s`) : e;
200
+ });
201
+ let answer: unknown;
202
+ try {
203
+ answer = JSON.parse(stdout);
204
+ } catch {}
205
+ if (!Value.Check(schema, answer)) throw new Error(`orca ${args[0]} ${args[1]} answered: ${stdout.trim().slice(0, 300)}`);
206
+ return answer;
207
+ }
208
+ }
209
+
210
+ function readText(file: string): string {
211
+ try {
212
+ return readFileSync(file, "utf8");
213
+ } catch {
214
+ return "";
215
+ }
216
+ }
217
+
218
+ function quote(text: string): string {
219
+ return `'${text.replaceAll("'", "'\\''")}'`;
220
+ }
221
+
222
+ // With --json the Orca CLI reports a failure on stdout.
223
+ function orcaError(e: unknown): string {
224
+ const { stdout = "", stderr = "" } = e as { stdout?: string; stderr?: string };
225
+ try {
226
+ const answer: unknown = JSON.parse(stdout);
227
+ if (Value.Check(failedResult, answer)) return answer.error.message;
228
+ } catch {}
229
+ return stderr.trim() || (e as Error).message;
230
+ }
@@ -1,4 +1,5 @@
1
1
  import { readFileSync } from "node:fs";
2
+ import { setTimeout as sleep } from "node:timers/promises";
2
3
  import { type Static, type TSchema, Type } from "typebox";
3
4
  import { Value } from "typebox/value";
4
5
 
@@ -6,6 +7,8 @@ import { alive, type ChildExit, type Fate } from "./child.ts";
6
7
 
7
8
  const PROTOCOL = "2025-06-18";
8
9
  const WAIT_MS = 30_000;
10
+ const LOST_LAUNCH = "pstack: the Pi session that started this agent ended before T3 Code answered its launch, so the task is cancelled.";
11
+ const LATE_STEER = "T3 Code put it in the agent's thread after its run had ended, so no run reads the reply.";
9
12
  // T3 Code's terminal task statuses (OrchestratorMcpTerminalDelegatedTaskStatus).
10
13
  const ENDED = new Set(["completed", "failed", "cancelled", "interrupted"]);
11
14
 
@@ -52,9 +55,16 @@ export interface T3Launch {
52
55
  model?: string;
53
56
  thinking?: string;
54
57
  threadId?: string;
58
+ requestId?: string;
59
+ graceMs: number;
55
60
  onStart: (task: T3Task) => void;
56
61
  }
57
62
 
63
+ interface T3Request {
64
+ requestId: string;
65
+ title: string;
66
+ }
67
+
58
68
  // A T3 Code thread takes no launch flags, so its first message carries the agent file's body.
59
69
  export function t3Brief(agent: { subagentType: string; systemPromptFile?: string }, prompt: string): string {
60
70
  const body = agent.systemPromptFile ? readFileSync(agent.systemPromptFile, "utf8").trim() : "";
@@ -70,23 +80,42 @@ export class T3Child {
70
80
  readonly activity = undefined;
71
81
  readonly exited: Promise<ChildExit>;
72
82
  private readonly mcp: T3Mcp;
83
+ private readonly onStart: (task: T3Task) => void;
73
84
  private threadId?: string;
74
85
  private taskId?: string;
75
- private settled = false;
86
+ private runId?: string;
87
+ private steers: Promise<unknown> = Promise.resolve();
88
+ private done = false;
76
89
  private ending = false;
77
- private cancelled?: Promise<void>;
90
+ private cancelled?: { taskId: string; done: Promise<void> };
78
91
  private readonly stopWaiting = new AbortController();
92
+ private readonly stopped = new Promise<void>((resolve) => this.stopWaiting.signal.addEventListener("abort", () => resolve()));
79
93
 
80
94
  constructor(session: T3Session, launch: T3Launch, prompt: string) {
81
95
  this.mcp = new T3Mcp(session);
96
+ this.onStart = launch.onStart;
82
97
  this.exited = this.drive(launch, prompt);
83
98
  }
84
99
 
85
- async steer(message: string): Promise<{ response: { success: boolean } | undefined; taken: boolean }> {
86
- if (this.settled || this.threadId === undefined) return { response: undefined, taken: false };
100
+ async steer(message: string): Promise<{ response: { success: boolean; error?: string } | undefined; taken: boolean }> {
101
+ const threadId = this.threadId;
102
+ if (this.done || threadId === undefined) return { response: undefined, taken: false };
103
+ const send = this.steers.then(async () => {
104
+ this.stopWaiting.signal.throwIfAborted();
105
+ // A stop never aborts a sent steer, so an answer that names a task the steer started still arrives, and that task is cancelled.
106
+ const { taskId, runId, delivery } = await this.mcp.call(sent, "t3_thread_send", { threadId, message, mode: "steer" });
107
+ if (delivery === "steered") return;
108
+ this.runId = runId;
109
+ if (!taskId) return;
110
+ this.taskId = taskId;
111
+ this.onStart({ threadId, taskId });
112
+ if (this.ending || this.done) void this.cancel();
113
+ });
114
+ this.steers = send.catch(() => undefined);
115
+ if (!(await this.steersAnswered())) return { response: undefined, taken: false };
87
116
  try {
88
- const { delivery } = await this.mcp.call(sent, "t3_thread_send", { threadId: this.threadId, message, mode: "steer" });
89
- return { response: { success: true }, taken: delivery === "steered" && !this.settled };
117
+ await send;
118
+ return this.done ? { response: { success: false, error: LATE_STEER }, taken: false } : { response: { success: true }, taken: true };
90
119
  } catch {
91
120
  return { response: undefined, taken: false };
92
121
  }
@@ -104,13 +133,26 @@ export class T3Child {
104
133
 
105
134
  private async drive(launch: T3Launch, prompt: string): Promise<ChildExit> {
106
135
  try {
107
- const { threadId, runId } = await this.start(launch, prompt);
136
+ const threadId = await this.start(launch, prompt);
108
137
  if (this.ending) await this.cancel();
109
- await settled(this.mcp, threadId, runId, this.stopWaiting.signal);
110
- const { status, summary } = await this.mcp.call(taskResult, "task_status", { taskId: this.taskId });
111
- this.settled = status === "completed";
138
+ let steers: Promise<unknown>;
139
+ let result: Static<typeof taskResult> | Error;
140
+ do {
141
+ steers = this.steers;
142
+ await this.steersAnswered();
143
+ try {
144
+ await settled(this.mcp, threadId, this.runId, this.stopWaiting.signal);
145
+ result = await this.mcp.call(taskResult, "task_status", { taskId: this.taskId });
146
+ } catch (e) {
147
+ result = e as Error;
148
+ if (steers === this.steers || !(await Promise.race([this.steersAnswered(), sleep(launch.graceMs, false, { ref: false })]))) break;
149
+ }
150
+ } while (steers !== this.steers);
151
+ this.done = true;
152
+ if (result instanceof Error) throw result;
153
+ const { status, summary } = result;
112
154
  const text = summary ?? "";
113
- if (this.settled) return { exitCode: 0, settled: true, finalText: text, errorMessage: "", stderr: "" };
155
+ if (status === "completed") return { exitCode: 0, settled: true, finalText: text, errorMessage: "", stderr: "" };
114
156
  return { exitCode: null, settled: false, finalText: "", errorMessage: text || `The T3 Code task ended with status ${status}.`, stderr: "" };
115
157
  } catch (e) {
116
158
  const message = (e as Error).message;
@@ -118,22 +160,24 @@ export class T3Child {
118
160
  }
119
161
  }
120
162
 
121
- private async start(launch: T3Launch, prompt: string): Promise<{ threadId: string; runId?: string }> {
163
+ private async start(launch: T3Launch, prompt: string): Promise<string> {
122
164
  if (launch.threadId !== undefined) {
123
165
  this.threadId = launch.threadId;
124
166
  const { taskId, runId } = await this.mcp.call(sent, "t3_thread_send", { threadId: launch.threadId, message: prompt, mode: "auto" });
125
167
  if (!taskId) throw new Error(`T3 Code took the message in thread ${launch.threadId} without starting a task.`);
126
168
  this.taskId = taskId;
169
+ this.runId = runId;
127
170
  launch.onStart({ threadId: launch.threadId, taskId });
128
- return { threadId: launch.threadId, runId };
171
+ return launch.threadId;
129
172
  }
130
173
  const thinking = launch.thinking && (await this.takesThinking(launch.model, launch.thinking)) ? { options: { thinking: launch.thinking } } : {};
131
174
  const target = { ...(launch.model && { model: launch.model }), ...thinking };
132
- const task = await this.mcp.call(delegated, "delegate_task", { task: prompt, title: launch.title, target, mode: "async" });
175
+ const task = await this.mcp.call(delegated, "delegate_task", { task: prompt, title: launch.title, target, mode: "async", clientRequestId: launch.requestId });
133
176
  this.threadId = task.childThreadId;
134
177
  this.taskId = task.taskId;
178
+ this.runId = task.childRunId ?? undefined;
135
179
  launch.onStart({ threadId: task.childThreadId, taskId: task.taskId });
136
- return { threadId: task.childThreadId, runId: task.childRunId ?? undefined };
180
+ return task.childThreadId;
137
181
  }
138
182
 
139
183
  private async takesThinking(model: string | undefined, thinking: string): Promise<boolean> {
@@ -147,18 +191,37 @@ export class T3Child {
147
191
  private cancel(): Promise<void> | undefined {
148
192
  const { taskId, threadId } = this;
149
193
  if (taskId === undefined) return;
150
- this.cancelled ??= this.mcp.call(Type.Unknown(), "task_cancel", { taskId, reason: "stop_agent" }).then(
151
- () => undefined,
152
- (e: Error) => this.stopWaiting.abort(new Error(`T3 Code did not cancel task ${taskId}, so thread ${threadId} may still be running: ${e.message}`)),
153
- );
154
- return this.cancelled;
194
+ if (this.cancelled?.taskId !== taskId) {
195
+ const done = this.mcp.call(Type.Unknown(), "task_cancel", { taskId, reason: "stop_agent" }).then(
196
+ () => undefined,
197
+ async (e: Error) => {
198
+ await this.steersAnswered();
199
+ if (this.taskId === taskId) this.stopWaiting.abort(new Error(`T3 Code did not cancel task ${taskId}, so thread ${threadId} may still be running: ${e.message}`));
200
+ },
201
+ );
202
+ this.cancelled = { taskId, done };
203
+ }
204
+ return this.cancelled.done;
205
+ }
206
+
207
+ private steersAnswered(): Promise<boolean> {
208
+ return Promise.race([this.steers.then(() => true), this.stopped.then(() => false)]);
155
209
  }
156
210
  }
157
211
 
158
- export async function cancelOrphan(task: T3Task): Promise<boolean> {
212
+ export async function cancelOrphan(orphan: T3Task | T3Request): Promise<boolean> {
159
213
  const session = t3Session();
160
214
  if (!session) return false;
161
215
  const mcp = new T3Mcp(session);
216
+ // T3 Code answers a request id it has seen with that launch's task, so a launch whose answer never came is found by sending it again.
217
+ const task =
218
+ "taskId" in orphan
219
+ ? orphan
220
+ : await mcp.call(delegated, "delegate_task", { task: LOST_LAUNCH, title: orphan.title, mode: "async", clientRequestId: orphan.requestId }).then(
221
+ ({ taskId, childThreadId }) => ({ taskId, threadId: childThreadId }),
222
+ () => undefined,
223
+ );
224
+ if (!task) return false;
162
225
  try {
163
226
  await mcp.call(Type.Unknown(), "task_cancel", { taskId: task.taskId, reason: "its Pi session ended" });
164
227
  await settled(mcp, task.threadId);
@@ -169,13 +232,16 @@ export async function cancelOrphan(task: T3Task): Promise<boolean> {
169
232
  }
170
233
  }
171
234
 
172
- type T3Record = { parentPid: number; t3TaskId?: string; agent: { t3ThreadId?: string } };
235
+ type T3Record = { parentPid: number; t3TaskId?: string; t3RequestId?: string; agent: { description: string; t3ThreadId?: string } };
173
236
 
174
237
  export const t3Host = {
175
- fate: ({ t3TaskId, parentPid }: T3Record): Fate => (t3TaskId === undefined ? "gone" : parentPid !== process.pid && alive(parentPid) ? "kept" : "orphan"),
176
- reap: async ({ t3TaskId, agent }: T3Record): Promise<Fate> =>
177
- t3TaskId && agent.t3ThreadId && (await cancelOrphan({ taskId: t3TaskId, threadId: agent.t3ThreadId })) ? "gone" : "orphan",
178
- notEnded: ({ t3TaskId }: T3Record): string => `T3 Code task ${t3TaskId} has not been cancelled`,
238
+ fate: ({ t3TaskId, t3RequestId, parentPid }: T3Record): Fate =>
239
+ t3TaskId === undefined && t3RequestId === undefined ? "gone" : parentPid !== process.pid && alive(parentPid) ? "kept" : "orphan",
240
+ reap: async ({ t3TaskId, t3RequestId, agent }: T3Record): Promise<Fate> => {
241
+ const orphan = t3TaskId && agent.t3ThreadId ? { taskId: t3TaskId, threadId: agent.t3ThreadId } : t3RequestId && { requestId: t3RequestId, title: agent.description };
242
+ return orphan && (await cancelOrphan(orphan)) ? "gone" : "orphan";
243
+ },
244
+ notEnded: ({ t3TaskId, t3RequestId }: T3Record): string => `T3 Code task ${t3TaskId ?? `of launch request ${t3RequestId}`} has not been cancelled`,
179
245
  };
180
246
 
181
247
  async function settled(mcp: T3Mcp, threadId: string, runId?: string, signal?: AbortSignal): Promise<void> {
@@ -18,7 +18,7 @@ The Antigravity CLI (`agy`) loads the native pstack plugin manifest, the skills,
18
18
  | Wait for a subagent result | End the turn (call no more tools). Antigravity resumes the session automatically when a subagent sends a message or finishes. |
19
19
  | Continue or steer a subagent (`SendMessage`) | `send_message` with `Recipient` set to the subagent's `conversationId` and `Message` |
20
20
  | List or stop subagents | `manage_subagents` with `Action: "list"`, `"kill"`, or `"kill_all"` and `ConversationIds` |
21
- | Track tasks (the todolist; `TaskCreate` / `TaskUpdate`, or `TodoWrite` on Claude Code) | Keep an uncommitted `todo.md` Markdown checklist in the work dir (or `.audit/<task-slug>.todo.md` when sessions share a checkout) |
21
+ | Track tasks (the todolist; `TaskCreate` / `TaskUpdate`, or `TodoWrite` on Claude Code) | `update_steps` with the whole `steps` list, each with a `title` and a `status` (`pending`, `in_progress`, `done`, `skipped`, `failed`); a skipped step keeps its place with status `skipped`. It takes at most 12 steps with titles of 2 to 6 words, so give it that short plan, and keep the uncommitted `todo.md` checklist poteto-mode describes as well (`.audit/<task-slug>.todo.md` when sessions share a checkout), with the playbook steps verbatim and each `skip: <reason>` line. |
22
22
  | Ask the human a fixed-choice question (`AskUserQuestion`) | `ask_question` with `questions` (`question`, `options`, `is_multi_select`) |
23
23
  | Schedule a self-paced re-invocation (`ScheduleWakeup`, the `loop` skill) | `schedule` with `DurationSeconds` (one-shot timer) or `CronExpression` (recurring schedule) and `Prompt` |
24
24
  | Call an MCP tool (`mcp__<server>__<tool>`) | Call the MCP tool directly as declared in the session's tool list |
@@ -20,7 +20,8 @@ pstack skills are written in Claude Code tool language (the `Skill` tool, the `A
20
20
  | Stop a subagent (`TaskStop`) | `close_agent` or `interrupt_agent`, whichever the session exposes. See [Agent lifecycle](#agent-lifecycle). |
21
21
  | Track tasks (the todolist; `TaskCreate` / `TaskUpdate`, or `TodoWrite` on Claude Code) | `update_plan` |
22
22
  | Ask the human a fixed-choice question (`AskUserQuestion`) | Use `request_user_input` when the current mode and client support delivering structured questions, such as an interactive Plan mode session. If support is unclear or the tool is unavailable, ask in plain text. Outside Plan mode, ask a required decision or approval in plain text, because Codex continues on its own judgment when `request_user_input` returns no answer. |
23
- | Read this workspace's session transcripts (Claude Code's `${CLAUDE_CONFIG_DIR:-$HOME/.claude}/projects/<encoded-cwd>/`) | Codex sessions live in `${CODEX_HOME:-~/.codex}/sessions/YYYY/MM/DD/`. Ordinary names end in `-<thread-id>.jsonl`; replacements after `thread/revert` end in `-<thread-id>_<rollout-id>.jsonl`. Revert keeps the old files. Resolve the current path from the state database's `threads.rollout_path`, matched by thread ID, rather than filename order or modification time. Archived sessions are in `${CODEX_HOME:-~/.codex}/archived_sessions/`. Older rollouts in both directories can end in `.jsonl.zst`; read those with `zstd -dc`. The first line of each rollout is a `session_meta` record. Keep only rollouts whose `payload.cwd` is the workspace or one of its worktrees. Never read other projects' sessions. |
23
+ | Read this workspace's session transcripts (Claude Code's `${CLAUDE_CONFIG_DIR:-$HOME/.claude}/projects/<encoded-cwd>/`) | `claude-project-dir.mjs` and the Claude projects directory are Claude Code only. For Codex, use `${CODEX_HOME:-~/.codex}/sessions/YYYY/MM/DD/`. Ordinary names end in `-<thread-id>.jsonl`; replacements after `thread/revert` end in `-<thread-id>_<rollout-id>.jsonl`. Revert keeps the old files. Resolve the current path from the state database's `threads.rollout_path`, matched by thread ID, rather than filename order or modification time. Archived sessions are in `${CODEX_HOME:-~/.codex}/archived_sessions/`. Older rollouts in both directories can end in `.jsonl.zst`; read those with `zstd -dc`. The first line of each rollout is a `session_meta` record. Keep only rollouts whose `payload.cwd` is the workspace or one of its worktrees. Never read other projects' sessions. Eval is the one exception. It selects each candidate's rollout by the thread ID recorded at dispatch, matched against `session_meta.payload.id`, the thread ID in the filename, or `threads.id`. Never match it against `payload.session_id`, which names the root thread, so every spawned candidate carries the parent's. A spawned candidate records the parent's working directory as its `payload.cwd`, so check the candidate's assigned work directory from its commands and artifacts. On a multi-agent V2 host, `spawn_agent` returns a task name and no thread ID. Treat missing or ambiguous history as unavailable. |
24
+ | Locate the Autopilot program store (`~/.claude/orchestrate/<slug>/`) | Use `pstack/orchestrate/<slug>/` under the Git common directory that [Resume storage](resume-storage.md) uses, for both the objective and the decision trail, so linked worktrees share the same store. Writes there need escalation under `workspace-write`, as [Sandbox writes under the Git common directory](#sandbox-writes-under-the-git-common-directory) describes. |
24
25
 
25
26
  Subagents are enabled by default in current Codex, and `agents.enabled` controls them. Inspect the current tool surface. If dispatch is unavailable, the fan-out skills (`interrogate`, `why`, `how`, `arena`, `reflect`) degrade to a labeled sequential pass. A required independent review does not degrade. It stays blocked, as poteto-mode's [Subagents](../SKILL.md#subagents) section says.
26
27
 
@@ -98,7 +99,7 @@ Affected skill entry points point here. Most skills need only the tables above.
98
99
  | `create-formal-verification-skill` | Write the generated skill to Codex's project-skill location, named for the area it verifies. The verifier and its run command are platform-neutral. |
99
100
  | `maintain-formal-verification-skill` | Project skills, the formal verification skill among them, live under Codex's project-skill location. |
100
101
  | `babysit` | `loop` and `AskUserQuestion` resolve through the tables above. |
101
- | `automate-me` | `plugin-dev:skill-development` resolves through the skills table above. |
102
+ | `automate-me` | Locate Codex history using the workspace-scoped transcript row above. Give mining delegates only the matched transcripts. `plugin-dev:skill-development` resolves through the skills table above. |
102
103
  | `architect` | A large or contested design goes through the **arena** skill, so its `spawn_agent` fan-out and model substitution apply here too. |
103
104
  | `arena` | The parallel candidates and the cross-judge map to `spawn_agent`; substitute your configured Codex models for the runners and the cross-judge pool (see Model names above). Run Phase C only when the effective judge and provisional winner are known to be different families. If the judge's family is unknown or repeats the winner's family, report the skipped cross-family check and continue with Phase D scoring. |
104
105
  | `how` | The one read-only subagent maps to `spawn_agent`. |
@@ -1,11 +1,15 @@
1
1
  # OMP tool mapping for pstack
2
2
 
3
- OMP loads these skills from the installed pstack marketplace plugin. Skill names are unqualified unless a collision changes their namespace. For a pstack skill named by the routing instruction, read its file under the installed plugin path supplied by that instruction. This avoids resolving a same-named skill from another source. For interactive invocation, use the name shown by OMP; Claude Code's `pstack:` prefix is not an OMP skill name.
3
+ OMP loads these skills from the installed pstack marketplace plugin. A pstack skill's URL is `skill://pstack/<name>` when OMP's skill list names `pstack/<name>`, and `skill://<name>` otherwise; a file inside it is that URL followed by `/<path>`. OMP gives a skill name to one copy, the highest-precedence one, and names pstack's copy `pstack/<name>` only when another skill holds the bare name: a project's `.claude/skills/<name>/` or `.omp/skills/<name>/`, another plugin's skill, or a copy edited with `reflect`. Never read a pstack skill by its path in the plugin install, which can sit in a folder the user restricted with `tools.restrictedFolders`: there every read asks for approval, and without an interactive UI the read is refused. For interactive invocation, use the name shown by OMP; Claude Code's `pstack:` prefix is not an OMP skill name.
4
+
5
+ Where poteto-mode asks for its absolute path in a `poteto-agent` prompt, write poteto-mode's URL. The first line of an agent's kickoff, `Read <path>/worker.md before anything else.`, becomes `Read skill://poteto-mode/worker.md before anything else.`, or `Read skill://pstack/poteto-mode/worker.md before anything else.` when the list names `pstack/poteto-mode`. Resolve a relative link against the directory of the skill that holds it, then read the result through the URL of the skill it lands in: from `why`, `../poteto-mode/references/codex-tools.md` is poteto-mode's URL followed by `/references/codex-tools.md`, and `../<name>/SKILL.md` is that skill's URL. OMP rejects `..` inside a `skill://` URL.
6
+
7
+ Where a skill runs a script under the installed plugin, as `<plugin>/skills/<name>/<path>`, run it by the physical path `realpath` prints for the skill's URL, from the repository's working directory: `node "$(realpath skill://poteto-mode)/scripts/check-playbooks.mjs"`. A restricted folder matches a `bash` call by its working directory, not its command text, so do not `cd` into the skill.
4
8
 
5
9
  | Claude Code action | OMP action |
6
10
  | --- | --- |
7
11
  | Read (`Read`), write (`Write`), edit (`Edit`), search (`Grep` / `Glob`), shell (`Bash`) | `read`, `write`, `edit`, `grep`, `glob`, `bash` |
8
- | Invoke the `Skill` tool | Read `skills/<name>/SKILL.md` in the installed plugin path supplied by the routing instruction |
12
+ | Invoke the `Skill` tool | Read the skill's URL: `skill://pstack/<name>` when OMP lists `pstack/<name>`, else `skill://<name>` |
9
13
  | Dispatch the `Agent` tool (`subagent_type`, `general-purpose`, `pstack:poteto-agent`) | Use `task` and its advertised agent roster; include the poteto-mode instructions in the brief |
10
14
  | Background dispatch (`run_in_background`) | Follow the active `task` schema; use `wait` for its result |
11
15
  | Read-only child (`readonly`) | Select an available read-only agent, or explicitly prohibit writes in its brief |
@@ -42,4 +46,4 @@ OMP uses its own model selection; without a pstack sheet, use the runtime's defa
42
46
  | `maintain-verification-skill` | Look for the project-local skill under `.omp/skills/` first, then under `.claude/skills/` and `.agents/skills/`. |
43
47
  | `create-formal-verification-skill` | On OMP write the generated skill to `.omp/skills/<area>/`, named for the area it verifies, with a `description` in its frontmatter, because OMP skips a native skill without one. The verifier and its run command are platform-neutral. |
44
48
  | `maintain-formal-verification-skill` | Look for project skills, the formal verification skill among them, under `.omp/skills/` first, then under `.claude/skills/` and `.agents/skills/`. |
45
- | `reflect` | For a pstack skill, never edit the installed plugin at the path the routing instruction names. Its edited copy is the one exception to keeping pstack skills out of a standalone directory. Before approval, show the destination in OMP's skill folders, and after approval copy the skill folder there: `.omp/skills/<skill>/` for a project copy, or `<skill>/` in the active profile's agent skills folder for a personal one. That folder is `~/.omp/profiles/$OMP_PROFILE/agent/skills/` when `OMP_PROFILE` is set, and `~/.omp/agent/skills/` otherwise. OMP skips Claude Code's personal skills folder by default, and loads it only when `skills.enableClaudeUser` is on, `enabledProviders` lists `claude`, or `CLAUDE_CONFIG_DIR` is set. Edit a project or personal skill where it already lives. OMP gives the edited copy the skill's bare name and lists the plugin's copy under a namespaced name. pstack's own skill invocations still read the plugin file, per the `Skill` row and the routing instruction, so the edited copy runs when the user or OMP's skill catalog invokes it by its bare name. |
49
+ | `reflect` | For a pstack skill, never edit the installed plugin. Its edited copy is the one exception to keeping pstack skills out of a standalone directory. Before approval, show the destination in OMP's skill folders, and after approval copy the skill folder there: `.omp/skills/<skill>/` for a project copy, or `<skill>/` in the active profile's agent skills folder for a personal one. That folder is `~/.omp/profiles/$OMP_PROFILE/agent/skills/` when `OMP_PROFILE` is set, and `~/.omp/agent/skills/` otherwise. OMP skips Claude Code's personal skills folder by default, and loads it only when `skills.enableClaudeUser` is on, `enabledProviders` lists `claude`, or `CLAUDE_CONFIG_DIR` is set. Edit a project or personal skill where it already lives. OMP gives the edited copy the skill's bare name and lists the plugin's copy as `pstack/<skill>`. pstack's own skill invocations then read `skill://pstack/<skill>`, per the `Skill` row and the routing instruction, so the edited copy runs only when the user or OMP's skill catalog invokes it by its bare name. |
@@ -35,8 +35,9 @@ poteto-mode's Subagents section applies on Pi through the `agent` tool:
35
35
  - `subagent_type` takes the same values. `pstack:poteto-agent`, `pstack:comment-sicko`, `pstack:thermo-nuclear-review-subagent`, and `pstack:thermo-nuclear-code-quality-review-subagent` resolve to the plugin's agent files. A `.md` file in `pstack-agents` in the Pi agent directory adds a type under its file name with no `pstack:` prefix, as a Claude Code user agent has no plugin prefix, and the body after the frontmatter is the child's system prompt. Its `tools:`, `disallowedTools:`, and `isolation:` fields are ignored, so pass `readonly: true` or `isolation: "worktree"` on the `agent` call instead. A hidden file, a file whose name has a colon, and one that cannot be read are skipped. The extension reads the frontmatter as YAML, and a repeated key keeps its last value, as in Claude Code. When the YAML does not parse, it retries as Claude Code 2.1.310 does, reading an unquoted top-level value that holds YAML syntax, such as `description: Use for a: b`, as text and turning leading tabs into spaces. It skips a user file whose frontmatter still does not parse. A user file never replaces a type, so `poteto-agent.md` there adds `poteto-agent` and leaves `pstack:poteto-agent` alone. The extension does not read Pi's `agents` folder, whose files other subagent extensions write with their own frontmatter. `general-purpose`, or no `subagent_type`, runs a child with no agent file. Claude Code's built-in types such as `Explore` and `Plan` do not exist on Pi, so use `general-purpose` and put the constraint in the prompt. An unknown type errors and lists the valid ones. The `agent` tool's `subagent_type` description lists each type the session starts with and what it is for, from each agent file's `description:`, the user's files included.
36
36
  - `readonly: true`, which the `how` subagent sets, runs the child without the `edit` and `write` tools. It keeps `bash`, so a reviewer can still run `git diff`; say in the prompt that it must not change files.
37
37
  - Each child is its own `pi --mode rpc` process in your working directory, and the extension sends it the prompt on its stdin. It loads the packages and settings saved on disk, so it sees the pstack skills when pstack was installed with `pi install`. It does not inherit the parent's command-line flags, such as `-e`, `--api-key`, or a one-off `-a` project trust, so a pstack loaded only through `-e` gives children no extension.
38
- - With a `pi agent host: hc` line in the sheet and the session inside herdr-core (`HC_TERMINAL_ID` is set), each child started there is instead an interactive `pi` in its own `hc` terminal, named by its agent id, with the same flags. The user can watch it and type into it, and `hc read <agentId>` shows its screen. Stop it with `stop_agent`, not `hc kill`. `send_message` to a running one types into its terminal with `hc send`, its reply is read from its transcript, `list_agents` shows no `activity` for it, and its terminal is removed when the run ends. A child that stops at a dialog fails with its screen as the error. It gets your environment, except herdr-core's own terminal variables, and your session's project trust. A prompt over 128 KiB fails on Linux; put long material in a file and name the file in the prompt. Messaged from a session outside herdr-core, it runs that turn as an RPC child.
39
- - With a `pi agent host: t3` line in the sheet and the session inside T3 Code (`T3_MCP_URL` and `T3_MCP_BEARER_TOKEN` are set), each child started there without `isolation: "worktree"` is instead a T3 Code child thread of your thread, titled with the agent's description, on the agent's model, in your thread's folder. Its effort goes to T3 Code only when T3 Code lists that level for the model. The user can watch it and type into it in T3 Code. `send_message` to a running one steers its turn, a finished one resumes in the same thread, and `stop_agent` cancels its task; when T3 Code refuses the cancel, the agent reads as stopped with the refusal as its text, and its thread can go on running. When T3 Code accepts the cancel but the thread has not settled after the kill grace, the agent also reads as stopped. A worktree agent and the agents it starts stay local processes in its worktree. A `readonly: true` agent and an agent at the third layer also stay local processes, because T3 Code cannot remove a thread's tools. A question it asks waits until someone answers it in T3 Code. T3 Code marks its first message as sent by an agent, so say in the prompt that the user started the task. The agent file's body arrives at the top of its first message. Only a Pi session inside T3 Code can message it. `list_agents` shows no `activity` and no transcript for it; its transcript is the T3 Code thread.
38
+ - With a `pi agent host: hc` line in the sheet and the session inside herdr-core (`HC_TERMINAL_ID` is set), each child started there is instead an interactive `pi` in its own `hc` terminal, named by its agent id, with the same flags. The user can watch it and type into it, and `hc read <agentId>` shows its screen. Stop it with `stop_agent`, not `hc kill`. `send_message` to a running one types into its terminal with `hc send`, its reply is read from its transcript, `list_agents` shows no `activity` for it, and its terminal is removed when the run ends. A child that stops at a dialog fails with its screen as the error. It gets your environment, except herdr-core's own terminal variables, and your session's project trust. A prompt over 128 KiB fails on Linux; put long material in a file and name the file in the prompt. A prompt that is empty once trimmed is refused, as is such a message to a finished one. Messaged from a session outside herdr-core, it runs that turn as an RPC child.
39
+ - With a `pi agent host: t3` line in the sheet and the session inside T3 Code (`T3_MCP_URL` and `T3_MCP_BEARER_TOKEN` are set), each child started there without `isolation: "worktree"` is instead a T3 Code child thread of your thread, titled with the agent's description, on the agent's model, in your thread's folder. Its effort goes to T3 Code only when T3 Code lists that level for the model. The user can watch it and type into it in T3 Code. `send_message` to a running one steers its turn, a finished one resumes in the same thread, and `stop_agent` cancels its task; when T3 Code refuses the cancel, the agent reads as stopped with the refusal as its text, and its thread can go on running. When T3 Code accepts the cancel but the thread has not settled after the kill grace, the agent also reads as stopped. A message that T3 Code queues or starts as a new turn instead of steering, such as one that starts with a slash command, is sent once, and the agent runs until that turn ends. A worktree agent and the agents it starts stay local processes in its worktree. A `readonly: true` agent and an agent at the third layer also stay local processes, because T3 Code cannot remove a thread's tools. A question it asks waits until someone answers it in T3 Code. T3 Code marks its first message as sent by an agent, so say in the prompt that the user started the task. The agent file's body arrives at the top of its first message. Only a Pi session inside T3 Code can message it. `list_agents` shows no `activity` and no transcript for it; its transcript is the T3 Code thread.
40
+ - With a `pi agent host: orca` line in the sheet and the session in an [Orca](https://github.com/stablyai/orca) terminal (`ORCA_TERMINAL_HANDLE` and `ORCA_WORKTREE_ID` or `ORCA_WORKSPACE_ID` are set, and `ORCA_CLI_COMMAND` too except on macOS, where the `orca` on `PATH` is used), each child started there is instead an interactive `pi` in its own tab of your Orca workspace, titled with the agent's description, with the same flags as an RPC child. When the sheet also has `pi agent host: hc` and the session is inside herdr-core, hc wins. The user can watch it and type into it. `send_message` to a running one types into its tab with Orca's `terminal send`, and its reply is read from its transcript. Pi's editor takes that message, so a message that starts with `!` or `/`, which the editor would run as a command, is refused, and the editor trims the message's ends and turns tabs into spaces and CRLF into LF, so an empty message is refused too. A prompt that starts with `@` or `/` reaches the child with one leading space. A prompt that is empty once trimmed is refused, as is such a message to a finished one. A run that the user stops with Escape in Orca ends `stopped`, and its notice starts a turn. Each Orca CLI call gives up after 10 seconds. A child that stops at a dialog waits until someone answers it in Orca. Stop it with `stop_agent`, not by closing its tab. Its tab closes when the run ends, and a message to a finished one resumes it in a new tab. It gets your environment, except Orca's own terminal variables (`ORCA_*`), and your session's project trust. A worktree agent's tab is in your workspace and runs in its worktree. `list_agents` shows no `activity` for it. On Linux, a prompt over 128 KiB fails and a message over 128 KiB is refused; put long material in a file and name the file in the prompt. Messaged from a session outside an Orca terminal, it runs that turn as an RPC child. Orca on Windows is not supported.
40
41
  - A child can start its own agents, down to three layers below the main session, as on Claude Code. A child at the third layer runs without the `agent` tool.
41
42
  - `isolation: "worktree"` runs the child in its own git worktree under `.claude/worktrees/`. A worktree the agent left nothing in is removed when the agent finishes; a change, a gitignored file it wrote, or a commit on its branch or on any commit its HEAD visited keeps it.
42
43
  - `run_in_background: true` returns the agent id at once. The completion joins the conversation after your current tool calls finish, as on Claude Code, or starts a turn when you are idle. In print and JSON mode (`pi -p`), where Pi exits once the run settles, the extension holds the settle while a background agent runs, so each completion still arrives as a turn and the process ends after the last one. A child agent holds its settle the same way while its own background agents run, because its parent closes its stdin once it settles, and a message from the parent ends the hold. Interactive and RPC main sessions settle as usual and take the completion when it arrives.
@@ -96,7 +97,7 @@ No skill file carries a Pi line. poteto-mode's Platform Adaptation section point
96
97
  | `interrogate` | Adversaries dispatch through `agent` with the same `subagent_type` and `model` (see Subagent policy). Keep the panel on distinct models (see Model names). |
97
98
  | `recall` | Search the Pi sessions directory for this workspace (see Tool actions). Do not list or read `${CLAUDE_CONFIG_DIR:-$HOME/.claude}/projects/`: it holds Claude Code transcripts, not this session's history. Match on `type: "message"` entries and their `message.role`. |
98
99
  | `show-me-your-work` | Check the log against this run's Pi session file (see Tool actions), not a Claude Code transcript. |
99
- | `setup-pstack` | The Pi sheet is `pstack-models.md` in the Pi agent directory, or a project's committed `.claude/pstack-models.md` (see Session routing), and the extension loads it, so no include line is needed. List models with `pi --list-models`. For a family whose model is not listed, offer a `pi models:` line (see Model names). The role rows and the five effort levels are identical. The `session hook` line applies on Pi too, where `off` stops the extension adding the mandate. When the user runs another Pi extension that registers `ask_user_question`, add `pi ask tool: off`, so the pstack extension leaves that tool name to it; Pi refuses to start while two extensions register the same name. When the user delegates through another Pi subagent extension, such as `pi-subagents`, add `pi agent tools: off`. The pstack extension then registers none of `agent`, `send_message`, `list_agents`, `stop_agent`, and `/pstack-agents`, so the model sees one set of delegation tools. When the user runs Pi inside herdr-core and wants to watch agents, add `pi agent host: hc`; inside T3 Code, add `pi agent host: t3`. When the session runs on `anthropic`, tell the user that Pi bills Claude per token as extra usage and that each multi-model panel multiplies that cost. |
100
+ | `setup-pstack` | The Pi sheet is `pstack-models.md` in the Pi agent directory, or a project's committed `.claude/pstack-models.md` (see Session routing), and the extension loads it, so no include line is needed. List models with `pi --list-models`. For a family whose model is not listed, offer a `pi models:` line (see Model names). The role rows and the five effort levels are identical. The `session hook` line applies on Pi too, where `off` stops the extension adding the mandate. When the user runs another Pi extension that registers `ask_user_question`, add `pi ask tool: off`, so the pstack extension leaves that tool name to it; Pi refuses to start while two extensions register the same name. When the user delegates through another Pi subagent extension, such as `pi-subagents`, add `pi agent tools: off`. The pstack extension then registers none of `agent`, `send_message`, `list_agents`, `stop_agent`, and `/pstack-agents`, so the model sees one set of delegation tools. When the user runs Pi inside herdr-core and wants to watch agents, add `pi agent host: hc`; inside T3 Code, add `pi agent host: t3`. In an Orca terminal, add `pi agent host: orca`. When the session runs on `anthropic`, tell the user that Pi bills Claude per token as extra usage and that each multi-model panel multiplies that cost. |
100
101
  | `no-comments` | `pstack:comment-sicko` resolves through `agent` as written. Pass it the scope, not a request to run `/no-comments`, and run it without `isolation: "worktree"`, because a worktree starts from `HEAD` and lacks the scope's uncommitted changes. |
101
102
  | `teach` | Running `how` and `why` in parallel maps to two background `agent` calls. Pi has no image generation tool, so draw with Mermaid or plain text. |
102
103
  | `create-verification-skill` | The generated skill lands under `.claude/skills/verify/` on Claude Code. Write it where Pi discovers project skills, `.pi/skills/verify/` or `.agents/skills/verify/`, instead. The app-driving harness is platform-neutral. |