pi-cowboy 0.0.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +281 -2
  3. package/agents/explore.toml +40 -0
  4. package/dist/agents/agent-assets.js +261 -0
  5. package/dist/agents/agent-cleanup.js +284 -0
  6. package/dist/agents/agent-discovery.js +108 -0
  7. package/dist/agents/agent-host.js +10 -0
  8. package/dist/agents/agent-manager.js +367 -0
  9. package/dist/agents/agent-reviver.js +64 -0
  10. package/dist/agents/agent-runner.js +288 -0
  11. package/dist/agents/agent-spawn-store.js +57 -0
  12. package/dist/agents/agent-template.js +46 -0
  13. package/dist/agents/agent-types.js +144 -0
  14. package/dist/agents/batch.js +92 -0
  15. package/dist/agents/cleanup-policy.js +194 -0
  16. package/dist/agents/cleanup-report.js +128 -0
  17. package/dist/agents/default-agents.js +19 -0
  18. package/dist/agents/harness/pi-bolt.js +15 -0
  19. package/dist/agents/harness/pi-compatible.js +68 -0
  20. package/dist/agents/harness/pig.js +16 -0
  21. package/dist/agents/harness/registry.js +27 -0
  22. package/dist/agents/harness.js +32 -0
  23. package/dist/agents/result-file-permissions.js +29 -0
  24. package/dist/agents/run-state.js +270 -0
  25. package/dist/agents/schemas/cleanup-batch.schema.js +19 -0
  26. package/dist/agents/schemas/cowboy-agents.schema.js +39 -0
  27. package/dist/agents/schemas/merge-batch.schema.js +25 -0
  28. package/dist/agents/schemas/steer-batch.schema.js +22 -0
  29. package/dist/agents/schemas/stop-batch.schema.js +18 -0
  30. package/dist/agents/spawn-defaults.js +70 -0
  31. package/dist/agents/subagent-session.js +601 -0
  32. package/dist/agents/tool-cleanup.js +57 -0
  33. package/dist/agents/tool-execution.js +125 -0
  34. package/dist/agents/tool-merge.js +190 -0
  35. package/dist/agents/tool-result.js +17 -0
  36. package/dist/agents/tool-steer.js +89 -0
  37. package/dist/agents/types.js +1 -0
  38. package/dist/availability.js +38 -0
  39. package/dist/config/config-io.js +261 -0
  40. package/dist/config/config-store.js +321 -0
  41. package/dist/config/config-validation.js +173 -0
  42. package/dist/config/layered-config.js +117 -0
  43. package/dist/config/types.js +23 -0
  44. package/dist/cow-support-launch.js +43 -0
  45. package/dist/events.js +146 -0
  46. package/dist/extension-toggle.js +28 -0
  47. package/dist/harness-availability-launch.js +23 -0
  48. package/dist/index.js +52 -0
  49. package/dist/infrastructure/exec-path.js +35 -0
  50. package/dist/infrastructure/git/cow-clone.js +398 -0
  51. package/dist/infrastructure/git/git-materializer.js +342 -0
  52. package/dist/infrastructure/git/git-merger.js +234 -0
  53. package/dist/infrastructure/git/git-retention.js +43 -0
  54. package/dist/infrastructure/git/git-runner.js +145 -0
  55. package/dist/infrastructure/git/git-worktree.js +143 -0
  56. package/dist/infrastructure/git/index.js +11 -0
  57. package/dist/infrastructure/git-client.js +11 -0
  58. package/dist/infrastructure/herdr/agent-stopper.js +60 -0
  59. package/dist/infrastructure/herdr/agents.js +329 -0
  60. package/dist/infrastructure/herdr/herdr-client.js +36 -0
  61. package/dist/infrastructure/herdr/herdr-transport.js +158 -0
  62. package/dist/infrastructure/herdr/index.js +15 -0
  63. package/dist/infrastructure/herdr/panes.js +174 -0
  64. package/dist/infrastructure/herdr/polling.js +44 -0
  65. package/dist/infrastructure/herdr/worktrees.js +76 -0
  66. package/dist/infrastructure/herdr-client.js +6 -0
  67. package/dist/infrastructure/herdr-host.js +163 -0
  68. package/dist/logger.js +79 -0
  69. package/dist/models/model-groups.js +72 -0
  70. package/dist/models/model-precedence.js +50 -0
  71. package/dist/models/model-request.js +108 -0
  72. package/dist/orchestrators/briefing-section.js +14 -0
  73. package/dist/orchestrators/context.js +116 -0
  74. package/dist/orchestrators/cues.js +90 -0
  75. package/dist/orchestrators/default-orchestrators.js +36 -0
  76. package/dist/orchestrators/orchestrator-discovery.js +68 -0
  77. package/dist/orchestrators/orchestrator-template.js +43 -0
  78. package/dist/orchestrators/orchestrator-types.js +78 -0
  79. package/dist/orchestrators/protocol.js +292 -0
  80. package/dist/orchestrators/types.js +7 -0
  81. package/dist/paths.js +66 -0
  82. package/dist/pi-settings.js +7 -0
  83. package/dist/predicates.js +25 -0
  84. package/dist/prompt/prompts.js +110 -0
  85. package/dist/prompt/skill-loader.js +153 -0
  86. package/dist/prompt/subagent-system-prompt.js +173 -0
  87. package/dist/registration.js +220 -0
  88. package/dist/shell.js +225 -0
  89. package/dist/spawn/cow-support.js +53 -0
  90. package/dist/spawn/herdr-launcher.js +80 -0
  91. package/dist/spawn/repo-lock.js +34 -0
  92. package/dist/spawn/sandbox.js +286 -0
  93. package/dist/spawn/spawn-coordinator.js +255 -0
  94. package/dist/spawn/spawn-id.js +39 -0
  95. package/dist/spawn/worktree-policy.js +137 -0
  96. package/dist/status-note.js +30 -0
  97. package/dist/subagent/ipc-protocol.js +68 -0
  98. package/dist/subagent/ipc.js +110 -0
  99. package/dist/subagent/pane-supervisor.js +24 -0
  100. package/dist/subagent/socket-ipc.js +240 -0
  101. package/dist/subagent/supervisor.js +315 -0
  102. package/dist/task-registry.js +258 -0
  103. package/dist/templates/template-files.js +84 -0
  104. package/dist/types.js +84 -0
  105. package/dist/ui/action-report.js +21 -0
  106. package/dist/ui/format.js +47 -0
  107. package/dist/ui/indicator.js +480 -0
  108. package/dist/ui/menu/helpers.js +227 -0
  109. package/dist/ui/menu/menu-agent-settings.js +182 -0
  110. package/dist/ui/menu/menu-agent-status.js +444 -0
  111. package/dist/ui/menu/menu-concurrency.js +226 -0
  112. package/dist/ui/menu/menu-model-settings.js +244 -0
  113. package/dist/ui/menu/menu-spawn-defaults.js +71 -0
  114. package/dist/ui/menu/menu-spawn-wizard.js +367 -0
  115. package/dist/ui/menu/menu-spawn-worktree.js +107 -0
  116. package/dist/ui/menu/menu-system-prompt.js +104 -0
  117. package/dist/ui/menu/menu-worktree-command.js +150 -0
  118. package/dist/ui/menu/menus.js +187 -0
  119. package/dist/ui/menu/model-picker.js +160 -0
  120. package/dist/ui/menu/screen-host.js +87 -0
  121. package/dist/ui/menu/submenus/confirm.js +23 -0
  122. package/dist/ui/menu/submenus/model-select.js +42 -0
  123. package/dist/ui/menu/submenus/name-field.js +43 -0
  124. package/dist/ui/menu/submenus/numeric-input.js +61 -0
  125. package/dist/ui/menu/submenus/target-select.js +129 -0
  126. package/dist/ui/menu/submenus/text-editor.js +49 -0
  127. package/dist/ui/menu/submenus/worktree-command-name.js +73 -0
  128. package/dist/ui/menu/submenus/worktree-name.js +53 -0
  129. package/dist/ui/menu/wrappers/settings-list.js +101 -0
  130. package/dist/ui/searchable-select.js +147 -0
  131. package/dist/ui/types.js +1 -0
  132. package/dist/utils.js +70 -0
  133. package/docs/assets/grazing.png +0 -0
  134. package/docs/assets/herdr-containers.png +0 -0
  135. package/docs/assets/logo-transparent.png +0 -0
  136. package/orchestrators/with-code-review.toml +20 -0
  137. package/package.json +109 -3
@@ -0,0 +1,39 @@
1
+ /**
2
+ * spawn-id.ts — the single canonical spawn identity.
3
+ * One id per spawn: worktree branch suffix, directory basename, agent/tab label, and spawn handle.
4
+ * 8 lowercase Crockford base32 chars (40 bits); unambiguous to copy, safe for branch/dir/herdr names.
5
+ * Uniqueness is the caller's business — see generateUniqueSpawnId.
6
+ */
7
+ import { randomBytes } from "node:crypto";
8
+ import { CrockfordBase32 } from "crockford-base32";
9
+ /** Spawn-id alphabet (lowercase Crockford base32); src/predicates.ts derives its pattern from this. */
10
+ export const SPAWN_ID_ALPHABET = "0123456789abcdefghjkmnpqrstvwxyz";
11
+ /** Exact length of every spawn id (40 bits ⇒ 8 base32 chars). */
12
+ export const SPAWN_ID_LENGTH = 8;
13
+ /** Random bytes per mint: 5 bytes = 40 bits = 8 base32 chars. */
14
+ const SPAWN_ID_BYTES = 5;
15
+ /** Unique-mint retry budget: bounded, never loops forever. */
16
+ export const SPAWN_ID_MINT_ATTEMPTS = 32;
17
+ /** Thrown when every mint attempt in the budget returned a taken id. */
18
+ export class SpawnIdExhaustedError extends Error {
19
+ constructor(attempts) {
20
+ super(`Could not mint a unique spawn id after ${attempts} attempts — the id space is exhausted or the taken-check is misreporting ids.`);
21
+ this.name = "SpawnIdExhaustedError";
22
+ }
23
+ }
24
+ /** Mint one spawn id. */
25
+ export function generateSpawnId() {
26
+ return CrockfordBase32.encode(randomBytes(SPAWN_ID_BYTES)).toLowerCase();
27
+ }
28
+ /**
29
+ * Mint an unclaimed spawn id, retrying taken candidates up to SPAWN_ID_MINT_ATTEMPTS times.
30
+ * `mint` is injectable so retry/exhaustion are testable without a random collision.
31
+ */
32
+ export function generateUniqueSpawnId(isTaken, mint = generateSpawnId) {
33
+ for (let attempt = 0; attempt < SPAWN_ID_MINT_ATTEMPTS; attempt++) {
34
+ const id = mint();
35
+ if (!isTaken(id))
36
+ return id;
37
+ }
38
+ throw new SpawnIdExhaustedError(SPAWN_ID_MINT_ATTEMPTS);
39
+ }
@@ -0,0 +1,137 @@
1
+ /**
2
+ * worktree-policy.ts — pure worktree placement, `cow-<task>-<id>` naming, and ownership recognition.
3
+ * The task slug comes from the cowboy_agent tool's required `task_name` parameter (no derivation fallback).
4
+ * Extension-owned = path under the worktree root AND basename with the `cow-` prefix.
5
+ */
6
+ import * as path from "node:path";
7
+ import { canonicalPath, defaultWorktreeRoot } from "../paths.js";
8
+ import { isAvailable } from "../availability.js";
9
+ import { SPAWN_ID_LENGTH } from "./spawn-id.js";
10
+ /** Branch prefix on every extension-created worktree (branch + tab label + path basename). */
11
+ const WORKTREE_BRANCH_PREFIX = "cow-";
12
+ /** Materialization used when none is configured. */
13
+ export const DEFAULT_WORKTREE_MATERIALIZATION = "copy-on-write";
14
+ /** Every selectable materialization, in menu order. */
15
+ export const VALID_WORKTREE_MATERIALIZATIONS = [
16
+ "copy-on-write",
17
+ "checkout",
18
+ ];
19
+ /** Parse untrusted materialization; invalid values fall back at the config boundary. */
20
+ export function parseWorktreeMaterialization(value) {
21
+ if (value === "copy-on-write" || value === "checkout")
22
+ return value;
23
+ return undefined;
24
+ }
25
+ /** Narrow untrusted input (config, menu) to a canonical materialization. */
26
+ export function isWorktreeMaterialization(value) {
27
+ return parseWorktreeMaterialization(value) !== undefined;
28
+ }
29
+ /**
30
+ * The materialization a spawn actually uses. A volume that cannot clone falls back
31
+ * to git's classic checkout whatever the setting says — the same answer the
32
+ * setting itself is narrowed to, so the menu can never disagree with a spawn.
33
+ */
34
+ export function resolveWorktreeMaterialization(configured, availability) {
35
+ if (!isAvailable("copy-on-write", availability))
36
+ return "checkout";
37
+ return configured ?? DEFAULT_WORKTREE_MATERIALIZATION;
38
+ }
39
+ /** Policy used when none is configured. */
40
+ export const DEFAULT_WORKTREE_CHECKOUT_TYPE = "clean";
41
+ /** Every selectable dirty-checkout policy, in menu order. */
42
+ export const VALID_WORKTREE_CHECKOUT_TYPES = [
43
+ "dirty",
44
+ "clean",
45
+ ];
46
+ /** Parse an untrusted dirty-checkout policy; invalid values fall back at the config boundary. */
47
+ export function parseWorktreeCheckoutType(value) {
48
+ if (value === "dirty" || value === "clean")
49
+ return value;
50
+ return undefined;
51
+ }
52
+ /** Narrow untrusted input (config, menu, template) to a canonical dirty-checkout policy. */
53
+ export function isWorktreeCheckoutType(value) {
54
+ return parseWorktreeCheckoutType(value) !== undefined;
55
+ }
56
+ /** Max words in a task slug (fits small UI elements). */
57
+ const TASK_SLUG_MAX_WORDS = 3;
58
+ /** herdr caps an agent name at 32 characters — the one value every name-length rule reads. */
59
+ export const HERDR_AGENT_NAME_MAX_LENGTH = 32;
60
+ /** Max slug length: a generated name spends `cow-`, `-`, and the spawn id, so the slug gets the rest. */
61
+ const TASK_SLUG_MAX_LENGTH = HERDR_AGENT_NAME_MAX_LENGTH -
62
+ WORKTREE_BRANCH_PREFIX.length -
63
+ 1 -
64
+ SPAWN_ID_LENGTH;
65
+ /** Lowercase a branch-name part into a filesystem/branch-safe slug; empty input gives "agent". */
66
+ export function slugifyWorktreeType(typeName) {
67
+ const slug = typeName
68
+ .toLowerCase()
69
+ .replace(/[^a-z0-9_-]+/g, "-")
70
+ .replace(/^-+|-+$/g, "");
71
+ return slug || "agent";
72
+ }
73
+ /** The words a task name contributes to its branch name. */
74
+ function taskNameWords(input) {
75
+ return input
76
+ .toLowerCase()
77
+ .replace(/[^a-z0-9]+/g, " ")
78
+ .trim()
79
+ .split(/\s+/)
80
+ .filter((w) => w.length > 0);
81
+ }
82
+ /** Turn an orchestrator-assigned name into a slug. Over-limit names throw (never truncate); empty throws too. */
83
+ export function buildTaskSlug(input) {
84
+ const words = taskNameWords(input);
85
+ if (words.length === 0) {
86
+ throw new Error("Task name is empty — provide a short 2-3 word name.");
87
+ }
88
+ if (words.length > TASK_SLUG_MAX_WORDS) {
89
+ throw new Error(`Task name "${input}" gives the branch name "${words.join("-")}" with ${words.length} words. The limit is ${TASK_SLUG_MAX_WORDS} words.`);
90
+ }
91
+ const slug = words.join("-");
92
+ if (slug.length > TASK_SLUG_MAX_LENGTH) {
93
+ throw new Error(`Task name "${input}" gives the branch name "${slug}" with ${slug.length} characters. The limit is ${TASK_SLUG_MAX_LENGTH} characters, because herdr limits agent names to 32 characters.`);
94
+ }
95
+ return slug;
96
+ }
97
+ /** Build the worktree branch/basename: `cow-<task>-<id>`. */
98
+ export function buildWorktreeBranch(taskSlug, id) {
99
+ return `${WORKTREE_BRANCH_PREFIX}${slugifyWorktreeType(taskSlug)}-${id}`;
100
+ }
101
+ /** Absolute path of a worktree under the given root. */
102
+ export function buildWorktreePath(root, taskSlug, id) {
103
+ return path.join(root, buildWorktreeBranch(taskSlug, id));
104
+ }
105
+ /** Resolve the worktree root: configured value as-is (relative against the repo root), else the extension working dir's `worktrees` subdir. */
106
+ export function resolveWorktreeRoot(configRoot, repoRoot) {
107
+ if (configRoot && configRoot.trim() !== "") {
108
+ return path.isAbsolute(configRoot)
109
+ ? configRoot
110
+ : path.resolve(repoRoot, configRoot);
111
+ }
112
+ return defaultWorktreeRoot();
113
+ }
114
+ /** Normalize a path for prefix comparison: the one real spelling, where one exists. */
115
+ function normalizeRoot(value) {
116
+ const canonical = canonicalPath(value) ?? value.replace(/\\/g, "/");
117
+ return canonical.replace(/\/+$/, "");
118
+ }
119
+ /**
120
+ * True when a name answers to a spawn id: `cow-` prefixed with that exact id suffix.
121
+ * Exact on purpose — the `cow-` prefix keeps a user's own same-suffixed branch out.
122
+ */
123
+ export function isSpawnArtifactName(name, id) {
124
+ return (id !== "" &&
125
+ name.startsWith(WORKTREE_BRANCH_PREFIX) &&
126
+ name.length > id.length &&
127
+ name.endsWith(`-${id}`));
128
+ }
129
+ /** True when a worktree is extension-owned: path inside the root AND `cow-` basename. */
130
+ export function isExtensionWorktree(worktreePath, root) {
131
+ const p = normalizeRoot(worktreePath);
132
+ const r = normalizeRoot(root);
133
+ if (p !== r && !p.startsWith(`${r}/`))
134
+ return false;
135
+ const base = p.split("/").filter(Boolean).pop() ?? "";
136
+ return base.startsWith(WORKTREE_BRANCH_PREFIX);
137
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * status-note.ts — the parenthetical note appended to a settled agent's result.
3
+ * Only stopped runs get one (who stopped it, and whether it ever started).
4
+ * A completed run carries no note: its result text IS the report.
5
+ */
6
+ import { hasOutcome, } from "./types.js";
7
+ const STOP_NOTES = {
8
+ user: "STOPPED BY THE USER before completion — output is partial; the task was NOT finished",
9
+ agent: "STOPPED BY YOU before completion — output is partial; the task was NOT finished",
10
+ };
11
+ /** Never-started spawns have no partial output, so the note says the task was not attempted. */
12
+ const NEVER_STARTED_STOP_NOTES = {
13
+ user: "STOPPED BY THE USER before the agent started — the task was NOT attempted",
14
+ agent: "STOPPED BY YOU before the agent started — the task was NOT attempted",
15
+ };
16
+ function stopNote(state) {
17
+ if (!hasOutcome(state) || state.status !== "stopped") {
18
+ // Unreachable — stopNote is only reached for stopped spawns.
19
+ return STOP_NOTES.agent;
20
+ }
21
+ const { stop } = state;
22
+ return state.phase === "never-started"
23
+ ? NEVER_STARTED_STOP_NOTES[stop.initiator]
24
+ : STOP_NOTES[stop.initiator];
25
+ }
26
+ export function getStatusNote(state) {
27
+ if (!hasOutcome(state) || state.status !== "stopped")
28
+ return "";
29
+ return ` (${stopNote(state)})`;
30
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * ipc-protocol.ts — the readiness handshake both ends share.
3
+ *
4
+ * The parent binds a per-agent endpoint before launching a subagent; the child
5
+ * pi process connects at boot and sends one ready frame carrying its own pid.
6
+ * The frame shape, its validation, and the child's one call live together here
7
+ * so the two ends cannot drift.
8
+ */
9
+ import { createLogger } from "../logger.js";
10
+ import { detectSubagentSpawn } from "../shell.js";
11
+ import { errorMessage } from "../utils.js";
12
+ import { createIpcClient, getIpcAddress, } from "./socket-ipc.js";
13
+ const log = createLogger("handshake");
14
+ /** The ready frame a child sends for itself; `pid` is a parameter so no test needs a child process. */
15
+ export function readyFrameFor(agentId, pid = process.pid) {
16
+ return { kind: "ready", agentId, pid };
17
+ }
18
+ /** Narrow an untrusted frame to the recognized union; null for anything unrecognized. */
19
+ export function parseSubagentFrame(value) {
20
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
21
+ return null;
22
+ }
23
+ const { kind, agentId, pid } = value;
24
+ if (kind !== "ready")
25
+ return null;
26
+ if (typeof agentId !== "string" || agentId === "")
27
+ return null;
28
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0)
29
+ return null;
30
+ return { kind: "ready", agentId, pid };
31
+ }
32
+ /**
33
+ * Tell the parent this process booted. Fire-and-forget and never throwing: the
34
+ * parent may have no listener (extensions disabled, a listener that failed to
35
+ * bind), and a missing handshake must not disturb the subagent's own work.
36
+ */
37
+ export function announceSubagentReady(agentId, deps = {}) {
38
+ const createClient = deps.createClient ?? createIpcClient;
39
+ void sendReady(agentId, createClient).catch((error) => {
40
+ log.warn("subagent readiness handshake failed", {
41
+ agentId,
42
+ errorMessage: errorMessage(error),
43
+ });
44
+ });
45
+ }
46
+ /**
47
+ * The delegated process's boot action. True when this argv carries a subagent
48
+ * token (the caller stays inert — and the parent was told); false for a root
49
+ * session, which announces nothing.
50
+ */
51
+ export function announceReadyForSpawn(argv = process.argv, announce = announceSubagentReady) {
52
+ const agentId = detectSubagentSpawn(argv);
53
+ if (agentId === undefined)
54
+ return false;
55
+ announce(agentId);
56
+ return true;
57
+ }
58
+ async function sendReady(agentId, createClient) {
59
+ const client = await createClient(getIpcAddress(agentId));
60
+ try {
61
+ const frame = { ...readyFrameFor(agentId) };
62
+ client.send(frame);
63
+ }
64
+ finally {
65
+ // Flush the frame, then close; a disconnect failure cannot undo delivery.
66
+ await client.disconnect().catch(() => { });
67
+ }
68
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * subagent/ipc.ts — SubagentIPC: the parent↔subagent message plane.
3
+ *
4
+ * The parent half is the HerdrSubagentIPC: a result file the child writes and
5
+ * the readiness endpoint the child announces its boot on.
6
+ */
7
+ import fs from "node:fs";
8
+ import * as path from "node:path";
9
+ import { createLogger } from "../logger.js";
10
+ import { errorMessage } from "../utils.js";
11
+ import { parseSubagentFrame } from "./ipc-protocol.js";
12
+ import { createIpcServer, getIpcAddress, } from "./socket-ipc.js";
13
+ const log = createLogger("ipc");
14
+ /** SubagentIPC for a subagent in a herdr pane: files, readiness channel, teardown. */
15
+ export class HerdrSubagentIPC {
16
+ agentId;
17
+ resultFile;
18
+ onFrame;
19
+ channel = null;
20
+ constructor(options) {
21
+ this.agentId = options.agentId;
22
+ this.resultFile = options.resultFile;
23
+ this.onFrame = options.onFrame;
24
+ }
25
+ /**
26
+ * Bind the run's endpoint. Resolves once listening, so the caller launches the
27
+ * child only when the parent is already reachable. One bind per run.
28
+ */
29
+ async start() {
30
+ if (this.channel !== null)
31
+ return;
32
+ const address = getIpcAddress(this.agentId);
33
+ this.channel = await createIpcServer(address, {
34
+ onMessage: (message) => this.handleFrame(message),
35
+ onError: (error) => log.warn("readiness channel error", {
36
+ agentId: this.agentId,
37
+ errorMessage: errorMessage(error),
38
+ }),
39
+ });
40
+ log.debug("readiness channel bound", { agentId: this.agentId, address });
41
+ }
42
+ /** Idempotent: close the channel and unlink the endpoint. */
43
+ async close() {
44
+ const server = this.channel;
45
+ if (server === null)
46
+ return;
47
+ this.channel = null;
48
+ await server.close().catch((error) => {
49
+ log.warn("readiness channel close failed", {
50
+ agentId: this.agentId,
51
+ errorMessage: errorMessage(error),
52
+ });
53
+ });
54
+ }
55
+ /**
56
+ * One frame from the child. A frame this run cannot claim — unparseable, or
57
+ * naming another agent — is dropped; the channel stays up either way.
58
+ */
59
+ handleFrame(message) {
60
+ const frame = parseSubagentFrame(message);
61
+ if (frame === null) {
62
+ log.debug("ignoring unrecognized frame", { agentId: this.agentId });
63
+ return;
64
+ }
65
+ if (frame.agentId !== this.agentId) {
66
+ log.warn("ignoring frame for another agent", {
67
+ agentId: this.agentId,
68
+ announcedAgentId: frame.agentId,
69
+ });
70
+ return;
71
+ }
72
+ log.debug("received frame", { agentId: this.agentId, kind: frame.kind });
73
+ this.onFrame?.(frame);
74
+ }
75
+ /**
76
+ * The child's last report, or null when it is absent, unreadable, or blank —
77
+ * the run has not finished. The content rides with the file's modification
78
+ * time, because a rewritten report of the same words is still news. The stamp
79
+ * is sampled before the content: a write landing between the two calls leaves
80
+ * the pair understating the file rather than overstating it, and the next poll
81
+ * corrects it.
82
+ */
83
+ async readDeliverable() {
84
+ try {
85
+ const mtime = fs.statSync(this.resultFile).mtimeMs;
86
+ const content = fs.readFileSync(this.resultFile, "utf-8").trim();
87
+ if (!content)
88
+ return null;
89
+ return { content, mtime };
90
+ }
91
+ catch {
92
+ return null;
93
+ }
94
+ }
95
+ }
96
+ /**
97
+ * Remove a run's result directory. Best effort, and safe when it is already
98
+ * gone — the files are ephemeral temp-dir artifacts.
99
+ *
100
+ * The artifacts outlive settlement: a settled run stays watched, so the child
101
+ * may keep writing reports to this same directory until the run is dropped.
102
+ */
103
+ export function removeResultArtifacts(resultFile) {
104
+ try {
105
+ fs.rmSync(path.dirname(resultFile), { recursive: true, force: true });
106
+ }
107
+ catch {
108
+ // Best effort: the agent's files are ephemeral temp-dir artifacts.
109
+ }
110
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * pane-supervisor.ts — Build the supervisor for one child process in a pane.
3
+ *
4
+ * Both attempt origins need the same construction: a SubagentIPC whose
5
+ * onFrame carries the child's frames, wrapped in a ProcessSupervisorEngine (a
6
+ * constructor that takes exactly that IPC). This module builds that pair and
7
+ * nothing else —
8
+ * launching the process (start), binding a live one (adopt), and beginning the
9
+ * watch all stay with the caller, which owns the placement and the checkpoint
10
+ * that may discard it, and which also drives the channel (IPC start/close).
11
+ */
12
+ import { ProcessSupervisorEngine, } from "./supervisor.js";
13
+ /** Wire the IPC and the engine over it. Starts, adopts, watches, and binds nothing. */
14
+ export function createPaneSupervisor(input) {
15
+ const ipc = input.transport.createIpc({
16
+ agentId: input.agentId,
17
+ resultFile: input.resultFile,
18
+ onFrame: input.onFrame,
19
+ });
20
+ return {
21
+ supervisor: new ProcessSupervisorEngine(input.host, ipc, input.supervisorOptions),
22
+ ipc,
23
+ };
24
+ }
@@ -0,0 +1,240 @@
1
+ /**
2
+ * subagent/socket-ipc.ts — local IPC transport: newline-delimited JSON over node:net.
3
+ *
4
+ * One address per channel (a Unix domain socket under os.tmpdir() on POSIX, a
5
+ * named pipe on Windows), one server, any number of clients. A frame is one JSON
6
+ * object on one line; the reader tolerates split chunks, CRLF endings, and blank
7
+ * lines, and never throws on a malformed peer. The message payload is the
8
+ * caller's contract — the transport only requires a JSON object.
9
+ */
10
+ import { createHash } from "node:crypto";
11
+ import { unlinkSync } from "node:fs";
12
+ import { connect, createServer } from "node:net";
13
+ import { tmpdir } from "node:os";
14
+ import { join } from "node:path";
15
+ /**
16
+ * Longest frame body tolerated without a newline. A peer that sends more has that
17
+ * frame dropped — a truncated giant frame must not be mistaken for a message.
18
+ */
19
+ export const MAX_FRAME_CHARS = 1_048_576;
20
+ /** Longest sanitized id carried in an address, keeping the POSIX path inside sun_path's 104-byte limit. */
21
+ const MAX_ADDRESS_ID_CHARS = 32;
22
+ /** Characters an agent id keeps in an address; every other character becomes "_". */
23
+ const UNSAFE_ADDRESS_CHARS = /[^A-Za-z0-9._-]/g;
24
+ /** One character an address can carry; an id with none has no address to be distinct in. */
25
+ const SAFE_ADDRESS_CHAR = /[A-Za-z0-9._-]/;
26
+ /** A named pipe is not a filesystem entry, so nothing may be unlinked for one. */
27
+ const NAMED_PIPE_PREFIX = "\\\\.\\pipe\\";
28
+ /**
29
+ * The address a local IPC channel for `agentId` listens on. `platform` is a
30
+ * parameter so the Windows and POSIX shapes are both testable from one host.
31
+ */
32
+ export function getIpcAddress(agentId, platform = process.platform) {
33
+ const safe = sanitizeAddressId(agentId);
34
+ return platform === "win32"
35
+ ? `${NAMED_PIPE_PREFIX}cowboy-${safe}`
36
+ : join(tmpdir(), `cowboy-ipc-${safe}.sock`);
37
+ }
38
+ /**
39
+ * Build a decoder for one byte stream. `onMessage` sees every complete frame in
40
+ * order; `onError` sees each dropped frame (malformed JSON, non-object JSON,
41
+ * oversized). Without `onError` those frames are dropped silently.
42
+ */
43
+ export function createNdjsonDecoder(onMessage, onError) {
44
+ let buffer = "";
45
+ // Once a frame is dropped for size, everything up to its terminating newline is
46
+ // that frame's tail; without this, the tail would be read as the next frame.
47
+ let discardingOversized = false;
48
+ return {
49
+ push(chunk) {
50
+ buffer += chunk;
51
+ let newline = buffer.indexOf("\n");
52
+ while (newline !== -1) {
53
+ const line = buffer.slice(0, newline).trim();
54
+ buffer = buffer.slice(newline + 1);
55
+ newline = buffer.indexOf("\n");
56
+ if (discardingOversized) {
57
+ discardingOversized = false;
58
+ continue;
59
+ }
60
+ if (line)
61
+ parseFrame(line, onMessage, onError);
62
+ }
63
+ if (discardingOversized) {
64
+ // Only the next newline matters; the retained tail is discarded frames.
65
+ buffer = "";
66
+ }
67
+ else if (buffer.length > MAX_FRAME_CHARS) {
68
+ onError?.(new Error(`ipc: dropping a ${buffer.length}-char frame with no newline within ${MAX_FRAME_CHARS} chars`));
69
+ buffer = "";
70
+ discardingOversized = true;
71
+ }
72
+ },
73
+ };
74
+ }
75
+ /**
76
+ * Listen on `address`. Resolves once the socket is bound, and rejects if the bind
77
+ * fails — including EADDRINUSE from a live peer, since a leftover socket file is
78
+ * removed before binding but a live listener is not something this can detect.
79
+ */
80
+ export async function createIpcServer(address, options) {
81
+ const report = (error) => options.onError?.(error);
82
+ const server = createServer();
83
+ const connections = new Map();
84
+ let nextConnectionId = 1;
85
+ let closed = false;
86
+ discardSocketFile(address, report);
87
+ server.on("connection", (socket) => {
88
+ const connectionId = `c${nextConnectionId++}`;
89
+ connections.set(connectionId, socket);
90
+ socket.setEncoding("utf8");
91
+ const decoder = createNdjsonDecoder(options.onMessage, report);
92
+ // setEncoding makes this a string at runtime; toString() is the no-op the Buffer typing asks for.
93
+ socket.on("data", (chunk) => decoder.push(chunk.toString()));
94
+ socket.on("error", report);
95
+ socket.on("close", () => {
96
+ connections.delete(connectionId);
97
+ options.onDisconnect?.(connectionId);
98
+ });
99
+ options.onConnect?.(connectionId);
100
+ });
101
+ await new Promise((resolve, reject) => {
102
+ const onBindError = (error) => reject(error);
103
+ server.once("error", onBindError);
104
+ server.listen(address, () => {
105
+ server.off("error", onBindError);
106
+ server.on("error", report);
107
+ resolve();
108
+ });
109
+ });
110
+ return {
111
+ address,
112
+ broadcast(message) {
113
+ if (closed)
114
+ throw new Error("ipc: server is closed");
115
+ const line = `${JSON.stringify(message)}\n`;
116
+ for (const socket of connections.values())
117
+ socket.write(line);
118
+ },
119
+ send(connectionId, message) {
120
+ if (closed)
121
+ throw new Error("ipc: server is closed");
122
+ const socket = connections.get(connectionId);
123
+ if (!socket)
124
+ throw new Error(`ipc: unknown connection ${connectionId}`);
125
+ socket.write(`${JSON.stringify(message)}\n`);
126
+ },
127
+ async close() {
128
+ if (closed)
129
+ return;
130
+ closed = true;
131
+ for (const socket of connections.values())
132
+ socket.destroy();
133
+ connections.clear();
134
+ await new Promise((resolve) => {
135
+ server.close(() => resolve());
136
+ });
137
+ discardSocketFile(address, report);
138
+ },
139
+ };
140
+ }
141
+ /**
142
+ * Connect to `address`. Resolves once connected, and rejects if the connection
143
+ * fails (a missing listener is the common case). A socket "error" never goes
144
+ * unhandled: before the connect settles it rejects this promise, after that it
145
+ * goes to `onError`.
146
+ */
147
+ export async function createIpcClient(address, options = {}) {
148
+ const socket = connect(address);
149
+ let disconnected = false;
150
+ let rejectConnect = null;
151
+ socket.setEncoding("utf8");
152
+ socket.on("error", (error) => {
153
+ if (rejectConnect)
154
+ rejectConnect(error);
155
+ else
156
+ options.onError?.(error);
157
+ });
158
+ const { onMessage } = options;
159
+ if (onMessage) {
160
+ const decoder = createNdjsonDecoder(onMessage, options.onError);
161
+ socket.on("data", (chunk) => decoder.push(chunk.toString()));
162
+ }
163
+ await new Promise((resolve, reject) => {
164
+ rejectConnect = (error) => reject(error);
165
+ socket.once("connect", () => {
166
+ rejectConnect = null;
167
+ resolve();
168
+ });
169
+ });
170
+ return {
171
+ address,
172
+ send(message) {
173
+ if (disconnected)
174
+ throw new Error("ipc: client is disconnected");
175
+ socket.write(`${JSON.stringify(message)}\n`);
176
+ },
177
+ async disconnect() {
178
+ if (disconnected)
179
+ return;
180
+ disconnected = true;
181
+ await new Promise((resolve) => {
182
+ if (socket.destroyed || socket.readyState === "closed") {
183
+ resolve();
184
+ return;
185
+ }
186
+ // Flush what is queued, then destroy: the peer's FIN is not what ends
187
+ // this socket, and an inbound stream nobody reads (a send-only client)
188
+ // would keep "close" back forever while we waited for it.
189
+ socket.once("close", () => resolve());
190
+ socket.end(() => socket.destroy());
191
+ });
192
+ },
193
+ };
194
+ }
195
+ /** Compact an agent id into address characters, hashing what truncation would otherwise merge. */
196
+ function sanitizeAddressId(agentId) {
197
+ if (!SAFE_ADDRESS_CHAR.test(agentId)) {
198
+ throw new Error("getIpcAddress requires an agent id with at least one [A-Za-z0-9._-] character");
199
+ }
200
+ const safe = agentId.replace(UNSAFE_ADDRESS_CHARS, "_");
201
+ if (safe.length <= MAX_ADDRESS_ID_CHARS)
202
+ return safe;
203
+ const digest = createHash("sha256").update(agentId).digest("hex");
204
+ // "-" + 8 hex chars fills the cap, so two long ids sharing a prefix stay distinct.
205
+ return `${safe.slice(0, MAX_ADDRESS_ID_CHARS - 9)}-${digest.slice(0, 8)}`;
206
+ }
207
+ function isNamedPipeAddress(address) {
208
+ return address.startsWith(NAMED_PIPE_PREFIX);
209
+ }
210
+ /** Best-effort removal of a stale POSIX socket file; failures are reported, never thrown. */
211
+ function discardSocketFile(address, report) {
212
+ if (isNamedPipeAddress(address))
213
+ return;
214
+ try {
215
+ unlinkSync(address);
216
+ }
217
+ catch (error) {
218
+ const code = error.code;
219
+ if (code !== "ENOENT")
220
+ report(error);
221
+ }
222
+ }
223
+ function parseFrame(line, onMessage, onError) {
224
+ let parsed;
225
+ try {
226
+ parsed = JSON.parse(line);
227
+ }
228
+ catch {
229
+ onError?.(new Error(`ipc: dropping an unparsable ${line.length}-char frame`));
230
+ return;
231
+ }
232
+ if (!isIpcMessage(parsed)) {
233
+ onError?.(new Error(`ipc: dropping a non-object ${line.length}-char frame`));
234
+ return;
235
+ }
236
+ onMessage(parsed);
237
+ }
238
+ function isIpcMessage(value) {
239
+ return typeof value === "object" && value !== null && !Array.isArray(value);
240
+ }