@xzzpig/pi-subagents 0.20.0 → 0.21.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 (140) hide show
  1. package/CHANGELOG.md +154 -0
  2. package/README.md +1 -1
  3. package/agents/oracle.md +8 -19
  4. package/agents/researcher.md +0 -3
  5. package/agents/reviewer.md +17 -61
  6. package/agents/scout.md +1 -4
  7. package/agents/worker.md +8 -25
  8. package/docs/agents.md +72 -7
  9. package/docs/configuration.md +58 -7
  10. package/docs/extension-api.md +36 -11
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +34 -17
  13. package/docs/models.md +1 -1
  14. package/docs/observability.md +10 -5
  15. package/docs/tool-reference.md +117 -84
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +16 -7
  18. package/index.ts +5 -0
  19. package/package.json +5 -3
  20. package/prompts/council.md +1 -1
  21. package/skills/pi-subagents/SKILL.md +1 -1
  22. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  23. package/skills/pi-subagents/references/execution-controls.md +16 -16
  24. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  25. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  26. package/src/agents/advertised-agent-prompt.ts +9 -1
  27. package/src/agents/agent-management.ts +4 -0
  28. package/src/agents/agent-memory.ts +3 -3
  29. package/src/agents/agent-scope.ts +4 -0
  30. package/src/agents/agent-serializer.ts +8 -1
  31. package/src/agents/agents.ts +191 -145
  32. package/src/api/preflight.ts +8 -4
  33. package/src/extension/config.ts +21 -2
  34. package/src/extension/context-injection.ts +6 -1
  35. package/src/extension/control-notices.ts +1 -9
  36. package/src/extension/declaration-pinning.ts +164 -0
  37. package/src/extension/doctor.ts +7 -10
  38. package/src/extension/fanout-child.ts +7 -8
  39. package/src/extension/index.ts +114 -132
  40. package/src/extension/reply-workflow-script.ts +20 -11
  41. package/src/extension/rpc.ts +11 -6
  42. package/src/extension/schemas.ts +34 -30
  43. package/src/extension/subagent-guide.ts +86 -6
  44. package/src/extension/subagent-options.ts +47 -0
  45. package/src/extension/tool-activation.ts +3 -2
  46. package/src/extension/tool-description.ts +51 -68
  47. package/src/inspectors/actions.ts +37 -11
  48. package/src/inspectors/plugins.ts +3 -2
  49. package/src/inspectors/tmux/actions.ts +204 -0
  50. package/src/inspectors/tmux/client.ts +85 -0
  51. package/src/inspectors/tmux/plugin.ts +21 -0
  52. package/src/integrations/herdr-status.ts +18 -49
  53. package/src/integrations/program-status.ts +215 -0
  54. package/src/intercom/native-supervisor-channel.ts +77 -4
  55. package/src/intercom/result-intercom.ts +3 -2
  56. package/src/intercom/supervisor-ui.ts +2 -174
  57. package/src/missions/store.ts +25 -5
  58. package/src/profiles/profiles.ts +24 -21
  59. package/src/runs/background/active-async-capacity.ts +58 -8
  60. package/src/runs/background/async-execution.ts +143 -38
  61. package/src/runs/background/async-job-tracker.ts +11 -4
  62. package/src/runs/background/async-resume.ts +5 -2
  63. package/src/runs/background/await-async-run.ts +14 -9
  64. package/src/runs/background/binary-bootstrap.ts +2 -1
  65. package/src/runs/background/calendar-schedule.ts +90 -0
  66. package/src/runs/background/chain-root-attachment.ts +9 -5
  67. package/src/runs/background/fleet-view.ts +5 -5
  68. package/src/runs/background/notify.ts +185 -12
  69. package/src/runs/background/result-files.ts +116 -5
  70. package/src/runs/background/result-watcher.ts +99 -66
  71. package/src/runs/background/resume-guidance.ts +2 -2
  72. package/src/runs/background/run-child-session.ts +16 -2
  73. package/src/runs/background/run-id-resolver.ts +8 -5
  74. package/src/runs/background/run-status.ts +21 -16
  75. package/src/runs/background/runner-child-launch.ts +1 -0
  76. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  77. package/src/runs/background/scheduled-runs.ts +256 -61
  78. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  79. package/src/runs/background/subagent-runner.ts +32 -12
  80. package/src/runs/background/subagent-wait.ts +38 -19
  81. package/src/runs/background/terminal-run-index.ts +46 -1
  82. package/src/runs/background/wait-completions.ts +1 -0
  83. package/src/runs/background/wait-tool.ts +33 -23
  84. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  85. package/src/runs/foreground/async-stop-action.ts +48 -22
  86. package/src/runs/foreground/execution.ts +94 -52
  87. package/src/runs/foreground/foreground-history.ts +1 -0
  88. package/src/runs/foreground/subagent-executor.ts +207 -77
  89. package/src/runs/shared/child-commands.ts +2 -1
  90. package/src/runs/shared/child-hooks.ts +4 -3
  91. package/src/runs/shared/child-launch.ts +3 -0
  92. package/src/runs/shared/child-session.ts +41 -24
  93. package/src/runs/shared/child-tool-plan.ts +13 -26
  94. package/src/runs/shared/dynamic-fanout.ts +1 -1
  95. package/src/runs/shared/fork-command-result.ts +10 -0
  96. package/src/runs/shared/herdr-placed-run.ts +5 -4
  97. package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -3
  98. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  99. package/src/runs/shared/model-resolution.ts +30 -1
  100. package/src/runs/shared/nested-events.ts +5 -0
  101. package/src/runs/shared/parallel-handoff.ts +56 -8
  102. package/src/runs/shared/parallel-utils.ts +2 -0
  103. package/src/runs/shared/partial-output.ts +48 -0
  104. package/src/runs/shared/runner-launcher.ts +25 -0
  105. package/src/runs/shared/single-output.ts +53 -0
  106. package/src/runs/shared/structured-output.ts +14 -7
  107. package/src/runs/shared/subagent-control.ts +3 -3
  108. package/src/runs/shared/subagent-prompt-runtime.ts +47 -24
  109. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  110. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  111. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  112. package/src/runs/shared/worktree-lock.ts +29 -0
  113. package/src/runs/shared/worktree.ts +12 -1
  114. package/src/shared/atomic-json.ts +4 -2
  115. package/src/shared/edit-distance.ts +33 -0
  116. package/src/shared/file-lease.ts +74 -0
  117. package/src/shared/formatters.ts +1 -5
  118. package/src/shared/model-info.ts +22 -0
  119. package/src/shared/package-version.ts +17 -0
  120. package/src/shared/parent-wake.ts +79 -0
  121. package/src/shared/pruned-fork.ts +7 -1
  122. package/src/shared/runtime-module-path.ts +19 -0
  123. package/src/shared/settings-file-lease.ts +36 -0
  124. package/src/shared/types.ts +36 -2
  125. package/src/shared/utils.ts +8 -6
  126. package/src/slash/slash-commands.ts +3 -3
  127. package/src/slash/subagents-admin.ts +2 -1
  128. package/src/tui/fleet-native-transcript.ts +2 -0
  129. package/src/tui/fleet-transcript.ts +12 -3
  130. package/src/tui/fleet.ts +11 -8
  131. package/src/tui/render.ts +27 -19
  132. package/src/tui/subagent-messages.ts +305 -0
  133. package/src/watchdog/diff-tool.ts +2 -2
  134. package/src/watchdog/register-main.ts +2 -22
  135. package/src/watchdog/render.ts +2 -24
  136. package/src/watchdog/runtime.ts +6 -4
  137. package/src/watchdog/settings.ts +18 -13
  138. package/src/watchdog/tool-actions.ts +2 -2
  139. package/src/workflows/scripted-workflow.ts +20 -6
  140. package/src/workflows/workflow-resources.ts +11 -0
@@ -7,6 +7,7 @@ import { listMissions, missionRecordPath, resolveMissionStoreLocation } from "..
7
7
  import type { MissionStoreConfig } from "../missions/types.ts";
8
8
  import { resolveAuthorityDecision, type AuthorityPolicyConfig } from "../policy/authority.ts";
9
9
  import { DIRS, type Details, type SubagentState } from "../shared/types.ts";
10
+ import { tryLease } from "../shared/file-lease.ts";
10
11
  import { readStatus } from "../shared/utils.ts";
11
12
  import { resolveSubagentRunId } from "../runs/background/run-id-resolver.ts";
12
13
  import { resolveNodeExecutable } from "../shared/node-executable.ts";
@@ -17,6 +18,9 @@ import type { InspectorAction, InspectorContext, InspectorLaunch, InspectorParam
17
18
  export { INSPECTOR_ACTIONS } from "./types.ts";
18
19
  export type { InspectorAction, InspectorParams, InspectorPlugin } from "./types.ts";
19
20
 
21
+ // Covers a provider's slowest normal open (a 15 s split or launch plus its follow-up commands).
22
+ const INSPECTOR_LEASE_WAIT_MS = 30_000;
23
+
20
24
  function result(text: string, isError = false): AgentToolResult<Details> {
21
25
  const response: AgentToolResult<Details> = {
22
26
  content: [{ type: "text", text }],
@@ -116,6 +120,8 @@ export interface InspectorDispatcherDeps {
116
120
  runnerPath?: string;
117
121
  env?: NodeJS.ProcessEnv;
118
122
  plugins?: readonly InspectorPlugin[];
123
+ /** How long open and close wait for another open or close of the same target. */
124
+ leaseWaitMs?: number;
119
125
  }
120
126
  export async function handleInspectorAction(action: InspectorAction, params: InspectorParams, deps: InspectorDispatcherDeps): Promise<AgentToolResult<Details>> {
121
127
  const target = resolveTarget(params, deps);
@@ -129,20 +135,40 @@ export async function handleInspectorAction(action: InspectorAction, params: Ins
129
135
  if (deps.now) context.now = deps.now;
130
136
  if (action === "inspector.command") return result(launchFor(target, deps).displayCommand);
131
137
  const plugins = deps.plugins ?? [];
132
- if (action === "inspector.open") {
133
- for (const plugin of plugins) {
134
- if (await plugin.available(context)) return plugin.open(context, launchFor(target, deps), params);
135
- }
136
- return result("No inspector plugin is available. Start a supported inspector host, or use inspector.command for a standalone command.", true);
137
- }
138
- const owner = plugins.find((plugin) => plugin.owns(context));
139
- if (!owner) return result(`No inspector plugin owns this binding for async run ${target.runId}.`);
140
138
  if (action === "inspector.status") {
139
+ const owner = plugins.find((plugin) => plugin.owns(context));
140
+ if (!owner) return result(`No inspector plugin owns this binding for async run ${target.runId}.`);
141
141
  return owner.status
142
142
  ? owner.status(context)
143
143
  : result(`Inspector plugin '${owner.name}' does not support status for async run ${target.runId}.`, true);
144
144
  }
145
- return owner.close
146
- ? owner.close(context)
147
- : result(`Inspector plugin '${owner.name}' does not support close for async run ${target.runId}.`, true);
145
+ // Open and close read, create and delete the target's binding. Two callers at once, including another Pi
146
+ // process sharing the run directory, would each open a pane and one binding would overwrite the other.
147
+ const label = target.index === undefined ? "" : ` child ${target.index}`;
148
+ const lockPath = path.join(fs.realpathSync.native(target.asyncDir), `inspector-${target.index ?? "root"}.lock`);
149
+ const deadline = Date.now() + (deps.leaseWaitMs ?? INSPECTOR_LEASE_WAIT_MS);
150
+ let release = tryLease(lockPath);
151
+ while (!release) {
152
+ if (deps.signal?.aborted) return result(`Inspector ${action} for async run ${target.runId}${label} was cancelled while waiting for another inspector open or close to finish.`, true);
153
+ if (Date.now() >= deadline) return result(`Another inspector open or close for async run ${target.runId}${label} is still in progress. Try again when it finishes.`, true);
154
+ await new Promise((resolve) => setTimeout(resolve, 50));
155
+ release = tryLease(lockPath);
156
+ }
157
+ try {
158
+ // The wait may end with the lease in the same tick the caller cancelled; never act for a cancelled caller.
159
+ if (deps.signal?.aborted) return result(`Inspector ${action} for async run ${target.runId}${label} was cancelled while waiting for another inspector open or close to finish.`, true);
160
+ if (action === "inspector.open") {
161
+ for (const plugin of plugins) {
162
+ if (await plugin.available(context)) return await plugin.open(context, launchFor(target, deps), params);
163
+ }
164
+ return result("No inspector plugin is available. Start a supported inspector host, or use inspector.command for a standalone command.", true);
165
+ }
166
+ const owner = plugins.find((plugin) => plugin.owns(context));
167
+ if (!owner) return result(`No inspector plugin owns this binding for async run ${target.runId}.`);
168
+ return owner.close
169
+ ? await owner.close(context)
170
+ : result(`Inspector plugin '${owner.name}' does not support close for async run ${target.runId}.`, true);
171
+ } finally {
172
+ release();
173
+ }
148
174
  }
@@ -2,6 +2,7 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { INSPECTOR_REGISTER_EVENT, type InspectorRegistrationRequest } from "../api/inspectors.ts";
3
3
  import { createHerdrInspectorPlugin } from "./herdr/plugin.ts";
4
4
  import { createGhosttyInspectorPlugin } from "./ghostty/plugin.ts";
5
+ import { createTmuxInspectorPlugin } from "./tmux/plugin.ts";
5
6
  import type { InspectorPlugin } from "./types.ts";
6
7
 
7
8
  type InspectorOwner = Pick<ExtensionAPI, "events">;
@@ -11,7 +12,7 @@ const registries = new WeakMap<InspectorOwner["events"], { plugins: Map<string,
11
12
 
12
13
  /** Built-ins retain host preference; external providers follow registration order. */
13
14
  export function getInspectorPlugins(pi: InspectorOwner): readonly InspectorPlugin[] {
14
- return [createHerdrInspectorPlugin(), createGhosttyInspectorPlugin(), ...(registries.get(pi.events)?.plugins.values() ?? [])];
15
+ return [createHerdrInspectorPlugin(), createGhosttyInspectorPlugin(), createTmuxInspectorPlugin(), ...(registries.get(pi.events)?.plugins.values() ?? [])];
15
16
  }
16
17
 
17
18
  /** Registrations live while any owner runtime listens on this bus; child runtimes use their own bus. */
@@ -23,7 +24,7 @@ export function registerInspectorEventListener(pi: InspectorOwner): () => void {
23
24
  }
24
25
  registry.owners += 1;
25
26
  const { plugins } = registry;
26
- const builtinNames = new Set([createHerdrInspectorPlugin().name, createGhosttyInspectorPlugin().name]);
27
+ const builtinNames = new Set([createHerdrInspectorPlugin().name, createGhosttyInspectorPlugin().name, createTmuxInspectorPlugin().name]);
27
28
  /* oxlint-disable anti-slop/no-runtime-typeof -- This listener validates the untyped event-bus boundary, including callable provider methods. */
28
29
  const unsubscribe = pi.events.on(INSPECTOR_REGISTER_EVENT, (rawRequest) => {
29
30
  if (!rawRequest || typeof rawRequest !== "object" || Array.isArray(rawRequest)) return;
@@ -0,0 +1,204 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
4
+ import { writeAtomicJson } from "../../shared/atomic-json.ts";
5
+ import type { Details } from "../../shared/types.ts";
6
+ import type { InspectorContext, InspectorLaunch, InspectorTarget } from "../types.ts";
7
+ import type { TmuxClient, TmuxErrorCode } from "./client.ts";
8
+
9
+ export interface TmuxInspectorBinding {
10
+ schemaVersion: 1;
11
+ kind: "tmux-inspector";
12
+ runId: string;
13
+ asyncDir: string;
14
+ childIndex?: number;
15
+ paneId: string;
16
+ serverPid?: string;
17
+ openedAt: string;
18
+ tmuxVersion?: string;
19
+ missionId?: string;
20
+ missionPath?: string;
21
+ command: string;
22
+ }
23
+
24
+ export function bindingPath(asyncDir: string, index?: number): string {
25
+ return path.join(asyncDir, "inspectors", `tmux${index === undefined ? "" : `-${index}`}.json`);
26
+ }
27
+
28
+ function parse(value: unknown): TmuxInspectorBinding | undefined {
29
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
30
+ const binding = value as Partial<TmuxInspectorBinding>;
31
+ if (binding.schemaVersion !== 1
32
+ || binding.kind !== "tmux-inspector"
33
+ || (binding.childIndex !== undefined && (!Number.isInteger(binding.childIndex) || binding.childIndex < 0))
34
+ || typeof binding.runId !== "string"
35
+ || typeof binding.asyncDir !== "string"
36
+ || typeof binding.paneId !== "string"
37
+ || (binding.serverPid !== undefined && typeof binding.serverPid !== "string")
38
+ || typeof binding.openedAt !== "string"
39
+ || typeof binding.command !== "string") return undefined;
40
+ return binding as TmuxInspectorBinding;
41
+ }
42
+
43
+ export function readTmuxInspectorBinding(asyncDir: string, index?: number): TmuxInspectorBinding | undefined {
44
+ try {
45
+ return parse(JSON.parse(fs.readFileSync(bindingPath(asyncDir, index), "utf8")));
46
+ } catch {
47
+ return undefined;
48
+ }
49
+ }
50
+
51
+ /** Read a binding only when it belongs to the requested inspector target. */
52
+ export function readTmuxInspectorBindingForTarget(target: InspectorTarget): TmuxInspectorBinding | undefined {
53
+ const binding = readTmuxInspectorBinding(target.asyncDir, target.index);
54
+ if (!binding || binding.runId !== target.runId || binding.childIndex !== target.index) return undefined;
55
+ try {
56
+ if (fs.realpathSync(binding.asyncDir) !== fs.realpathSync(target.asyncDir)) return undefined;
57
+ } catch {
58
+ return undefined;
59
+ }
60
+ return binding;
61
+ }
62
+
63
+ function result(text: string, isError = false): AgentToolResult<Details> {
64
+ return {
65
+ content: [{ type: "text", text }],
66
+ ...(isError ? { isError: true } : {}),
67
+ details: { mode: "management", results: [] },
68
+ };
69
+ }
70
+
71
+ function errorText(input: { code: TmuxErrorCode; message: string }): string {
72
+ return `tmux inspector error (${input.code}): ${input.message}`;
73
+ }
74
+
75
+ /** Pane option carrying this run's ownership marker; a pane without it is never ours to kill. */
76
+ const OWNER_OPTION = "@pi-subagents-inspector";
77
+
78
+ function ownerTag(runId: string, index?: number): string {
79
+ return `pi-subagents:${runId}:${index ?? "-"}`;
80
+ }
81
+
82
+ type PaneProbe =
83
+ | { state: "alive" }
84
+ | { state: "gone" }
85
+ | { state: "stale" }
86
+ | { state: "error"; error: { code: TmuxErrorCode; message: string } };
87
+
88
+ /** Verify the pane is alive AND ours: list-panes fails on a gone pane, while display-message silently returns empty on tmux 3.3+; the marker survives pane-id reuse after a server restart. */
89
+ async function probePane(client: TmuxClient, binding: TmuxInspectorBinding, signal?: AbortSignal): Promise<PaneProbe> {
90
+ const probe = await client.run(["list-panes", "-t", binding.paneId, "-F", `#{pane_id}|#{${OWNER_OPTION}}|#{pid}`], { timeoutMs: 5_000, signal });
91
+ if (!probe.ok) return probe.error.code === "PANE_GONE" ? { state: "gone" } : { state: "error", error: probe.error };
92
+ // A pane target resolves to its window, so list-panes reports every pane in it; read the target's line.
93
+ const line = probe.data.split(/\r?\n/).map((entry) => entry.trim()).find((entry) => entry.startsWith(`${binding.paneId}|`));
94
+ if (!line) return { state: "gone" };
95
+ const [tag, serverPid] = line.split("|").slice(1);
96
+ if (tag !== ownerTag(binding.runId, binding.childIndex)) return { state: "stale" };
97
+ if (binding.serverPid !== undefined && binding.serverPid !== serverPid) return { state: "stale" };
98
+ return { state: "alive" };
99
+ }
100
+
101
+ export async function openTmuxInspector(
102
+ context: InspectorContext,
103
+ launch: InspectorLaunch,
104
+ focus: boolean,
105
+ client: TmuxClient,
106
+ ): Promise<AgentToolResult<Details>> {
107
+ const detected = await client.run(["-V"], { timeoutMs: 3_000, signal: context.signal });
108
+ if (!detected.ok) return result(errorText(detected.error), true);
109
+ const existing = readTmuxInspectorBindingForTarget(context.target);
110
+ if (existing) {
111
+ const probe = await probePane(client, existing, context.signal);
112
+ if (probe.state === "alive") {
113
+ if (focus) {
114
+ const refocus = await client.run(["select-pane", "-t", existing.paneId], { timeoutMs: 5_000, signal: context.signal });
115
+ if (!refocus.ok) return result(errorText(refocus.error), true);
116
+ }
117
+ return result(`tmux inspector pane ${existing.paneId} is already open for async run ${context.target.runId}. Ctrl-C inside the pane closes it.`);
118
+ }
119
+ // A gone or stale binding falls through to a fresh split; other failures must not open a duplicate.
120
+ if (probe.state === "error") return result(errorText(probe.error), true);
121
+ }
122
+ // The split activates the new pane; when focus is not requested, remember the
123
+ // active pane so it can be re-selected after the split.
124
+ const originalPane = focus ? undefined : await client.run(["display-message", "-p", "#{pane_id}"], { timeoutMs: 5_000, signal: context.signal });
125
+ const split = await client.run([
126
+ "split-window", "-h", "-P", "-F", "#{pane_id}",
127
+ "-c", context.target.status.cwd ?? context.cwd,
128
+ launch.displayCommand,
129
+ ], { timeoutMs: 15_000, signal: context.signal });
130
+ if (!split.ok) return result(errorText(split.error), true);
131
+ const id = split.data;
132
+ if (!id.startsWith("%")) return result(errorText({ code: "TMUX_ERROR", message: `split-window returned no pane id ('${id}').` }), true);
133
+ if (context.signal?.aborted) {
134
+ await client.run(["kill-pane", "-t", id], { timeoutMs: 5_000 });
135
+ return result(errorText({ code: "TIMEOUT", message: `tmux inspector open was aborted.` }), true);
136
+ }
137
+ if (originalPane?.ok && originalPane.data) {
138
+ await client.run(["select-pane", "-t", originalPane.data], { timeoutMs: 5_000, signal: context.signal });
139
+ }
140
+ // Stamp and cleanup run without the signal: aborting mid-stamp must not orphan an unstamped pane.
141
+ const stamp = await client.run(["set-option", "-p", "-t", id, OWNER_OPTION, ownerTag(context.target.runId, context.target.index)], { timeoutMs: 5_000 });
142
+ if (!stamp.ok) {
143
+ await client.run(["kill-pane", "-t", id], { timeoutMs: 5_000 });
144
+ return result(errorText(stamp.error), true);
145
+ }
146
+ const server = await client.run(["display-message", "-p", "#{pid}"], { timeoutMs: 5_000 });
147
+ const binding: TmuxInspectorBinding = {
148
+ schemaVersion: 1,
149
+ kind: "tmux-inspector",
150
+ runId: context.target.runId,
151
+ asyncDir: context.target.asyncDir,
152
+ ...(context.target.index === undefined ? {} : { childIndex: context.target.index }),
153
+ paneId: id,
154
+ ...(server.ok ? { serverPid: server.data } : {}),
155
+ openedAt: (context.now?.() ?? new Date()).toISOString(),
156
+ tmuxVersion: detected.data,
157
+ ...(launch.mission ? { missionId: launch.mission.id, missionPath: launch.mission.path } : {}),
158
+ command: launch.displayCommand,
159
+ };
160
+ try {
161
+ writeAtomicJson(bindingPath(context.target.asyncDir, context.target.index), binding);
162
+ } catch (error) {
163
+ // Without a binding, status and close cannot find the pane, so remove it before reporting the failure.
164
+ await client.run(["kill-pane", "-t", id], { timeoutMs: 5_000 });
165
+ throw error;
166
+ }
167
+ return result(`Opened read-only tmux inspector pane ${id} for async run ${context.target.runId}. Closing the pane does not stop the run.\nControls inside the pane: steer <message>, stop, status. Ctrl-C closes the pane.`);
168
+ }
169
+
170
+ export async function statusTmuxInspector(context: InspectorContext, client: TmuxClient): Promise<AgentToolResult<Details>> {
171
+ const binding = readTmuxInspectorBindingForTarget(context.target);
172
+ if (!binding) {
173
+ return result(`No tmux inspector binding exists for async run ${context.target.runId}${context.target.index === undefined ? "" : ` child ${context.target.index}`}.`);
174
+ }
175
+ const label = context.target.index === undefined ? "" : ` child ${context.target.index}`;
176
+ const probe = await probePane(client, binding, context.signal);
177
+ if (probe.state === "error") return result(errorText(probe.error), true);
178
+ if (probe.state === "stale") {
179
+ return result(`tmux inspector pane ${binding.paneId} (run ${context.target.runId}${label}) is alive but does not carry this run's inspector marker; it may belong to other work after a tmux server restart.\nBinding: ${bindingPath(context.target.asyncDir, context.target.index)}\nRun state remains authoritative: ${context.target.status.state}.`);
180
+ }
181
+ if (probe.state === "gone") {
182
+ return result(`tmux inspector pane ${binding.paneId} (run ${context.target.runId}${label}) no longer exists.\nBinding: ${bindingPath(context.target.asyncDir, context.target.index)}\nRun state remains authoritative: ${context.target.status.state}.`);
183
+ }
184
+ return result(`tmux inspector pane ${binding.paneId} is open for async run ${context.target.runId}${label}.\nRun state: ${context.target.status.state}\nBinding: ${bindingPath(context.target.asyncDir, context.target.index)}`);
185
+ }
186
+
187
+ export async function closeTmuxInspector(context: InspectorContext, client: TmuxClient): Promise<AgentToolResult<Details>> {
188
+ const binding = readTmuxInspectorBindingForTarget(context.target);
189
+ if (!binding) return result(`No tmux inspector binding exists for async run ${context.target.runId}.`);
190
+ const probe = await probePane(client, binding, context.signal);
191
+ if (probe.state === "error") return result(errorText(probe.error), true);
192
+ if (probe.state === "stale") {
193
+ fs.rmSync(bindingPath(context.target.asyncDir, context.target.index), { force: true });
194
+ return result(`tmux inspector pane ${binding.paneId} does not carry this run's inspector marker; removed the stale binding without killing the pane.`);
195
+ }
196
+ if (probe.state === "alive") {
197
+ const closed = await client.run(["kill-pane", "-t", binding.paneId], { timeoutMs: 10_000, signal: context.signal });
198
+ if (!closed.ok && closed.error.code !== "PANE_GONE") {
199
+ return result(errorText(closed.error), true);
200
+ }
201
+ }
202
+ fs.rmSync(bindingPath(context.target.asyncDir, context.target.index), { force: true });
203
+ return result(`Closed tmux inspector pane ${binding.paneId} for async run ${context.target.runId}. The subagent run was not stopped.`);
204
+ }
@@ -0,0 +1,85 @@
1
+ import { execFile } from "node:child_process";
2
+
3
+ export type TmuxErrorCode =
4
+ | "TMUX_UNAVAILABLE"
5
+ | "TMUX_ERROR"
6
+ | "PANE_GONE"
7
+ | "TIMEOUT";
8
+
9
+ export type TmuxResult<T> =
10
+ | { ok: true; data: T }
11
+ | { ok: false; error: { code: TmuxErrorCode; message: string; details?: unknown } };
12
+
13
+ export interface TmuxClient {
14
+ run(args: string[], options?: { timeoutMs?: number; signal?: AbortSignal }): Promise<TmuxResult<string>>;
15
+ }
16
+
17
+ type ExecTmux = (
18
+ file: string,
19
+ args: readonly string[],
20
+ options: { timeout: number; signal?: AbortSignal },
21
+ callback: (error: Error | null, stdout: string, stderr?: string) => void,
22
+ ) => unknown;
23
+
24
+ function error(code: TmuxErrorCode, message: string, details?: unknown): TmuxResult<never> {
25
+ return { ok: false, error: { code, message, ...(details !== undefined ? { details } : {}) } };
26
+ }
27
+
28
+ function failureText(execError: Error, stderr?: string): string {
29
+ const direct = stderr?.split(/\r?\n/).map((line) => line.trim()).find(Boolean);
30
+ if (direct) return direct;
31
+ const lines = execError.message.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
32
+ const withoutPrefix = lines.filter((line) => !/^Command failed:/.test(line));
33
+ return withoutPrefix[0] ?? "tmux failed.";
34
+ }
35
+
36
+ function classifyFailure(text: string): TmuxErrorCode {
37
+ const lower = text.toLowerCase();
38
+ if (lower.includes("can't find pane") || lower.includes("can't find window")) return "PANE_GONE";
39
+ if (lower.includes("no server running") || lower.includes("no current client")) return "TMUX_UNAVAILABLE";
40
+ return "TMUX_ERROR";
41
+ }
42
+
43
+ export function createTmuxClient(options: { bin?: string; exec?: ExecTmux } = {}): TmuxClient {
44
+ const bin = options.bin ?? process.env.TMUX_BIN ?? "tmux";
45
+ const execImpl = options.exec ?? execFile;
46
+ return {
47
+ run(args: string[], runOptions: { timeoutMs?: number; signal?: AbortSignal } = {}): Promise<TmuxResult<string>> {
48
+ return new Promise((resolve) => {
49
+ let settled = false;
50
+ const abort = () => finish(error("TIMEOUT", `tmux command '${args.join(" ")}' was aborted.`));
51
+ const finish = (result: TmuxResult<string>) => {
52
+ if (settled) return;
53
+ settled = true;
54
+ runOptions.signal?.removeEventListener("abort", abort);
55
+ resolve(result);
56
+ };
57
+ if (runOptions.signal?.aborted) {
58
+ abort();
59
+ return;
60
+ }
61
+ runOptions.signal?.addEventListener("abort", abort, { once: true });
62
+ execImpl(bin, args, { timeout: runOptions.timeoutMs ?? 10_000, signal: runOptions.signal }, (execError, stdout, stderr) => {
63
+ if (execError) {
64
+ const code = (execError as NodeJS.ErrnoException).code;
65
+ if (code === "ENOENT") {
66
+ finish(error("TMUX_UNAVAILABLE", "tmux is not installed or is not on PATH."));
67
+ return;
68
+ }
69
+ // Node reports its own timeout expiry as a killed child, not as our abort listener firing.
70
+ const killed = execError as NodeJS.ErrnoException & { killed?: boolean; signal?: string };
71
+ if (killed.killed === true || killed.signal) {
72
+ finish(error("TIMEOUT", `tmux command '${args.join(" ")}' timed out.`));
73
+ return;
74
+ }
75
+ const text = failureText(execError, stderr);
76
+ const exitCode = Number(code);
77
+ finish(error(exitCode === 127 ? "TMUX_UNAVAILABLE" : classifyFailure(text), text));
78
+ return;
79
+ }
80
+ finish({ ok: true, data: stdout.trim() });
81
+ });
82
+ });
83
+ },
84
+ };
85
+ }
@@ -0,0 +1,21 @@
1
+ import { closeTmuxInspector, openTmuxInspector, readTmuxInspectorBindingForTarget, statusTmuxInspector } from "./actions.ts";
2
+ import { createTmuxClient, type TmuxClient } from "./client.ts";
3
+ import type { InspectorPlugin } from "../types.ts";
4
+
5
+ export interface TmuxPluginDeps {
6
+ platform?: NodeJS.Platform;
7
+ client?: TmuxClient;
8
+ }
9
+
10
+ export function createTmuxInspectorPlugin(deps: TmuxPluginDeps = {}): InspectorPlugin {
11
+ const platform = deps.platform ?? process.platform;
12
+ const client = deps.client ?? createTmuxClient();
13
+ return {
14
+ name: "tmux",
15
+ available: (context) => platform !== "win32" && Boolean(context.env.TMUX),
16
+ owns: (context) => readTmuxInspectorBindingForTarget(context.target) !== undefined,
17
+ open: (context, launch, params) => openTmuxInspector(context, launch, params.focus === true, client),
18
+ status: (context) => statusTmuxInspector(context, client),
19
+ close: (context) => closeTmuxInspector(context, client),
20
+ };
21
+ }
@@ -35,7 +35,6 @@ export interface HerdrStatusRun {
35
35
  /** Explicit launch/workflow label only; raw prompts never enter pane metadata. */
36
36
  taskLabel?: string;
37
37
  needsAttention?: boolean;
38
- attentionLabel?: string;
39
38
  }
40
39
 
41
40
  export interface HerdrStatusBridgeOptions {
@@ -124,15 +123,10 @@ function completedRunId(data: unknown): string | undefined {
124
123
  return typeof id === "string" && id.length > 0 ? id : undefined;
125
124
  }
126
125
 
127
- function attentionNotice(data: unknown): { runId: string; label: string } | undefined {
126
+ function attentionRunId(data: unknown): string | undefined {
128
127
  if (!isRecord(data) || data.source !== "async" || !isRecord(data.event)) return undefined;
129
128
  if (data.event.type !== "needs_attention" || typeof data.event.runId !== "string" || !data.event.runId) return undefined;
130
- const label = typeof data.noticeText === "string" && data.noticeText
131
- ? data.noticeText
132
- : typeof data.event.message === "string" && data.event.message
133
- ? data.event.message
134
- : "subagent needs attention";
135
- return { runId: data.event.runId, label };
129
+ return data.event.runId;
136
130
  }
137
131
 
138
132
  export function registerHerdrStatusBridge(options: HerdrStatusBridgeOptions): HerdrStatusBridge {
@@ -144,15 +138,15 @@ export function registerHerdrStatusBridge(options: HerdrStatusBridgeOptions): He
144
138
  const refreshMs = options.refreshMs ?? DEFAULT_REFRESH_MS;
145
139
  const timers = options.timers ?? { setInterval, clearInterval };
146
140
  const runs = new Map<string, HerdrStatusRun>();
147
- const attentionLabels = new Map<string, string>();
141
+ // Child attention is addressed to the parent agent, so it only adds ⚠ to the
142
+ // metadata label and never raises Herdr's human-blocked state.
143
+ const attentionRuns = new Set<string>();
148
144
  const acknowledgedAttention = new Set<string>();
149
145
  const subscriptions: Array<() => void> = [];
150
146
  let rootSession = false;
151
147
  let published = false;
152
148
  let busyRaised = false;
153
149
  let busyLabel: string | undefined;
154
- let blockedRaised = false;
155
- let blockedLabel: string | undefined;
156
150
  let disposed = false;
157
151
  let pendingReport: readonly string[] | undefined;
158
152
  let draining = false;
@@ -176,7 +170,7 @@ export function registerHerdrStatusBridge(options: HerdrStatusBridgeOptions): He
176
170
  const paneText = panes > 0 ? ` · ${panes} pane${panes === 1 ? "" : "s"}` : "";
177
171
  const task = activeTaskLabel();
178
172
  const taskText = task ? ` · ${task}` : "";
179
- const attention = includeAttention && attentionLabels.size > 0 ? " ⚠" : "";
173
+ const attention = includeAttention && attentionRuns.size > 0 ? " ⚠" : "";
180
174
  return `⏳ ${activeCount} subagent${activeCount === 1 ? "" : "s"}${who}${paneText}${taskText}${attention}`;
181
175
  };
182
176
 
@@ -186,7 +180,7 @@ export function registerHerdrStatusBridge(options: HerdrStatusBridgeOptions): He
186
180
  const activeCount = activeSubagentCount();
187
181
  const task = boundedTaskLabel(activeTaskLabel(), MAX_TITLE_TASK_CHARS);
188
182
  const target = task ?? (activeCount === 1 && agentNames.length === 1 ? agentNames[0]! : String(activeCount));
189
- return `⏳${target}${attentionLabels.size > 0 ? "⚠" : ""}`;
183
+ return `⏳${target}${attentionRuns.size > 0 ? "⚠" : ""}`;
190
184
  };
191
185
 
192
186
  const enqueue = (args: readonly string[]): void => {
@@ -273,44 +267,22 @@ export function registerHerdrStatusBridge(options: HerdrStatusBridgeOptions): He
273
267
  }
274
268
  };
275
269
 
276
- const syncBlocked = (): void => {
277
- if (!enabled || !rootSession || disposed) return;
278
- const nextLabel = [...attentionLabels.values()].at(-1);
279
- if (nextLabel !== undefined) {
280
- if (blockedRaised && blockedLabel === nextLabel) return;
281
- // Herdr's sibling overlay contract is counted. Lower before changing
282
- // the active label so this bridge continues to own exactly one count.
283
- if (blockedRaised) options.events.emit("herdr:blocked", { active: false });
284
- blockedRaised = true;
285
- blockedLabel = nextLabel;
286
- options.events.emit("herdr:blocked", { active: true, label: nextLabel });
287
- return;
288
- }
289
- if (blockedRaised) {
290
- blockedRaised = false;
291
- blockedLabel = undefined;
292
- options.events.emit("herdr:blocked", { active: false });
293
- }
294
- };
295
-
296
270
  const clearAttention = (): void => {
297
- attentionLabels.clear();
298
- syncBlocked();
271
+ attentionRuns.clear();
299
272
  publish();
300
273
  };
301
274
 
302
- const raiseAttention = (runId: string, labelText: string): void => {
303
- if (!rootSession || attentionLabels.has(runId)) return;
275
+ const raiseAttention = (runId: string): void => {
276
+ if (!rootSession || attentionRuns.has(runId)) return;
304
277
  acknowledgedAttention.delete(runId);
305
- attentionLabels.set(runId, labelText);
306
- syncBlocked();
278
+ attentionRuns.add(runId);
307
279
  publish();
308
280
  };
309
281
 
310
282
  const replaceRuns = (nextRuns: Iterable<HerdrStatusRun>): void => {
311
- const nextAttention = new Map<string, string>();
312
283
  const activeIds = new Set<string>();
313
284
  runs.clear();
285
+ attentionRuns.clear();
314
286
  for (const run of nextRuns) {
315
287
  if (!run || typeof run.id !== "string" || !run.id) continue;
316
288
  activeIds.add(run.id);
@@ -320,17 +292,14 @@ export function registerHerdrStatusBridge(options: HerdrStatusBridgeOptions): He
320
292
  if (!run.needsAttention) {
321
293
  acknowledgedAttention.delete(run.id);
322
294
  } else if (!acknowledgedAttention.has(run.id)) {
323
- nextAttention.set(run.id, run.attentionLabel || attentionLabels.get(run.id) || "subagent needs attention");
295
+ attentionRuns.add(run.id);
324
296
  }
325
297
  }
326
298
  for (const id of acknowledgedAttention) {
327
299
  if (!activeIds.has(id)) acknowledgedAttention.delete(id);
328
300
  }
329
- attentionLabels.clear();
330
- for (const [id, labelText] of nextAttention) attentionLabels.set(id, labelText);
331
301
  syncBusy();
332
302
  syncRefreshTimer();
333
- syncBlocked();
334
303
  publish();
335
304
  };
336
305
 
@@ -371,22 +340,22 @@ export function registerHerdrStatusBridge(options: HerdrStatusBridgeOptions): He
371
340
  const id = completedRunId(data);
372
341
  if (!id || !runs.delete(id)) return;
373
342
  acknowledgedAttention.delete(id);
374
- if (attentionLabels.delete(id)) syncBlocked();
343
+ attentionRuns.delete(id);
375
344
  syncBusy();
376
345
  syncRefreshTimer();
377
346
  publish();
378
347
  });
379
348
  subscribe(SUBAGENT_CONTROL_EVENT, (data) => {
380
349
  if (!rootSession) return;
381
- const notice = attentionNotice(data);
382
- if (!notice || !runs.has(notice.runId)) return;
383
- raiseAttention(notice.runId, notice.label);
350
+ const runId = attentionRunId(data);
351
+ if (!runId || !runs.has(runId)) return;
352
+ raiseAttention(runId);
384
353
  });
385
354
  }
386
355
 
387
356
  return {
388
357
  agentStarted() {
389
- for (const id of attentionLabels.keys()) acknowledgedAttention.add(id);
358
+ for (const id of attentionRuns) acknowledgedAttention.add(id);
390
359
  clearAttention();
391
360
  },
392
361
  sessionStarted({ hasUI, runs: restoredRuns }) {