@caupulican/pi-adaptative 0.81.32 → 0.81.37
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 +46 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/README.md +69 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts +53 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts.map +1 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.js +1282 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.js.map +1 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.ts +1453 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/templates/builder-validator.json +14 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/templates/claude-trio.json +32 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/templates/full-provider-review.json +15 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/templates/provider-prompt-smoke.json +14 -0
- package/dist/bundled-resources/prompts/extensionify.md +5 -4
- package/dist/bundled-resources/prompts/skillify.md +5 -5
- package/dist/bundled-resources/skills/pi-harness-learning/SKILL.md +6 -3
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +10 -8
- package/dist/cli/args.js.map +1 -1
- package/dist/config.d.ts +5 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +10 -2
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session.d.ts +12 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +42 -2
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/autonomy/approval-gate.d.ts.map +1 -1
- package/dist/core/autonomy/approval-gate.js +2 -0
- package/dist/core/autonomy/approval-gate.js.map +1 -1
- package/dist/core/autonomy/foreground-envelope.d.ts.map +1 -1
- package/dist/core/autonomy/foreground-envelope.js +2 -0
- package/dist/core/autonomy/foreground-envelope.js.map +1 -1
- package/dist/core/autonomy/gates.d.ts.map +1 -1
- package/dist/core/autonomy/gates.js +9 -2
- package/dist/core/autonomy/gates.js.map +1 -1
- package/dist/core/autonomy/risk-assessment.d.ts.map +1 -1
- package/dist/core/autonomy/risk-assessment.js +2 -0
- package/dist/core/autonomy/risk-assessment.js.map +1 -1
- package/dist/core/background-lane-controller.d.ts +12 -3
- package/dist/core/background-lane-controller.d.ts.map +1 -1
- package/dist/core/background-lane-controller.js +67 -26
- package/dist/core/background-lane-controller.js.map +1 -1
- package/dist/core/bash-execution-controller.d.ts +9 -4
- package/dist/core/bash-execution-controller.d.ts.map +1 -1
- package/dist/core/bash-execution-controller.js +7 -6
- package/dist/core/bash-execution-controller.js.map +1 -1
- package/dist/core/bash-executor.d.ts +2 -0
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +10 -5
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/context/context-store-retention.d.ts +4 -1
- package/dist/core/context/context-store-retention.d.ts.map +1 -1
- package/dist/core/context/context-store-retention.js +42 -151
- package/dist/core/context/context-store-retention.js.map +1 -1
- package/dist/core/context-pipeline.d.ts.map +1 -1
- package/dist/core/context-pipeline.js +6 -6
- package/dist/core/context-pipeline.js.map +1 -1
- package/dist/core/default-tool-surface.d.ts +7 -0
- package/dist/core/default-tool-surface.d.ts.map +1 -1
- package/dist/core/default-tool-surface.js +29 -10
- package/dist/core/default-tool-surface.js.map +1 -1
- package/dist/core/doctor.d.ts +10 -10
- package/dist/core/doctor.d.ts.map +1 -1
- package/dist/core/doctor.js +30 -20
- package/dist/core/doctor.js.map +1 -1
- package/dist/core/exec.d.ts +2 -0
- package/dist/core/exec.d.ts.map +1 -1
- package/dist/core/exec.js +26 -39
- package/dist/core/exec.js.map +1 -1
- package/dist/core/extensions/loader.d.ts +9 -2
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +105 -21
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/types.d.ts +13 -3
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js +3 -0
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/footer-data-provider.d.ts.map +1 -1
- package/dist/core/footer-data-provider.js +2 -0
- package/dist/core/footer-data-provider.js.map +1 -1
- package/dist/core/goals/goal-state.d.ts +10 -0
- package/dist/core/goals/goal-state.d.ts.map +1 -1
- package/dist/core/goals/goal-state.js +37 -0
- package/dist/core/goals/goal-state.js.map +1 -1
- package/dist/core/goals/goal-tool-core.d.ts +11 -0
- package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
- package/dist/core/goals/goal-tool-core.js +51 -1
- package/dist/core/goals/goal-tool-core.js.map +1 -1
- package/dist/core/improvement-loop.d.ts.map +1 -1
- package/dist/core/improvement-loop.js +26 -5
- package/dist/core/improvement-loop.js.map +1 -1
- package/dist/core/memory/memory-manager.d.ts.map +1 -1
- package/dist/core/memory/memory-manager.js +1 -0
- package/dist/core/memory/memory-manager.js.map +1 -1
- package/dist/core/model-capability.d.ts.map +1 -1
- package/dist/core/model-capability.js +2 -0
- package/dist/core/model-capability.js.map +1 -1
- package/dist/core/model-router/tool-escalation.d.ts.map +1 -1
- package/dist/core/model-router/tool-escalation.js +17 -3
- package/dist/core/model-router/tool-escalation.js.map +1 -1
- package/dist/core/models/fitness-store.d.ts.map +1 -1
- package/dist/core/models/fitness-store.js +1 -1
- package/dist/core/models/fitness-store.js.map +1 -1
- package/dist/core/models/local-runtime.d.ts +6 -4
- package/dist/core/models/local-runtime.d.ts.map +1 -1
- package/dist/core/models/local-runtime.js +108 -36
- package/dist/core/models/local-runtime.js.map +1 -1
- package/dist/core/output-guard.d.ts.map +1 -1
- package/dist/core/output-guard.js +23 -8
- package/dist/core/output-guard.js.map +1 -1
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +44 -59
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/profile-resource-selection.d.ts +16 -0
- package/dist/core/profile-resource-selection.d.ts.map +1 -1
- package/dist/core/profile-resource-selection.js +41 -0
- package/dist/core/profile-resource-selection.js.map +1 -1
- package/dist/core/python-runtime.d.ts +46 -0
- package/dist/core/python-runtime.d.ts.map +1 -0
- package/dist/core/python-runtime.js +157 -0
- package/dist/core/python-runtime.js.map +1 -0
- package/dist/core/reflection-controller.d.ts.map +1 -1
- package/dist/core/reflection-controller.js +18 -1
- package/dist/core/reflection-controller.js.map +1 -1
- package/dist/core/reload-blockers.d.ts +1 -0
- package/dist/core/reload-blockers.d.ts.map +1 -1
- package/dist/core/reload-blockers.js +6 -2
- package/dist/core/reload-blockers.js.map +1 -1
- package/dist/core/resource-loader.d.ts +2 -0
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +50 -28
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/runtime-builder.d.ts +4 -0
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +31 -9
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/security/untrusted-boundary.d.ts +2 -2
- package/dist/core/security/untrusted-boundary.d.ts.map +1 -1
- package/dist/core/security/untrusted-boundary.js +4 -3
- package/dist/core/security/untrusted-boundary.js.map +1 -1
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +3 -1
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +9 -1
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +13 -2
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tasks/session-task-state.d.ts +10 -0
- package/dist/core/tasks/session-task-state.d.ts.map +1 -0
- package/dist/core/tasks/session-task-state.js +29 -0
- package/dist/core/tasks/session-task-state.js.map +1 -0
- package/dist/core/tasks/task-command.d.ts +30 -0
- package/dist/core/tasks/task-command.d.ts.map +1 -0
- package/dist/core/tasks/task-command.js +79 -0
- package/dist/core/tasks/task-command.js.map +1 -0
- package/dist/core/tasks/task-state.d.ts +71 -0
- package/dist/core/tasks/task-state.d.ts.map +1 -0
- package/dist/core/tasks/task-state.js +372 -0
- package/dist/core/tasks/task-state.js.map +1 -0
- package/dist/core/tool-selection/tool-selection-controller.d.ts.map +1 -1
- package/dist/core/tool-selection/tool-selection-controller.js +1 -1
- package/dist/core/tool-selection/tool-selection-controller.js.map +1 -1
- package/dist/core/toolkit/script-runner.d.ts.map +1 -1
- package/dist/core/toolkit/script-runner.js +58 -24
- package/dist/core/toolkit/script-runner.js.map +1 -1
- package/dist/core/tools/bash.d.ts +20 -2
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +132 -220
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/extensionify.d.ts +2 -1
- package/dist/core/tools/extensionify.d.ts.map +1 -1
- package/dist/core/tools/extensionify.js +11 -8
- package/dist/core/tools/extensionify.js.map +1 -1
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +57 -48
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/git-filter.d.ts.map +1 -1
- package/dist/core/tools/git-filter.js +20 -32
- package/dist/core/tools/git-filter.js.map +1 -1
- package/dist/core/tools/goal.d.ts +1 -1
- package/dist/core/tools/goal.d.ts.map +1 -1
- package/dist/core/tools/goal.js +10 -3
- package/dist/core/tools/goal.js.map +1 -1
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +92 -80
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/index.d.ts +9 -6
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +24 -9
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts +2 -0
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +7 -4
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/core/tools/python.d.ts +64 -0
- package/dist/core/tools/python.d.ts.map +1 -0
- package/dist/core/tools/python.js +241 -0
- package/dist/core/tools/python.js.map +1 -0
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +4 -3
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/shell-contract-router.d.ts +13 -0
- package/dist/core/tools/shell-contract-router.d.ts.map +1 -0
- package/dist/core/tools/shell-contract-router.js +295 -0
- package/dist/core/tools/shell-contract-router.js.map +1 -0
- package/dist/core/tools/task-steps.d.ts +46 -0
- package/dist/core/tools/task-steps.d.ts.map +1 -0
- package/dist/core/tools/task-steps.js +160 -0
- package/dist/core/tools/task-steps.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts +2 -0
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +23 -4
- package/dist/main.js.map +1 -1
- package/dist/migrations.d.ts.map +1 -1
- package/dist/migrations.js +18 -4
- package/dist/migrations.js.map +1 -1
- package/dist/modes/interactive/auth-dialogs-controller.d.ts +10 -0
- package/dist/modes/interactive/auth-dialogs-controller.d.ts.map +1 -1
- package/dist/modes/interactive/auth-dialogs-controller.js +94 -27
- package/dist/modes/interactive/auth-dialogs-controller.js.map +1 -1
- package/dist/modes/interactive/auto-learn-controller.d.ts.map +1 -1
- package/dist/modes/interactive/auto-learn-controller.js +2 -1
- package/dist/modes/interactive/auto-learn-controller.js.map +1 -1
- package/dist/modes/interactive/components/bordered-loader.d.ts +1 -0
- package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -1
- package/dist/modes/interactive/components/bordered-loader.js +8 -0
- package/dist/modes/interactive/components/bordered-loader.js.map +1 -1
- package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-editor.js +6 -15
- package/dist/modes/interactive/components/extension-editor.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts +3 -1
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +20 -8
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/components/profile-resource-editor.d.ts +4 -1
- package/dist/modes/interactive/components/profile-resource-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/profile-resource-editor.js +22 -39
- package/dist/modes/interactive/components/profile-resource-editor.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +1 -1
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/config-backup.d.ts +1 -0
- package/dist/modes/interactive/config-backup.d.ts.map +1 -1
- package/dist/modes/interactive/config-backup.js +14 -3
- package/dist/modes/interactive/config-backup.js.map +1 -1
- package/dist/modes/interactive/editor-overlay-host.d.ts +12 -0
- package/dist/modes/interactive/editor-overlay-host.d.ts.map +1 -1
- package/dist/modes/interactive/editor-overlay-host.js +55 -0
- package/dist/modes/interactive/editor-overlay-host.js.map +1 -1
- package/dist/modes/interactive/extension-ui-host.d.ts +2 -1
- package/dist/modes/interactive/extension-ui-host.d.ts.map +1 -1
- package/dist/modes/interactive/extension-ui-host.js +161 -96
- package/dist/modes/interactive/extension-ui-host.js.map +1 -1
- package/dist/modes/interactive/external-editor.d.ts.map +1 -1
- package/dist/modes/interactive/external-editor.js +23 -28
- package/dist/modes/interactive/external-editor.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +1 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +26 -8
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/profile-menu-controller.d.ts +5 -1
- package/dist/modes/interactive/profile-menu-controller.d.ts.map +1 -1
- package/dist/modes/interactive/profile-menu-controller.js +118 -24
- package/dist/modes/interactive/profile-menu-controller.js.map +1 -1
- package/dist/modes/interactive/resource-shell-commands.d.ts +1 -0
- package/dist/modes/interactive/resource-shell-commands.d.ts.map +1 -1
- package/dist/modes/interactive/resource-shell-commands.js +5 -1
- package/dist/modes/interactive/resource-shell-commands.js.map +1 -1
- package/dist/modes/interactive/session-flow-commands.d.ts +10 -0
- package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -1
- package/dist/modes/interactive/session-flow-commands.js +143 -7
- package/dist/modes/interactive/session-flow-commands.js.map +1 -1
- package/dist/modes/interactive/session-io-commands.d.ts.map +1 -1
- package/dist/modes/interactive/session-io-commands.js +80 -50
- package/dist/modes/interactive/session-io-commands.js.map +1 -1
- package/dist/modes/interactive/startup-checks.d.ts.map +1 -1
- package/dist/modes/interactive/startup-checks.js +14 -17
- package/dist/modes/interactive/startup-checks.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +20 -19
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +10 -19
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/utils/child-process.d.ts +13 -7
- package/dist/utils/child-process.d.ts.map +1 -1
- package/dist/utils/child-process.js +56 -3
- package/dist/utils/child-process.js.map +1 -1
- package/dist/utils/clipboard-image.d.ts.map +1 -1
- package/dist/utils/clipboard-image.js +3 -2
- package/dist/utils/clipboard-image.js.map +1 -1
- package/dist/utils/clipboard.d.ts.map +1 -1
- package/dist/utils/clipboard.js +17 -10
- package/dist/utils/clipboard.js.map +1 -1
- package/dist/utils/external-editor-command.d.ts +8 -0
- package/dist/utils/external-editor-command.d.ts.map +1 -0
- package/dist/utils/external-editor-command.js +60 -0
- package/dist/utils/external-editor-command.js.map +1 -0
- package/dist/utils/paths.d.ts.map +1 -1
- package/dist/utils/paths.js +10 -2
- package/dist/utils/paths.js.map +1 -1
- package/dist/utils/shell.d.ts +6 -8
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +61 -70
- package/dist/utils/shell.js.map +1 -1
- package/dist/utils/tools-manager.d.ts +23 -3
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +117 -21
- package/dist/utils/tools-manager.js.map +1 -1
- package/dist/utils/work-directory.d.ts +36 -0
- package/dist/utils/work-directory.d.ts.map +1 -0
- package/dist/utils/work-directory.js +462 -0
- package/dist/utils/work-directory.js.map +1 -0
- package/docs/index.md +4 -0
- package/docs/python.md +43 -0
- package/docs/resources.md +2 -2
- package/docs/rpc.md +1 -1
- package/docs/settings.md +7 -3
- package/docs/task-steps.md +90 -0
- package/docs/termux.md +7 -0
- package/docs/tmux-agent-manager.md +48 -0
- package/docs/usage.md +5 -6
- package/docs/windows.md +104 -8
- package/docs/work-directory.md +41 -0
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +32 -37
- package/package.json +9 -7
- package/scripts/postinstall-python-runtime.mjs +20 -0
|
@@ -0,0 +1,1282 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import * as crypto from "node:crypto";
|
|
3
|
+
import * as fs from "node:fs";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import * as path from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { getProcessWorkRun } from "@caupulican/pi-adaptative";
|
|
8
|
+
import { Type } from "typebox";
|
|
9
|
+
export const piConfig = { tools: ["tmux_agent_manager"] };
|
|
10
|
+
const EXTENSION_ROOT = path.dirname(fileURLToPath(import.meta.url));
|
|
11
|
+
export function getTmuxAgentManagerDataRoot() {
|
|
12
|
+
const agentDir = process.env.PI_ADAPTATIVE_CODING_AGENT_DIR ||
|
|
13
|
+
process.env["PI-ADAPTATIVE_CODING_AGENT_DIR"] ||
|
|
14
|
+
process.env.PI_CODING_AGENT_DIR ||
|
|
15
|
+
process.env.PI_AGENT_DIR ||
|
|
16
|
+
path.join(homedir(), ".pi", "agent");
|
|
17
|
+
return getProcessWorkRun(agentDir, "background", "tmux-agent-manager", "state").path;
|
|
18
|
+
}
|
|
19
|
+
function jobsRoot() {
|
|
20
|
+
return path.join(getTmuxAgentManagerDataRoot(), "jobs");
|
|
21
|
+
}
|
|
22
|
+
function archiveRoot() {
|
|
23
|
+
return path.join(getTmuxAgentManagerDataRoot(), "archives");
|
|
24
|
+
}
|
|
25
|
+
function templateDirs() {
|
|
26
|
+
return [path.join(EXTENSION_ROOT, "templates"), path.join(getTmuxAgentManagerDataRoot(), "templates")];
|
|
27
|
+
}
|
|
28
|
+
const MAX_OUTPUT = 12_000;
|
|
29
|
+
const DEFAULT_AGENT_PROVIDERS = ["pi", "agy", "codex"];
|
|
30
|
+
const PROVIDER_COMMANDS = {
|
|
31
|
+
pi: "pi",
|
|
32
|
+
codex: "codex",
|
|
33
|
+
agy: "agy",
|
|
34
|
+
claude: "claude",
|
|
35
|
+
opencode: "opencode",
|
|
36
|
+
custom: "",
|
|
37
|
+
};
|
|
38
|
+
const DEFAULT_DEADLINE_SECONDS = 20 * 60;
|
|
39
|
+
const MAX_DEADLINE_SECONDS = 24 * 60 * 60;
|
|
40
|
+
const TEAM_TEMPLATES = [
|
|
41
|
+
{
|
|
42
|
+
name: "provider-prompt-smoke",
|
|
43
|
+
description: "Real minimal interactive prompt smoke for native Claude, Agy, and Pi. Consumes provider/model tokens.",
|
|
44
|
+
deadlineSeconds: 10 * 60,
|
|
45
|
+
agents: [
|
|
46
|
+
{ provider: "claude", name: "claude-prompt-smoke" },
|
|
47
|
+
{ provider: "agy", name: "agy-prompt-smoke" },
|
|
48
|
+
{ provider: "pi", name: "pi-prompt-smoke" },
|
|
49
|
+
],
|
|
50
|
+
notes: [
|
|
51
|
+
"Use only when model-token/auth validation is intended.",
|
|
52
|
+
"The manager opens each CLI in tmux, injects the prompt, captures pane output, and watches DONE/BLOCKED markers.",
|
|
53
|
+
],
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
name: "full-provider-review",
|
|
57
|
+
description: "Interactive native-provider review team: Pi lead, Claude reviewer, Agy validator, Agy reviewer. Consumes provider/model tokens.",
|
|
58
|
+
deadlineSeconds: 30 * 60,
|
|
59
|
+
agents: [
|
|
60
|
+
{ provider: "pi", name: "pi-lead" },
|
|
61
|
+
{ provider: "claude", name: "claude-reviewer" },
|
|
62
|
+
{ provider: "agy", name: "agy-validator" },
|
|
63
|
+
{ provider: "agy", name: "agy-reviewer" },
|
|
64
|
+
],
|
|
65
|
+
notes: [
|
|
66
|
+
"Best for non-trivial review/QA where independent native CLIs help.",
|
|
67
|
+
"Keep the task objective bounded; inspect captured panes/result files before accepting PASS.",
|
|
68
|
+
],
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
name: "builder-validator",
|
|
72
|
+
description: "Interactive implementation loop: Agy builder, Claude reviewer, Agy validator, Pi coordinator. Good default for scoped code work.",
|
|
73
|
+
deadlineSeconds: 25 * 60,
|
|
74
|
+
agents: [
|
|
75
|
+
{ provider: "agy", name: "builder" },
|
|
76
|
+
{ provider: "claude", name: "code-reviewer" },
|
|
77
|
+
{ provider: "agy", name: "validator" },
|
|
78
|
+
{ provider: "pi", name: "coordinator" },
|
|
79
|
+
],
|
|
80
|
+
notes: [
|
|
81
|
+
"Use for owner-approved implementation/QA batches; never claim complete until result files and validation evidence are inspected.",
|
|
82
|
+
],
|
|
83
|
+
},
|
|
84
|
+
];
|
|
85
|
+
function cap(text, max = MAX_OUTPUT) {
|
|
86
|
+
return text.length <= max ? text : `${text.slice(0, max)}\n...[truncated ${text.length - max} chars]`;
|
|
87
|
+
}
|
|
88
|
+
function firstString(...values) {
|
|
89
|
+
for (const value of values)
|
|
90
|
+
if (typeof value === "string" && value.trim())
|
|
91
|
+
return value.trim();
|
|
92
|
+
return undefined;
|
|
93
|
+
}
|
|
94
|
+
function errorMessage(error) {
|
|
95
|
+
return error instanceof Error ? error.message : String(error);
|
|
96
|
+
}
|
|
97
|
+
function clampInt(value, fallback, min, max) {
|
|
98
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
99
|
+
return fallback;
|
|
100
|
+
return Math.max(min, Math.min(max, Math.trunc(value)));
|
|
101
|
+
}
|
|
102
|
+
function findExecutable(name) {
|
|
103
|
+
for (const dir of (process.env.PATH || "").split(path.delimiter)) {
|
|
104
|
+
if (!dir)
|
|
105
|
+
continue;
|
|
106
|
+
const candidate = path.join(dir, process.platform === "win32" ? `${name}.exe` : name);
|
|
107
|
+
try {
|
|
108
|
+
if (fs.statSync(candidate).isFile())
|
|
109
|
+
return candidate;
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
/* ignore */
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return undefined;
|
|
116
|
+
}
|
|
117
|
+
function quoteShell(value) {
|
|
118
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
119
|
+
}
|
|
120
|
+
function ensureDir(dir) {
|
|
121
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
122
|
+
}
|
|
123
|
+
function resolveCwd(ctx, requested) {
|
|
124
|
+
const cwd = path.resolve(ctx.cwd || process.cwd(), requested?.trim() || ".");
|
|
125
|
+
const stat = fs.statSync(cwd);
|
|
126
|
+
if (!stat.isDirectory())
|
|
127
|
+
throw new Error(`cwd is not a directory: ${cwd}`);
|
|
128
|
+
return cwd;
|
|
129
|
+
}
|
|
130
|
+
function safeName(value, fallback = "pi-agents") {
|
|
131
|
+
const safe = value
|
|
132
|
+
.toLowerCase()
|
|
133
|
+
.replace(/[^a-z0-9_.:-]+/g, "-")
|
|
134
|
+
.replace(/^-+|-+$/g, "")
|
|
135
|
+
.slice(0, 60);
|
|
136
|
+
return safe || fallback;
|
|
137
|
+
}
|
|
138
|
+
function makeJobId() {
|
|
139
|
+
return `tmux-${Date.now().toString(36)}-${crypto.randomBytes(4).toString("hex")}`;
|
|
140
|
+
}
|
|
141
|
+
function safeStatusKey(value) {
|
|
142
|
+
const raw = value?.trim() || "pi-agents";
|
|
143
|
+
if (!/^[a-zA-Z0-9_.:-]{1,80}$/.test(raw))
|
|
144
|
+
throw new Error("statusKey must be 1-80 chars: letters, numbers, _, ., :, or -");
|
|
145
|
+
return raw;
|
|
146
|
+
}
|
|
147
|
+
function runTmux(args, timeoutMs = 5_000) {
|
|
148
|
+
const tmux = process.env.PI_TMUX_MANAGER_TMUX_BIN || findExecutable("tmux") || "tmux";
|
|
149
|
+
const result = spawnSync(tmux, args, {
|
|
150
|
+
encoding: "utf8",
|
|
151
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
152
|
+
timeout: timeoutMs,
|
|
153
|
+
maxBuffer: 256 * 1024,
|
|
154
|
+
});
|
|
155
|
+
return {
|
|
156
|
+
ok: !result.error && result.status === 0,
|
|
157
|
+
status: result.status,
|
|
158
|
+
stdout: cap(result.stdout || ""),
|
|
159
|
+
stderr: cap(result.stderr || ""),
|
|
160
|
+
error: result.error ? String(result.error.message || result.error) : undefined,
|
|
161
|
+
args: [tmux, ...args],
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
function detectTmux() {
|
|
165
|
+
const tmuxBin = process.env.PI_TMUX_MANAGER_TMUX_BIN || findExecutable("tmux");
|
|
166
|
+
const errors = [];
|
|
167
|
+
let version;
|
|
168
|
+
let currentSession;
|
|
169
|
+
let sessions = [];
|
|
170
|
+
const insideTmux = Boolean(process.env.TMUX);
|
|
171
|
+
if (!tmuxBin)
|
|
172
|
+
errors.push("tmux CLI not found on PATH.");
|
|
173
|
+
else {
|
|
174
|
+
const versionRun = runTmux(["-V"], 2_000);
|
|
175
|
+
if (versionRun.ok)
|
|
176
|
+
version = versionRun.stdout.trim();
|
|
177
|
+
else
|
|
178
|
+
errors.push(`tmux -V failed: ${versionRun.error || versionRun.stderr || `exit ${versionRun.status}`}`);
|
|
179
|
+
const listRun = runTmux(["list-sessions", "-F", "#{session_name}"]);
|
|
180
|
+
if (listRun.ok)
|
|
181
|
+
sessions = listRun.stdout.trim() ? listRun.stdout.trim().split(/\n+/) : [];
|
|
182
|
+
else if (!/no server running/i.test(listRun.stderr))
|
|
183
|
+
errors.push(`tmux list-sessions failed: ${listRun.error || listRun.stderr || `exit ${listRun.status}`}`);
|
|
184
|
+
if (insideTmux) {
|
|
185
|
+
const sessionRun = runTmux(["display-message", "-p", "#S"], 2_000);
|
|
186
|
+
if (sessionRun.ok)
|
|
187
|
+
currentSession = sessionRun.stdout.trim();
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return {
|
|
191
|
+
insideTmux,
|
|
192
|
+
tmuxBin,
|
|
193
|
+
cliAvailable: Boolean(tmuxBin),
|
|
194
|
+
version,
|
|
195
|
+
currentSession,
|
|
196
|
+
sessions,
|
|
197
|
+
env: { tmux: process.env.TMUX, term: process.env.TERM },
|
|
198
|
+
errors,
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
function formatDetection(d) {
|
|
202
|
+
return [
|
|
203
|
+
`tmux: ${d.cliAvailable ? "available" : "missing"}`,
|
|
204
|
+
d.tmuxBin ? `bin: ${d.tmuxBin}` : undefined,
|
|
205
|
+
d.version ? `version: ${d.version}` : undefined,
|
|
206
|
+
`insideTmux: ${d.insideTmux}`,
|
|
207
|
+
d.currentSession ? `currentSession: ${d.currentSession}` : undefined,
|
|
208
|
+
d.sessions.length ? `sessions: ${d.sessions.join(", ")}` : "sessions: none",
|
|
209
|
+
d.errors.length ? `errors:\n- ${d.errors.join("\n- ")}` : undefined,
|
|
210
|
+
]
|
|
211
|
+
.filter(Boolean)
|
|
212
|
+
.join("\n");
|
|
213
|
+
}
|
|
214
|
+
function setupHelp(d) {
|
|
215
|
+
if (d.cliAvailable)
|
|
216
|
+
return `tmux CLI available: ${d.tmuxBin || "tmux"}\nUse tmux_agent_manager action=workspace_plan or fire_task. Set dryRun=true only when a preview is useful.`;
|
|
217
|
+
return [
|
|
218
|
+
"tmux CLI not found.",
|
|
219
|
+
"Install tmux for your environment, then reload Pi:",
|
|
220
|
+
"- Debian/Ubuntu/WSL: sudo apt-get install tmux",
|
|
221
|
+
"- Fedora: sudo dnf install tmux",
|
|
222
|
+
"- Arch: sudo pacman -S tmux",
|
|
223
|
+
"- macOS: brew install tmux",
|
|
224
|
+
"- Windows: use WSL/MSYS2/Cygwin where a real tmux binary is available on PATH.",
|
|
225
|
+
"cmux is macOS-only and intentionally not used by this tmux manager.",
|
|
226
|
+
].join("\n");
|
|
227
|
+
}
|
|
228
|
+
async function guardTmux(_ctx, detection, purpose) {
|
|
229
|
+
if (detection.cliAvailable)
|
|
230
|
+
return { allowed: true, text: `tmux available for ${purpose}.` };
|
|
231
|
+
return { allowed: false, text: `${setupHelp(detection)}\n\nCannot run tmux-managed work until tmux is on PATH.` };
|
|
232
|
+
}
|
|
233
|
+
function tmuxManagerInstructions(toolName, detection) {
|
|
234
|
+
return [
|
|
235
|
+
`tmux is available (${detection.version || detection.tmuxBin || "tmux"}). For managed ${toolName} work, use tmux_agent_manager instead of direct foreground/background dispatch.`,
|
|
236
|
+
"Suggested next call:",
|
|
237
|
+
'tmux_agent_manager({ action: "fire_task", teamTemplate: "builder-validator", task: "<objective>" })',
|
|
238
|
+
"The launch returns immediately after panes, event watchers, and prompt handoffs are armed.",
|
|
239
|
+
"Managed mode creates panes, prompt files, result files, event-driven terminal handoffs, tmux display-message notifications, @pi_* status options, shared variables, and one-shot deadlines.",
|
|
240
|
+
].join("\n");
|
|
241
|
+
}
|
|
242
|
+
function validateTemplate(value, source) {
|
|
243
|
+
if (!value || typeof value !== "object")
|
|
244
|
+
throw new Error(`${source}: template must be an object`);
|
|
245
|
+
const template = value;
|
|
246
|
+
if (!firstString(template.name))
|
|
247
|
+
throw new Error(`${source}: missing name`);
|
|
248
|
+
if (!firstString(template.description))
|
|
249
|
+
throw new Error(`${source}: missing description`);
|
|
250
|
+
if (!Array.isArray(template.agents) || template.agents.length < 1)
|
|
251
|
+
throw new Error(`${source}: agents must be a non-empty array`);
|
|
252
|
+
if (template.agents.length > 12)
|
|
253
|
+
throw new Error(`${source}: agents max is 12`);
|
|
254
|
+
template.agents.forEach((agent, index) => {
|
|
255
|
+
const provider = agent.provider || "custom";
|
|
256
|
+
if (!Object.hasOwn(PROVIDER_COMMANDS, provider))
|
|
257
|
+
throw new Error(`${source}: unsupported provider at agents[${index}]: ${provider}`);
|
|
258
|
+
if (provider === "custom" && !firstString(agent.command))
|
|
259
|
+
throw new Error(`${source}: custom agent ${agent.name || index} needs command`);
|
|
260
|
+
});
|
|
261
|
+
return template;
|
|
262
|
+
}
|
|
263
|
+
function loadTemplateFiles() {
|
|
264
|
+
const templates = [];
|
|
265
|
+
const errors = [];
|
|
266
|
+
for (const dir of templateDirs()) {
|
|
267
|
+
let entries = [];
|
|
268
|
+
try {
|
|
269
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
270
|
+
}
|
|
271
|
+
catch {
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
for (const entry of entries) {
|
|
275
|
+
if (!entry.isFile() || !entry.name.endsWith(".json"))
|
|
276
|
+
continue;
|
|
277
|
+
const filePath = path.join(dir, entry.name);
|
|
278
|
+
try {
|
|
279
|
+
const parsed = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
280
|
+
templates.push(validateTemplate(parsed, filePath));
|
|
281
|
+
}
|
|
282
|
+
catch (error) {
|
|
283
|
+
errors.push(`${filePath}: ${errorMessage(error)}`);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
return { templates, errors };
|
|
288
|
+
}
|
|
289
|
+
function getTeamTemplates() {
|
|
290
|
+
const byName = new Map();
|
|
291
|
+
for (const template of TEAM_TEMPLATES)
|
|
292
|
+
byName.set(template.name.toLowerCase(), template);
|
|
293
|
+
const loaded = loadTemplateFiles();
|
|
294
|
+
for (const template of loaded.templates)
|
|
295
|
+
byName.set(template.name.toLowerCase(), template);
|
|
296
|
+
return { templates: Array.from(byName.values()), errors: loaded.errors };
|
|
297
|
+
}
|
|
298
|
+
function findTeamTemplate(name) {
|
|
299
|
+
if (!name)
|
|
300
|
+
return undefined;
|
|
301
|
+
const wanted = name.trim().toLowerCase();
|
|
302
|
+
return getTeamTemplates().templates.find((template) => template.name.toLowerCase() === wanted);
|
|
303
|
+
}
|
|
304
|
+
function requireTeamTemplate(name) {
|
|
305
|
+
const { templates, errors } = getTeamTemplates();
|
|
306
|
+
const wanted = name?.trim().toLowerCase();
|
|
307
|
+
const template = wanted ? templates.find((item) => item.name.toLowerCase() === wanted) : undefined;
|
|
308
|
+
if (!template)
|
|
309
|
+
throw new Error(`unknown teamTemplate '${name || ""}'. Use action=list_templates.${errors.length ? ` Template load errors: ${errors.join("; ")}` : ""}`);
|
|
310
|
+
return template;
|
|
311
|
+
}
|
|
312
|
+
function templateSummary() {
|
|
313
|
+
const loaded = getTeamTemplates();
|
|
314
|
+
const lines = loaded.templates.map((template) => `- ${template.name}: ${template.description}`);
|
|
315
|
+
if (loaded.errors.length)
|
|
316
|
+
lines.push("", "Template load errors:", ...loaded.errors.map((error) => `- ${error}`));
|
|
317
|
+
return { text: lines.join("\n"), ...loaded };
|
|
318
|
+
}
|
|
319
|
+
function formatTemplate(template) {
|
|
320
|
+
return JSON.stringify(template, null, 2);
|
|
321
|
+
}
|
|
322
|
+
function templateDefaults(params) {
|
|
323
|
+
return findTeamTemplate(params.teamTemplate) || {};
|
|
324
|
+
}
|
|
325
|
+
function normalizeAgents(params) {
|
|
326
|
+
const template = findTeamTemplate(params.teamTemplate);
|
|
327
|
+
const input = params.agents?.length
|
|
328
|
+
? params.agents
|
|
329
|
+
: template?.agents?.length
|
|
330
|
+
? template.agents
|
|
331
|
+
: DEFAULT_AGENT_PROVIDERS.map((provider) => ({ provider }));
|
|
332
|
+
if (input.length < 1)
|
|
333
|
+
throw new Error("agents must contain at least one agent");
|
|
334
|
+
if (input.length > 12)
|
|
335
|
+
throw new Error("agents max is 12");
|
|
336
|
+
return input.map((agent, index) => {
|
|
337
|
+
const provider = agent.provider || "custom";
|
|
338
|
+
if (!Object.hasOwn(PROVIDER_COMMANDS, provider))
|
|
339
|
+
throw new Error(`unsupported provider: ${provider}`);
|
|
340
|
+
const name = firstString(agent.name, provider === "custom" ? `custom-${index + 1}` : provider) || `agent-${index + 1}`;
|
|
341
|
+
const baseCommand = firstString(agent.command, PROVIDER_COMMANDS[provider]);
|
|
342
|
+
if (!baseCommand)
|
|
343
|
+
throw new Error(`agent ${name} needs command when provider=custom`);
|
|
344
|
+
const tools = Array.isArray(agent.tools) && agent.tools.length > 0 ? agent.tools : undefined;
|
|
345
|
+
const command = tools ? `${baseCommand} --tools ${tools.join(",")}` : baseCommand;
|
|
346
|
+
return { provider, name, command, cwd: agent.cwd, tools };
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
function defaultProviderInvocation(provider) {
|
|
350
|
+
switch (provider) {
|
|
351
|
+
case "pi":
|
|
352
|
+
return "pi";
|
|
353
|
+
case "agy":
|
|
354
|
+
return "agy";
|
|
355
|
+
case "codex":
|
|
356
|
+
return "codex";
|
|
357
|
+
case "claude":
|
|
358
|
+
return "claude";
|
|
359
|
+
case "opencode":
|
|
360
|
+
return "opencode";
|
|
361
|
+
case "custom":
|
|
362
|
+
return "";
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
function interactivePromptText(prompt) {
|
|
366
|
+
return prompt.replace(/\r?\n/g, "\\n");
|
|
367
|
+
}
|
|
368
|
+
function spellMarker(marker) {
|
|
369
|
+
return marker.split("").join(" ");
|
|
370
|
+
}
|
|
371
|
+
function managedPrompt(task, jobId, agent, doneMarker, blockedMarker, varsPath) {
|
|
372
|
+
return [
|
|
373
|
+
`You are ${agent.name} (${agent.provider}) working inside a tmux-managed Pi worker pane.`,
|
|
374
|
+
`Job id: ${jobId}`,
|
|
375
|
+
`Shared variable file: ${varsPath}`,
|
|
376
|
+
"",
|
|
377
|
+
"Objective:",
|
|
378
|
+
task,
|
|
379
|
+
"",
|
|
380
|
+
"Rules:",
|
|
381
|
+
"- Work autonomously until honest PASS or BLOCKED.",
|
|
382
|
+
"- Verify important claims before PASS; include concise evidence.",
|
|
383
|
+
"- If user input, credentials, destructive approval, publishing, or unavailable dependency blocks you, report BLOCKED instead of waiting silently.",
|
|
384
|
+
"- Never print secrets/tokens. Prompts, commands, and logs persist under ~/.pi/agent/work/background/tmux-agent-manager/state/jobs.",
|
|
385
|
+
"- If a task names an external decision variable, read it only at the decision point; never loop or poll the shared JSON file.",
|
|
386
|
+
"",
|
|
387
|
+
"Completion contract:",
|
|
388
|
+
"Your final response must contain exactly one marker line. Build it by removing spaces from one of these character sequences:",
|
|
389
|
+
` DONE: ${spellMarker(doneMarker)}`,
|
|
390
|
+
` BLOCKED: ${spellMarker(blockedMarker)}`,
|
|
391
|
+
"If BLOCKED, print a short reason on the next line. Do not print either marker until the final answer. After marker, stop.",
|
|
392
|
+
].join("\n");
|
|
393
|
+
}
|
|
394
|
+
function buildWorkspacePlan(ctx, params) {
|
|
395
|
+
const cwd = resolveCwd(ctx, params.cwd);
|
|
396
|
+
const agents = normalizeAgents(params).map((agent, index) => ({
|
|
397
|
+
...agent,
|
|
398
|
+
cwd: resolveCwd(ctx, agent.cwd || cwd),
|
|
399
|
+
id: `${safeName(agent.name || agent.provider || "agent")}-${index + 1}`,
|
|
400
|
+
}));
|
|
401
|
+
const workspaceName = firstString(params.workspaceName, `pi-agents-${Date.now().toString(36)}`) || "pi-agents";
|
|
402
|
+
const sessionName = safeName(workspaceName, "pi-agents");
|
|
403
|
+
const launchCommands = agents.map((agent) => `tmux pane: ${agent.name} -> cd ${quoteShell(agent.cwd)} && ${agent.command}`);
|
|
404
|
+
return { workspaceName, sessionName, cwd, agents, launchCommands };
|
|
405
|
+
}
|
|
406
|
+
export function makePaneWatcherScript(job) {
|
|
407
|
+
const agentCases = job.agents.flatMap((agent) => [
|
|
408
|
+
` ${agent.id})`,
|
|
409
|
+
` agent_name=${quoteShell(agent.name)}`,
|
|
410
|
+
` agent_id_json=${quoteShell(JSON.stringify(agent.id))}`,
|
|
411
|
+
` agent_name_json=${quoteShell(JSON.stringify(agent.name))}`,
|
|
412
|
+
` done_marker=${quoteShell(agent.doneMarker)}`,
|
|
413
|
+
` blocked_marker=${quoteShell(agent.blockedMarker)}`,
|
|
414
|
+
` log_path=${quoteShell(agent.logPath)}`,
|
|
415
|
+
` log_path_json=${quoteShell(JSON.stringify(agent.logPath))}`,
|
|
416
|
+
` result_path=${quoteShell(agent.resultPath)}`,
|
|
417
|
+
` stop_request_path=${quoteShell(`${agent.resultPath}.stop-requested`)}`,
|
|
418
|
+
` pane_id=${quoteShell(agent.paneId || "")}`,
|
|
419
|
+
` pane_id_json=${quoteShell(JSON.stringify(agent.paneId || null))}`,
|
|
420
|
+
" ;;",
|
|
421
|
+
]);
|
|
422
|
+
return [
|
|
423
|
+
"#!/bin/sh",
|
|
424
|
+
"set -eu",
|
|
425
|
+
"umask 077",
|
|
426
|
+
"LC_ALL=C",
|
|
427
|
+
"export LC_ALL",
|
|
428
|
+
`job_id=${quoteShell(job.id)}`,
|
|
429
|
+
`job_id_json=${quoteShell(JSON.stringify(job.id))}`,
|
|
430
|
+
`session_name=${quoteShell(job.sessionName)}`,
|
|
431
|
+
`deadline=${Math.max(1, job.deadlineSeconds)}`,
|
|
432
|
+
// biome-ignore lint/suspicious/noTemplateCurlyInString: POSIX shell parameter expansion.
|
|
433
|
+
"agent_id=${1:-}",
|
|
434
|
+
'case "$agent_id" in',
|
|
435
|
+
...agentCases,
|
|
436
|
+
" *) printf 'unknown tmux agent id: %s\\n' \"$agent_id\" >&2; exit 2 ;;",
|
|
437
|
+
"esac",
|
|
438
|
+
"lock_path=$result_path.lock",
|
|
439
|
+
"status_path=$result_path.status.$$",
|
|
440
|
+
"timer_pid=",
|
|
441
|
+
"awk_pid=",
|
|
442
|
+
"finish() {",
|
|
443
|
+
" status=$1",
|
|
444
|
+
" notified_by=$2",
|
|
445
|
+
' [ ! -e "$result_path" ] || return 0',
|
|
446
|
+
' mkdir "$lock_path" 2>/dev/null || return 0',
|
|
447
|
+
" finished_at=$(date -u +%Y-%m-%dT%H:%M:%SZ)",
|
|
448
|
+
" temporary=$result_path.tmp.$$",
|
|
449
|
+
' printf \'{\\n "jobId": %s,\\n "agentId": %s,\\n "agentName": %s,\\n "status": "%s",\\n "exitCode": null,\\n "logPath": %s,\\n "paneId": %s,\\n "finishedAt": "%s",\\n "notifiedBy": "%s"\\n}\\n\' \\',
|
|
450
|
+
' "$job_id_json" "$agent_id_json" "$agent_name_json" "$status" "$log_path_json" "$pane_id_json" "$finished_at" "$notified_by" > "$temporary"',
|
|
451
|
+
' mv "$temporary" "$result_path"',
|
|
452
|
+
' rm -f "$stop_request_path"',
|
|
453
|
+
" option_suffix=$(printf '%s' \"$job_id-$agent_id\" | tr -c 'A-Za-z0-9_.:-' '-')",
|
|
454
|
+
' tmux set-option -t "$session_name" "@pi_$option_suffix" "$status" >/dev/null 2>&1 || true',
|
|
455
|
+
' tmux set-option -t "$session_name" "@pi_$job_id" "$status:$agent_name" >/dev/null 2>&1 || true',
|
|
456
|
+
' tmux display-message -t "$session_name" "tmux agent $agent_name: $status (job $job_id)" >/dev/null 2>&1 || true',
|
|
457
|
+
"}",
|
|
458
|
+
"cleanup() {",
|
|
459
|
+
' [ -z "$timer_pid" ] || kill "$timer_pid" 2>/dev/null || true',
|
|
460
|
+
' [ -z "$awk_pid" ] || kill "$awk_pid" 2>/dev/null || true',
|
|
461
|
+
' rm -f "$status_path"',
|
|
462
|
+
"}",
|
|
463
|
+
"terminate() { cleanup; exit 0; }",
|
|
464
|
+
"trap terminate TERM INT HUP",
|
|
465
|
+
"trap cleanup EXIT",
|
|
466
|
+
"parent_pid=$$",
|
|
467
|
+
"exec 3<&0",
|
|
468
|
+
"(",
|
|
469
|
+
" sleep_pid=",
|
|
470
|
+
' stop_timer() { [ -z "$sleep_pid" ] || kill "$sleep_pid" 2>/dev/null || true; exit 0; }',
|
|
471
|
+
" trap stop_timer TERM INT HUP",
|
|
472
|
+
' sleep "$deadline" &',
|
|
473
|
+
" sleep_pid=$!",
|
|
474
|
+
' wait "$sleep_pid" 2>/dev/null || exit 0',
|
|
475
|
+
" sleep_pid=",
|
|
476
|
+
' if [ -e "$stop_request_path" ]; then finish stopped stop-requested-event; else finish timeout deadline-event; fi',
|
|
477
|
+
' kill -TERM "$parent_pid" 2>/dev/null || true',
|
|
478
|
+
") &",
|
|
479
|
+
"timer_pid=$!",
|
|
480
|
+
"logged_bytes=0",
|
|
481
|
+
'[ ! -f "$log_path" ] || logged_bytes=$(wc -c < "$log_path" | tr -d \' \')',
|
|
482
|
+
'awk -v done="$done_marker" -v blocked="$blocked_marker" -v log_file="$log_path" -v status_file="$status_path" -v logged="$logged_bytes" -v max=4194304 -v esc="$(printf \'\\033\')" \'',
|
|
483
|
+
'function settle(status, reason) { print status "|" reason > status_file; close(status_file); settled = 1; exit }',
|
|
484
|
+
"{",
|
|
485
|
+
" raw = $0 ORS",
|
|
486
|
+
" remaining = max - logged",
|
|
487
|
+
' if (remaining > 0) { if (length(raw) > remaining) raw = substr(raw, 1, remaining); printf "%s", raw >> log_file; logged += length(raw) }',
|
|
488
|
+
" clean = $0",
|
|
489
|
+
' gsub(esc "\\\\[[0-9;?]*[ -/]*[@-~]", "", clean)',
|
|
490
|
+
' gsub(/\\r/, "", clean)',
|
|
491
|
+
' sub(/^[ \\t]+/, "", clean); sub(/[ \\t]+$/, "", clean)',
|
|
492
|
+
' if (clean == done) settle("done", "pane-output-event")',
|
|
493
|
+
' if (clean == blocked) settle("blocked", "pane-output-event")',
|
|
494
|
+
"}",
|
|
495
|
+
'END { if (!settled) { print "failed|pane-stream-ended" > status_file; close(status_file) } }',
|
|
496
|
+
"' <&3 &",
|
|
497
|
+
"awk_pid=$!",
|
|
498
|
+
'wait "$awk_pid" || true',
|
|
499
|
+
"awk_pid=",
|
|
500
|
+
'kill "$timer_pid" 2>/dev/null || true',
|
|
501
|
+
'wait "$timer_pid" 2>/dev/null || true',
|
|
502
|
+
"timer_pid=",
|
|
503
|
+
'if [ -e "$stop_request_path" ]; then',
|
|
504
|
+
" finish stopped stop-requested-event",
|
|
505
|
+
'elif [ -f "$status_path" ]; then',
|
|
506
|
+
' terminal=$(cat "$status_path")',
|
|
507
|
+
// biome-ignore lint/suspicious/noTemplateCurlyInString: POSIX shell parameter expansion.
|
|
508
|
+
' finish "${terminal%%|*}" "${terminal#*|}"',
|
|
509
|
+
"else",
|
|
510
|
+
" finish failed watcher-status-missing",
|
|
511
|
+
"fi",
|
|
512
|
+
"exit 0",
|
|
513
|
+
].join("\n");
|
|
514
|
+
}
|
|
515
|
+
function buildFireTaskPlan(ctx, params) {
|
|
516
|
+
const defaults = templateDefaults(params);
|
|
517
|
+
const task = firstString(params.task, params.body);
|
|
518
|
+
if (!task)
|
|
519
|
+
throw new Error("fire_task requires task (or body) with the worker objective");
|
|
520
|
+
const cwd = resolveCwd(ctx, params.cwd);
|
|
521
|
+
const id = firstString(params.jobId) || makeJobId();
|
|
522
|
+
if (!/^[a-zA-Z0-9_.:-]{4,80}$/.test(id))
|
|
523
|
+
throw new Error("jobId must be 4-80 chars: letters, numbers, _, ., :, or -");
|
|
524
|
+
const jobDir = path.join(jobsRoot(), id);
|
|
525
|
+
const workspaceName = firstString(params.workspaceName, `Pi job ${id}`) || `Pi job ${id}`;
|
|
526
|
+
const sessionName = safeName(workspaceName, id);
|
|
527
|
+
const rawAgents = normalizeAgents(params);
|
|
528
|
+
const agents = rawAgents.map((agent, index) => {
|
|
529
|
+
const provider = agent.provider || "custom";
|
|
530
|
+
const slug = `${safeName(agent.name || provider)}-${index + 1}`;
|
|
531
|
+
const markerBase = `TMUX_${crypto.createHash("sha1").update(`${id}:${slug}`).digest("hex").slice(0, 10).toUpperCase()}`;
|
|
532
|
+
const doneMarker = `${markerBase}_DONE`;
|
|
533
|
+
const blockedMarker = `${markerBase}_BLOCKED`;
|
|
534
|
+
return {
|
|
535
|
+
id: slug,
|
|
536
|
+
name: firstString(agent.name, provider) || slug,
|
|
537
|
+
provider,
|
|
538
|
+
command: firstString(agent.command, PROVIDER_COMMANDS[provider]),
|
|
539
|
+
cwd: resolveCwd(ctx, agent.cwd || cwd),
|
|
540
|
+
// tools already baked into command by normalizeAgents
|
|
541
|
+
doneMarker,
|
|
542
|
+
blockedMarker,
|
|
543
|
+
promptPath: path.join(jobDir, `${slug}.prompt.md`),
|
|
544
|
+
logPath: path.join(jobDir, `${slug}.log`),
|
|
545
|
+
resultPath: path.join(jobDir, `${slug}.result.json`),
|
|
546
|
+
};
|
|
547
|
+
});
|
|
548
|
+
const job = {
|
|
549
|
+
id,
|
|
550
|
+
createdAt: new Date().toISOString(),
|
|
551
|
+
parentSessionFile: ctx.sessionManager.getSessionFile(),
|
|
552
|
+
workspaceName,
|
|
553
|
+
sessionName,
|
|
554
|
+
cwd,
|
|
555
|
+
task,
|
|
556
|
+
teamTemplate: params.teamTemplate,
|
|
557
|
+
deadlineSeconds: clampInt(params.deadlineSeconds, defaults.deadlineSeconds || DEFAULT_DEADLINE_SECONDS, 5, MAX_DEADLINE_SECONDS),
|
|
558
|
+
jobDir,
|
|
559
|
+
jobPath: path.join(jobDir, "job.json"),
|
|
560
|
+
varsPath: path.join(jobDir, "variables.json"),
|
|
561
|
+
watcherPath: path.join(jobDir, "pane-watcher.sh"),
|
|
562
|
+
agents,
|
|
563
|
+
launchCommands: [],
|
|
564
|
+
};
|
|
565
|
+
job.launchCommands = agents.map((agent) => `${agent.command || defaultProviderInvocation(agent.provider)} then inject ${path.basename(agent.promptPath)}`);
|
|
566
|
+
return job;
|
|
567
|
+
}
|
|
568
|
+
function archiveExistingJobDir(jobDir) {
|
|
569
|
+
const root = archiveRoot();
|
|
570
|
+
ensureDir(root);
|
|
571
|
+
const target = path.join(root, `${path.basename(jobDir)}-${new Date().toISOString().replace(/[:.]/g, "-")}`);
|
|
572
|
+
fs.renameSync(jobDir, target);
|
|
573
|
+
return target;
|
|
574
|
+
}
|
|
575
|
+
function prepareJobDirForLaunch(job, force) {
|
|
576
|
+
if (!fs.existsSync(job.jobDir))
|
|
577
|
+
return undefined;
|
|
578
|
+
if (!force)
|
|
579
|
+
throw new Error(`tmux job already exists: ${job.id}. Use a new jobId, or pass force:true to archive the old job before launching.`);
|
|
580
|
+
return archiveExistingJobDir(job.jobDir);
|
|
581
|
+
}
|
|
582
|
+
function writeFireTaskFiles(job) {
|
|
583
|
+
ensureDir(job.jobDir);
|
|
584
|
+
if (!fs.existsSync(job.varsPath))
|
|
585
|
+
fs.writeFileSync(job.varsPath, `${JSON.stringify({ updatedAt: null, variables: {} }, null, 2)}\n`, {
|
|
586
|
+
mode: 0o600,
|
|
587
|
+
});
|
|
588
|
+
for (const agent of job.agents) {
|
|
589
|
+
fs.writeFileSync(agent.promptPath, `${managedPrompt(job.task, job.id, agent, agent.doneMarker, agent.blockedMarker, job.varsPath)}\n`, { mode: 0o600 });
|
|
590
|
+
fs.writeFileSync(agent.logPath, `[tmux-agent-manager] waiting for captured pane output\njob=${job.id} agent=${agent.name} pane=${agent.paneId || "pending"} command=${agent.command || defaultProviderInvocation(agent.provider)}\n`, { mode: 0o600 });
|
|
591
|
+
}
|
|
592
|
+
fs.writeFileSync(job.watcherPath, makePaneWatcherScript(job), { mode: 0o700 });
|
|
593
|
+
fs.chmodSync(job.watcherPath, 0o700);
|
|
594
|
+
fs.writeFileSync(job.jobPath, `${JSON.stringify({ ...job, agents: job.agents.map((agent) => ({ ...agent, result: null })) }, null, 2)}\n`, { mode: 0o600 });
|
|
595
|
+
}
|
|
596
|
+
function startPaneWatchers(job) {
|
|
597
|
+
const started = [];
|
|
598
|
+
for (const agent of job.agents) {
|
|
599
|
+
if (!agent.paneId)
|
|
600
|
+
throw new Error(`Missing pane id for tmux agent ${agent.name}`);
|
|
601
|
+
const command = `sh ${quoteShell(job.watcherPath)} ${quoteShell(agent.id)}`;
|
|
602
|
+
const result = runTmux(["pipe-pane", "-O", "-t", agent.paneId, command]);
|
|
603
|
+
if (!result.ok) {
|
|
604
|
+
throw new Error(`Failed to arm completion watcher for ${agent.name}: ${result.error || result.stderr || result.stdout}`);
|
|
605
|
+
}
|
|
606
|
+
started.push({ agentId: agent.id, paneId: agent.paneId });
|
|
607
|
+
}
|
|
608
|
+
return started;
|
|
609
|
+
}
|
|
610
|
+
function targetDisplayName(agent, index) {
|
|
611
|
+
return firstString(agent.name, agent.provider, `agent-${index + 1}`) || `agent-${index + 1}`;
|
|
612
|
+
}
|
|
613
|
+
function tmuxSessionExists(name) {
|
|
614
|
+
return runTmux(["has-session", "-t", name], 2_000).ok;
|
|
615
|
+
}
|
|
616
|
+
function sendCommandToPane(paneId, command) {
|
|
617
|
+
runTmux(["send-keys", "-t", paneId, "-l", command]);
|
|
618
|
+
runTmux(["send-keys", "-t", paneId, "Enter"]);
|
|
619
|
+
}
|
|
620
|
+
function launchTmuxSession(sessionName, cwd, panes) {
|
|
621
|
+
if (tmuxSessionExists(sessionName))
|
|
622
|
+
throw new Error(`tmux session already exists: ${sessionName}. Use stop_session/stop_job first or choose a different workspaceName.`);
|
|
623
|
+
const runs = [];
|
|
624
|
+
const paneIds = [];
|
|
625
|
+
const first = panes[0];
|
|
626
|
+
const create = runTmux(["new-session", "-d", "-P", "-F", "#{pane_id}", "-s", sessionName, "-n", "agents", "-c", first.cwd || cwd], 5_000);
|
|
627
|
+
runs.push(create);
|
|
628
|
+
if (!create.ok)
|
|
629
|
+
throw new Error(`tmux new-session failed: ${create.error || create.stderr || `exit ${create.status}`}`);
|
|
630
|
+
const firstPane = create.stdout.trim();
|
|
631
|
+
paneIds.push(firstPane);
|
|
632
|
+
sendCommandToPane(firstPane, first.command);
|
|
633
|
+
for (const pane of panes.slice(1)) {
|
|
634
|
+
const split = runTmux(["split-window", "-d", "-P", "-F", "#{pane_id}", "-t", `${sessionName}:0`, "-c", pane.cwd || cwd], 5_000);
|
|
635
|
+
runs.push(split);
|
|
636
|
+
if (!split.ok)
|
|
637
|
+
throw new Error(`tmux split-window failed: ${split.error || split.stderr || `exit ${split.status}`}`);
|
|
638
|
+
const paneId = split.stdout.trim();
|
|
639
|
+
paneIds.push(paneId);
|
|
640
|
+
sendCommandToPane(paneId, pane.command);
|
|
641
|
+
}
|
|
642
|
+
runs.push(runTmux(["select-layout", "-t", `${sessionName}:0`, "tiled"], 3_000));
|
|
643
|
+
return { runs, paneIds };
|
|
644
|
+
}
|
|
645
|
+
function injectPromptToPane(paneId, prompt, provider) {
|
|
646
|
+
const text = interactivePromptText(prompt);
|
|
647
|
+
if (provider === "claude") {
|
|
648
|
+
const bufferName = `pi-tmux-${crypto.randomBytes(4).toString("hex")}`;
|
|
649
|
+
runTmux(["set-buffer", "-b", bufferName, text], 10_000);
|
|
650
|
+
runTmux(["paste-buffer", "-b", bufferName, "-t", paneId], 10_000);
|
|
651
|
+
runTmux(["send-keys", "-t", paneId, "Enter"], 3_000);
|
|
652
|
+
runTmux(["delete-buffer", "-b", bufferName], 3_000);
|
|
653
|
+
return;
|
|
654
|
+
}
|
|
655
|
+
runTmux(["send-keys", "-t", paneId, "-l", text], 10_000);
|
|
656
|
+
runTmux(["send-keys", "-t", paneId, provider === "agy" ? "C-m" : "Enter"], 3_000);
|
|
657
|
+
}
|
|
658
|
+
function stopTmuxSession(sessionName, dryRun, confirm) {
|
|
659
|
+
if (!sessionName)
|
|
660
|
+
throw new Error("session name required");
|
|
661
|
+
const existed = tmuxSessionExists(sessionName);
|
|
662
|
+
if (!existed)
|
|
663
|
+
return { text: `tmux session not running: ${sessionName}`, existed: false };
|
|
664
|
+
if (dryRun)
|
|
665
|
+
return { text: `DRY RUN would stop tmux session: ${sessionName}`, existed: true };
|
|
666
|
+
if (confirm !== "yes-tmux-stop")
|
|
667
|
+
throw new Error("real stop requires confirm=yes-tmux-stop");
|
|
668
|
+
const run = runTmux(["kill-session", "-t", sessionName], 5_000);
|
|
669
|
+
if (!run.ok)
|
|
670
|
+
throw new Error(`tmux kill-session failed: ${run.error || run.stderr || `exit ${run.status}`}`);
|
|
671
|
+
return { text: `Stopped tmux session: ${sessionName}`, run, existed: true };
|
|
672
|
+
}
|
|
673
|
+
function isAlreadyExistsError(error) {
|
|
674
|
+
return typeof error === "object" && error !== null && "code" in error && error.code === "EEXIST";
|
|
675
|
+
}
|
|
676
|
+
function markStopRequested(job) {
|
|
677
|
+
for (const agent of job.agents) {
|
|
678
|
+
if (fs.existsSync(agent.resultPath))
|
|
679
|
+
continue;
|
|
680
|
+
try {
|
|
681
|
+
fs.writeFileSync(`${agent.resultPath}.stop-requested`, `${new Date().toISOString()}\n`, {
|
|
682
|
+
encoding: "utf8",
|
|
683
|
+
mode: 0o600,
|
|
684
|
+
flag: "wx",
|
|
685
|
+
});
|
|
686
|
+
}
|
|
687
|
+
catch (error) {
|
|
688
|
+
if (!isAlreadyExistsError(error))
|
|
689
|
+
throw error;
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
function clearStopRequested(job) {
|
|
694
|
+
for (const agent of job.agents)
|
|
695
|
+
fs.rmSync(`${agent.resultPath}.stop-requested`, { force: true });
|
|
696
|
+
}
|
|
697
|
+
function persistStoppedResults(job) {
|
|
698
|
+
for (const agent of job.agents) {
|
|
699
|
+
if (!fs.existsSync(agent.resultPath)) {
|
|
700
|
+
const result = {
|
|
701
|
+
jobId: job.id,
|
|
702
|
+
agentId: agent.id,
|
|
703
|
+
agentName: agent.name,
|
|
704
|
+
status: "stopped",
|
|
705
|
+
exitCode: null,
|
|
706
|
+
logPath: agent.logPath,
|
|
707
|
+
paneId: agent.paneId || null,
|
|
708
|
+
finishedAt: new Date().toISOString(),
|
|
709
|
+
notifiedBy: "stop-action-event",
|
|
710
|
+
};
|
|
711
|
+
try {
|
|
712
|
+
fs.writeFileSync(agent.resultPath, `${JSON.stringify(result, null, 2)}\n`, {
|
|
713
|
+
encoding: "utf8",
|
|
714
|
+
mode: 0o600,
|
|
715
|
+
flag: "wx",
|
|
716
|
+
});
|
|
717
|
+
}
|
|
718
|
+
catch (error) {
|
|
719
|
+
if (!isAlreadyExistsError(error))
|
|
720
|
+
throw error;
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
fs.rmSync(`${agent.resultPath}.stop-requested`, { force: true });
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
function stopTmuxSessionWithJobSignals(sessionName, jobs, dryRun, confirm) {
|
|
727
|
+
if (!dryRun && confirm !== "yes-tmux-stop")
|
|
728
|
+
throw new Error("real stop requires confirm=yes-tmux-stop");
|
|
729
|
+
if (!dryRun)
|
|
730
|
+
for (const job of jobs)
|
|
731
|
+
markStopRequested(job);
|
|
732
|
+
try {
|
|
733
|
+
const result = stopTmuxSession(sessionName, dryRun, confirm);
|
|
734
|
+
if (!dryRun)
|
|
735
|
+
for (const job of jobs)
|
|
736
|
+
persistStoppedResults(job);
|
|
737
|
+
return result;
|
|
738
|
+
}
|
|
739
|
+
catch (error) {
|
|
740
|
+
for (const job of jobs)
|
|
741
|
+
clearStopRequested(job);
|
|
742
|
+
throw error;
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
function formatWorkspacePreview(plan) {
|
|
746
|
+
return [
|
|
747
|
+
`Session: ${plan.sessionName}`,
|
|
748
|
+
`Cwd: ${plan.cwd}`,
|
|
749
|
+
"Panes:",
|
|
750
|
+
...plan.agents.map((agent, index) => `- ${targetDisplayName(agent, index)}: ${agent.command} (cwd ${agent.cwd})`),
|
|
751
|
+
].join("\n");
|
|
752
|
+
}
|
|
753
|
+
function formatFireTaskPreview(job) {
|
|
754
|
+
return [
|
|
755
|
+
`Job: ${job.id}`,
|
|
756
|
+
`Session: ${job.sessionName}`,
|
|
757
|
+
`Cwd: ${job.cwd}`,
|
|
758
|
+
`State: ${job.jobPath}`,
|
|
759
|
+
`Deadline: ${job.deadlineSeconds}s enforced by each event-driven pane watcher`,
|
|
760
|
+
"Workers:",
|
|
761
|
+
...job.agents.map((agent) => `- ${agent.name}: ${agent.command || defaultProviderInvocation(agent.provider)}`),
|
|
762
|
+
].join("\n");
|
|
763
|
+
}
|
|
764
|
+
function loadJob(id) {
|
|
765
|
+
const jobPath = path.join(jobsRoot(), id, "job.json");
|
|
766
|
+
if (!fs.existsSync(jobPath))
|
|
767
|
+
throw new Error(`tmux job not found: ${id}`);
|
|
768
|
+
const parsed = JSON.parse(fs.readFileSync(jobPath, "utf8"));
|
|
769
|
+
if (!Array.isArray(parsed.agents))
|
|
770
|
+
throw new Error(`tmux job has invalid agents: ${id}`);
|
|
771
|
+
for (const agent of parsed.agents) {
|
|
772
|
+
try {
|
|
773
|
+
agent.result = JSON.parse(fs.readFileSync(agent.resultPath, "utf8"));
|
|
774
|
+
}
|
|
775
|
+
catch {
|
|
776
|
+
delete agent.result;
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
try {
|
|
780
|
+
parsed.variables = readVariables(parsed.varsPath);
|
|
781
|
+
}
|
|
782
|
+
catch {
|
|
783
|
+
parsed.variables = { updatedAt: null, variables: {} };
|
|
784
|
+
}
|
|
785
|
+
return parsed;
|
|
786
|
+
}
|
|
787
|
+
function loadJobPlans() {
|
|
788
|
+
try {
|
|
789
|
+
return fs
|
|
790
|
+
.readdirSync(jobsRoot(), { withFileTypes: true })
|
|
791
|
+
.filter((entry) => entry.isDirectory())
|
|
792
|
+
.flatMap((entry) => {
|
|
793
|
+
try {
|
|
794
|
+
return [loadJob(entry.name)];
|
|
795
|
+
}
|
|
796
|
+
catch {
|
|
797
|
+
return [];
|
|
798
|
+
}
|
|
799
|
+
});
|
|
800
|
+
}
|
|
801
|
+
catch {
|
|
802
|
+
return [];
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
function listJobs() {
|
|
806
|
+
try {
|
|
807
|
+
return fs
|
|
808
|
+
.readdirSync(jobsRoot(), { withFileTypes: true })
|
|
809
|
+
.filter((d) => d.isDirectory())
|
|
810
|
+
.map((d) => {
|
|
811
|
+
try {
|
|
812
|
+
const job = loadJob(d.name);
|
|
813
|
+
return {
|
|
814
|
+
id: job.id,
|
|
815
|
+
workspaceName: job.workspaceName,
|
|
816
|
+
sessionName: job.sessionName,
|
|
817
|
+
createdAt: job.createdAt,
|
|
818
|
+
agents: job.agents.map((agent) => ({ name: agent.name, status: agent.result?.status || "pending" })),
|
|
819
|
+
};
|
|
820
|
+
}
|
|
821
|
+
catch (error) {
|
|
822
|
+
return { id: d.name, error: errorMessage(error) };
|
|
823
|
+
}
|
|
824
|
+
});
|
|
825
|
+
}
|
|
826
|
+
catch {
|
|
827
|
+
return [];
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
function readVariables(varsPath) {
|
|
831
|
+
try {
|
|
832
|
+
return JSON.parse(fs.readFileSync(varsPath, "utf8"));
|
|
833
|
+
}
|
|
834
|
+
catch {
|
|
835
|
+
return { updatedAt: null, variables: {} };
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
function setVariable(jobId, name, value) {
|
|
839
|
+
if (!/^[a-zA-Z0-9_.:-]{1,80}$/.test(name))
|
|
840
|
+
throw new Error("variableName must be 1-80 chars: letters, numbers, _, ., :, or -");
|
|
841
|
+
const job = loadJob(jobId);
|
|
842
|
+
const current = readVariables(job.varsPath);
|
|
843
|
+
current.variables[name] = value;
|
|
844
|
+
current.updatedAt = new Date().toISOString();
|
|
845
|
+
fs.writeFileSync(job.varsPath, `${JSON.stringify(current, null, 2)}\n`, { mode: 0o600 });
|
|
846
|
+
return { varsPath: job.varsPath, variables: current.variables, updatedAt: current.updatedAt };
|
|
847
|
+
}
|
|
848
|
+
async function executeTool(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
849
|
+
const action = params.action || "status";
|
|
850
|
+
const detection = detectTmux();
|
|
851
|
+
if (action === "status")
|
|
852
|
+
return { content: [{ type: "text", text: formatDetection(detection) }], details: { action, detection } };
|
|
853
|
+
if (action === "setup_help")
|
|
854
|
+
return { content: [{ type: "text", text: setupHelp(detection) }], details: { action, detection } };
|
|
855
|
+
if (action === "guard") {
|
|
856
|
+
const guard = await guardTmux(ctx, detection, "tmux-managed interactive subagent/provider orchestration");
|
|
857
|
+
return { content: [{ type: "text", text: guard.text }], details: { action, detection, guard } };
|
|
858
|
+
}
|
|
859
|
+
if (action === "list_jobs")
|
|
860
|
+
return { content: [{ type: "text", text: JSON.stringify(listJobs(), null, 2) }], details: { action } };
|
|
861
|
+
if (action === "list_templates") {
|
|
862
|
+
const summary = templateSummary();
|
|
863
|
+
return {
|
|
864
|
+
content: [{ type: "text", text: summary.text }],
|
|
865
|
+
details: { action, templates: summary.templates, errors: summary.errors, templateDirs: templateDirs() },
|
|
866
|
+
};
|
|
867
|
+
}
|
|
868
|
+
if (action === "show_template") {
|
|
869
|
+
const template = requireTeamTemplate(params.teamTemplate || params.title);
|
|
870
|
+
return { content: [{ type: "text", text: formatTemplate(template) }], details: { action, template } };
|
|
871
|
+
}
|
|
872
|
+
if (action === "job_status") {
|
|
873
|
+
if (!params.jobId)
|
|
874
|
+
throw new Error("job_status requires jobId");
|
|
875
|
+
const job = loadJob(params.jobId);
|
|
876
|
+
return { content: [{ type: "text", text: JSON.stringify(job, null, 2) }], details: { action, job } };
|
|
877
|
+
}
|
|
878
|
+
if (action === "list_variables") {
|
|
879
|
+
if (!params.jobId)
|
|
880
|
+
throw new Error("list_variables requires jobId");
|
|
881
|
+
const job = loadJob(params.jobId);
|
|
882
|
+
return {
|
|
883
|
+
content: [{ type: "text", text: JSON.stringify(job.variables || { variables: {} }, null, 2) }],
|
|
884
|
+
details: { action, jobId: params.jobId, variables: job.variables },
|
|
885
|
+
};
|
|
886
|
+
}
|
|
887
|
+
if (action === "set_variable") {
|
|
888
|
+
if (!params.jobId)
|
|
889
|
+
throw new Error("set_variable requires jobId");
|
|
890
|
+
if (!params.variableName)
|
|
891
|
+
throw new Error("set_variable requires variableName");
|
|
892
|
+
const value = firstString(params.variableValue, params.body, params.status, "") || "";
|
|
893
|
+
const result = setVariable(params.jobId, params.variableName, value);
|
|
894
|
+
return {
|
|
895
|
+
content: [
|
|
896
|
+
{
|
|
897
|
+
type: "text",
|
|
898
|
+
text: `Set tmux job variable ${params.variableName} for ${params.jobId}. Workers read ${result.varsPath} only at the named decision point.`,
|
|
899
|
+
},
|
|
900
|
+
],
|
|
901
|
+
details: { action, jobId: params.jobId, variableName: params.variableName, result },
|
|
902
|
+
};
|
|
903
|
+
}
|
|
904
|
+
const guard = await guardTmux(ctx, detection, `tmux ${action}`);
|
|
905
|
+
if (!guard.allowed)
|
|
906
|
+
return { content: [{ type: "text", text: guard.text }], details: { action, detection, guard, skipped: true } };
|
|
907
|
+
if (action === "stop_job") {
|
|
908
|
+
if (!params.jobId)
|
|
909
|
+
throw new Error("stop_job requires jobId");
|
|
910
|
+
const job = loadJob(params.jobId);
|
|
911
|
+
const result = stopTmuxSessionWithJobSignals(job.sessionName, [job], params.dryRun !== false, params.confirm);
|
|
912
|
+
return {
|
|
913
|
+
content: [{ type: "text", text: result.text }],
|
|
914
|
+
details: {
|
|
915
|
+
action,
|
|
916
|
+
detection,
|
|
917
|
+
jobId: params.jobId,
|
|
918
|
+
sessionName: job.sessionName,
|
|
919
|
+
dryRun: params.dryRun !== false,
|
|
920
|
+
result,
|
|
921
|
+
},
|
|
922
|
+
};
|
|
923
|
+
}
|
|
924
|
+
if (action === "stop_session") {
|
|
925
|
+
const sessionName = firstString(params.workspaceName, params.title);
|
|
926
|
+
if (!sessionName)
|
|
927
|
+
throw new Error("stop_session requires workspaceName or title with the tmux session name");
|
|
928
|
+
const jobs = loadJobPlans().filter((job) => job.sessionName === sessionName);
|
|
929
|
+
const result = stopTmuxSessionWithJobSignals(sessionName, jobs, params.dryRun !== false, params.confirm);
|
|
930
|
+
return {
|
|
931
|
+
content: [{ type: "text", text: result.text }],
|
|
932
|
+
details: { action, detection, sessionName, dryRun: params.dryRun !== false, result },
|
|
933
|
+
};
|
|
934
|
+
}
|
|
935
|
+
if (action === "workspace_plan" || action === "launch_workspace") {
|
|
936
|
+
const plan = buildWorkspacePlan(ctx, params);
|
|
937
|
+
const preview = formatWorkspacePreview(plan);
|
|
938
|
+
if (action === "workspace_plan" || params.dryRun === true)
|
|
939
|
+
return {
|
|
940
|
+
content: [{ type: "text", text: `DRY RUN tmux workspace plan\n${preview}` }],
|
|
941
|
+
details: { action, detection, dryRun: true, plan },
|
|
942
|
+
};
|
|
943
|
+
const panes = plan.agents.map((agent, index) => ({
|
|
944
|
+
title: targetDisplayName(agent, index),
|
|
945
|
+
cwd: agent.cwd || plan.cwd,
|
|
946
|
+
command: agent.command || PROVIDER_COMMANDS[agent.provider || "custom"],
|
|
947
|
+
}));
|
|
948
|
+
const launch = launchTmuxSession(plan.sessionName, plan.cwd, panes);
|
|
949
|
+
return {
|
|
950
|
+
content: [
|
|
951
|
+
{
|
|
952
|
+
type: "text",
|
|
953
|
+
text: `Launched tmux session '${plan.sessionName}'. Attach with: tmux attach -t ${plan.sessionName}`,
|
|
954
|
+
},
|
|
955
|
+
],
|
|
956
|
+
details: { action, detection, runs: launch.runs, paneIds: launch.paneIds, plan },
|
|
957
|
+
};
|
|
958
|
+
}
|
|
959
|
+
if (action === "fire_task") {
|
|
960
|
+
const job = buildFireTaskPlan(ctx, params);
|
|
961
|
+
if (params.dryRun === true)
|
|
962
|
+
return {
|
|
963
|
+
content: [{ type: "text", text: `DRY RUN tmux interactive task\n${formatFireTaskPreview(job)}` }],
|
|
964
|
+
details: { action, detection, dryRun: true, job },
|
|
965
|
+
};
|
|
966
|
+
if (tmuxSessionExists(job.sessionName))
|
|
967
|
+
throw new Error(`tmux session already exists: ${job.sessionName}. Use stop_job/stop_session first or choose a different workspaceName.`);
|
|
968
|
+
const archivedJobDir = prepareJobDirForLaunch(job, params.force);
|
|
969
|
+
const panes = job.agents.map((agent) => ({
|
|
970
|
+
title: agent.name,
|
|
971
|
+
cwd: agent.cwd,
|
|
972
|
+
command: agent.command || defaultProviderInvocation(agent.provider),
|
|
973
|
+
}));
|
|
974
|
+
const launch = launchTmuxSession(job.sessionName, job.cwd, panes);
|
|
975
|
+
job.agents.forEach((agent, index) => {
|
|
976
|
+
agent.paneId = launch.paneIds[index];
|
|
977
|
+
});
|
|
978
|
+
writeFireTaskFiles(job);
|
|
979
|
+
const watcherPanes = startPaneWatchers(job);
|
|
980
|
+
for (const agent of job.agents) {
|
|
981
|
+
if (!agent.paneId)
|
|
982
|
+
continue;
|
|
983
|
+
injectPromptToPane(agent.paneId, fs.readFileSync(agent.promptPath, "utf8"), agent.provider);
|
|
984
|
+
}
|
|
985
|
+
return {
|
|
986
|
+
content: [
|
|
987
|
+
{
|
|
988
|
+
type: "text",
|
|
989
|
+
text: [
|
|
990
|
+
`Launched tmux interactive fire-and-forget job ${job.id}.`,
|
|
991
|
+
`Session: ${job.sessionName}`,
|
|
992
|
+
`Attach: tmux attach -t ${job.sessionName}`,
|
|
993
|
+
`Job state: ${job.jobPath}`,
|
|
994
|
+
archivedJobDir ? `Archived previous job dir: ${archivedJobDir}` : undefined,
|
|
995
|
+
"Completion: event-driven pane output watchers armed (no polling).",
|
|
996
|
+
]
|
|
997
|
+
.filter(Boolean)
|
|
998
|
+
.join("\n"),
|
|
999
|
+
},
|
|
1000
|
+
],
|
|
1001
|
+
details: { action, detection, job, runs: launch.runs, paneIds: launch.paneIds, watcherPanes, archivedJobDir },
|
|
1002
|
+
};
|
|
1003
|
+
}
|
|
1004
|
+
if (action === "notify") {
|
|
1005
|
+
const title = firstString(params.title, "Pi") || "Pi";
|
|
1006
|
+
const body = firstString(params.body, "Pi needs attention") || "Pi needs attention";
|
|
1007
|
+
const target = firstString(params.workspaceName, detection.currentSession, detection.sessions[0]);
|
|
1008
|
+
if (!target)
|
|
1009
|
+
throw new Error("notify requires an active tmux session or workspaceName target");
|
|
1010
|
+
const run = runTmux(["display-message", "-t", target, `${title}: ${body}`], 3_000);
|
|
1011
|
+
if (!run.ok)
|
|
1012
|
+
throw new Error(`tmux display-message failed: ${run.error || run.stderr || `exit ${run.status}`}`);
|
|
1013
|
+
return {
|
|
1014
|
+
content: [{ type: "text", text: `Sent tmux display-message to ${target}: ${title}` }],
|
|
1015
|
+
details: { action, detection, run },
|
|
1016
|
+
};
|
|
1017
|
+
}
|
|
1018
|
+
if (action === "set_status") {
|
|
1019
|
+
const key = safeStatusKey(params.statusKey);
|
|
1020
|
+
const value = firstString(params.status, params.body, "") || "";
|
|
1021
|
+
const target = firstString(params.workspaceName, detection.currentSession, detection.sessions[0]);
|
|
1022
|
+
const args = target
|
|
1023
|
+
? ["set-option", "-t", target, `@pi_${key}`, value]
|
|
1024
|
+
: ["set-option", "-g", `@pi_${key}`, value];
|
|
1025
|
+
const run = runTmux(args, 3_000);
|
|
1026
|
+
if (!run.ok)
|
|
1027
|
+
throw new Error(`tmux set-option failed: ${run.error || run.stderr || `exit ${run.status}`}`);
|
|
1028
|
+
return {
|
|
1029
|
+
content: [{ type: "text", text: `Set tmux user option @pi_${key}=${value}` }],
|
|
1030
|
+
details: { action, detection, run },
|
|
1031
|
+
};
|
|
1032
|
+
}
|
|
1033
|
+
if (action === "clear_status") {
|
|
1034
|
+
const key = safeStatusKey(params.statusKey);
|
|
1035
|
+
const target = firstString(params.workspaceName, detection.currentSession, detection.sessions[0]);
|
|
1036
|
+
const args = target ? ["set-option", "-u", "-t", target, `@pi_${key}`] : ["set-option", "-gu", `@pi_${key}`];
|
|
1037
|
+
const run = runTmux(args, 3_000);
|
|
1038
|
+
if (!run.ok)
|
|
1039
|
+
throw new Error(`tmux clear status failed: ${run.error || run.stderr || `exit ${run.status}`}`);
|
|
1040
|
+
return {
|
|
1041
|
+
content: [{ type: "text", text: `Cleared tmux user option @pi_${key}` }],
|
|
1042
|
+
details: { action, detection, run },
|
|
1043
|
+
};
|
|
1044
|
+
}
|
|
1045
|
+
throw new Error(`unsupported action: ${action}`);
|
|
1046
|
+
}
|
|
1047
|
+
function isFireTaskTerminal(job) {
|
|
1048
|
+
return job.agents.length > 0 && job.agents.every((agent) => agent.result !== undefined);
|
|
1049
|
+
}
|
|
1050
|
+
function readBoundedLogTail(filePath, maxBytes = 2048) {
|
|
1051
|
+
try {
|
|
1052
|
+
const size = fs.statSync(filePath).size;
|
|
1053
|
+
const length = Math.min(size, maxBytes);
|
|
1054
|
+
const buffer = Buffer.alloc(length);
|
|
1055
|
+
const descriptor = fs.openSync(filePath, "r");
|
|
1056
|
+
try {
|
|
1057
|
+
fs.readSync(descriptor, buffer, 0, length, Math.max(0, size - length));
|
|
1058
|
+
}
|
|
1059
|
+
finally {
|
|
1060
|
+
fs.closeSync(descriptor);
|
|
1061
|
+
}
|
|
1062
|
+
return buffer.toString("utf8").replace(/<(?=\/?untrusted_content\b)/gi, "<");
|
|
1063
|
+
}
|
|
1064
|
+
catch {
|
|
1065
|
+
return "(no captured output)";
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
function formatFireTaskHandoff(job) {
|
|
1069
|
+
const included = job.agents.slice(0, 4);
|
|
1070
|
+
return [
|
|
1071
|
+
`tmux background task terminal handoff: ${job.id}`,
|
|
1072
|
+
`session: ${job.sessionName}`,
|
|
1073
|
+
...included.flatMap((agent) => [
|
|
1074
|
+
`- ${agent.name}: ${agent.result?.status ?? "unknown"}`,
|
|
1075
|
+
`<untrusted_content source="tmux_agent:${job.id}:${agent.id}">`,
|
|
1076
|
+
readBoundedLogTail(agent.logPath),
|
|
1077
|
+
"</untrusted_content>",
|
|
1078
|
+
]),
|
|
1079
|
+
...(job.agents.length > included.length
|
|
1080
|
+
? [`- ${job.agents.length - included.length} additional agent handoff(s) omitted.`]
|
|
1081
|
+
: []),
|
|
1082
|
+
"This event woke the parent; do not poll. Continue safe scoped work from the bounded handoff and inspect terminal artifacts only if needed for a material claim.",
|
|
1083
|
+
].join("\n");
|
|
1084
|
+
}
|
|
1085
|
+
function markFireTaskNotified(job) {
|
|
1086
|
+
const current = JSON.parse(fs.readFileSync(job.jobPath, "utf8"));
|
|
1087
|
+
current.notifiedAt = new Date().toISOString();
|
|
1088
|
+
const temporaryPath = `${job.jobPath}.tmp-${process.pid}-${Date.now()}`;
|
|
1089
|
+
fs.writeFileSync(temporaryPath, `${JSON.stringify(current, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
|
|
1090
|
+
fs.renameSync(temporaryPath, job.jobPath);
|
|
1091
|
+
job.notifiedAt = current.notifiedAt;
|
|
1092
|
+
}
|
|
1093
|
+
export default function tmuxAgentManagerExtension(pi) {
|
|
1094
|
+
let handoffContext;
|
|
1095
|
+
let handoffTail = Promise.resolve();
|
|
1096
|
+
const jobWatchers = new Map();
|
|
1097
|
+
const closeJobWatchers = () => {
|
|
1098
|
+
for (const watcher of jobWatchers.values())
|
|
1099
|
+
watcher.close();
|
|
1100
|
+
jobWatchers.clear();
|
|
1101
|
+
};
|
|
1102
|
+
const refreshJobHandoffs = async (ctx) => {
|
|
1103
|
+
const sessionFile = ctx.sessionManager.getSessionFile();
|
|
1104
|
+
const jobs = loadJobPlans().filter((job) => !job.parentSessionFile || job.parentSessionFile === sessionFile);
|
|
1105
|
+
for (const job of jobs) {
|
|
1106
|
+
if (!isFireTaskTerminal(job) || job.notifiedAt)
|
|
1107
|
+
continue;
|
|
1108
|
+
pi.sendMessage({
|
|
1109
|
+
customType: "tmux-background-completion",
|
|
1110
|
+
content: formatFireTaskHandoff(job),
|
|
1111
|
+
display: true,
|
|
1112
|
+
details: {
|
|
1113
|
+
jobId: job.id,
|
|
1114
|
+
sessionName: job.sessionName,
|
|
1115
|
+
agents: job.agents.map((agent) => ({ id: agent.id, name: agent.name, status: agent.result?.status })),
|
|
1116
|
+
},
|
|
1117
|
+
}, { triggerTurn: true, deliverAs: "followUp" });
|
|
1118
|
+
markFireTaskNotified(job);
|
|
1119
|
+
if (ctx.hasUI)
|
|
1120
|
+
ctx.ui.notify(`tmux background task ${job.id} completed.`, "info");
|
|
1121
|
+
}
|
|
1122
|
+
const activeIds = new Set(jobs.filter((job) => !isFireTaskTerminal(job)).map((job) => job.id));
|
|
1123
|
+
for (const [jobId, watcher] of jobWatchers) {
|
|
1124
|
+
if (activeIds.has(jobId))
|
|
1125
|
+
continue;
|
|
1126
|
+
watcher.close();
|
|
1127
|
+
jobWatchers.delete(jobId);
|
|
1128
|
+
}
|
|
1129
|
+
for (const job of jobs) {
|
|
1130
|
+
if (isFireTaskTerminal(job) || jobWatchers.has(job.id))
|
|
1131
|
+
continue;
|
|
1132
|
+
try {
|
|
1133
|
+
const watcher = fs.watch(job.jobDir, { persistent: false }, (_event, fileName) => {
|
|
1134
|
+
if (fileName && !String(fileName).endsWith(".result.json") && String(fileName) !== "job.json")
|
|
1135
|
+
return;
|
|
1136
|
+
if (handoffContext)
|
|
1137
|
+
void queueJobHandoffRefresh(handoffContext);
|
|
1138
|
+
});
|
|
1139
|
+
watcher.on("error", (error) => {
|
|
1140
|
+
watcher.close();
|
|
1141
|
+
jobWatchers.delete(job.id);
|
|
1142
|
+
if (ctx.hasUI)
|
|
1143
|
+
ctx.ui.notify(`tmux completion signal failed for ${job.id}: ${error.message}`, "warning");
|
|
1144
|
+
});
|
|
1145
|
+
jobWatchers.set(job.id, watcher);
|
|
1146
|
+
}
|
|
1147
|
+
catch (error) {
|
|
1148
|
+
if (ctx.hasUI)
|
|
1149
|
+
ctx.ui.notify(`tmux completion signal failed for ${job.id}: ${errorMessage(error)}`, "warning");
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
};
|
|
1153
|
+
function queueJobHandoffRefresh(ctx) {
|
|
1154
|
+
const refresh = handoffTail.then(() => refreshJobHandoffs(ctx));
|
|
1155
|
+
const guarded = refresh.catch((error) => {
|
|
1156
|
+
if (ctx.hasUI) {
|
|
1157
|
+
ctx.ui.notify(`tmux terminal handoff failed: ${error instanceof Error ? error.message : String(error)}`, "warning");
|
|
1158
|
+
}
|
|
1159
|
+
});
|
|
1160
|
+
handoffTail = guarded;
|
|
1161
|
+
return guarded;
|
|
1162
|
+
}
|
|
1163
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
1164
|
+
handoffContext = ctx;
|
|
1165
|
+
closeJobWatchers();
|
|
1166
|
+
await queueJobHandoffRefresh(ctx);
|
|
1167
|
+
});
|
|
1168
|
+
pi.on("session_shutdown", async () => {
|
|
1169
|
+
handoffContext = undefined;
|
|
1170
|
+
closeJobWatchers();
|
|
1171
|
+
handoffTail = Promise.resolve();
|
|
1172
|
+
});
|
|
1173
|
+
pi.registerTool({
|
|
1174
|
+
name: "tmux_agent_manager",
|
|
1175
|
+
label: "tmux Agent Manager",
|
|
1176
|
+
description: "tmux-exclusive interactive agent/workspace manager for Windows/Linux/macOS environments where tmux is on PATH. Opens real provider CLIs in panes, injects prompts, captures output, and replaces cmux outside iOS/macOS cmux use.",
|
|
1177
|
+
promptSnippet: "Use tmux to launch managed interactive agent/provider panes with prompt injection, captured output, completion markers, shared variables, and final notifications.",
|
|
1178
|
+
promptGuidelines: [
|
|
1179
|
+
"Use tmux_agent_manager for Windows/Linux tmux-managed workers. Do not use cmux on Windows/Linux; cmux is macOS-only and manual-disabled there.",
|
|
1180
|
+
"Prefer action=fire_task for interactive worker batches. It returns after event watchers and prompts are armed; do not wait, poll, or peek for completion.",
|
|
1181
|
+
"Use action=list_templates/show_template before assembling repeated teams; pass teamTemplate when a built-in team fits.",
|
|
1182
|
+
"Use action=workspace_plan before launch_workspace when designing a pane layout.",
|
|
1183
|
+
"Use stop_job/stop_session dry-run first, then confirm=yes-tmux-stop for real cleanup.",
|
|
1184
|
+
"Do not put secrets in task text or command strings; prompts, commands, and logs persist under ~/.pi/agent/work/background/tmux-agent-manager/state/jobs.",
|
|
1185
|
+
"tmux display/status actions are metadata only; validate worker result/log files before claiming task completion.",
|
|
1186
|
+
],
|
|
1187
|
+
parameters: Type.Object({
|
|
1188
|
+
action: Type.Optional(Type.Union([
|
|
1189
|
+
Type.Literal("status"),
|
|
1190
|
+
Type.Literal("setup_help"),
|
|
1191
|
+
Type.Literal("guard"),
|
|
1192
|
+
Type.Literal("notify"),
|
|
1193
|
+
Type.Literal("set_status"),
|
|
1194
|
+
Type.Literal("clear_status"),
|
|
1195
|
+
Type.Literal("workspace_plan"),
|
|
1196
|
+
Type.Literal("launch_workspace"),
|
|
1197
|
+
Type.Literal("fire_task"),
|
|
1198
|
+
Type.Literal("job_status"),
|
|
1199
|
+
Type.Literal("list_jobs"),
|
|
1200
|
+
Type.Literal("set_variable"),
|
|
1201
|
+
Type.Literal("list_variables"),
|
|
1202
|
+
Type.Literal("list_templates"),
|
|
1203
|
+
Type.Literal("show_template"),
|
|
1204
|
+
Type.Literal("stop_job"),
|
|
1205
|
+
Type.Literal("stop_session"),
|
|
1206
|
+
], {
|
|
1207
|
+
description: "status, setup_help, guard, notify, set_status, clear_status, workspace_plan, launch_workspace, fire_task, job_status, list_jobs, set_variable, list_variables, list_templates, show_template, stop_job, or stop_session. Default status.",
|
|
1208
|
+
})),
|
|
1209
|
+
title: Type.Optional(Type.String({ description: "Notification title or workspace title context." })),
|
|
1210
|
+
body: Type.Optional(Type.String({ description: "Notification body/status text, or fallback task text for fire_task." })),
|
|
1211
|
+
subtitle: Type.Optional(Type.String({ description: "Accepted for cmux parity; tmux display-message ignores subtitle." })),
|
|
1212
|
+
statusKey: Type.Optional(Type.String({
|
|
1213
|
+
description: "Status key for tmux set_status/clear_status. Stored as @pi_<key>. Default pi-agents.",
|
|
1214
|
+
})),
|
|
1215
|
+
status: Type.Optional(Type.String({ description: "Status value for set_status." })),
|
|
1216
|
+
icon: Type.Optional(Type.String({ description: "Accepted for cmux parity; tmux display-message/user options ignore icon." })),
|
|
1217
|
+
color: Type.Optional(Type.String({ description: "Accepted for cmux parity; tmux display-message/user options ignore color." })),
|
|
1218
|
+
workspaceName: Type.Optional(Type.String({
|
|
1219
|
+
description: "tmux session name/title for workspace_plan/launch_workspace/fire_task, or target for notify/status.",
|
|
1220
|
+
})),
|
|
1221
|
+
cwd: Type.Optional(Type.String({
|
|
1222
|
+
description: "Working directory for planned/launched agent workspace. Defaults to current cwd.",
|
|
1223
|
+
})),
|
|
1224
|
+
teamTemplate: Type.Optional(Type.String({
|
|
1225
|
+
description: "Built-in team template name for workspace/fire_task, or target for show_template. Use list_templates first. Current templates include provider-prompt-smoke, full-provider-review, builder-validator, plus JSON templates under templates/.",
|
|
1226
|
+
})),
|
|
1227
|
+
task: Type.Optional(Type.String({
|
|
1228
|
+
description: "Fire-and-forget worker objective. Required for fire_task unless body is provided.",
|
|
1229
|
+
})),
|
|
1230
|
+
jobId: Type.Optional(Type.String({
|
|
1231
|
+
description: "Job id for fire_task (optional), job_status/list_variables/set_variable (required).",
|
|
1232
|
+
})),
|
|
1233
|
+
variableName: Type.Optional(Type.String({
|
|
1234
|
+
description: "For set_variable: named condition/decision variable workers read only at the decision point.",
|
|
1235
|
+
})),
|
|
1236
|
+
variableValue: Type.Optional(Type.String({ description: "For set_variable: value to write. body/status can also supply the value." })),
|
|
1237
|
+
deadlineSeconds: Type.Optional(Type.Number({
|
|
1238
|
+
description: "For fire_task: seconds before each event-driven pane watcher records a timeout. Default 1200.",
|
|
1239
|
+
minimum: 5,
|
|
1240
|
+
maximum: MAX_DEADLINE_SECONDS,
|
|
1241
|
+
})),
|
|
1242
|
+
agents: Type.Optional(Type.Array(Type.Object({
|
|
1243
|
+
provider: Type.Optional(Type.Union([
|
|
1244
|
+
Type.Literal("pi"),
|
|
1245
|
+
Type.Literal("codex"),
|
|
1246
|
+
Type.Literal("agy"),
|
|
1247
|
+
Type.Literal("claude"),
|
|
1248
|
+
Type.Literal("opencode"),
|
|
1249
|
+
Type.Literal("custom"),
|
|
1250
|
+
])),
|
|
1251
|
+
name: Type.Optional(Type.String({ description: "Pane/worker name." })),
|
|
1252
|
+
command: Type.Optional(Type.String({
|
|
1253
|
+
description: "Interactive CLI start command for this pane, e.g. claude, agy, pi, or a custom wrapper CLI. The manager injects the prompt after launch and captures pane output.",
|
|
1254
|
+
})),
|
|
1255
|
+
cwd: Type.Optional(Type.String({ description: "Optional per-agent cwd." })),
|
|
1256
|
+
}), { description: "Agents/providers to lay out in tmux. Default: pi, agy, codex." })),
|
|
1257
|
+
dryRun: Type.Optional(Type.Boolean({
|
|
1258
|
+
description: "Preview only when true. Launch actions run by default; stop actions remain previews by default.",
|
|
1259
|
+
})),
|
|
1260
|
+
force: Type.Optional(Type.Boolean({
|
|
1261
|
+
description: "For fire_task only: archive an existing job directory with the same jobId before launch. Existing tmux sessions are still refused; stop them first.",
|
|
1262
|
+
})),
|
|
1263
|
+
confirm: Type.Optional(Type.String({ description: "Required for real stop_job/stop_session: yes-tmux-stop." })),
|
|
1264
|
+
}),
|
|
1265
|
+
async execute(toolCallId, params, signal, onUpdate, ctx) {
|
|
1266
|
+
const result = await executeTool(toolCallId, params, signal, onUpdate, ctx);
|
|
1267
|
+
await queueJobHandoffRefresh(ctx);
|
|
1268
|
+
return result;
|
|
1269
|
+
},
|
|
1270
|
+
});
|
|
1271
|
+
pi.registerCommand("tmux-agents", {
|
|
1272
|
+
description: "Check tmux availability and show managed-agent guidance.",
|
|
1273
|
+
handler: async (_args, ctx) => {
|
|
1274
|
+
const detection = detectTmux();
|
|
1275
|
+
const text = detection.cliAvailable
|
|
1276
|
+
? tmuxManagerInstructions("agent/provider", detection)
|
|
1277
|
+
: setupHelp(detection);
|
|
1278
|
+
ctx.ui.notify(text, detection.cliAvailable ? "info" : "warning");
|
|
1279
|
+
},
|
|
1280
|
+
});
|
|
1281
|
+
}
|
|
1282
|
+
//# sourceMappingURL=index.js.map
|