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,367 @@
1
+ /**
2
+ * agent-manager.ts — Fleet controller for independently running subagents.
3
+ * Exports AgentManager, ClearOutcome/ClearRefusal; re-exports transport, spawn,
4
+ * and steer types.
5
+ */
6
+ import { getAgentSpawns, getCoordinatorOrNull, getPiInstance, getSessionCtx, subagentResultFileFor, } from "../shell.js";
7
+ import { HerdrTaskRegistry, } from "../task-registry.js";
8
+ import { createLogger } from "../logger.js";
9
+ import { errorMessage } from "../utils.js";
10
+ import { ACTIVE_AGENT_PHASES, ALL_AGENT_PHASES, hasOutcome, lifecycleStartTime, lifecycleStatus, } from "../types.js";
11
+ import { removeResultArtifacts } from "../subagent/ipc.js";
12
+ import { createCleanup } from "./agent-cleanup.js";
13
+ import { createHerdrAgentAssets, } from "./agent-assets.js";
14
+ import { DISPOSE_QUEUED_MESSAGE, SubagentSession, defaultAgentManagerTransport, } from "./subagent-session.js";
15
+ /**
16
+ * Removal address for a spawn's owned checkout. An owned checkout that no
17
+ * recorded repository cwd can reach is `unaddressable`: its teardown has no
18
+ * place to run, which is not the same as having none left to remove.
19
+ */
20
+ function removalAddressFor(spawn) {
21
+ const worktree = spawn.display.worktree;
22
+ if (worktree?.kind !== "owned")
23
+ return { kind: "none" };
24
+ const repoCwd = spawn.execution.spawnCtx?.cwd;
25
+ if (!repoCwd)
26
+ return { kind: "unaddressable", path: worktree.path };
27
+ const target = {
28
+ workspaceId: spawn.execution.host?.workspaceId,
29
+ worktreePath: worktree.path,
30
+ repoCwd,
31
+ branchName: worktree.branch,
32
+ };
33
+ const host = spawn.execution.host;
34
+ return {
35
+ kind: "owned",
36
+ target: host === undefined
37
+ ? { kind: "detached", worktree: target, pane: null }
38
+ : {
39
+ kind: "adopted",
40
+ worktree: { ...target, workspaceId: host.workspaceId },
41
+ pane: null,
42
+ ref: host,
43
+ },
44
+ };
45
+ }
46
+ const log = createLogger("manager");
47
+ function isTerminal(spawn) {
48
+ const status = lifecycleStatus(spawn.lifecycle);
49
+ return status !== "spawned" && status !== "queued";
50
+ }
51
+ /** Fleet controller; each session owns exactly one lifecycle. */
52
+ export class AgentManager {
53
+ transport;
54
+ /** Live sessions by id; the spawn itself stays identity-stable. */
55
+ sessions = new Map();
56
+ onComplete;
57
+ onFollowUp;
58
+ /**
59
+ * Teardowns in flight, by agent id. One teardown owns an id's artifacts at a
60
+ * time: a clear that arrives during one is refused, and a cleanup waits for
61
+ * the running one instead of racing it for the same checkout.
62
+ */
63
+ teardowns = new Map();
64
+ registry;
65
+ constructor(onComplete, concurrency, registry, transport = defaultAgentManagerTransport) {
66
+ this.transport = transport;
67
+ this.onComplete = onComplete;
68
+ this.registry =
69
+ registry ??
70
+ new HerdrTaskRegistry({
71
+ listAgents: () => this.listAgents(ACTIVE_AGENT_PHASES),
72
+ spawn: (type, prompt, options) => this.spawn(getPiInstance(), getSessionCtx(), type, prompt, options),
73
+ getSpawn: (id) => this.getSpawn(id),
74
+ findTaskAttempts: (taskSlug) => this.transport.createHost(getPiInstance()).findAttempts(taskSlug),
75
+ }, concurrency);
76
+ }
77
+ getRegistry() {
78
+ return this.registry;
79
+ }
80
+ setConcurrency(config) {
81
+ this.registry.setConcurrency(config);
82
+ }
83
+ setOnComplete(cb) {
84
+ this.onComplete = cb;
85
+ }
86
+ setOnFollowUp(cb) {
87
+ this.onFollowUp = cb;
88
+ }
89
+ /**
90
+ * Mint a spawn id unique across every retained spawn, settled ones included:
91
+ * a retained spawn still owns its id, branch, worktree, and herdr name.
92
+ */
93
+ mintSpawnId() {
94
+ return getAgentSpawns().mint();
95
+ }
96
+ spawn(pi, ctx, type, prompt, options) {
97
+ // The caller mints the id, so it matches the branch/worktree/herdr suffix.
98
+ const id = options.spawnId;
99
+ const args = { pi, ctx, type, prompt, options };
100
+ const admission = this.registry.admitSpawn(options.modelSelection?.key, {
101
+ id,
102
+ start: (reservation) => this.startSession(id, args, reservation),
103
+ });
104
+ let session;
105
+ try {
106
+ // Registration refuses a duplicate id; release the granted admission first.
107
+ session = new SubagentSession({
108
+ id,
109
+ args,
110
+ deps: {
111
+ transport: this.transport,
112
+ slots: this.registry,
113
+ onRunEnded: (spawn) => this.notifyComplete(spawn),
114
+ onFollowUpResult: (spawn, deliverable) => this.notifyFollowUp(spawn, deliverable),
115
+ },
116
+ });
117
+ }
118
+ catch (err) {
119
+ void this.registry.release(id);
120
+ throw err;
121
+ }
122
+ this.sessions.set(id, session);
123
+ if (options.signal?.aborted) {
124
+ void session.abort("user");
125
+ return id;
126
+ }
127
+ if (admission.kind === "queue")
128
+ return id;
129
+ try {
130
+ session.start(admission.reservation);
131
+ }
132
+ catch (err) {
133
+ session.rollbackStart();
134
+ void this.registry.release(id);
135
+ this.sessions.delete(id);
136
+ // A start that never happened leaves no spawn: an orphan would trip dedup on retry.
137
+ getAgentSpawns().drop(id);
138
+ throw err;
139
+ }
140
+ return id;
141
+ }
142
+ startSession(id, _args, reservation) {
143
+ const session = this.sessions.get(id);
144
+ if (!session || !session.isQueued())
145
+ return false;
146
+ try {
147
+ session.start(reservation);
148
+ }
149
+ catch (err) {
150
+ // Queued-start failure keeps the reservation (asymmetric with direct spawn).
151
+ session.settleStartFailure(err);
152
+ }
153
+ return true;
154
+ }
155
+ /**
156
+ * Route a message to the agent's session. Unknown ids are refused with the
157
+ * reason; settled agents revive in their session. See SubagentSession.
158
+ */
159
+ async steer(id, message) {
160
+ // Steer revives a settled agent, whose worktree a teardown may be removing.
161
+ if (this.teardowns.has(id)) {
162
+ return {
163
+ kind: "refused",
164
+ reason: `agent ${id} is being cleaned up, so its worktree is on its way out — wait for the report before steering it.`,
165
+ };
166
+ }
167
+ const session = this.sessions.get(id);
168
+ if (!session) {
169
+ return {
170
+ kind: "refused",
171
+ reason: `no live session tracks agent ${id} — check the id from its spawn or completion result (a cleaned-up agent is gone for good).`,
172
+ };
173
+ }
174
+ return session.steer(message);
175
+ }
176
+ /** One spawn by id, unfiltered, so cleanup reaches settled spawns too. */
177
+ getSpawn(id) {
178
+ return getAgentSpawns().get(id);
179
+ }
180
+ /** Assets seam, built per call so probes run against the current shell. */
181
+ assets() {
182
+ return createHerdrAgentAssets(getPiInstance());
183
+ }
184
+ /**
185
+ * Locate one agent's artifacts. Read-only: nothing is stopped, removed, or
186
+ * released. Covers ids no session tracks (a `/reload` rebuilt the store).
187
+ */
188
+ async locate(id) {
189
+ return this.assets().locate(id, this.getSpawn(id));
190
+ }
191
+ /**
192
+ * Retained spawns in the given phases (default: all), newest start first.
193
+ * Pass ACTIVE_AGENT_PHASES for in-flight work, ALL_AGENT_PHASES for status.
194
+ */
195
+ listAgents(phases = ALL_AGENT_PHASES) {
196
+ return getAgentSpawns()
197
+ .list(phases)
198
+ .sort((a, b) => lifecycleStartTime(b.lifecycle) - lifecycleStartTime(a.lifecycle));
199
+ }
200
+ /**
201
+ * Clear a terminal spawn: tear its owned checkout down first and drop the
202
+ * spawn only once the removal is confirmed. A kept or failed removal leaves
203
+ * the spawn listed, with the reason recorded, so the caller can report it and
204
+ * the operator can retry it. Spawn-keyed so a spawn whose session is gone
205
+ * stays clearable.
206
+ */
207
+ async clear(id) {
208
+ const spawn = getAgentSpawns().get(id);
209
+ if (!spawn)
210
+ return { kind: "refused", reason: "unknown-id" };
211
+ if (!isTerminal(spawn))
212
+ return { kind: "refused", reason: "not-terminal" };
213
+ // The first teardown's verdict is the answer for every clear that arrives
214
+ // while it runs; a second removal of the same checkout would race the first.
215
+ if (this.teardowns.has(id))
216
+ return { kind: "refused", reason: "in-flight" };
217
+ const address = removalAddressFor(spawn);
218
+ if (address.kind === "none") {
219
+ this.dropSpawn(spawn);
220
+ return { kind: "cleared" };
221
+ }
222
+ if (address.kind === "unaddressable") {
223
+ const reason = {
224
+ kind: "unverifiable",
225
+ detail: "the run recorded no repository cwd",
226
+ };
227
+ this.recordRetention(spawn, reason);
228
+ return { kind: "kept", path: address.path, reason };
229
+ }
230
+ const removal = this.runRemoval(spawn, address.target);
231
+ this.teardowns.set(id, removal);
232
+ try {
233
+ return await removal;
234
+ }
235
+ finally {
236
+ // A cleanup may have queued behind this removal and taken the id over.
237
+ if (this.teardowns.get(id) === removal)
238
+ this.teardowns.delete(id);
239
+ }
240
+ }
241
+ /** Tear one owned checkout down and settle the spawn on what it did. */
242
+ async runRemoval(spawn, target) {
243
+ const outcome = await createCleanup(this.assets()).removeWorktree(target);
244
+ switch (outcome.kind) {
245
+ case "removed":
246
+ case "absent":
247
+ this.dropSpawn(spawn);
248
+ return { kind: "cleared" };
249
+ case "kept":
250
+ this.recordRetention(spawn, outcome.reason);
251
+ return { kind: "kept", path: outcome.path, reason: outcome.reason };
252
+ case "removal-failed":
253
+ this.recordRetention(spawn, {
254
+ kind: "unverifiable",
255
+ detail: `the removal was not confirmed (${outcome.detail})`,
256
+ });
257
+ log.warn("worktree removal failed after clear", {
258
+ spawnId: spawn.id,
259
+ path: outcome.path,
260
+ detail: outcome.detail,
261
+ });
262
+ return {
263
+ kind: "removal-failed",
264
+ path: outcome.path,
265
+ detail: outcome.detail,
266
+ };
267
+ }
268
+ }
269
+ async abort(id, initiator) {
270
+ return (await this.sessions.get(id)?.abort(initiator)) ?? false;
271
+ }
272
+ notifyComplete(spawn) {
273
+ try {
274
+ this.onComplete?.(spawn);
275
+ }
276
+ catch (err) {
277
+ // The listener's throw never fails the settle, but the completion it was
278
+ // meant to announce must not vanish with it.
279
+ log.warn("completion notification failed", {
280
+ spawnId: spawn.id,
281
+ detail: errorMessage(err),
282
+ });
283
+ }
284
+ }
285
+ notifyFollowUp(spawn, deliverable) {
286
+ try {
287
+ this.onFollowUp?.(spawn, deliverable);
288
+ }
289
+ catch (err) {
290
+ // The run it reports on is already settled, so a failed announcement
291
+ // costs the report, never the run.
292
+ log.warn("follow-up notification failed", {
293
+ spawnId: spawn.id,
294
+ detail: errorMessage(err),
295
+ });
296
+ }
297
+ }
298
+ /**
299
+ * Record why a spawn's checkout survived. The caller reports the outcome and
300
+ * the reason rides the spawn, so status still states it after the menu leaves.
301
+ */
302
+ recordRetention(spawn, reason) {
303
+ const lifecycle = spawn.lifecycle;
304
+ // Clear takes only an ended spawn, so the ended phases can carry the reason.
305
+ if (hasOutcome(lifecycle)) {
306
+ lifecycle.worktreeRetentionReason = reason;
307
+ }
308
+ }
309
+ /**
310
+ * Drop runtime session and store entry for good, and with them the run's
311
+ * staging directory. The removal is keyed on the id, not the session: a
312
+ * disposal leaves a settled spawn tracked with no session at all, and only
313
+ * the canonical path can still name the directory that run wrote to.
314
+ */
315
+ dropSpawn(spawn) {
316
+ this.sessions.get(spawn.id)?.drop();
317
+ this.sessions.delete(spawn.id);
318
+ removeResultArtifacts(subagentResultFileFor(spawn.id));
319
+ getAgentSpawns().drop(spawn.id);
320
+ }
321
+ async cleanup(id, opts) {
322
+ const run = this.runCleanup(id, this.teardowns.get(id), opts);
323
+ this.teardowns.set(id, run);
324
+ try {
325
+ return await run;
326
+ }
327
+ finally {
328
+ // Only the newest teardown clears the id; an older one leaves it alone.
329
+ if (this.teardowns.get(id) === run)
330
+ this.teardowns.delete(id);
331
+ }
332
+ }
333
+ /** Clean one agent up, after whatever teardown for its id is already running. */
334
+ async runCleanup(id, inFlight, opts) {
335
+ // The earlier teardown's failure is its own report; this one still runs.
336
+ await inFlight?.catch(() => { });
337
+ // Before the teardown, which is slow enough for a pending nudge to fire.
338
+ getCoordinatorOrNull()?.dropNudge(id);
339
+ // Whether the spawn is tracked now: only a tracked run has a recorded
340
+ // result, so it is the only one whose staging directory may be removed
341
+ // without losing something nobody has read (see cleanup's report).
342
+ const tracked = this.getSpawn(id) !== undefined;
343
+ const report = await createCleanup(this.assets()).cleanupAgent(id, {
344
+ getSpawn: (rid) => this.getSpawn(rid),
345
+ dropSpawn: (spawn) => this.dropSpawn(spawn),
346
+ }, opts);
347
+ // A teardown that finished the run takes the staging directory with it even
348
+ // when its spawn is kept (a failed or unconfirmed removal): the artifacts
349
+ // are ephemeral, and a later retry does not read them. A refusal removed
350
+ // nothing, so it leaves them where they are.
351
+ if (tracked && report.outcome.kind === "torn-down") {
352
+ removeResultArtifacts(subagentResultFileFor(id));
353
+ }
354
+ return report;
355
+ }
356
+ /**
357
+ * Dispose every runtime session. The shell-owned spawn store stays: settled
358
+ * spawns must stay cleanable and untracked live ones stay visible.
359
+ */
360
+ dispose() {
361
+ this.registry.clearQueue();
362
+ for (const session of this.sessions.values())
363
+ session.settleForDispose();
364
+ this.sessions.clear();
365
+ }
366
+ }
367
+ export { DISPOSE_QUEUED_MESSAGE };
@@ -0,0 +1,64 @@
1
+ /**
2
+ * agent-reviver.ts — Return a settled run to active. Exports reviveSettledRun.
3
+ *
4
+ * The pane still holds a live pi process, so a delivered message starts a
5
+ * second turn. The result dir is recreated empty first: settlement deletes it
6
+ * (child writes would fail ENOENT) and a stale report would settle the
7
+ * revive with the first run's outcome. A fresh supervisor adopts the host
8
+ * (one run per instance). A revive is not an admission, so the run cannot wait
9
+ * for room: it charges its pools immediately and can pass a limit. The promise
10
+ * keeps the first run's gate: it opened with the first
11
+ * turn's result, so the revived turn is reported through its completion message
12
+ * alone.
13
+ */
14
+ import * as fs from "node:fs";
15
+ import * as path from "node:path";
16
+ import { getPiInstance, subagentResultFileFor } from "../shell.js";
17
+ import { createPaneSupervisor, } from "../subagent/pane-supervisor.js";
18
+ import { ensureResultDir } from "./result-file-permissions.js";
19
+ /**
20
+ * Reset settlement artifacts, adopt the host with a fresh supervisor, and arm
21
+ * the second-settlement watch. The spawn's state stays with the session: the
22
+ * attach seam returns the run to active, so this function writes none of it.
23
+ * Synchronous: the message is already delivered, so nothing here waits on
24
+ * the agent.
25
+ */
26
+ export function reviveSettledRun(request) {
27
+ const { spawn, hostRef, transport } = request;
28
+ const launch = resumeLaunch(spawn);
29
+ const resultDir = path.dirname(launch.resultFile);
30
+ // Reused dir: enforce owner-only mode even when it exists, so the revive
31
+ // fails instead of continuing with world-readable secrets.
32
+ ensureResultDir(resultDir);
33
+ fs.rmSync(launch.resultFile, { force: true });
34
+ const { supervisor } = createPaneSupervisor({
35
+ host: transport.createHost(getPiInstance()),
36
+ resultFile: launch.resultFile,
37
+ supervisorOptions: request.supervisorOptions,
38
+ transport,
39
+ agentId: spawn.id,
40
+ });
41
+ // Adopted, never launched: the pane already holds the run's pi process.
42
+ supervisor.adopt(hostRef);
43
+ request.attachSupervisor(supervisor, launch);
44
+ request.rebindParentSignal();
45
+ void supervisor
46
+ .watch()
47
+ .then((outcome) => request.reportOutcome(supervisor, outcome));
48
+ }
49
+ /**
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. The revived
52
+ * turn binds no channel and the child does not reboot, so only an
53
+ * announcement already heard still names its process.
54
+ */
55
+ function resumeLaunch(spawn) {
56
+ const { lifecycle } = spawn;
57
+ const resumed = lifecycle.phase === "settled" ? lifecycle.launch : undefined;
58
+ return {
59
+ resultFile: resumed?.resultFile ?? subagentResultFileFor(spawn.id),
60
+ handshake: resumed?.handshake?.kind === "announced"
61
+ ? resumed.handshake
62
+ : { kind: "unavailable", reason: "revive" },
63
+ };
64
+ }