@xzzpig/pi-subagents 0.19.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.
- package/CHANGELOG.md +214 -0
- package/README.md +1 -1
- package/agents/oracle.md +8 -19
- package/agents/researcher.md +0 -3
- package/agents/reviewer.md +17 -61
- package/agents/scout.md +1 -4
- package/agents/worker.md +8 -25
- package/docs/agents.md +86 -11
- package/docs/configuration.md +68 -7
- package/docs/extension-api.md +37 -12
- package/docs/fork-extensions.md +1 -0
- package/docs/missions.md +48 -17
- package/docs/models.md +7 -3
- package/docs/observability.md +18 -8
- package/docs/tool-reference.md +138 -80
- package/docs/watchdog.md +8 -6
- package/docs/workflows.md +18 -9
- package/index.ts +5 -0
- package/package.json +5 -3
- package/prompts/council.md +1 -1
- package/skills/pi-subagents/SKILL.md +1 -1
- package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
- package/skills/pi-subagents/references/execution-controls.md +16 -16
- package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
- package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
- package/src/agents/advertised-agent-prompt.ts +9 -1
- package/src/agents/agent-management.ts +4 -0
- package/src/agents/agent-memory.ts +3 -3
- package/src/agents/agent-scope.ts +4 -0
- package/src/agents/agent-serializer.ts +8 -1
- package/src/agents/agents.ts +224 -122
- package/src/api/preflight.ts +50 -5
- package/src/extension/config.ts +24 -2
- package/src/extension/context-injection.ts +6 -1
- package/src/extension/control-notices.ts +1 -9
- package/src/extension/declaration-pinning.ts +164 -0
- package/src/extension/doctor.ts +7 -10
- package/src/extension/fanout-child.ts +7 -8
- package/src/extension/index.ts +134 -145
- package/src/extension/public-execution.ts +3 -0
- package/src/extension/reply-workflow-script.ts +21 -12
- package/src/extension/rpc.ts +12 -7
- package/src/extension/schemas.ts +39 -33
- package/src/extension/subagent-guide.ts +86 -6
- package/src/extension/subagent-options.ts +47 -0
- package/src/extension/tool-activation.ts +3 -2
- package/src/extension/tool-description.ts +51 -68
- package/src/inspectors/actions.ts +37 -11
- package/src/inspectors/plugins.ts +3 -2
- package/src/inspectors/tmux/actions.ts +204 -0
- package/src/inspectors/tmux/client.ts +85 -0
- package/src/inspectors/tmux/plugin.ts +21 -0
- package/src/integrations/herdr-status.ts +18 -49
- package/src/integrations/program-status.ts +215 -0
- package/src/intercom/native-supervisor-channel.ts +77 -4
- package/src/intercom/result-intercom.ts +3 -2
- package/src/intercom/supervisor-ui.ts +2 -174
- package/src/missions/goal-driver.ts +44 -31
- package/src/missions/store.ts +35 -6
- package/src/profiles/profiles.ts +29 -23
- package/src/runs/background/active-async-capacity.ts +58 -8
- package/src/runs/background/async-execution.ts +231 -44
- package/src/runs/background/async-job-tracker.ts +12 -4
- package/src/runs/background/async-resume.ts +5 -2
- package/src/runs/background/await-async-run.ts +18 -11
- package/src/runs/background/binary-bootstrap.ts +2 -1
- package/src/runs/background/calendar-schedule.ts +90 -0
- package/src/runs/background/chain-root-attachment.ts +9 -5
- package/src/runs/background/control-channel.ts +43 -0
- package/src/runs/background/fleet-view.ts +5 -5
- package/src/runs/background/notify.ts +185 -12
- package/src/runs/background/result-files.ts +116 -5
- package/src/runs/background/result-watcher.ts +99 -66
- package/src/runs/background/resume-guidance.ts +2 -2
- package/src/runs/background/run-child-session.ts +29 -8
- package/src/runs/background/run-id-resolver.ts +8 -5
- package/src/runs/background/run-status.ts +21 -16
- package/src/runs/background/runner-aliases.ts +7 -4
- package/src/runs/background/runner-child-launch.ts +1 -0
- package/src/runs/background/runner-http-dispatcher.ts +3 -0
- package/src/runs/background/scheduled-runs.ts +282 -72
- package/src/runs/background/stale-run-reconciler.ts +13 -2
- package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
- package/src/runs/background/subagent-runner.ts +75 -16
- package/src/runs/background/subagent-wait.ts +38 -19
- package/src/runs/background/terminal-run-index.ts +46 -1
- package/src/runs/background/wait-completions.ts +1 -0
- package/src/runs/background/wait-tool.ts +33 -23
- package/src/runs/background/workflow-terminal-proof.ts +39 -22
- package/src/runs/foreground/async-stop-action.ts +48 -22
- package/src/runs/foreground/command-action.ts +41 -0
- package/src/runs/foreground/execution.ts +109 -58
- package/src/runs/foreground/foreground-history.ts +1 -0
- package/src/runs/foreground/subagent-executor.ts +270 -89
- package/src/runs/shared/child-commands.ts +229 -0
- package/src/runs/shared/child-hooks.ts +4 -3
- package/src/runs/shared/child-launch.ts +3 -0
- package/src/runs/shared/child-session.ts +131 -40
- package/src/runs/shared/child-tool-plan.ts +14 -27
- package/src/runs/shared/claude-code-adapter.ts +157 -2
- package/src/runs/shared/dynamic-fanout.ts +2 -2
- package/src/runs/shared/external-cli-preflight.ts +54 -6
- package/src/runs/shared/external-cli-runner.ts +5 -1
- package/src/runs/shared/fork-command-result.ts +10 -0
- package/src/runs/shared/herdr-placed-run.ts +5 -4
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +8 -5
- package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
- package/src/runs/shared/model-resolution.ts +39 -2
- package/src/runs/shared/nested-events.ts +5 -0
- package/src/runs/shared/parallel-handoff.ts +56 -8
- package/src/runs/shared/parallel-utils.ts +4 -0
- package/src/runs/shared/partial-output.ts +48 -0
- package/src/runs/shared/run-history.ts +87 -0
- package/src/runs/shared/runner-launcher.ts +25 -0
- package/src/runs/shared/single-output.ts +53 -0
- package/src/runs/shared/structured-output.ts +14 -7
- package/src/runs/shared/subagent-control.ts +33 -18
- package/src/runs/shared/subagent-prompt-runtime.ts +59 -30
- package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
- package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
- package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
- package/src/runs/shared/worktree-lock.ts +29 -0
- package/src/runs/shared/worktree.ts +12 -1
- package/src/shared/atomic-json.ts +4 -2
- package/src/shared/edit-distance.ts +33 -0
- package/src/shared/file-lease.ts +74 -0
- package/src/shared/formatters.ts +1 -5
- package/src/shared/model-info.ts +22 -0
- package/src/shared/package-version.ts +17 -0
- package/src/shared/parent-wake.ts +79 -0
- package/src/shared/pruned-fork.ts +7 -1
- package/src/shared/required-child-extensions.ts +39 -5
- package/src/shared/runtime-module-path.ts +19 -0
- package/src/shared/settings-file-lease.ts +36 -0
- package/src/shared/types.ts +42 -3
- package/src/shared/utils.ts +8 -6
- package/src/slash/slash-commands.ts +3 -3
- package/src/slash/subagent-cost.ts +9 -5
- package/src/slash/subagents-admin.ts +2 -1
- package/src/tui/fleet-native-transcript.ts +2 -0
- package/src/tui/fleet-transcript.ts +12 -3
- package/src/tui/fleet.ts +11 -8
- package/src/tui/render.ts +28 -20
- package/src/tui/subagent-messages.ts +305 -0
- package/src/watchdog/diff-tool.ts +2 -2
- package/src/watchdog/register-main.ts +2 -22
- package/src/watchdog/render.ts +2 -24
- package/src/watchdog/runtime.ts +6 -4
- package/src/watchdog/settings.ts +18 -13
- package/src/watchdog/tool-actions.ts +2 -2
- package/src/workflows/scripted-workflow.ts +20 -6
- package/src/workflows/workflow-receipt.ts +2 -2
- package/src/workflows/workflow-resources.ts +18 -4
|
@@ -6,8 +6,6 @@ import { resolveDisabledFeatureSurface, type DisabledFeatureSurface, type Subage
|
|
|
6
6
|
|
|
7
7
|
const CUSTOM_TOOL_DESCRIPTION_FILE = "subagent-tool-description.md";
|
|
8
8
|
const CUSTOM_TOOL_DESCRIPTION_MAX_BYTES = 50 * 1024;
|
|
9
|
-
const AGENT_SELECTION_GUIDANCE = 'First call {action:"list",capabilities:true}: executable, non-disabled agents only; external-cli requires runner.available === true. Passive PATH/PATHEXT/X_OK is not authentication/version/launch proof; preflight is authoritative.';
|
|
10
|
-
const SUBAGENT_FAILURE_RECOVERY_GUIDANCE = "Workflow, child launch, prompt runtime, extension load or child tooling failure is a lane infrastructure blocker. Stop; report exact failure, run/status and repo/cwd/worktree/branch/ref; verify clean worktree or capture partial diff before same-protocol retry or asking the owner. Never silently switch to interactive_shell, pi -ne, Codex/Claude/Cursor CLI or foreground/external mode: governed-workflow fallback requires explicit owner approval, not Pi core's generic pi -ne hint. Explicit foreground/CLI requests and work outside that protocol remain valid.";
|
|
11
9
|
|
|
12
10
|
type FeatureText = (feature: SubagentSurfaceFeature, text: string, disabledText?: string) => string;
|
|
13
11
|
|
|
@@ -15,60 +13,58 @@ function featureText(disabled: DisabledFeatureSurface): FeatureText {
|
|
|
15
13
|
return (feature, text, disabledText = "") => disabled.features.has(feature) ? disabledText : text;
|
|
16
14
|
}
|
|
17
15
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
Model override: first call {action:"models"}; copy exact provider/id, not agent names. Thinking uses model suffix${on("watchdog", ", not watchdog-only thinking")}.
|
|
35
|
-
Named resources: {workflow:'review',args:{task:'...'}} or {workflow:'run-ci',args:{command:'npm test'}}. Raw scripts also accept bounded plain-data args; raw-script args persist as evidence, so never include secrets. worktree:true requires clean source; baseRef defaults to HEAD at allocation or a supported named ref, never full 40/64-character commit IDs or revision expressions.`;
|
|
36
|
-
|
|
37
|
-
const structuredExecutionGuidance = (on: FeatureText) => `Delegate one child with {agent,task?}. tasks:[{agent,task},...] runs children in parallel. chain:[{agent,task?,as?} or {parallel:[{agent,task},...]}] runs steps in order; a parallel step waits for all its children and a failed step stops the chain.
|
|
38
|
-
Chain task placeholders: {task} is the top-level task (the original request); {previous} is the prior step's output (a parallel step's outputs in order), and the default when task is omitted; {outputs.name} is the output of an earlier step with as:'name'.
|
|
39
|
-
agent, chain and tasks exclude each other and action. action is management/control; agent may target management actions.
|
|
40
|
-
External CLI agents support native options only when their runner declares them; read guide tool-reference before passing model, structured output, acceptance/agentContract, ${on("tool-budgets", "tool budget, ")}fast, fork context or skills/tools.
|
|
41
|
-
Model override: first call {action:"models"}; copy exact provider/id, not agent names. Thinking uses model suffix${on("watchdog", ", not watchdog-only thinking")}.
|
|
42
|
-
worktree:true requires clean source; baseRef defaults to HEAD at allocation or a supported named ref, never full 40/64-character commit IDs or revision expressions.`;
|
|
43
|
-
|
|
44
|
-
const defaultDescription = (on: FeatureText) => `${on("workflow-scripts", scriptExecutionGuidance(on), structuredExecutionGuidance(on))}\n\n${safetyGuidance(on)}`;
|
|
16
|
+
// Part of every built-in description and appended to custom ones, so it is sent on every request.
|
|
17
|
+
export const SUBAGENT_SAFETY_GUIDANCE = `SAFETY-CRITICAL SUBAGENT GUIDANCE:
|
|
18
|
+
- Delegate only when the operator asked, directly or through applicable user/project instructions; size, complexity or risk alone is not authorization.
|
|
19
|
+
- Native async completion wakes this session: return control; do not sleep, poll or call bg_wait for it.
|
|
20
|
+
- One writer per cwd/worktree; isolate concurrent writers.
|
|
21
|
+
- After a launch or runtime failure, stop and report it; never silently switch to interactive_shell, pi -ne or another CLI.`;
|
|
22
|
+
|
|
23
|
+
const scriptCalls = "One child: {agent,task}. Independent parallel children: {workflow:\"parallel\",args:{tasks:[{agent,task},...]}}. Dependent multi-step work: exactly one top-level subagent workflow call with async:true; write one ```js workflow block in this reply, then call subagent({workflow:true}); children launch only inside it.";
|
|
24
|
+
const structuredCalls = "One child: {agent,task}. Parallel: tasks:[{agent,task},...]. In order: chain:[{agent,task?,as?} or {parallel:[{agent,task},...]}]; step tasks can use {task}, {previous} and {outputs.name}. Use exactly one top-level subagent chain or tasks call with async:true.";
|
|
25
|
+
|
|
26
|
+
const essentials = (on: FeatureText) => `${on("workflow-scripts", scriptCalls, structuredCalls)}
|
|
27
|
+
Management: {action,id?,options:{...}}; fields not in this schema go in options.
|
|
28
|
+
Launch agents by name and pass models as exact provider/id; an unknown agent or model returns the valid choices.
|
|
29
|
+
Details: guide workflows/recommended-orchestration-pattern (async, review, failure recovery), ${on("workflow-scripts", "guide workflows/scripted-workflows, ")}guide tool-reference/retained-children, guide tool-reference/external-cli-agent-profiles.
|
|
30
|
+
|
|
31
|
+
${SUBAGENT_SAFETY_GUIDANCE}`;
|
|
45
32
|
|
|
46
33
|
const managementDiscovery = (on: FeatureText) => [
|
|
47
34
|
["list/get/models/guide"],
|
|
48
35
|
[on("agent-management", "create/update/delete/eject/disable/enable/reset/refine")],
|
|
49
36
|
[on("missions", "mission.*"), on("schedules", "schedule.*"), on("watchdog", "watchdog.*"), on("panes", "inspector.*, project.*"), on("lane-management", "lane.status/recordMerge/recordSupersession")],
|
|
50
|
-
[on("lane-management", "worktree.discard and
|
|
37
|
+
[on("lane-management", "worktree.discard and reviewed worktree.cleanup")],
|
|
51
38
|
[`doctor${on("spawn-budget-grants", " and grant-spawn-budget")}`],
|
|
52
39
|
].map((group) => group.filter(Boolean).join(", ")).filter(Boolean).join("; ");
|
|
53
40
|
|
|
54
|
-
const
|
|
41
|
+
const scriptDetails = `• Scripts: JavaScript statement bodies with explicit return, top-level await, plain helpers/Promise chains; nested async function/arrow/method helpers are rejected. Await runs.run('key',{agent,task}) before .output; await runs.all([{key,agent,task},...]) for an ordered array, not a key map. Observe every stored run promise with direct await, Promise.race or Promise.all. Await/return runs.steer(key,message,options?) for a prior key, never raw run ids; queued/delivered/missed/failed receipts are not compliance proof.
|
|
42
|
+
• workflow:'./path.js' (any value with '/') loads a file from request cwd; other strings name a resource, such as {workflow:'review',args:{task:'...'}}. agent/task exclude workflow; task excludes action; validate accepts workflow:true or a path without launching. Raw-script sandboxes add deeply frozen args that persist as evidence, so never include secrets; raw scripts cannot use runs.host. Granted commands/relative outputs use workflow cwd, never per-step cwd.
|
|
43
|
+
• runs.lanes([{key,stages:[{key,agent,task},{key,resume:'previous',task}]}]) runs first stages together, later stages sequentially per lane. Failures stay lane-local; only explicit structuredOutput.verdict === 'blocked' blocks a successful stage, never reviewer prose.
|
|
44
|
+
`;
|
|
55
45
|
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
46
|
+
// Opt-in through toolDescriptionMode "full": the rarer rules the default leaves to guide sections.
|
|
47
|
+
const fullDetails = (on: FeatureText) => `DETAILS:
|
|
48
|
+
${on("workflow-scripts", scriptDetails)}• ${on("workflow-scripts", "Workflow child controls default onto runs.run/runs.all items; child fields override them.", "Top-level child controls apply to every chain/tasks child.")} worktree:true requires clean source, isolates each child and returns handoff artifacts; options.baseRef defaults to HEAD at allocation or a supported named ref, never full 40/64-character commit IDs or revision expressions.${on("usage-budgets", " usageBudget is shared across the workflow; already-running children are not stopped.")}
|
|
49
|
+
• Async follows asyncByDefault (normally true); async:false only to block the parent, not for final reviews/gates. Consume results at dependency barriers. bg_wait is for provider/detached work without native notification that needs a same-turn result.
|
|
50
|
+
• Bind durable output ${on("workflow-scripts", "on runs.run/runs.all", "with output")}, not task filename prose; return actual outputReference/outputPathMapping/artifactPaths, evidence and residual risks.
|
|
51
|
+
• Ordinary child subagents are not orchestrators; only configured fanout within depth/session limits. Use fresh-context read-only reviewers when independent review was requested. Oracle/advisor unknowns use supervisor dialogue; one-shot only when requested.
|
|
52
|
+
• children.list is workflow-only, not an exhaustive list of direct native children: resume only resumable rows. When an intended child's exact run id is known, inspect it with {action:"status",id}; if status identifies the candidate, attempt {action:"resume",id,message}. Resume authoritatively checks eligibility and may reject it. Use a labeled same-role fallback only when no known candidate exists or resume rejects eligibility.${on("workflow-scripts", " Scripts await runs.run(newKey,{resume:runId,task}); continue from the latest returned runId. Each distinct resume pass needs a new stable key; same-key reuse requires identical launch parameters.")}
|
|
53
|
+
• External CLI agents need an installed, authenticated CLI; preflight at launch decides, and passive PATH/PATHEXT/X_OK is not authentication/version/launch proof. They support native options only when their runner declares them: model, structured output, acceptance/agentContract, ${on("tool-budgets", "tool budget, ")}fast, fork context or skills/tools.
|
|
54
|
+
• Model override: copy exact provider/id, not agent names. Thinking uses model suffix${on("watchdog", ", not watchdog-only thinking")}.
|
|
55
|
+
• Missions auto-attach${on("missions", " unless options.mission:false")}; ${on("workflow-scripts", "await state.get(key)/state.set(key,JSONValue) requires a mission. ")}See guide topic missions. Omit acceptance for reviewer/read-only calls; acceptance.review.required requests independent writer review.
|
|
56
|
+
• Inspect asyncId/asyncDir (status.json, events.jsonl, logs) with status/debug.run; control with interrupt/stop/resume/steer. For local Pi children explicitly granted subagent_command, command.status/yield/cancel targets one exact toolCallId without interrupting the child.
|
|
57
|
+
• After a failure, report the exact failure, run/status and repo/cwd/worktree/branch/ref, and verify a clean worktree or capture the partial diff before a same-protocol retry. Governed-workflow fallback to foreground/CLI needs explicit owner approval, not Pi core's generic pi -ne hint.
|
|
59
58
|
• Management discovery: ${managementDiscovery(on)}. Use guide topics agents, ${on("missions", "missions, ")}observability, tool-reference, configuration, models${on("watchdog", ", watchdog")} or extension-api for exact action fields.${on("schedules", on("workflow-scripts", " Schedules take script inputs, not direct children; recipes live in the missions guide."))}`;
|
|
60
59
|
|
|
61
|
-
const
|
|
60
|
+
const fullDescription = (on: FeatureText) => `${essentials(on)}\n\n${fullDetails(on)}`;
|
|
62
61
|
|
|
63
|
-
|
|
62
|
+
const allEnabled = featureText(resolveDisabledFeatureSurface({}));
|
|
64
63
|
|
|
65
|
-
export const DEFAULT_SUBAGENT_TOOL_DESCRIPTION =
|
|
64
|
+
export const DEFAULT_SUBAGENT_TOOL_DESCRIPTION = essentials(allEnabled);
|
|
66
65
|
|
|
67
|
-
export const SUBAGENT_TOOL_PROMPT_SNIPPET = "
|
|
68
|
-
const STRUCTURED_SUBAGENT_TOOL_PROMPT_SNIPPET = "
|
|
69
|
-
export const SUBAGENT_TOOL_PROMPT_GUIDELINES = [
|
|
70
|
-
"Do not invoke subagents unless the operator requested delegation directly or through applicable instructions.",
|
|
71
|
-
];
|
|
66
|
+
export const SUBAGENT_TOOL_PROMPT_SNIPPET = "Delegate focused work to child agents; compose multi-child work in one workflow call.";
|
|
67
|
+
const STRUCTURED_SUBAGENT_TOOL_PROMPT_SNIPPET = "Delegate focused work to child agents; compose multi-child work in one chain or tasks call.";
|
|
72
68
|
|
|
73
69
|
export const COMPACT_SUBAGENT_TOOL_DESCRIPTION = DEFAULT_SUBAGENT_TOOL_DESCRIPTION;
|
|
74
70
|
|
|
@@ -90,17 +86,10 @@ export interface ToolDescriptionOptions {
|
|
|
90
86
|
disabledFeatures?: DisabledFeatureSurface;
|
|
91
87
|
}
|
|
92
88
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
promptGuidelines?: string[];
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
export function buildSubagentToolPromptMetadata(config: Pick<ExtensionConfig, "toolDescriptionMode"> = {}, disabledFeatures?: DisabledFeatureSurface): SubagentToolPromptMetadata {
|
|
89
|
+
// No promptGuidelines: the description carries the authorization rule, so it is stated once.
|
|
90
|
+
export function buildSubagentToolPromptMetadata(config: Pick<ExtensionConfig, "toolDescriptionMode"> = {}, disabledFeatures?: DisabledFeatureSurface): { promptSnippet?: string } {
|
|
99
91
|
if (config.toolDescriptionMode !== undefined) return {};
|
|
100
|
-
return {
|
|
101
|
-
promptSnippet: disabledFeatures?.features.has("workflow-scripts") ? STRUCTURED_SUBAGENT_TOOL_PROMPT_SNIPPET : SUBAGENT_TOOL_PROMPT_SNIPPET,
|
|
102
|
-
promptGuidelines: SUBAGENT_TOOL_PROMPT_GUIDELINES,
|
|
103
|
-
};
|
|
92
|
+
return { promptSnippet: disabledFeatures?.features.has("workflow-scripts") ? STRUCTURED_SUBAGENT_TOOL_PROMPT_SNIPPET : SUBAGENT_TOOL_PROMPT_SNIPPET };
|
|
104
93
|
}
|
|
105
94
|
|
|
106
95
|
export function resolveToolDescriptionMode(config: Pick<ExtensionConfig, "toolDescriptionMode">, options?: ToolDescriptionOptions): ToolDescriptionMode {
|
|
@@ -179,32 +168,26 @@ function loadCustomToolDescription(options?: ToolDescriptionOptions): string | u
|
|
|
179
168
|
return undefined;
|
|
180
169
|
}
|
|
181
170
|
|
|
182
|
-
function withMandatorySafetyGuidance(description: string
|
|
171
|
+
function withMandatorySafetyGuidance(description: string): string {
|
|
183
172
|
const customDescription = description
|
|
184
173
|
.split(SUBAGENT_SAFETY_GUIDANCE)
|
|
185
|
-
.flatMap((part) => part.split(safety))
|
|
186
|
-
.flatMap((part) => part.split(SUBAGENT_FAILURE_RECOVERY_GUIDANCE))
|
|
187
174
|
.map((part) => part.trim())
|
|
188
175
|
.filter(Boolean)
|
|
189
176
|
.join("\n\n");
|
|
190
177
|
return customDescription
|
|
191
|
-
? `${customDescription}\n\n${
|
|
192
|
-
:
|
|
178
|
+
? `${customDescription}\n\n${SUBAGENT_SAFETY_GUIDANCE}`
|
|
179
|
+
: SUBAGENT_SAFETY_GUIDANCE;
|
|
193
180
|
}
|
|
194
181
|
|
|
195
182
|
export function buildSubagentToolDescription(config: Pick<ExtensionConfig, "toolDescriptionMode"> = {}, options?: ToolDescriptionOptions): string {
|
|
196
183
|
const on = options?.disabledFeatures ? featureText(options.disabledFeatures) : allEnabled;
|
|
197
|
-
if (config.toolDescriptionMode === undefined) return
|
|
184
|
+
if (config.toolDescriptionMode === undefined) return essentials(on);
|
|
198
185
|
const mode = resolveToolDescriptionMode(config, options);
|
|
199
|
-
|
|
200
|
-
if (mode === "
|
|
201
|
-
else if (mode === "custom") {
|
|
186
|
+
if (mode === "compact") return essentials(on);
|
|
187
|
+
if (mode === "custom") {
|
|
202
188
|
const custom = loadCustomToolDescription(options);
|
|
203
|
-
if (custom)
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
}
|
|
208
|
-
} else description = fullDescription(on);
|
|
209
|
-
return description;
|
|
189
|
+
if (custom) return withMandatorySafetyGuidance(custom);
|
|
190
|
+
warn(options, `${CUSTOM_TOOL_DESCRIPTION_FILE} was not found or valid for toolDescriptionMode "custom"; using full description.`);
|
|
191
|
+
}
|
|
192
|
+
return fullDescription(on);
|
|
210
193
|
}
|
|
@@ -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
|
-
|
|
146
|
-
|
|
147
|
-
|
|
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
|
+
}
|