pi-cowboy 0.3.7 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agents/agent-assets.js +2 -1
- package/dist/agents/agent-manager.js +13 -5
- package/dist/agents/agent-reviver.js +4 -9
- package/dist/agents/agent-runner.js +2 -2
- package/dist/agents/subagent-session.js +6 -71
- package/dist/index.js +3 -5
- package/dist/orchestrators/protocol.js +13 -1
- package/dist/paths.js +44 -6
- package/dist/shell.js +5 -32
- package/dist/spawn/spawn-coordinator.js +2 -2
- package/dist/subagent/deliverable.js +39 -0
- package/dist/subagent/pane-supervisor.js +8 -17
- package/dist/subagent/result-artifacts.js +25 -0
- package/dist/subagent/supervisor.js +5 -5
- package/dist/types.js +0 -7
- package/package.json +1 -1
- package/dist/subagent/ipc-protocol.js +0 -68
- package/dist/subagent/ipc.js +0 -110
- package/dist/subagent/socket-ipc.js +0 -240
|
@@ -13,7 +13,8 @@ import * as path from "node:path";
|
|
|
13
13
|
import { deleteWorktreeBranch, isWorktreeDirty, removeGitWorktree, resolveMainCheckout, } from "../infrastructure/git-client.js";
|
|
14
14
|
import { getAgentInfo, listAgentRecords, listWorktrees, normalizeHerdrPath, } from "../infrastructure/herdr-client.js";
|
|
15
15
|
import { createHerdrHost } from "../infrastructure/herdr-host.js";
|
|
16
|
-
import { getSessionCtx, getStore
|
|
16
|
+
import { getSessionCtx, getStore } from "../shell.js";
|
|
17
|
+
import { subagentResultFileFor } from "../paths.js";
|
|
17
18
|
import { buildWorktreeBranch, isExtensionWorktree, isSpawnArtifactName, resolveWorktreeRoot, slugifyWorktreeType, } from "../spawn/worktree-policy.js";
|
|
18
19
|
async function probeList(read) {
|
|
19
20
|
try {
|
|
@@ -1,17 +1,25 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* agent-manager.ts — Fleet controller for independently running subagents.
|
|
3
|
-
* Exports AgentManager, ClearOutcome/ClearRefusal; re-exports
|
|
4
|
-
*
|
|
3
|
+
* Exports AgentManager, ClearOutcome/ClearRefusal; re-exports spawn and steer
|
|
4
|
+
* types.
|
|
5
5
|
*/
|
|
6
|
-
import { getAgentSpawns, getCoordinatorOrNull, getPiInstance, getSessionCtx,
|
|
6
|
+
import { getAgentSpawns, getCoordinatorOrNull, getPiInstance, getSessionCtx, } from "../shell.js";
|
|
7
|
+
import { subagentResultFileFor } from "../paths.js";
|
|
8
|
+
import { createHerdrRuntime } from "../infrastructure/herdr-host.js";
|
|
7
9
|
import { HerdrTaskRegistry, } from "../task-registry.js";
|
|
8
10
|
import { createLogger } from "../logger.js";
|
|
9
11
|
import { errorMessage } from "../utils.js";
|
|
10
12
|
import { ACTIVE_AGENT_PHASES, ALL_AGENT_PHASES, hasOutcome, lifecycleStartTime, lifecycleStatus, } from "../types.js";
|
|
11
|
-
import {
|
|
13
|
+
import { FileDeliverable } from "../subagent/deliverable.js";
|
|
14
|
+
import { removeResultArtifacts } from "../subagent/result-artifacts.js";
|
|
12
15
|
import { createCleanup } from "./agent-cleanup.js";
|
|
13
16
|
import { createHerdrAgentAssets, } from "./agent-assets.js";
|
|
14
|
-
import { DISPOSE_QUEUED_MESSAGE, SubagentSession,
|
|
17
|
+
import { DISPOSE_QUEUED_MESSAGE, SubagentSession, } from "./subagent-session.js";
|
|
18
|
+
/** The transport the manager wires its sessions with unless the caller supplies one. */
|
|
19
|
+
export const defaultAgentManagerTransport = {
|
|
20
|
+
createHost: (pi) => createHerdrRuntime(pi).host,
|
|
21
|
+
createDeliverable: (resultFile) => new FileDeliverable(resultFile),
|
|
22
|
+
};
|
|
15
23
|
/**
|
|
16
24
|
* Removal address for a spawn's owned checkout. An owned checkout that no
|
|
17
25
|
* recorded repository cwd can reach is `unaddressable`: its teardown has no
|
|
@@ -13,7 +13,8 @@
|
|
|
13
13
|
*/
|
|
14
14
|
import * as fs from "node:fs";
|
|
15
15
|
import * as path from "node:path";
|
|
16
|
-
import { getPiInstance
|
|
16
|
+
import { getPiInstance } from "../shell.js";
|
|
17
|
+
import { subagentResultFileFor } from "../paths.js";
|
|
17
18
|
import { createPaneSupervisor, } from "../subagent/pane-supervisor.js";
|
|
18
19
|
import { ensureResultDir } from "./result-file-permissions.js";
|
|
19
20
|
/**
|
|
@@ -31,12 +32,11 @@ export function reviveSettledRun(request) {
|
|
|
31
32
|
// fails instead of continuing with world-readable secrets.
|
|
32
33
|
ensureResultDir(resultDir);
|
|
33
34
|
fs.rmSync(launch.resultFile, { force: true });
|
|
34
|
-
const
|
|
35
|
+
const supervisor = createPaneSupervisor({
|
|
35
36
|
host: transport.createHost(getPiInstance()),
|
|
36
37
|
resultFile: launch.resultFile,
|
|
37
38
|
supervisorOptions: request.supervisorOptions,
|
|
38
39
|
transport,
|
|
39
|
-
agentId: spawn.id,
|
|
40
40
|
});
|
|
41
41
|
// Adopted, never launched: the pane already holds the run's pi process.
|
|
42
42
|
supervisor.adopt(hostRef);
|
|
@@ -48,17 +48,12 @@ export function reviveSettledRun(request) {
|
|
|
48
48
|
}
|
|
49
49
|
/**
|
|
50
50
|
* What the revived turn resumes: the settled turn's own artifacts, or a fresh
|
|
51
|
-
* report path for a run that settled before it launched anything.
|
|
52
|
-
* turn binds no channel and the child does not reboot, so only an
|
|
53
|
-
* announcement already heard still names its process.
|
|
51
|
+
* report path for a run that settled before it launched anything.
|
|
54
52
|
*/
|
|
55
53
|
function resumeLaunch(spawn) {
|
|
56
54
|
const { lifecycle } = spawn;
|
|
57
55
|
const resumed = lifecycle.phase === "settled" ? lifecycle.launch : undefined;
|
|
58
56
|
return {
|
|
59
57
|
resultFile: resumed?.resultFile ?? subagentResultFileFor(spawn.id),
|
|
60
|
-
handshake: resumed?.handshake?.kind === "announced"
|
|
61
|
-
? resumed.handshake
|
|
62
|
-
: { kind: "unavailable", reason: "revive" },
|
|
63
58
|
};
|
|
64
59
|
}
|
|
@@ -10,8 +10,8 @@ import fs from "node:fs";
|
|
|
10
10
|
import path from "node:path";
|
|
11
11
|
import { SettingsManager, } from "@earendil-works/pi-coding-agent";
|
|
12
12
|
import { errorMessage } from "../utils.js";
|
|
13
|
-
import { agentDir } from "../paths.js";
|
|
14
|
-
import { getStore
|
|
13
|
+
import { agentDir, subagentResultDirFor, subagentResultFileFor, subagentSystemFileFor, subagentTaskFileFor, subagentTokenFor, } from "../paths.js";
|
|
14
|
+
import { getStore } from "../shell.js";
|
|
15
15
|
import { buildSubagentSystemPrompt, buildWorktreeBranchSection, } from "../prompt/subagent-system-prompt.js";
|
|
16
16
|
import { getAgentConfig, getConfig, } from "./agent-types.js";
|
|
17
17
|
import { ensureResultDir, writeResultFile } from "./result-file-permissions.js";
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* subagent-session.ts — One subagent run's lifecycle and spawn projection.
|
|
3
|
-
* Exports SubagentSession, buildAgentSpawn, DISPOSE_QUEUED_MESSAGE
|
|
3
|
+
* Exports SubagentSession, buildAgentSpawn, DISPOSE_QUEUED_MESSAGE.
|
|
4
4
|
*/
|
|
5
5
|
import { createLogger } from "../logger.js";
|
|
6
|
-
import { createHerdrRuntime } from "../infrastructure/herdr-host.js";
|
|
7
6
|
import { worktreeRetentionReason } from "../infrastructure/git-client.js";
|
|
8
|
-
import { getAgentSpawns, getPiInstance, getStore, getWorktreeMaterialization,
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
7
|
+
import { getAgentSpawns, getPiInstance, getStore, getWorktreeMaterialization, } from "../shell.js";
|
|
8
|
+
import { subagentResultFileFor } from "../paths.js";
|
|
9
|
+
import { removeResultArtifacts } from "../subagent/result-artifacts.js";
|
|
10
|
+
import { createPaneSupervisor, } from "../subagent/pane-supervisor.js";
|
|
11
11
|
import { lifecycleResult } from "../types.js";
|
|
12
12
|
import { errorMessage } from "../utils.js";
|
|
13
13
|
import { buildWorktreeBranch, slugifyWorktreeType, } from "../spawn/worktree-policy.js";
|
|
@@ -19,10 +19,6 @@ import { abortQueuedRun, activateRun, createRun, disposeLiveRun, disposeQueuedRu
|
|
|
19
19
|
import { reviveSettledRun } from "./agent-reviver.js";
|
|
20
20
|
export { DISPOSE_QUEUED_MESSAGE } from "./run-state.js";
|
|
21
21
|
const log = createLogger("session");
|
|
22
|
-
export const defaultAgentManagerTransport = {
|
|
23
|
-
createHost: (pi) => createHerdrRuntime(pi).host,
|
|
24
|
-
createIpc: (options) => new HerdrSubagentIPC(options),
|
|
25
|
-
};
|
|
26
22
|
/** Spawn is born queued and mutated in place; its identity is public API. */
|
|
27
23
|
export function buildAgentSpawn(args, promise) {
|
|
28
24
|
const { type, options } = args;
|
|
@@ -81,8 +77,6 @@ export class SubagentSession {
|
|
|
81
77
|
retention;
|
|
82
78
|
/** Live supervisor attachment: launched, or adopted on revive. */
|
|
83
79
|
supervisor;
|
|
84
|
-
/** The run's channel: bound before the launch, released when the run is over for us. */
|
|
85
|
-
ipc;
|
|
86
80
|
parentBinding;
|
|
87
81
|
constructor({ id, args, deps }) {
|
|
88
82
|
this.id = id;
|
|
@@ -280,7 +274,6 @@ export class SubagentSession {
|
|
|
280
274
|
// it; only a run whose removal is confirmed lets go of its artifacts.
|
|
281
275
|
this.supervisor?.detach();
|
|
282
276
|
this.supervisor = undefined;
|
|
283
|
-
this.closeChannel();
|
|
284
277
|
removeResultArtifacts(this.resultFilePath());
|
|
285
278
|
this.detachParentBinding();
|
|
286
279
|
this.gate.open("");
|
|
@@ -298,7 +291,6 @@ export class SubagentSession {
|
|
|
298
291
|
// Disposal stops tracking only: abandon the poll loop, leave pane and process alive.
|
|
299
292
|
this.supervisor?.abandon();
|
|
300
293
|
this.supervisor = undefined;
|
|
301
|
-
this.closeChannel();
|
|
302
294
|
this.detachParentBinding();
|
|
303
295
|
}
|
|
304
296
|
async launch() {
|
|
@@ -379,18 +371,13 @@ export class SubagentSession {
|
|
|
379
371
|
this.spawn.execution.host = ref;
|
|
380
372
|
// The pane exists now, so the harness can bring it into its launch state.
|
|
381
373
|
await harness.prepare({ pi, paneId: ref.paneId, cwd: plan.cwd });
|
|
382
|
-
const
|
|
374
|
+
const supervisor = createPaneSupervisor({
|
|
383
375
|
host,
|
|
384
376
|
resultFile: launch.resultFile,
|
|
385
377
|
supervisorOptions: this.supervisorOptions(),
|
|
386
378
|
transport: this.deps.transport,
|
|
387
|
-
agentId: this.spawn.id,
|
|
388
|
-
onFrame: (frame) => this.handleFrame(launch, frame),
|
|
389
379
|
});
|
|
390
380
|
this.supervisor = supervisor;
|
|
391
|
-
this.ipc = ipc;
|
|
392
|
-
// The child connects at boot, so the parent must already be listening.
|
|
393
|
-
await this.openChannel(launch);
|
|
394
381
|
await supervisor.start({
|
|
395
382
|
name: agentName,
|
|
396
383
|
cwd: plan.cwd,
|
|
@@ -430,56 +417,6 @@ export class SubagentSession {
|
|
|
430
417
|
resultFilePath() {
|
|
431
418
|
return this.launchState?.resultFile ?? subagentResultFileFor(this.id);
|
|
432
419
|
}
|
|
433
|
-
/**
|
|
434
|
-
* Bind the run's channel before the child launches, so the child finds its
|
|
435
|
-
* parent listening, and record what the channel can carry. A bind failure is
|
|
436
|
-
* not a launch failure: the handshake is observability, and the run's own
|
|
437
|
-
* reporting does not depend on it.
|
|
438
|
-
*/
|
|
439
|
-
async openChannel(launch) {
|
|
440
|
-
const { ipc } = this;
|
|
441
|
-
if (ipc === undefined || ipc.start === undefined) {
|
|
442
|
-
launch.handshake = {
|
|
443
|
-
kind: "unavailable",
|
|
444
|
-
reason: "no-channel",
|
|
445
|
-
};
|
|
446
|
-
return;
|
|
447
|
-
}
|
|
448
|
-
try {
|
|
449
|
-
await ipc.start();
|
|
450
|
-
launch.handshake = { kind: "awaiting" };
|
|
451
|
-
}
|
|
452
|
-
catch (error) {
|
|
453
|
-
launch.handshake = {
|
|
454
|
-
kind: "unavailable",
|
|
455
|
-
reason: "bind-failed",
|
|
456
|
-
};
|
|
457
|
-
log.warn("subagent channel failed to bind", {
|
|
458
|
-
agentId: this.id,
|
|
459
|
-
errorMessage: errorMessage(error),
|
|
460
|
-
});
|
|
461
|
-
}
|
|
462
|
-
}
|
|
463
|
-
/**
|
|
464
|
-
* Release the run's channel, leaving the artifacts alone: the run may still
|
|
465
|
-
* write reports to them, so only drop() removes the directory.
|
|
466
|
-
*/
|
|
467
|
-
closeChannel() {
|
|
468
|
-
const ipc = this.ipc;
|
|
469
|
-
this.ipc = undefined;
|
|
470
|
-
void ipc?.close?.().catch(() => { });
|
|
471
|
-
}
|
|
472
|
-
/**
|
|
473
|
-
* The child's frames. `ready` is the only kind the protocol defines so far, so
|
|
474
|
-
* there is nothing to dispatch on: a ready frame names the run's process, and
|
|
475
|
-
* only while the run is still awaiting one — a child reload announces again,
|
|
476
|
-
* and a run whose channel was unavailable never gets to this at all.
|
|
477
|
-
*/
|
|
478
|
-
handleFrame(launch, frame) {
|
|
479
|
-
if (launch.handshake?.kind === "awaiting") {
|
|
480
|
-
launch.handshake = { kind: "announced", pid: frame.pid };
|
|
481
|
-
}
|
|
482
|
-
}
|
|
483
420
|
async applySupervisorOutcome(supervisor, outcome) {
|
|
484
421
|
if (!this.isActive() || this.supervisor !== supervisor)
|
|
485
422
|
return;
|
|
@@ -546,8 +483,6 @@ export class SubagentSession {
|
|
|
546
483
|
const settlingRun = this.run;
|
|
547
484
|
if (settlingRun.shell !== "held" || settlingRun.process.kind !== "settling")
|
|
548
485
|
return;
|
|
549
|
-
// The run is past its last frame: nothing will announce again.
|
|
550
|
-
this.closeChannel();
|
|
551
486
|
// The gate opens once: snapshot the entered run's result before a revive
|
|
552
487
|
// can re-project the lifecycle to spawned.
|
|
553
488
|
const result = lifecycleResult(this.spawn.lifecycle);
|
package/dist/index.js
CHANGED
|
@@ -3,8 +3,7 @@
|
|
|
3
3
|
* The tool's per-call `model` parameter is the caller's and is never written
|
|
4
4
|
* by the listener; config lives in ConfigStore.
|
|
5
5
|
*/
|
|
6
|
-
import { setPiInstance, setRuntime, isInsideHerdr } from "./shell.js";
|
|
7
|
-
import { announceReadyForSpawn } from "./subagent/ipc-protocol.js";
|
|
6
|
+
import { setPiInstance, setRuntime, isInsideHerdr, detectSubagentSpawn, } from "./shell.js";
|
|
8
7
|
import { createHerdrRuntime } from "./infrastructure/herdr-host.js";
|
|
9
8
|
import { missingCloneProgramReport } from "./infrastructure/git/cow-clone.js";
|
|
10
9
|
import { registerCowboyCommand, registerTools } from "./registration.js";
|
|
@@ -27,9 +26,8 @@ export default function (pi) {
|
|
|
27
26
|
// Subagents launch through the parent session's `herdr` CLI.
|
|
28
27
|
if (!isInsideHerdr())
|
|
29
28
|
return;
|
|
30
|
-
// Stay inert so subagents can never spawn further subagents
|
|
31
|
-
|
|
32
|
-
if (announceReadyForSpawn())
|
|
29
|
+
// Stay inert so subagents can never spawn further subagents.
|
|
30
|
+
if (detectSubagentSpawn() !== undefined)
|
|
33
31
|
return;
|
|
34
32
|
// A program the clone path needs is missing, so copy-on-write could never
|
|
35
33
|
// work here. Staying unregistered says so once; a volume that cannot clone
|
|
@@ -83,6 +83,15 @@ function settledOutcome(lifecycle) {
|
|
|
83
83
|
return assertNever(lifecycle);
|
|
84
84
|
}
|
|
85
85
|
}
|
|
86
|
+
/**
|
|
87
|
+
* The settled report's headline: which agent, and how it ended. The settled cue
|
|
88
|
+
* is the run's own report and names no id, so both deliveries — the blocking
|
|
89
|
+
* call's return and the completion nudge — headline it the same way, and the
|
|
90
|
+
* caller always leaves with the id it must still stop, merge and clean up.
|
|
91
|
+
*/
|
|
92
|
+
export function settledHeadline(spawn) {
|
|
93
|
+
return `[Cowboy agent "${spawn.display.type}" ${spawn.id} ${lifecycleStatus(spawn.lifecycle)}]`;
|
|
94
|
+
}
|
|
86
95
|
/** Result text plus status note, for display. Errors pass through verbatim. Worktree settles append a lifecycle note stating what remains and directing the orchestrator to call cleanup_cowboy_agent — removal is never implied to happen on its own. */
|
|
87
96
|
export function formatResultContent(spawn) {
|
|
88
97
|
const lifecycle = spawn.lifecycle;
|
|
@@ -202,7 +211,10 @@ export class DelegationProtocol {
|
|
|
202
211
|
if (hasOutcome(spawn.lifecycle) && spawn.lifecycle.status === "error") {
|
|
203
212
|
throw new Error(`agent ${agentId} stopped with an error: ${spawn.lifecycle.error || "no error message was recorded"}`);
|
|
204
213
|
}
|
|
205
|
-
return {
|
|
214
|
+
return {
|
|
215
|
+
message: `${settledHeadline(spawn)}\n\n${formatResultContent(spawn)}`,
|
|
216
|
+
details,
|
|
217
|
+
};
|
|
206
218
|
}
|
|
207
219
|
// The spawn-time cue is gated on the worktree the launch will provision, never on a spawn field: its branch names exactly the ref the orchestrator merges.
|
|
208
220
|
const cueWorktree = worktree;
|
package/dist/paths.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* paths.ts — extension-level directory resolution.
|
|
3
|
-
*
|
|
4
|
-
* can be redirected per process, so a snapshot would freeze the
|
|
5
|
-
*
|
|
2
|
+
* paths.ts — extension-level directory and staging resolution.
|
|
3
|
+
* A directory resolves per call rather than into a module-scope constant: the
|
|
4
|
+
* agent dir can be redirected per process, so a snapshot would freeze the
|
|
5
|
+
* wrong one. Resolving a directory must not pull pi's library barrel into the
|
|
6
6
|
* boot-time import graph.
|
|
7
7
|
*/
|
|
8
8
|
import * as fs from "node:fs";
|
|
@@ -56,11 +56,49 @@ export function defaultWorktreeRoot() {
|
|
|
56
56
|
}
|
|
57
57
|
/**
|
|
58
58
|
* Staging root for a spawn's briefing, prompt and result files:
|
|
59
|
-
* `<tmpdir>/pi-cowboy
|
|
60
|
-
*
|
|
59
|
+
* `<tmpdir>/pi-cowboy/`. Resolved per call, like every directory here, so a
|
|
60
|
+
* `TMPDIR` override moves the whole staging area with it.
|
|
61
61
|
*/
|
|
62
62
|
export function subagentResultDir() {
|
|
63
63
|
return path.join(tmpdir(), "pi-cowboy");
|
|
64
64
|
}
|
|
65
|
+
/**
|
|
66
|
+
* Canonical staging directory for a subagent id. Parent and child derive the
|
|
67
|
+
* same path independently, so no path ever travels between them.
|
|
68
|
+
*/
|
|
69
|
+
export function subagentResultDirFor(agentId) {
|
|
70
|
+
return path.join(subagentResultDir(), agentId);
|
|
71
|
+
}
|
|
72
|
+
/** Canonical result.md for a subagent id. */
|
|
73
|
+
export function subagentResultFileFor(agentId) {
|
|
74
|
+
return path.join(subagentResultDirFor(agentId), "result.md");
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* pi reads a file whenever `--system-prompt`'s value is an existing path, so
|
|
78
|
+
* multi-line instructions ride out of herdr's single-line argv. The staging
|
|
79
|
+
* file name is fixed here, beside the path that joins it.
|
|
80
|
+
*/
|
|
81
|
+
const SUBAGENT_SYSTEM_FILE_NAME = "system.md";
|
|
82
|
+
/** The pane's `@<file>` initial message; holds the task text and nothing else. */
|
|
83
|
+
const SUBAGENT_TASK_FILE_NAME = "prompt.md";
|
|
84
|
+
/** pi reads a file from `--system-prompt` when the value names an existing path. */
|
|
85
|
+
export function subagentSystemFileFor(agentId) {
|
|
86
|
+
return path.join(subagentResultDirFor(agentId), SUBAGENT_SYSTEM_FILE_NAME);
|
|
87
|
+
}
|
|
88
|
+
/** Canonical task file for a subagent id — the `@<file>` initial message. */
|
|
89
|
+
export function subagentTaskFileFor(agentId) {
|
|
90
|
+
return path.join(subagentResultDirFor(agentId), SUBAGENT_TASK_FILE_NAME);
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Marker prefix a spawn injects into the child's argv so the child can tell it
|
|
94
|
+
* is a subagent. The shape is shell-inert on purpose: herdr types the launch
|
|
95
|
+
* arguments into the pane's shell, and `[...]` would be a glob there — zsh
|
|
96
|
+
* aborts the whole line with "no matches found" before pi ever runs.
|
|
97
|
+
*/
|
|
98
|
+
export const SUBAGENT_TOKEN_PREFIX = "cowboy-subagent-";
|
|
99
|
+
/** The marker a spawn injects into the child's argv; see `detectSubagentSpawn`. */
|
|
100
|
+
export function subagentTokenFor(agentId) {
|
|
101
|
+
return `${SUBAGENT_TOKEN_PREFIX}${agentId}`;
|
|
102
|
+
}
|
|
65
103
|
export const EXTENSION_AGENTS_DIR = fileURLToPath(new URL("../agents/", import.meta.url));
|
|
66
104
|
export const EXTENSION_ORCHESTRATORS_DIR = fileURLToPath(new URL("../orchestrators/", import.meta.url));
|
package/dist/shell.js
CHANGED
|
@@ -2,15 +2,13 @@
|
|
|
2
2
|
* shell.ts — the single mutable container for all per-session state.
|
|
3
3
|
* Handler modules read via getter functions — no module-level mutable globals.
|
|
4
4
|
*/
|
|
5
|
-
import * as path from "node:path";
|
|
6
5
|
import { RepoLock } from "./spawn/repo-lock.js";
|
|
7
6
|
import { resolveWorktreeMaterialization, } from "./spawn/worktree-policy.js";
|
|
8
7
|
import { resolveHarness } from "./agents/harness.js";
|
|
9
8
|
import { unprobed } from "./availability.js";
|
|
10
9
|
import { AgentSpawnStore } from "./agents/agent-spawn-store.js";
|
|
11
10
|
import { ConfigStore } from "./config/config-store.js";
|
|
12
|
-
import {
|
|
13
|
-
import { SUBAGENT_SYSTEM_FILE_NAME, SUBAGENT_TASK_FILE_NAME } from "./types.js";
|
|
11
|
+
import { SUBAGENT_TOKEN_PREFIX } from "./paths.js";
|
|
14
12
|
const NO_SCAN_DIRS = { user: "", project: "", shared: "" };
|
|
15
13
|
/** Empty registries — the state every session starts from. */
|
|
16
14
|
export function createSessionTemplates() {
|
|
@@ -181,21 +179,12 @@ export function setRuntime(r) {
|
|
|
181
179
|
export function setSessionTemplates(next) {
|
|
182
180
|
shell.sessionTemplates = next;
|
|
183
181
|
}
|
|
182
|
+
/** The token within one argv entry; the id is a spawn id or an agent name. */
|
|
183
|
+
const SUBAGENT_TOKEN = new RegExp(`${SUBAGENT_TOKEN_PREFIX}([A-Za-z0-9_-]+)`);
|
|
184
184
|
/**
|
|
185
|
-
*
|
|
186
|
-
* is
|
|
187
|
-
* subagent can never spawn further subagents.
|
|
188
|
-
*
|
|
189
|
-
* The shape is shell-inert on purpose: herdr types the launch arguments into the
|
|
190
|
-
* pane's shell, and `[...]` would be a glob there — zsh aborts the whole
|
|
191
|
-
* command line with "no matches found" before pi ever runs.
|
|
185
|
+
* Agent id from our argv's subagent token, or undefined in a root session. The
|
|
186
|
+
* marker is written by `subagentTokenFor`; this is its only reader.
|
|
192
187
|
*/
|
|
193
|
-
export function subagentTokenFor(agentId) {
|
|
194
|
-
return `cowboy-subagent-${agentId}`;
|
|
195
|
-
}
|
|
196
|
-
/** The token within one argv entry; the id is a spawn id or an agent name. */
|
|
197
|
-
const SUBAGENT_TOKEN = /cowboy-subagent-([A-Za-z0-9_-]+)/;
|
|
198
|
-
/** Agent id from our argv's subagent token, or undefined in a root session. */
|
|
199
188
|
export function detectSubagentSpawn(argv = process.argv) {
|
|
200
189
|
for (const arg of argv) {
|
|
201
190
|
const match = SUBAGENT_TOKEN.exec(arg);
|
|
@@ -204,22 +193,6 @@ export function detectSubagentSpawn(argv = process.argv) {
|
|
|
204
193
|
}
|
|
205
194
|
return undefined;
|
|
206
195
|
}
|
|
207
|
-
/** Canonical staging directory for a subagent id (parent and child derive the same path). */
|
|
208
|
-
export function subagentResultDirFor(agentId) {
|
|
209
|
-
return path.join(subagentResultDir(), agentId);
|
|
210
|
-
}
|
|
211
|
-
/** Canonical result.md for a subagent id. */
|
|
212
|
-
export function subagentResultFileFor(agentId) {
|
|
213
|
-
return path.join(subagentResultDirFor(agentId), "result.md");
|
|
214
|
-
}
|
|
215
|
-
/** pi reads a file from `--system-prompt` when the value names an existing path. */
|
|
216
|
-
export function subagentSystemFileFor(agentId) {
|
|
217
|
-
return path.join(subagentResultDirFor(agentId), SUBAGENT_SYSTEM_FILE_NAME);
|
|
218
|
-
}
|
|
219
|
-
/** Canonical task file for a subagent id — the `@<file>` initial message. */
|
|
220
|
-
export function subagentTaskFileFor(agentId) {
|
|
221
|
-
return path.join(subagentResultDirFor(agentId), SUBAGENT_TASK_FILE_NAME);
|
|
222
|
-
}
|
|
223
196
|
export function isInsideHerdr() {
|
|
224
197
|
return process.env.HERDR_ENV === "1";
|
|
225
198
|
}
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { getPiInstance, getRuntime } from "../shell.js";
|
|
9
9
|
import { hasOutcome, lifecycleStatus, } from "../types.js";
|
|
10
|
-
import { buildAgentDetails, formatResultContent, } from "../orchestrators/protocol.js";
|
|
10
|
+
import { buildAgentDetails, formatResultContent, settledHeadline, } from "../orchestrators/protocol.js";
|
|
11
11
|
import { findTaskDedup, TaskAlreadyInFlightError, } from "../task-registry.js";
|
|
12
12
|
import { isExtensionEnabled } from "../extension-toggle.js";
|
|
13
13
|
import { actionReport } from "../ui/action-report.js";
|
|
@@ -224,7 +224,7 @@ export class SpawnCoordinator {
|
|
|
224
224
|
// so a completion never interrupts work the orchestrator already started.
|
|
225
225
|
pi.sendMessage({
|
|
226
226
|
customType: "subagent-result",
|
|
227
|
-
content:
|
|
227
|
+
content: `${settledHeadline(spawn)}\n\n${formatResultContent(spawn)}`,
|
|
228
228
|
details,
|
|
229
229
|
display: true,
|
|
230
230
|
}, {
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* deliverable.ts — the child's report: the file it writes, the parent's read of
|
|
3
|
+
* it.
|
|
4
|
+
*
|
|
5
|
+
* A run's deliverable is a file on disk, not a message. The child is told where
|
|
6
|
+
* to write it by its prompt, and the parent reads it here. No protocol carries
|
|
7
|
+
* it, and nothing here needs the child to run the extension.
|
|
8
|
+
*/
|
|
9
|
+
import fs from "node:fs";
|
|
10
|
+
/**
|
|
11
|
+
* The deliverable as the run's result file. Parent and child derive the path
|
|
12
|
+
* independently (`subagentResultFileFor`), so no path ever travels between them.
|
|
13
|
+
*/
|
|
14
|
+
export class FileDeliverable {
|
|
15
|
+
resultFile;
|
|
16
|
+
constructor(resultFile) {
|
|
17
|
+
this.resultFile = resultFile;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The child's last report, or null when it is absent, unreadable, or blank —
|
|
21
|
+
* the run has not finished. The content rides with the file's modification
|
|
22
|
+
* time, because a rewritten report of the same words is still news. The stamp
|
|
23
|
+
* is sampled before the content: a write landing between the two calls leaves
|
|
24
|
+
* the pair understating the file rather than overstating it, and the next poll
|
|
25
|
+
* corrects it.
|
|
26
|
+
*/
|
|
27
|
+
async readDeliverable() {
|
|
28
|
+
try {
|
|
29
|
+
const mtime = fs.statSync(this.resultFile).mtimeMs;
|
|
30
|
+
const content = fs.readFileSync(this.resultFile, "utf-8").trim();
|
|
31
|
+
if (!content)
|
|
32
|
+
return null;
|
|
33
|
+
return { content, mtime };
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
@@ -1,24 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* pane-supervisor.ts — Build the supervisor for one child process in a pane.
|
|
3
3
|
*
|
|
4
|
-
* Both attempt origins need the same construction:
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
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).
|
|
4
|
+
* Both attempt origins need the same construction: the deliverable the
|
|
5
|
+
* supervisor polls, wrapped in a ProcessSupervisorEngine. This module builds
|
|
6
|
+
* that and nothing else — launching the process (start), binding a live one
|
|
7
|
+
* (adopt), and beginning the watch all stay with the caller, which owns the
|
|
8
|
+
* placement and the checkpoint that may discard it.
|
|
11
9
|
*/
|
|
12
10
|
import { ProcessSupervisorEngine, } from "./supervisor.js";
|
|
13
|
-
/** Wire the
|
|
11
|
+
/** Wire the deliverable and the engine over it. Starts, adopts, and watches nothing. */
|
|
14
12
|
export function createPaneSupervisor(input) {
|
|
15
|
-
const
|
|
16
|
-
|
|
17
|
-
resultFile: input.resultFile,
|
|
18
|
-
onFrame: input.onFrame,
|
|
19
|
-
});
|
|
20
|
-
return {
|
|
21
|
-
supervisor: new ProcessSupervisorEngine(input.host, ipc, input.supervisorOptions),
|
|
22
|
-
ipc,
|
|
23
|
-
};
|
|
13
|
+
const deliverable = input.transport.createDeliverable(input.resultFile);
|
|
14
|
+
return new ProcessSupervisorEngine(input.host, deliverable, input.supervisorOptions);
|
|
24
15
|
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* result-artifacts.ts — the staging directory a run's files live in.
|
|
3
|
+
*
|
|
4
|
+
* A spawn stages its briefing, prompt, and report under
|
|
5
|
+
* `<tmpdir>/pi-cowboy/<agentId>/` (see paths.ts). Those files are ephemeral, so
|
|
6
|
+
* the directory's whole lifecycle here is "remove it once nothing can report
|
|
7
|
+
* into it".
|
|
8
|
+
*/
|
|
9
|
+
import fs from "node:fs";
|
|
10
|
+
import * as path from "node:path";
|
|
11
|
+
/**
|
|
12
|
+
* Remove a run's result directory. Best effort, and safe when it is already
|
|
13
|
+
* gone — the files are ephemeral temp-dir artifacts.
|
|
14
|
+
*
|
|
15
|
+
* The artifacts outlive settlement: a settled run stays watched, so the child
|
|
16
|
+
* may keep writing reports to this same directory until the run is dropped.
|
|
17
|
+
*/
|
|
18
|
+
export function removeResultArtifacts(resultFile) {
|
|
19
|
+
try {
|
|
20
|
+
fs.rmSync(path.dirname(resultFile), { recursive: true, force: true });
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
// Best effort: the agent's files are ephemeral temp-dir artifacts.
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
* watch() never settles.
|
|
21
21
|
* - Artifacts are NOT this engine's to remove: a settled run stays watched, so
|
|
22
22
|
* its result directory survives settlement and is removed when the run is
|
|
23
|
-
* dropped (see removeResultArtifacts).
|
|
23
|
+
* dropped (see removeResultArtifacts in result-artifacts.ts).
|
|
24
24
|
* - One supervisor per run: re-delegation and revive each use a fresh instance.
|
|
25
25
|
*/
|
|
26
26
|
import { createLogger } from "../logger.js";
|
|
@@ -38,7 +38,7 @@ function deferred() {
|
|
|
38
38
|
}
|
|
39
39
|
export class ProcessSupervisorEngine {
|
|
40
40
|
host;
|
|
41
|
-
|
|
41
|
+
deliverable;
|
|
42
42
|
pollMs;
|
|
43
43
|
stopInitiator;
|
|
44
44
|
onFollowUp;
|
|
@@ -59,9 +59,9 @@ export class ProcessSupervisorEngine {
|
|
|
59
59
|
/** A report seen once; a report still being written is not final. */
|
|
60
60
|
held = null;
|
|
61
61
|
watchStartedAt = 0;
|
|
62
|
-
constructor(host,
|
|
62
|
+
constructor(host, deliverable, options = {}) {
|
|
63
63
|
this.host = host;
|
|
64
|
-
this.
|
|
64
|
+
this.deliverable = deliverable;
|
|
65
65
|
this.pollMs = options.pollMs ?? DEFAULT_POLL_MS;
|
|
66
66
|
this.stopInitiator = options.stopInitiator ?? "user";
|
|
67
67
|
this.onFollowUp = options.onFollowUp;
|
|
@@ -295,7 +295,7 @@ export class ProcessSupervisorEngine {
|
|
|
295
295
|
/** One artifact read; a failed read is a poll with nothing in it. */
|
|
296
296
|
async readDeliverable() {
|
|
297
297
|
try {
|
|
298
|
-
return await this.
|
|
298
|
+
return await this.deliverable.readDeliverable();
|
|
299
299
|
}
|
|
300
300
|
catch (err) {
|
|
301
301
|
log.debug("readDeliverable failed", {
|
package/dist/types.js
CHANGED
|
@@ -1,10 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* pi reads a file whenever `--system-prompt`'s value is an existing path, so
|
|
3
|
-
* multi-line instructions ride out of herdr's single-line argv.
|
|
4
|
-
*/
|
|
5
|
-
export const SUBAGENT_SYSTEM_FILE_NAME = "system.md";
|
|
6
|
-
/** The pane's `@<file>` initial message; holds the task text and nothing else. */
|
|
7
|
-
export const SUBAGENT_TASK_FILE_NAME = "prompt.md";
|
|
8
1
|
/**
|
|
9
2
|
* Built-in fallbacks for the configurable spawn defaults. A persisted setting
|
|
10
3
|
* that is unset or names a type/template that no longer resolves degrades to
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-cowboy",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"packageManager": "pnpm@12.9.1",
|
|
6
6
|
"description": "Agent orchestrator for pi: each subagent runs as its own pi process in a background Herdr pane, isolated by a copy-on-write git worktree.",
|
|
@@ -1,68 +0,0 @@
|
|
|
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
|
-
}
|
package/dist/subagent/ipc.js
DELETED
|
@@ -1,110 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -1,240 +0,0 @@
|
|
|
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
|
-
}
|