@xzzpig/pi-subagents 0.2.0 → 0.4.0

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 (103) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/README.md +2 -0
  3. package/agents/oracle.md +7 -5
  4. package/agents/researcher.md +1 -1
  5. package/agents/reviewer.md +2 -2
  6. package/agents/scout.md +1 -1
  7. package/agents/worker.md +1 -1
  8. package/docs/agents.md +3 -0
  9. package/docs/configuration.md +121 -10
  10. package/docs/extension-api.md +36 -0
  11. package/docs/missions.md +5 -3
  12. package/docs/observability.md +43 -3
  13. package/docs/tool-reference.md +20 -3
  14. package/docs/workflows.md +2 -2
  15. package/package.json +4 -4
  16. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  17. package/skills/pi-subagents/references/execution-controls.md +5 -4
  18. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  19. package/skills/pi-subagents/references/prompting-and-roles.md +31 -15
  20. package/src/agents/agent-serializer.ts +2 -0
  21. package/src/agents/agents.ts +46 -15
  22. package/src/api/external-runs.ts +174 -84
  23. package/src/api/preflight.ts +13 -7
  24. package/src/extension/config.ts +59 -0
  25. package/src/extension/doctor.ts +40 -0
  26. package/src/extension/index.ts +83 -9
  27. package/src/extension/public-execution.ts +37 -4
  28. package/src/extension/rpc.ts +8 -10
  29. package/src/extension/schemas.ts +12 -10
  30. package/src/extension/tool-description.ts +13 -9
  31. package/src/inspectors/herdr/actions.ts +13 -8
  32. package/src/inspectors/herdr/inspector-runner.ts +16 -3
  33. package/src/inspectors/herdr/project-panes.ts +2 -6
  34. package/src/inspectors/herdr/shell-command.ts +16 -0
  35. package/src/intercom/intercom-bridge.ts +9 -5
  36. package/src/intercom/native-supervisor-channel.ts +19 -42
  37. package/src/missions/goal-driver.ts +3 -1
  38. package/src/missions/lifecycle.ts +4 -7
  39. package/src/missions/store.ts +12 -7
  40. package/src/missions/workflow-state.ts +6 -2
  41. package/src/runs/background/active-async-capacity.ts +431 -0
  42. package/src/runs/background/active-run-index.ts +77 -3
  43. package/src/runs/background/async-execution.ts +190 -72
  44. package/src/runs/background/async-job-tracker.ts +5 -0
  45. package/src/runs/background/async-resume.ts +21 -7
  46. package/src/runs/background/async-status-snapshot.ts +277 -0
  47. package/src/runs/background/async-status.ts +17 -6
  48. package/src/runs/background/chain-append.ts +33 -15
  49. package/src/runs/background/chain-root-attachment.ts +2 -2
  50. package/src/runs/background/completion-replay.ts +11 -1
  51. package/src/runs/background/fleet-view.ts +21 -6
  52. package/src/runs/background/owned-process-tree.ts +104 -0
  53. package/src/runs/background/process-terminal.ts +17 -3
  54. package/src/runs/background/result-files.ts +437 -0
  55. package/src/runs/background/result-watcher.ts +188 -41
  56. package/src/runs/background/resume-guidance.ts +27 -7
  57. package/src/runs/background/retained-children.ts +75 -18
  58. package/src/runs/background/run-id-resolver.ts +30 -24
  59. package/src/runs/background/run-status.ts +106 -5
  60. package/src/runs/background/scheduled-runs.ts +54 -28
  61. package/src/runs/background/stale-run-reconciler.ts +30 -16
  62. package/src/runs/background/subagent-runner.ts +352 -62
  63. package/src/runs/background/subagent-wait.ts +2 -0
  64. package/src/runs/background/wait-completions.ts +5 -2
  65. package/src/runs/foreground/async-dismiss-action.ts +2 -1
  66. package/src/runs/foreground/chain-execution.ts +53 -2
  67. package/src/runs/foreground/execution.ts +309 -34
  68. package/src/runs/foreground/foreground-control.ts +12 -0
  69. package/src/runs/foreground/prompt-audit.ts +172 -0
  70. package/src/runs/foreground/subagent-executor.ts +936 -224
  71. package/src/runs/shared/acceptance.ts +13 -4
  72. package/src/runs/shared/completion-guard.ts +107 -1
  73. package/src/runs/shared/external-cli-runner.ts +4 -0
  74. package/src/runs/shared/llm-intent-arbiter.ts +302 -0
  75. package/src/runs/shared/model-fallback.ts +16 -2
  76. package/src/runs/shared/nested-events.ts +66 -62
  77. package/src/runs/shared/orca-progress-tabs.ts +375 -0
  78. package/src/runs/shared/parallel-utils.ts +4 -0
  79. package/src/runs/shared/pi-args.ts +44 -1
  80. package/src/runs/shared/run-fanout-budget.ts +280 -0
  81. package/src/runs/shared/single-output.ts +4 -2
  82. package/src/runs/shared/subagent-control.ts +15 -0
  83. package/src/runs/shared/subagent-prompt-runtime.ts +1 -9
  84. package/src/runs/shared/subagent-startup-retry.ts +12 -0
  85. package/src/runs/shared/task-intent.ts +19 -3
  86. package/src/runs/shared/tool-timeout.ts +93 -0
  87. package/src/runs/shared/worktree.ts +17 -5
  88. package/src/shared/agent-stream-options.ts +5 -0
  89. package/src/shared/artifacts.ts +2 -6
  90. package/src/shared/display-text.ts +50 -0
  91. package/src/shared/node-executable.ts +21 -0
  92. package/src/shared/types.ts +143 -5
  93. package/src/shared/utils.ts +3 -1
  94. package/src/slash/slash-commands.ts +34 -25
  95. package/src/slash/slash-live-state.ts +3 -0
  96. package/src/tui/fleet-status.ts +164 -47
  97. package/src/tui/fleet-transcript.ts +1 -48
  98. package/src/tui/fleet.ts +352 -27
  99. package/src/tui/render.ts +122 -44
  100. package/src/watchdog/permission-arbiter.ts +2 -1
  101. package/src/watchdog/review.ts +4 -3
  102. package/src/workflows/chat-progress.ts +10 -2
  103. package/src/workflows/scripted-workflow.ts +292 -79
@@ -17,6 +17,7 @@ export interface RunnerOptions {
17
17
  refreshMs: number;
18
18
  allowSteer?: boolean;
19
19
  allowStop?: boolean;
20
+ sessionRoots: string[];
20
21
  }
21
22
 
22
23
  function readMission(filePath: string | undefined): MissionRecord | undefined {
@@ -24,7 +25,7 @@ function readMission(filePath: string | undefined): MissionRecord | undefined {
24
25
  try { return parseMissionRecord(JSON.parse(fs.readFileSync(filePath, "utf-8")), filePath); } catch { return undefined; }
25
26
  }
26
27
 
27
- export function formatInspectorDashboard(input: { status: AsyncStatus; asyncDir: string; index?: number; mission?: MissionRecord; allowSteer?: boolean; allowStop?: boolean }): string {
28
+ export function formatInspectorDashboard(input: { status: AsyncStatus; asyncDir: string; index?: number; mission?: MissionRecord; allowSteer?: boolean; allowStop?: boolean; sessionRoots?: string[] }): string {
28
29
  const { status, asyncDir, mission } = input;
29
30
  const lines = [
30
31
  `pi-subagents inspector for ${status.runId}`,
@@ -37,7 +38,7 @@ export function formatInspectorDashboard(input: { status: AsyncStatus; asyncDir:
37
38
  if (open.length) lines.push(`Open decisions: ${open.map((decision) => `${decision.id}: ${decision.title}`).join(" | ")}`);
38
39
  lines.push("");
39
40
  }
40
- lines.push(formatAsyncRunTranscript(status, asyncDir, { index: input.index, lines: 60 }));
41
+ lines.push(formatAsyncRunTranscript(status, asyncDir, { index: input.index, lines: 60, sessionRoots: input.sessionRoots }));
41
42
  const controls = [input.allowSteer === false ? undefined : "steer <message>", input.allowStop === false ? undefined : "stop", "status"].filter(Boolean);
42
43
  lines.push("", `Controls: ${controls.join(" | ")}`, "Supervisor replies remain in the parent Pi session (subagent_supervisor/intercom).");
43
44
  return lines.join("\n");
@@ -57,6 +58,17 @@ function parseArgs(argv: string[]): RunnerOptions {
57
58
  const indexRaw = values.get("--index");
58
59
  const childIndex = indexRaw === undefined ? undefined : Number(indexRaw);
59
60
  if (childIndex !== undefined && (!Number.isInteger(childIndex) || childIndex < 0)) throw new Error("--index must be a non-negative integer.");
61
+ const sessionRootsRaw = values.get("--session-roots");
62
+ let sessionRoots: string[] = [];
63
+ if (sessionRootsRaw !== undefined) {
64
+ try {
65
+ const parsed = JSON.parse(sessionRootsRaw) as unknown;
66
+ if (!Array.isArray(parsed) || parsed.some((root) => typeof root !== "string")) throw new Error();
67
+ sessionRoots = parsed;
68
+ } catch {
69
+ throw new Error("--session-roots must be a JSON array of strings.");
70
+ }
71
+ }
60
72
  const refreshRaw = values.get("--refresh-ms");
61
73
  const refreshMs = refreshRaw === undefined ? 1_500 : Number(refreshRaw);
62
74
  if (!Number.isInteger(refreshMs) || refreshMs < 250) throw new Error("--refresh-ms must be an integer >= 250.");
@@ -65,6 +77,7 @@ function parseArgs(argv: string[]): RunnerOptions {
65
77
  runId,
66
78
  ...(childIndex !== undefined ? { index: childIndex } : {}),
67
79
  ...(values.get("--mission-path") ? { missionPath: path.resolve(values.get("--mission-path")!) } : {}),
80
+ sessionRoots,
68
81
  refreshMs,
69
82
  allowSteer: values.get("--allow-steer") !== "false",
70
83
  allowStop: values.get("--allow-stop") !== "false",
@@ -115,7 +128,7 @@ export function runInspector(argv = process.argv.slice(2)): void {
115
128
  process.stdout.write(`\x1b[2J\x1b[Hpi-subagents inspector\n\nLifecycle status for ${options.runId} is unavailable.\n`);
116
129
  return;
117
130
  }
118
- process.stdout.write(`\x1b[2J\x1b[H${formatInspectorDashboard({ status, asyncDir: options.asyncDir, index: options.index, mission: readMission(options.missionPath), allowSteer: options.allowSteer, allowStop: options.allowStop })}${notice ? `\n\n${notice}` : ""}\n> `);
131
+ process.stdout.write(`\x1b[2J\x1b[H${formatInspectorDashboard({ status, asyncDir: options.asyncDir, index: options.index, mission: readMission(options.missionPath), allowSteer: options.allowSteer, allowStop: options.allowStop, sessionRoots: options.sessionRoots })}${notice ? `\n\n${notice}` : ""}\n> `);
119
132
  if (isTerminal(status) && timer) {
120
133
  clearInterval(timer);
121
134
  timer = undefined;
@@ -6,6 +6,7 @@ import { getProjectSubagentsDir } from "../../shared/artifacts.ts";
6
6
  import { writeAtomicJson } from "../../shared/atomic-json.ts";
7
7
  import type { Details } from "../../shared/types.ts";
8
8
  import { createHerdrClient, detectHerdr, type HerdrClient, type HerdrErrorCode } from "./client.ts";
9
+ import { formatShellCommand } from "./shell-command.ts";
9
10
 
10
11
  export const HERDR_PROJECT_PANE_ACTIONS = ["project.open", "project.status", "project.close"] as const;
11
12
  export type HerdrProjectPaneAction = typeof HERDR_PROJECT_PANE_ACTIONS[number];
@@ -257,11 +258,6 @@ function projectPaneRuntime(value: unknown): ProjectPaneRuntime | undefined {
257
258
  };
258
259
  }
259
260
 
260
- function shellQuote(value: string): string {
261
- if (process.platform === "win32") return `"${value.replaceAll('"', '\\"')}"`;
262
- return `'${value.replaceAll("'", "'\\''")}'`;
263
- }
264
-
265
261
  function resolveProjectRoot(requested: string): ProjectPaneResult<string> {
266
262
  const resolved = path.resolve(requested);
267
263
  try {
@@ -284,7 +280,7 @@ async function inspectPane(client: HerdrClient, paneId: string, signal?: AbortSi
284
280
  function projectPaneCommand(message: string | undefined): string {
285
281
  const args = message?.trim() ? [message.trim()] : [];
286
282
  const command = getPiSpawnCommand(args);
287
- return `${process.platform === "win32" ? "& " : ""}${[command.command, ...command.args].map(shellQuote).join(" ")}`;
283
+ return formatShellCommand(command.command, command.args);
288
284
  }
289
285
 
290
286
  function canonicalRuntimePath(value: string | undefined): string | undefined {
@@ -0,0 +1,16 @@
1
+ function shellQuote(value: string, platform: NodeJS.Platform): string {
2
+ if (platform === "win32") return `"${value.replaceAll('"', '\\"')}"`;
3
+ return `'${value.replaceAll("'", "'\\''")}'`;
4
+ }
5
+
6
+ function isBareExecutable(value: string): boolean {
7
+ return /^[\w./@:-]+$/.test(value);
8
+ }
9
+
10
+ export function formatShellCommand(exe: string, args: readonly string[], platform: NodeJS.Platform = process.platform): string {
11
+ const quotedArgs = args.map((arg) => shellQuote(arg, platform));
12
+ if (platform === "win32") return `& ${[shellQuote(exe, platform), ...quotedArgs].join(" ")}`;
13
+ // Nushell treats a leading quoted token as a string, so use a bare invoker for paths that need quoting.
14
+ const invocation = isBareExecutable(exe) ? exe : `sh -c 'exec "$0" "$@"' ${shellQuote(exe, platform)}`;
15
+ return [invocation, ...quotedArgs].join(" ");
16
+ }
@@ -26,9 +26,8 @@ Use contact_supervisor first. It resolves the supervisor session "{orchestratorT
26
26
  - After contact_supervisor with reason "need_decision" or "interview_request", stay alive and continue only after the reply arrives. Do not finish your final response with a choose-one question.
27
27
  - Do not ask for clarification when the only conflict is review-only/no-edit versus progress-writing or artifact-writing instructions. If an output path is configured but no write-capable tool is available, return the complete artifact in your final response; the runtime will persist it. Do not contact the supervisor merely because you cannot write that output path directly.
28
28
  - Meaningful progress or unexpected discoveries that change the plan: contact_supervisor({ reason: "progress_update", message: "UPDATE: <summary>" })
29
- - Generic intercom is lower-level plumbing/fallback only: intercom({ action: "ask", to: "{orchestratorTarget}", message: "<question>" })
30
29
 
31
- Do not use contact_supervisor or intercom for routine completion handoffs. If no coordination is needed, return a focused task result.`;
30
+ Do not use contact_supervisor for routine completion handoffs. If no coordination is needed, return a focused task result.`;
32
31
 
33
32
  export interface IntercomBridgeState {
34
33
  active: boolean;
@@ -51,6 +50,8 @@ export interface IntercomBridgeDiagnostic {
51
50
 
52
51
  interface ResolveIntercomBridgeInput {
53
52
  config: ExtensionConfig["intercomBridge"];
53
+ /** Per-run config replaces the global config when supplied. */
54
+ override?: IntercomBridgeConfig;
54
55
  context: "fresh" | "fork" | undefined;
55
56
  orchestratorTarget?: string;
56
57
  cwd?: string;
@@ -63,7 +64,10 @@ export function resolveIntercomSessionTarget(sessionName: string | undefined, se
63
64
  if (trimmedName) return trimmedName;
64
65
  const fallbackSessionId = intercomSessionId?.trim() || sessionId;
65
66
  const normalizedSessionId = fallbackSessionId.startsWith("session-") ? fallbackSessionId.slice("session-".length) : fallbackSessionId;
66
- return `${DEFAULT_INTERCOM_TARGET_PREFIX}-${normalizedSessionId.slice(0, 8)}`;
67
+ // NOTE: keep slice length in sync with pi-intercom's resolveIntercomPresenceName
68
+ // (index.ts: DEFAULT_UNNAMED_SESSION_ALIAS_PREFIX + slice(0, 18)); mismatched lengths
69
+ // make fallback orchestrator targets unresolvable ("Session not found").
70
+ return `${DEFAULT_INTERCOM_TARGET_PREFIX}-${normalizedSessionId.slice(0, 18)}`;
67
71
  }
68
72
 
69
73
  function sanitizeIntercomTargetPart(value: string): string {
@@ -140,7 +144,7 @@ export function diagnoseIntercomBridge(input: ResolveIntercomBridgeInput): Inter
140
144
  }
141
145
 
142
146
  export function resolveIntercomBridge(input: ResolveIntercomBridgeInput): IntercomBridgeState {
143
- const config = resolveIntercomBridgeConfig(input.config);
147
+ const config = resolveIntercomBridgeConfig(input.override !== undefined ? input.override : input.config);
144
148
  const mode = config.mode;
145
149
  const orchestratorTarget = input.orchestratorTarget?.trim();
146
150
  const agentDir = path.resolve(input.agentDir ?? defaultAgentDir());
@@ -166,7 +170,7 @@ export function resolveIntercomBridge(input: ResolveIntercomBridgeInput): Interc
166
170
  export function applyIntercomBridgeToAgent(agent: AgentConfig, bridge: IntercomBridgeState): AgentConfig {
167
171
  if (!bridge.active || !bridge.orchestratorTarget) return agent;
168
172
 
169
- const bridgeTools = ["intercom", "contact_supervisor"];
173
+ const bridgeTools = ["contact_supervisor"];
170
174
  const tools = agent.tools && agent.tools.length > 0
171
175
  ? [...agent.tools, ...bridgeTools.filter((tool) => !agent.tools?.includes(tool))]
172
176
  : agent.tools;
@@ -295,38 +295,18 @@ function hasTool(pi: ExtensionAPI, name: string): boolean {
295
295
  }
296
296
  }
297
297
 
298
- export function registerNativeSupervisorClient(pi: ExtensionAPI, options: { includeIntercomFallback?: boolean } = {}): void {
299
- if (!readChildMetadata()) return;
300
- const includeIntercomFallback = options.includeIntercomFallback !== false;
301
- if (!hasTool(pi, "contact_supervisor")) {
302
- const tool: ToolDefinition<typeof ContactSupervisorParamsSchema, Record<string, unknown>> = {
303
- name: "contact_supervisor",
304
- label: "Contact Supervisor",
305
- description: "Contact the parent/supervisor session for a blocking decision, structured interview, or progress update.",
306
- parameters: ContactSupervisorParamsSchema,
307
- execute(_id, params, signal) {
308
- return sendSupervisorRequest(params as ContactSupervisorParams, signal);
309
- },
310
- };
311
- pi.registerTool(tool);
312
- }
313
- if (includeIntercomFallback && !hasTool(pi, "intercom")) {
314
- const tool: ToolDefinition<typeof IntercomParamsSchema, Record<string, unknown>> = {
315
- name: "intercom",
316
- label: "Intercom",
317
- description: "Native supervisor-channel intercom fallback for subagents. Prefer contact_supervisor when available.",
318
- parameters: IntercomParamsSchema,
319
- async execute(_id, params, signal) {
320
- const action = (params as IntercomParams).action;
321
- if (action === "status") return { content: [{ type: "text", text: "Native supervisor channel is active." }], details: { active: true } };
322
- if (action === "list") return { content: [{ type: "text", text: "Supervisor session available through contact_supervisor." }], details: { sessions: [] } };
323
- if (action === "send") return sendSupervisorRequest({ reason: "progress_update", message: (params as IntercomParams).message ?? "" }, signal);
324
- if (action === "ask") return sendSupervisorRequest({ reason: "need_decision", message: (params as IntercomParams).message ?? "" }, signal);
325
- throw new Error("Native child intercom supports status, list, send, and ask. Use parent intercom reply from the supervisor session.");
326
- },
327
- };
328
- pi.registerTool(tool);
329
- }
298
+ export function registerNativeSupervisorClient(pi: ExtensionAPI): void {
299
+ if (!readChildMetadata() || hasTool(pi, "contact_supervisor")) return;
300
+ const tool: ToolDefinition<typeof ContactSupervisorParamsSchema, Record<string, unknown>> = {
301
+ name: "contact_supervisor",
302
+ label: "Contact Supervisor",
303
+ description: "Contact the parent/supervisor session for a blocking decision, structured interview, or progress update.",
304
+ parameters: ContactSupervisorParamsSchema,
305
+ execute(_id, params, signal) {
306
+ return sendSupervisorRequest(params as ContactSupervisorParams, signal);
307
+ },
308
+ };
309
+ pi.registerTool(tool);
330
310
  }
331
311
 
332
312
  function parseRequestFile(file: string, channelDir: string): PendingSupervisorRequest | undefined {
@@ -601,13 +581,11 @@ function publicPendingRequests(pending: Map<string, PendingSupervisorRequest>):
601
581
  }));
602
582
  }
603
583
 
604
- function buildParentIntercomTool(pending: Map<string, PendingSupervisorRequest>, state: SubagentState, name = "intercom"): ToolDefinition<typeof IntercomParamsSchema, Record<string, unknown>> {
584
+ function buildParentSupervisorTool(pending: Map<string, PendingSupervisorRequest>, state: SubagentState): ToolDefinition<typeof IntercomParamsSchema, Record<string, unknown>> {
605
585
  return {
606
- name,
607
- label: name === "intercom" ? "Intercom" : "Subagent Supervisor",
608
- description: name === "intercom"
609
- ? "Native pi-subagents supervisor channel. Use reply/pending/status to answer child subagent requests."
610
- : "Native pi-subagents supervisor channel. Use reply/pending/status to answer child subagent requests without overriding pi-intercom.",
586
+ name: NATIVE_SUPERVISOR_TOOL_NAME,
587
+ label: "Subagent Supervisor",
588
+ description: "Native pi-subagents supervisor channel. Use reply/pending/status to answer child subagent requests without overriding pi-intercom.",
611
589
  parameters: IntercomParamsSchema,
612
590
  async execute(_id, params) {
613
591
  refreshPendingRequests(pending, state, state.lastUiContext ?? undefined);
@@ -627,9 +605,9 @@ function buildParentIntercomTool(pending: Map<string, PendingSupervisorRequest>,
627
605
  return { content: [{ type: "text", text: `Replied to supervisor request ${request.id}.` }], details: { replyTo: request.id, runId: request.runId, agent: request.agent } };
628
606
  }
629
607
  if (input.action === "send" || input.action === "ask") {
630
- throw new Error("Native pi-subagents intercom currently handles supervisor replies. Child agents initiate asks with contact_supervisor.");
608
+ throw new Error("The native subagent supervisor handles replies only. Child agents initiate asks with contact_supervisor.");
631
609
  }
632
- throw new Error(`Unsupported intercom action: ${input.action}`);
610
+ throw new Error(`Unsupported supervisor action: ${input.action}`);
633
611
  },
634
612
  };
635
613
  }
@@ -647,8 +625,7 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
647
625
  let lastStaleCleanupAt = 0;
648
626
 
649
627
  const registerParentTools = (): void => {
650
- if (!hasTool(pi, NATIVE_SUPERVISOR_TOOL_NAME)) pi.registerTool(buildParentIntercomTool(pending, state, NATIVE_SUPERVISOR_TOOL_NAME));
651
- if (!hasTool(pi, "intercom")) pi.registerTool(buildParentIntercomTool(pending, state));
628
+ if (!hasTool(pi, NATIVE_SUPERVISOR_TOOL_NAME)) pi.registerTool(buildParentSupervisorTool(pending, state));
652
629
  };
653
630
 
654
631
  const cleanupStaleChannelsIfDue = (): void => {
@@ -99,7 +99,9 @@ function missionStateAction(location: MissionStoreLocation, record: MissionRecor
99
99
  function retainedResumeTarget(record: MissionRecord, retainedChildren: RetainedChild[]): RetainedChild | undefined {
100
100
  const latestRun = record.runs.at(-1);
101
101
  if (!latestRun) return undefined;
102
- return retainedChildren.find((child) => child.runId === latestRun.runId || child.parentRunId === latestRun.runId);
102
+ return retainedChildren.find((child) =>
103
+ child.resumability.state === "resumable" && (child.runId === latestRun.runId || child.parentRunId === latestRun.runId)
104
+ );
103
105
  }
104
106
 
105
107
  function nextReadyAction(location: MissionStoreLocation, record: MissionRecord, retainedChildren: RetainedChild[]): string {
@@ -2,6 +2,7 @@ import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
4
4
  import { writePrivateAtomicJson } from "../shared/atomic-json.ts";
5
+ import { PROMPT_REDACTED } from "../shared/utils.ts";
5
6
  import type { Details, SubagentRunMode } from "../shared/types.ts";
6
7
  import { validateMissionLaunch } from "./actions.ts";
7
8
  import type { MissionArtifact, MissionRecord, MissionRunLink, MissionRunMode, MissionStatus, MissionStoreConfig, MissionStoreLocation } from "./types.ts";
@@ -47,11 +48,6 @@ function workflowObjective(params: MissionLaunchParams): string | undefined {
47
48
  return undefined;
48
49
  }
49
50
 
50
- function conciseTitle(objective: string): string {
51
- const firstLine = objective.split(/\r?\n/, 1)[0]?.trim() || objective.trim();
52
- return firstLine.length > 100 ? `${firstLine.slice(0, 97)}...` : firstLine;
53
- }
54
-
55
51
  export function prepareMissionLaunch(input: {
56
52
  params: MissionLaunchParams;
57
53
  projectRoot: string;
@@ -73,10 +69,11 @@ export function prepareMissionLaunch(input: {
73
69
  return { missionId, location, autoCreated: false, announceInContent: true };
74
70
  }
75
71
  const mission = input.params.mission !== undefined ? validateMissionLaunch(input.params.mission) : undefined;
76
- const title = mission?.title || conciseTitle(objective!);
72
+ const promptDerivedObjective = mission?.objective ?? (mission ? mission.title : objective ? PROMPT_REDACTED : undefined);
73
+ const title = mission?.title || PROMPT_REDACTED;
77
74
  const record = createMission(location, {
78
75
  title,
79
- objective: mission?.objective || objective || title,
76
+ objective: promptDerivedObjective || title,
80
77
  ...(mission?.goal === true ? { goal: true as const } : {}),
81
78
  ...(mission?.budget ? { budget: mission.budget } : {}),
82
79
  status: "active",
@@ -2,7 +2,6 @@ import { createHash, randomUUID } from "node:crypto";
2
2
  import * as fs from "node:fs";
3
3
  import * as os from "node:os";
4
4
  import * as path from "node:path";
5
- import { getProjectSubagentsDir } from "../shared/artifacts.ts";
6
5
  import { writePrivateAtomicJson } from "../shared/atomic-json.ts";
7
6
  import { getAgentDir } from "../shared/utils.ts";
8
7
  import {
@@ -259,6 +258,11 @@ function expandConfiguredPath(value: string, projectRoot: string): string {
259
258
  return path.isAbsolute(expanded) ? path.normalize(expanded) : path.resolve(projectRoot, expanded);
260
259
  }
261
260
 
261
+ function projectMissionDirectory(agentDir: string, projectRoot: string): string {
262
+ const projectKey = createHash("sha256").update(projectRoot).digest("hex");
263
+ return path.join(agentDir, "missions", "projects", projectKey);
264
+ }
265
+
262
266
  export function validateMissionStoreConfig(value: unknown, label = "config.missions"): MissionStoreConfig | undefined {
263
267
  if (value === undefined) return undefined;
264
268
  const input = asObject(value, label);
@@ -289,12 +293,13 @@ export function resolveMissionStoreLocation(input: {
289
293
  agentDir?: string;
290
294
  }): MissionStoreLocation {
291
295
  const projectRoot = path.resolve(input.projectRoot);
296
+ const agentDir = input.agentDir ?? getAgentDir();
292
297
  const missionDir = input.config?.directory
293
298
  ? expandConfiguredPath(input.config.directory, projectRoot)
294
- : path.join(getProjectSubagentsDir(projectRoot), "missions");
299
+ : projectMissionDirectory(agentDir, projectRoot);
295
300
  const globalIndexDir = input.config?.globalIndexDir
296
301
  ? expandConfiguredPath(input.config.globalIndexDir, projectRoot)
297
- : path.join(input.agentDir ?? getAgentDir(), "missions", "index");
302
+ : path.join(agentDir, "missions", "index");
298
303
  return {
299
304
  projectRoot,
300
305
  missionDir,
@@ -396,11 +401,11 @@ export class MissionNotFoundError extends Error {
396
401
  readonly missionId: string;
397
402
  readonly missionDir: string;
398
403
 
399
- constructor(missionId: string, missionDir: string) {
400
- super(`Mission '${missionId}' was not found in ${missionDir}`);
404
+ constructor(missionId: string, location: MissionStoreLocation) {
405
+ super(`Mission '${missionId}' was not found in mission directory '${location.missionDir}' for project root '${location.projectRoot}'. If it was created in another worktree, run the request from that worktree.`);
401
406
  this.name = "MissionNotFoundError";
402
407
  this.missionId = missionId;
403
- this.missionDir = missionDir;
408
+ this.missionDir = location.missionDir;
404
409
  }
405
410
  }
406
411
 
@@ -410,7 +415,7 @@ export function readMission(location: MissionStoreLocation, missionId: string):
410
415
  try {
411
416
  raw = fs.readFileSync(filePath, "utf-8");
412
417
  } catch (error) {
413
- if ((error as NodeJS.ErrnoException).code === "ENOENT") throw new MissionNotFoundError(missionId, location.missionDir);
418
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") throw new MissionNotFoundError(missionId, location);
414
419
  throw error;
415
420
  }
416
421
  try {
@@ -95,8 +95,12 @@ function stateLockIsStale(lockPath: string, now = Date.now()): boolean {
95
95
  const owner = readStateLockOwner(lockPath);
96
96
  if (owner) {
97
97
  if (!isProcessAlive(owner.pid)) return true;
98
- const currentProcessKey = processStartKey(owner.pid);
99
- return Boolean(owner.processKey && currentProcessKey && owner.processKey !== currentProcessKey);
98
+ if (owner.processKey) {
99
+ const currentProcessKey = owner.pid === process.pid ? CURRENT_PROCESS_KEY : processStartKey(owner.pid);
100
+ if (currentProcessKey) return owner.processKey !== currentProcessKey;
101
+ if (owner.pid === process.pid) return true;
102
+ }
103
+ return false;
100
104
  }
101
105
  try {
102
106
  return now - fs.statSync(lockPath).mtimeMs > STATE_LOCK_STALE_MS;