@howaboua/pi-shepherdr 1.0.0 → 1.0.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # @howaboua/pi-shepherdr
2
2
 
3
+ ## 1.0.2
4
+
5
+ - Fixed resumed workers failing to start or losing completion reports after crashes or restarts.
6
+ - Fixed agent launches and window focus in standalone Bun builds of Pi.
7
+ - Sender labels now show machine, full agent address and terminal without repeated labels.
8
+ - Empty turns from unassigned workers no longer trigger completion notices.
9
+ - Agent guidance now favours outcome-focused delegation, actionable handoffs and fewer duplicate completion messages.
10
+ - Tool examples no longer prescribe `await`.
11
+ - New general profiles use GPT-6.2 Sol.
12
+
13
+ ## 1.0.1
14
+
15
+ - Reduce CPU use when monitoring long sessions.
16
+
3
17
  ## 1.0.0
4
18
 
5
19
  ### Breaking changes
package/README.md CHANGED
@@ -87,7 +87,7 @@ Nonblocking extension messages notify the controller once; blocking messages arr
87
87
 
88
88
  Use `send` for messages and work updates without adding supervision. Use `assign` to delegate work and receive its monitored result, automatically or through an explicit blocking call. It also accepts updates to running work, sharing that work's pending result rather than replacing it. If another call is already waiting, the update returns after submission and leaves that waiter intact. Close finished workers silently instead of waking them with completion acknowledgements or shutdown notices.
89
89
 
90
- When a parent sends or assigns work to one of its closed workers, Shepherdr reopens that worker's saved Pi session before delivering the message. Use its session reference, previous terminal target or saved routing name. The result reports `resumed: true` and the current target. This applies only to children recorded in the parent's selected session branch, not arbitrary peers or attachments. The saved session and its original machine must remain accessible. `/quit` never reopens a closed worker.
90
+ When a parent sends or assigns work to one of its closed workers, Shepherdr reopens that worker's saved Pi session before delivering the message. Use its session reference, previous terminal target or saved routing name. The result reports `resumed: true` and the current target. Resumed workers keep automatic completion reporting unless explicitly unwatched. A later `watch` or `assign` restores reporting. This applies only to children recorded in the parent's selected session branch, not arbitrary peers or attachments. The saved session and its original machine must remain accessible. `/quit` never reopens a closed worker.
91
91
 
92
92
  Delegation and explicit `watch` keep reporting subsequent work until `unwatch` or the agent's terminal closes. Finishing or failing a task clears that task, not its watch. Follow-up messages through `send` retain completion reporting without replacing the task.
93
93
 
@@ -231,7 +231,7 @@ Shepherdr works without Notes or PCC. A target without active Notes sharing stil
231
231
 
232
232
  On first load, Shepherdr installs three editable profiles:
233
233
 
234
- - `general` uses `openai-codex/gpt-6-sol` with `high` thinking for implementation
234
+ - `general` uses `openai-codex/gpt-6.2-sol` with `high` thinking for implementation
235
235
  - `explorer` uses `openai-codex/gpt-6-luna` with `high` thinking for read-only discovery
236
236
  - `reviewer` uses `openai-codex/gpt-6-luna` with `xhigh` thinking for generic read-only review
237
237
 
package/index.ts CHANGED
@@ -39,6 +39,7 @@ export default async function shepherdrExtension(
39
39
  acceptFocus(pi, ctx, fleet, pane, request),
40
40
  );
41
41
  const board = AgentBoard.create(pi, fleet);
42
+ const sharedContext = await registerSharedAgentContext(pi, fleet, board);
42
43
  registerPeerInbox(
43
44
  pi,
44
45
  peerCommands,
@@ -46,7 +47,6 @@ export default async function shepherdrExtension(
46
47
  (ctx) => board.promptCatchup(ctx),
47
48
  (ctx) => workerRole.isWorker(ctx.sessionManager),
48
49
  );
49
- const sharedContext = await registerSharedAgentContext(pi, fleet, board);
50
50
  registerWorkerService(pi, fleet, sharedContext, board, workerRole);
51
51
  let promptMode: { readonly active: boolean } | undefined;
52
52
  const tool = createAgentsTool(
@@ -61,9 +61,8 @@ export default async function shepherdrExtension(
61
61
  registerAgentEventRenderer(pi);
62
62
  pi.registerTool(tool);
63
63
  try {
64
- const { registerGptPromptMode } = await import(
65
- "@howaboua/pi-codex-conversion/prompt-mode"
66
- );
64
+ const { registerGptPromptMode } =
65
+ await import("@howaboua/pi-codex-conversion/prompt-mode");
67
66
  promptMode = registerGptPromptMode(pi, () => [tool]);
68
67
  } catch (error) {
69
68
  if (
package/package.json CHANGED
@@ -1,85 +1,85 @@
1
1
  {
2
- "name": "@howaboua/pi-shepherdr",
3
- "version": "1.0.0",
4
- "description": "Persistent blocking and asynchronous Pi agents through Herdr.",
5
- "type": "module",
6
- "license": "MIT",
7
- "author": "Igor Warzocha",
8
- "homepage": "https://github.com/IgorWarzocha/howaboua-pi-stuff/tree/main/packages/pi-shepherdr#readme",
9
- "repository": {
10
- "type": "git",
11
- "url": "git+https://github.com/IgorWarzocha/howaboua-pi-stuff.git",
12
- "directory": "packages/pi-shepherdr"
13
- },
14
- "bugs": {
15
- "url": "https://github.com/IgorWarzocha/howaboua-pi-stuff/issues"
16
- },
17
- "keywords": [
18
- "pi-package",
19
- "pi-extension",
20
- "pi",
21
- "herdr",
22
- "shepherdr",
23
- "agents",
24
- "orchestration"
25
- ],
26
- "files": [
27
- "index.ts",
28
- "worker-api.ts",
29
- "src",
30
- "profiles",
31
- "README.md",
32
- "LICENSE",
33
- "tsconfig.json",
34
- "biome.json",
35
- "CHANGELOG.md"
36
- ],
37
- "scripts": {
38
- "check": "bun run lint && bun run typecheck",
39
- "prepack": "bun run check",
40
- "typecheck": "tsgo --noEmit",
41
- "lint": "biome check .",
42
- "format": "biome check --write .",
43
- "pack:dry": "npm pack --dry-run"
44
- },
45
- "peerDependencies": {
46
- "@howaboua/pi-codex-conversion": ">=4.0.10",
47
- "@earendil-works/pi-ai": ">=1.1.0",
48
- "@earendil-works/pi-coding-agent": ">=1.5.0",
49
- "@earendil-works/pi-tui": ">=1.1.0"
50
- },
51
- "peerDependenciesMeta": {
52
- "@howaboua/pi-codex-conversion": {
53
- "optional": true
54
- }
55
- },
56
- "devDependencies": {
57
- "@howaboua/pi-agent-comms": "0.0.1",
58
- "@howaboua/pi-codex-conversion": "4.0.10",
59
- "@biomejs/biome": "^2.6.6",
60
- "@earendil-works/pi-ai": "1.5.2",
61
- "@earendil-works/pi-coding-agent": "1.5.2",
62
- "@earendil-works/pi-tui": "1.5.2",
63
- "@types/node": "^26.6.6",
64
- "typescript": "^7.0.2"
65
- },
66
- "pi": {
67
- "extensions": [
68
- "./index.ts"
69
- ]
70
- },
71
- "engines": {
72
- "node": ">=22.19.0"
73
- },
74
- "main": "index.ts",
75
- "exports": {
76
- ".": "./index.ts",
77
- "./worker-api": "./worker-api.ts"
78
- },
79
- "publishConfig": {
80
- "access": "public"
81
- },
82
- "dependencies": {
83
- "@earendil-works/pi-schema": "1.5.2"
84
- }
2
+ "name": "@howaboua/pi-shepherdr",
3
+ "version": "1.0.2",
4
+ "description": "Persistent blocking and asynchronous Pi agents through Herdr.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Igor Warzocha",
8
+ "homepage": "https://github.com/IgorWarzocha/howaboua-pi-stuff/tree/main/packages/pi-shepherdr#readme",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/IgorWarzocha/howaboua-pi-stuff.git",
12
+ "directory": "packages/pi-shepherdr"
13
+ },
14
+ "bugs": {
15
+ "url": "https://github.com/IgorWarzocha/howaboua-pi-stuff/issues"
16
+ },
17
+ "keywords": [
18
+ "pi-package",
19
+ "pi-extension",
20
+ "pi",
21
+ "herdr",
22
+ "shepherdr",
23
+ "agents",
24
+ "orchestration"
25
+ ],
26
+ "files": [
27
+ "index.ts",
28
+ "worker-api.ts",
29
+ "src",
30
+ "profiles",
31
+ "README.md",
32
+ "LICENSE",
33
+ "tsconfig.json",
34
+ "CHANGELOG.md"
35
+ ],
36
+ "scripts": {
37
+ "check": "bun run lint && bun run typecheck",
38
+ "prepack": "bun run check",
39
+ "typecheck": "tsrs --noEmit",
40
+ "lint": "bun run format:check && oxlint --type-aware",
41
+ "format": "oxfmt --write '**/*.{js,cjs,mjs,jsx,ts,cts,mts,tsx,json,jsonc,json5,css}'",
42
+ "pack:dry": "npm pack --dry-run",
43
+ "format:check": "oxfmt --check '**/*.{js,cjs,mjs,jsx,ts,cts,mts,tsx,json,jsonc,json5,css}'"
44
+ },
45
+ "peerDependencies": {
46
+ "@howaboua/pi-codex-conversion": ">=5.0.1",
47
+ "@earendil-works/pi-ai": ">=1.1.0",
48
+ "@earendil-works/pi-coding-agent": ">=1.5.0",
49
+ "@earendil-works/pi-tui": ">=1.1.0"
50
+ },
51
+ "peerDependenciesMeta": {
52
+ "@howaboua/pi-codex-conversion": {
53
+ "optional": true
54
+ }
55
+ },
56
+ "devDependencies": {
57
+ "@howaboua/pi-agent-comms": "0.0.3",
58
+ "@howaboua/pi-codex-conversion": "5.0.1",
59
+ "@earendil-works/pi-ai": "1.5.2",
60
+ "@earendil-works/pi-coding-agent": "1.5.2",
61
+ "@earendil-works/pi-tui": "1.5.2",
62
+ "@types/node": "^26.6.6",
63
+ "typescript": "^7.0.2",
64
+ "oxfmt": "^0.78.0"
65
+ },
66
+ "pi": {
67
+ "extensions": [
68
+ "./index.ts"
69
+ ]
70
+ },
71
+ "engines": {
72
+ "node": ">=22.19.0"
73
+ },
74
+ "main": "index.ts",
75
+ "exports": {
76
+ ".": "./index.ts",
77
+ "./worker-api": "./worker-api.ts"
78
+ },
79
+ "publishConfig": {
80
+ "access": "public"
81
+ },
82
+ "dependencies": {
83
+ "@earendil-works/pi-schema": "1.5.2"
84
+ }
85
85
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "description": "General implementation",
3
- "model": "openai-codex/gpt-6-sol",
3
+ "model": "openai-codex/gpt-6.2-sol",
4
4
  "thinking": "high",
5
5
  "prompt": "prompt.md",
6
6
  "accepts": [],
@@ -23,6 +23,7 @@ export async function nativeAgentName(
23
23
  !("sessionId" in value) ||
24
24
  typeof value.sessionId !== "string" ||
25
25
  !value.sessionId ||
26
+ // oxlint-disable-next-line no-control-regex -- Intentionally matches terminal controls or rejects control characters at the boundary.
26
27
  /[/\\\u0000]/.test(value.sessionId)
27
28
  )
28
29
  throw new Error(
@@ -68,8 +68,8 @@ export async function agentsHelp(
68
68
  ? "target=Pi session reference or terminal; /root=live spawn root"
69
69
  : "Use the Pi session reference or terminal target; /root selects the live root of saved spawn ancestry",
70
70
  resume: gpt
71
- ? "send/assign to owned closed worker→resume saved session; /quit never resumes"
72
- : "Sending or assigning to a closed worker recorded by this parent resumes its saved session; /quit never resumes",
71
+ ? "send/assign to owned closed worker→resume saved session+reporting unless unwatched; /quit never resumes"
72
+ : "Sending or assigning to an owned closed worker resumes its saved session and reporting unless unwatched; /quit never resumes",
73
73
  label: "Short Pi session name; app tabs use default names",
74
74
  placement:
75
75
  "terminal (default), new_tab, new_workspace; new_tab needs space ID",
@@ -81,8 +81,8 @@ export async function agentsHelp(
81
81
  }
82
82
  : {}),
83
83
  send: gpt
84
- ? "Messages wake idle agents; send ONLY to change recipient next action, NO acknowledgements/status-only/standby. Close→/quit directly, NO preceding message or wait/watch"
85
- : "Messages wake idle agents. Send only when it changes the recipient's next action; skip acknowledgements, status-only updates and standby reminders. Close with /quit directly, without another message first. No waiting or watching.",
84
+ ? "Messages wake idle agents; ONLY concrete blocker/ownership conflict/usable handoff that changes next action. NO acknowledgements/status-only/standby. Close→/quit directly, NO preceding message or wait/watch"
85
+ : "Messages wake idle agents. Send only a concrete blocker, ownership conflict or usable handoff that changes the recipient's next action; skip acknowledgements, status-only updates and standby reminders. Close with /quit directly, without another message first. No waiting or watching.",
86
86
  assign: gpt
87
87
  ? "Delegate/update work; active→share pending result, NEVER replace wait"
88
88
  : "Delegate or update work; active updates share its pending result, never replace an existing wait",
@@ -100,8 +100,8 @@ export async function agentsHelp(
100
100
  ? "Idle target; stop context/board independently; omitted=false, at least one true; counterpart checkpoints remain readonly"
101
101
  : "Stop context/board independently; omitted=false, at least one true; retain counterpart checkpoints read-only; idle target",
102
102
  blocking: gpt
103
- ? "spawn/assign default false→dispatch then return; true→wait for result; profile overrides spawn. Parallel blocking calls: await Promise.allSettled. Background reports automatic→do other work/end turn, NO poll or await timers/extra Promises"
104
- : "spawn/assign return after dispatch by default. Set blocking:true to wait for the result; profile blocking overrides spawn. Use await Promise.allSettled for parallel blocking calls, including failures. Background reports arrive automatically: do other work or end this turn, never poll or await timers or extra Promises for reports",
103
+ ? "spawn/assign default false→dispatch then return; true→wait for result; profile overrides spawn. Background reports automatic→do other work/end turn, NO poll"
104
+ : "spawn/assign return after dispatch by default. Set blocking:true to wait for the result; profile blocking overrides spawn. Background reports arrive automatically: do other work or end this turn, never poll",
105
105
  share_context: gpt
106
106
  ? "Profile false→isolated notes/history; otherwise→controller sharing setting"
107
107
  : "Profile false isolates notes/history; otherwise follows controller sharing setting",
@@ -109,8 +109,8 @@ export async function agentsHelp(
109
109
  ? "Delegation/watch→report subsequent work UNTIL unwatch/close"
110
110
  : "Delegation and watch keep reporting subsequent work until unwatch or close",
111
111
  prompt: gpt
112
- ? "Task + necessary context; trust agent to choose approach. Avoid unnecessary restrictions and overly narrow scope"
113
- : "Give the task and necessary context. Trust the agent to choose its approach. Avoid unnecessary restrictions and overly narrow scope",
112
+ ? "Outcome + completion evidence + context. Shared dependency→ONE owner; peers consume handoff. Keep original outcome covered when redirecting. Trust agent approach; avoid needless restrictions/narrowing"
113
+ : "Give a distinct outcome, completion evidence and necessary context. Shared dependencies need one owner; peers consume its handoff. Keep the original outcome covered when redirecting work. Trust the agent's approach; avoid unnecessary restrictions and overly narrow scope",
114
114
  slash: gpt
115
115
  ? "Leading / routes target commands/skills/templates; commands skip task wait EVEN assign/spawn; blocked→choices; /quit exits Pi+closes terminal"
116
116
  : "Leading / routes target commands/skills/templates. Commands skip task waiting, even with assign/spawn; blocked commands return available choices. /quit shuts down Pi and closes its terminal",
@@ -120,6 +120,7 @@ export function readFocus(value: unknown): FocusRequest {
120
120
  if (
121
121
  "agent" in source &&
122
122
  (typeof source["agent"] !== "string" ||
123
+ // oxlint-disable-next-line no-control-regex -- Intentionally matches terminal controls or rejects control characters at the boundary.
123
124
  !/^\/[^/\\\u0000]+$/.test(source["agent"]))
124
125
  )
125
126
  throw new Error("Invalid focus agent");
@@ -232,7 +232,7 @@ export async function spawnAgent(
232
232
  target: started.id,
233
233
  name,
234
234
  status: "working",
235
- next: "Do other work or end this turn; completion/blockage arrives automatically. Do not poll or await timers/extra Promises for reports",
235
+ next: "Do other work or end this turn; completion/blockage arrives automatically. Do not poll or use timers/extra Promises for reports",
236
236
  }),
237
237
  agent: agentName,
238
238
  ...(boardBinding || sharing
@@ -32,6 +32,7 @@ import type { AgentFleet } from "./fleet/index.js";
32
32
  import { attributeAgentPrompt } from "./messages/attribution.js";
33
33
  import type { createPeerCommands } from "./peer-commands.js";
34
34
  import type { SharedAgentContext } from "./shared-context.js";
35
+ import { setChildSupervision } from "./spawn-ownership.js";
35
36
  import { WorkerResumer } from "./worker-resume.js";
36
37
 
37
38
  export function createAgentsTool(
@@ -147,6 +148,13 @@ export function createAgentsTool(
147
148
  });
148
149
  }
149
150
  await runtime.monitor.unwatch(record.paneId);
151
+ setChildSupervision(
152
+ pi,
153
+ ctx,
154
+ runtime.local ? fleet.localMachine() : runtime.machine,
155
+ { pane_id: record.paneId },
156
+ false,
157
+ );
150
158
  return toolResult({
151
159
  unwatched: true,
152
160
  machine: runtime.machine,
@@ -181,11 +189,18 @@ export function createAgentsTool(
181
189
  }
182
190
  if (params.action === "watch") {
183
191
  await runtime.monitor.watch(panel);
192
+ setChildSupervision(
193
+ pi,
194
+ ctx,
195
+ runtime.local ? fleet.localMachine() : runtime.machine,
196
+ panel,
197
+ true,
198
+ );
184
199
  return toolResult({
185
200
  watched: true,
186
201
  machine: runtime.machine,
187
202
  target: panel.pane_id,
188
- next: "Do other work or end this turn; completion/blockage arrives automatically. Do not poll or await timers/extra Promises for reports",
203
+ next: "Do other work or end this turn; completion/blockage arrives automatically. Do not poll",
189
204
  });
190
205
  }
191
206
  if (params.action === "read") {
@@ -227,7 +242,7 @@ export function createAgentsTool(
227
242
  ]
228
243
  .filter(Boolean)
229
244
  .join("\n");
230
- if (params.action === "send") {
245
+ if (params.action === "send" && !owned?.restoreSupervision) {
231
246
  executionSignal.throwIfAborted();
232
247
  const receipt = await runtime.client.sendMessage(
233
248
  panel,
@@ -247,12 +262,25 @@ export function createAgentsTool(
247
262
  runtime,
248
263
  panel,
249
264
  message,
250
- params.blocking === true,
265
+ params.action === "assign" && params.blocking === true,
251
266
  executionSignal,
252
267
  update,
253
268
  () => runtime.client.sendMessage(panel, attributedMessage),
254
- { expectUserMessage: true },
269
+ {
270
+ expectUserMessage: true,
271
+ },
255
272
  );
273
+ if (params.action === "send")
274
+ return toolResult(
275
+ {
276
+ sent: true,
277
+ ...(owned?.resumed ? { resumed: true } : {}),
278
+ ...(dispatch.command ? { commandSubmitted: true } : {}),
279
+ machine: runtime.machine,
280
+ target: panel.pane_id,
281
+ },
282
+ dispatch.warning,
283
+ );
256
284
  return toolResult(
257
285
  {
258
286
  ...(owned?.resumed ? { resumed: true } : {}),
@@ -272,7 +300,7 @@ export function createAgentsTool(
272
300
  machine: runtime.machine,
273
301
  target: panel.pane_id,
274
302
  status: "working",
275
- next: "Do other work or end this turn; completion/blockage arrives automatically. Do not poll or await timers/extra Promises for reports",
303
+ next: "Do other work or end this turn; completion/blockage arrives automatically. Do not poll",
276
304
  }),
277
305
  },
278
306
  dispatch.warning,
@@ -128,7 +128,10 @@ export async function dispatchAgentWork(
128
128
  signal: AbortSignal,
129
129
  onUpdate: AgentToolUpdateCallback<Record<string, unknown>>,
130
130
  send: () => Promise<PeerDelivery | void>,
131
- options: { expectUserMessage?: boolean; replyingTo?: ExtensionReply } = {},
131
+ options: {
132
+ expectUserMessage?: boolean;
133
+ replyingTo?: ExtensionReply;
134
+ } = {},
132
135
  ): Promise<{
133
136
  settlement?: ClaimedSettlement;
134
137
  command?: true;
@@ -30,6 +30,7 @@ function nativeIdentity(value: unknown): NativeSessionIdentity {
30
30
  !("sessionId" in value) ||
31
31
  typeof value.sessionId !== "string" ||
32
32
  !value.sessionId ||
33
+ // oxlint-disable-next-line no-control-regex -- Intentionally matches terminal controls or rejects control characters at the boundary.
33
34
  /[/\\\u0000]/.test(value.sessionId) ||
34
35
  !("sessionFile" in value) ||
35
36
  typeof value.sessionFile !== "string" ||
@@ -148,8 +148,9 @@ export async function connectAdmission(
148
148
  });
149
149
  }
150
150
  signal.throwIfAborted();
151
+ // Standalone Pi's Bun executable runs Pi, not arbitrary JavaScript.
151
152
  const child = spawn(
152
- process.execPath,
153
+ process.versions["bun"] ? "node" : process.execPath,
153
154
  [
154
155
  fileURLToPath(new URL("./admission-broker.mjs", import.meta.url)),
155
156
  createHash("sha256").update(path).digest("hex"),
@@ -70,7 +70,9 @@ export async function resolvePiAgent(
70
70
  return agent;
71
71
  }
72
72
 
73
- export function sessionPath(agent: PaneInfo): string | undefined {
73
+ export function sessionPath(
74
+ agent: Pick<PaneInfo, "agent_session">,
75
+ ): string | undefined {
74
76
  return agent.agent_session?.kind === "path"
75
77
  ? agent.agent_session.value
76
78
  : undefined;
@@ -103,7 +103,11 @@ export async function focusCoreWindow(
103
103
  try {
104
104
  const created = object(
105
105
  await core.request("terminal.run", {
106
- argv: [process.execPath, "-e", "setTimeout(()=>{},120000)"],
106
+ argv: [
107
+ process.versions["bun"] ? "node" : process.execPath,
108
+ "-e",
109
+ "setTimeout(()=>{},120000)",
110
+ ],
107
111
  name,
108
112
  labels: { "herdr.space": space, "herdr.tab": tab },
109
113
  no_parent: true,
@@ -188,13 +192,16 @@ export async function focusCoreWindow(
188
192
  "kind" in error &&
189
193
  error.kind === "not_found"
190
194
  ) {
195
+ // oxlint-disable-next-line no-unsafe-finally -- Preserve the focus result while treating an already-closed probe as successful cleanup.
191
196
  if (failed) throw failure;
197
+ // oxlint-disable-next-line no-unsafe-finally -- Preserve the focus result while treating an already-closed probe as successful cleanup.
192
198
  return;
193
199
  }
194
200
  const cleanupFailure = new Error(
195
201
  `${focused ? "Focus succeeded" : `Focus failed: ${String(failure)}`} but its temporary terminal could not be closed: ${String(error)}`,
196
202
  { cause: failure ?? error },
197
203
  );
204
+ // oxlint-disable-next-line no-unsafe-finally -- Preserve the focus result while treating an already-closed probe as successful cleanup.
198
205
  throw dispatched ? cleanupFailure : rejected(cleanupFailure);
199
206
  }
200
207
  }
@@ -63,8 +63,10 @@ const wire = focusWire(
63
63
  );
64
64
  process.stdin.setRawMode(true);
65
65
  process.stdin.on("data", (bytes) => wire.push(bytes));
66
+ // oxlint-disable-next-line typescript/no-misused-promises -- Shutdown owns process termination and a bounded cleanup deadline.
66
67
  process.stdin.on("error", stop);
67
68
  process.stdin.on("end", () => void stop());
69
+ // oxlint-disable-next-line typescript/no-misused-promises -- Shutdown owns process termination and a bounded cleanup deadline.
68
70
  process.stdout.on("error", stop);
69
71
  process.on("SIGTERM", () => void stop());
70
72
  process.on("SIGHUP", () => void stop());
@@ -15,9 +15,9 @@ export function terminalPane(value: unknown): PaneInfo {
15
15
  state === "error"
16
16
  ? "done"
17
17
  : state === "idle" ||
18
- state === "working" ||
19
- state === "blocked" ||
20
- state === "done"
18
+ state === "working" ||
19
+ state === "blocked" ||
20
+ state === "done"
21
21
  ? state
22
22
  : "unknown";
23
23
  const session = livePiSession(terminal);
@@ -1,9 +1,9 @@
1
- import { getCurrentPane, getSnapshot } from "../core/agents.js";
1
+ import { getCurrentPane } from "../core/agents.js";
2
2
  import type { CoreConnection } from "../core/backend.js";
3
3
  import type { PaneInfo, PeerMessage } from "../types.js";
4
4
 
5
5
  const DELEGATED_WORKER_GUIDANCE =
6
- "If blocked mid-run, use a question-asking tool, not peer messages. Without one, end with the blocker. Finish with an assistant reply, not a separate send report; never watch your parent.";
6
+ "Keep the assigned outcome primary. Peer coordination must unblock it, not become a separate task. After a handoff or agreement, return to the work. Reopen settled decisions only for new evidence; do not trade plans.\n\nYour final assistant reply automatically reports the result or blocker to the parent. End the turn instead of sending a separate completion message. If blocked mid-run, use a question-asking tool, not peer messages. Without one, end with the blocker. Never watch your parent.";
7
7
 
8
8
  export function xml(value: string): string {
9
9
  return value
@@ -54,24 +54,15 @@ export async function attributeAgentPrompt(
54
54
  kind: "message" | "task",
55
55
  initialProfile?: string,
56
56
  ): Promise<PeerMessage> {
57
- const [pane, snapshot] = await Promise.all([
57
+ const [pane, identity] = await Promise.all([
58
58
  getCurrentPane(client),
59
- getSnapshot(client),
59
+ client.machineIdentity(),
60
60
  ]);
61
- const workspace = snapshot.workspaces.find(
62
- (workspace) => workspace.workspace_id === pane.workspace_id,
63
- )?.label;
64
- const tab = snapshot.tabs.find((tab) => tab.tab_id === pane.tab_id)?.label;
65
- const identity = await client.machineIdentity();
66
61
  const source = {
67
62
  kind,
68
- host: identity.host,
69
63
  machine: identity.session,
70
64
  agent: `/${sessionId}`,
71
- ...agentSource(pane, {
72
- ...(workspace ? { workspace } : {}),
73
- ...(tab ? { tab } : {}),
74
- }),
65
+ terminal: pane.terminal_id,
75
66
  };
76
67
  return {
77
68
  sender: `<herdr_sender ${sourceAttributes(source)} />`,
@@ -116,7 +116,7 @@ function agentEvent(options: AgentEventOptions): {
116
116
  message: message.reply,
117
117
  };
118
118
  const call = codeMode
119
- ? `await tools.${agentToolName}(${JSON.stringify(request)})`
119
+ ? `tools.${agentToolName}(${JSON.stringify(request)})`
120
120
  : `${agentToolName} ${JSON.stringify(request)}`;
121
121
  lines.push(`Reply: ${call}`);
122
122
  }
@@ -21,7 +21,7 @@ export function focusArrivalContent(
21
21
  voice: request.voice === true,
22
22
  };
23
23
  const args = JSON.stringify(returnFocus);
24
- const callable = codeMode ? `await tools.agents(${args})` : `agents ${args}`;
24
+ const callable = codeMode ? `tools.agents(${args})` : `agents ${args}`;
25
25
  return {
26
26
  returnFocus,
27
27
  content: `User arrived from ${JSON.stringify(focusOrigin(request))}\nReturn: ${callable}${request.voice ? "\nVoice transfer pending" : ""}${request.handoff ? `\nHandoff from that agent:\n${request.handoff}` : ""}`,
@@ -50,7 +50,7 @@ function stableActivity(value: unknown): StableAgentActivity | undefined {
50
50
  : attemptId === false
51
51
  ? undefined
52
52
  : expectedUserAfter === false ||
53
- (expectedUserAfter !== undefined && !task)
53
+ (expectedUserAfter !== undefined && !task)
54
54
  ? undefined
55
55
  : {
56
56
  phase: "working",
@@ -110,9 +110,9 @@ export function parseMonitoredAgent(
110
110
  record["notifiedExtensionMessages"] === undefined
111
111
  ? undefined
112
112
  : Array.isArray(record["notifiedExtensionMessages"]) &&
113
- record["notifiedExtensionMessages"].every(
113
+ record["notifiedExtensionMessages"].every(
114
114
  (value) => typeof value === "string",
115
- )
115
+ )
116
116
  ? (record["notifiedExtensionMessages"] as string[])
117
117
  : false;
118
118
  const name = optionalString(record, "name");
package/src/peer-inbox.ts CHANGED
@@ -123,6 +123,7 @@ async function openInbox(
123
123
  socket.on("close", () => sockets.delete(socket));
124
124
  let buffer = "";
125
125
  let received = false;
126
+ // oxlint-disable-next-line typescript/no-misused-promises -- Async delivery branches return explicit peer rejection/failure replies.
126
127
  socket.on("data", async (chunk: string) => {
127
128
  if (received) return;
128
129
  buffer += chunk;
@@ -1,5 +1,6 @@
1
1
  // @howaboua/pi-shepherdr managed bridge
2
2
 
3
+ import { createHash } from "node:crypto";
3
4
  import { open, stat } from "node:fs/promises";
4
5
  import { homedir } from "node:os";
5
6
  import { join } from "node:path";
@@ -12,7 +13,8 @@ function record(value) {
12
13
  }
13
14
 
14
15
  const READ_CHUNK_BYTES = 64 * 1024;
15
- /** @type {Map<string,{mtimeMs:number,size:number,result:import("../types.js").SessionView}>} */
16
+ /** @typedef {{leaf:string|undefined,entries:Record<string,unknown>[],result:import("../types.js").SessionView}} ViewSummary */
17
+ /** @type {Map<string,{mtimeMs:number,ctimeMs:number,ino:number,dev:number,size:number,digest:string,terminated:boolean,summary:ViewSummary}>} */
16
18
  const sessionCache = new Map();
17
19
 
18
20
  /** @param {string} path */
@@ -95,9 +97,45 @@ export function extensionMessageKey(value) {
95
97
  return JSON.stringify([value.extension, value.id]);
96
98
  }
97
99
 
98
- /** @param {string} path @param {number} size @returns {Promise<import("../types.js").SessionView>} */
99
- async function sessionView(path, size) {
100
- const file = await open(path, "r");
100
+ /** Verify the whole prefix: native Pi can rewrite a file in place, even to a larger size.
101
+ * @param {import("node:fs/promises").FileHandle} file
102
+ * @param {number} size
103
+ * @param {{size:number,digest:string}|undefined} cached
104
+ */
105
+ async function fingerprint(file, size, cached) {
106
+ const hash = createHash("sha256");
107
+ const buffer = Buffer.allocUnsafe(1024 * 1024);
108
+ let position = 0;
109
+ let prefixMatches = false;
110
+ let terminated = false;
111
+ while (position < size) {
112
+ const boundary = cached && position < cached.size ? cached.size : size;
113
+ const length = Math.min(buffer.length, boundary - position);
114
+ const { bytesRead } = await file.read(buffer, 0, length, position);
115
+ if (!bytesRead) break;
116
+ hash.update(buffer.subarray(0, bytesRead));
117
+ position += bytesRead;
118
+ terminated = buffer[bytesRead - 1] === 0x0a;
119
+ if (position === cached?.size)
120
+ prefixMatches = hash.copy().digest("hex") === cached.digest;
121
+ }
122
+ return {
123
+ digest: hash.digest("hex"),
124
+ prefixMatches,
125
+ terminated,
126
+ complete: position === size,
127
+ };
128
+ }
129
+
130
+ /** @param {import("node:fs/promises").FileHandle} file @param {number} size
131
+ * @param {{size:number,summary:ViewSummary}|undefined} cached
132
+ * @returns {Promise<ViewSummary>}
133
+ */
134
+ async function sessionView(file, size, cached) {
135
+ /** @type {string | undefined} */
136
+ let leaf;
137
+ /** @type {Record<string,unknown>[]} */
138
+ const entries = [];
101
139
  /** @type {string | undefined} */
102
140
  let targetId;
103
141
  /** @type {import("../types.js").LatestAssistant | undefined} */
@@ -123,20 +161,14 @@ async function sessionView(path, size) {
123
161
  ? { assistantAfterInput: assistantDepth < inputDepth }
124
162
  : {}),
125
163
  });
126
- /** @param {Buffer} line */
127
- const inspect = (line) => {
128
- if (line.length === 0) return false;
129
- /** @type {unknown} */
130
- let parsed;
131
- try {
132
- parsed = JSON.parse(line.toString("utf8"));
133
- } catch {
134
- return false;
135
- }
136
- const entry = record(parsed);
137
- if (!entry || typeof entry["id"] !== "string") return false;
138
- targetId ??= entry["id"];
139
- if (entry["id"] !== targetId) return false;
164
+ /** Only retain semantic records, never image/tool payloads or the whole transcript.
165
+ * @param {Record<string,unknown>} entry
166
+ */
167
+ const consume = (entry) => {
168
+ if (typeof entry["id"] !== "string") return;
169
+ /** @type {Record<string,unknown>} */
170
+ const retained = { id: entry["id"], type: entry["type"] };
171
+ let keep = false;
140
172
  const currentDepth = depth;
141
173
  depth += 1;
142
174
  if (
@@ -156,12 +188,16 @@ async function sessionView(path, size) {
156
188
  id: update["id"],
157
189
  });
158
190
  if (!resolved.has(key)) {
159
- if (update["state"] === "closed") resolved.add(key);
160
- else {
191
+ if (update["state"] === "closed") {
192
+ // Suppress older pending records; closures need no cached replay.
193
+ resolved.add(key);
194
+ } else {
161
195
  const pending = readExtensionMessage(update);
162
196
  if (pending) {
163
197
  extensionMessages.push(pending);
164
198
  resolved.add(key);
199
+ retained["data"] = { version: 1, state: "pending", ...pending };
200
+ keep = true;
165
201
  }
166
202
  }
167
203
  }
@@ -176,6 +212,8 @@ async function sessionView(path, size) {
176
212
  ) {
177
213
  input = { id: entry["id"], text: entry["content"] };
178
214
  inputDepth = currentDepth;
215
+ retained["content"] = input.text;
216
+ keep = true;
179
217
  }
180
218
  const message = record(entry["message"]);
181
219
  if (message && typeof message === "object") {
@@ -185,8 +223,15 @@ async function sessionView(path, size) {
185
223
  if (message["stopReason"] === "toolUse") {
186
224
  assistantSeen = true;
187
225
  assistantPending = !assistant;
226
+ retained["message"] = { role: "assistant", stopReason: "toolUse" };
227
+ keep = true;
188
228
  } else {
189
229
  const candidate = assistantFromMessage(entry["id"], message);
230
+ retained["message"] = {
231
+ role: "assistant",
232
+ content: candidate?.text,
233
+ stopReason: candidate?.stopReason,
234
+ };
190
235
  if (
191
236
  !assistant ||
192
237
  candidate?.text ||
@@ -194,43 +239,81 @@ async function sessionView(path, size) {
194
239
  ) {
195
240
  assistant = candidate;
196
241
  if (assistant) assistantDepth = currentDepth;
242
+ keep = true;
197
243
  }
198
244
  assistantSeen = !!candidate?.text || candidate?.stopReason !== "stop";
199
245
  }
200
246
  }
201
247
  if (!input) {
202
248
  input = inputFromMessage(entry["id"], message);
203
- if (input) inputDepth = currentDepth;
249
+ if (input) {
250
+ inputDepth = currentDepth;
251
+ retained["message"] = { role: "user", content: input.text };
252
+ keep = true;
253
+ }
204
254
  }
205
255
  }
206
256
  if (input) assistantSeen = true;
257
+ if (keep) {
258
+ if (entry["customType"] !== undefined)
259
+ retained["customType"] = entry["customType"];
260
+ entries.push(retained);
261
+ }
262
+ };
263
+ const summary = () => ({ leaf, entries, result: result() });
264
+ /** @param {Buffer} line */
265
+ const inspect = (line) => {
266
+ if (line.length === 0) return false;
267
+ let parsed;
268
+ try {
269
+ parsed = JSON.parse(line.toString("utf8"));
270
+ } catch {
271
+ return false;
272
+ }
273
+ const entry = record(parsed);
274
+ if (!entry || typeof entry["id"] !== "string") return false;
275
+ leaf ??= entry["id"];
276
+ targetId ??= entry["id"];
277
+ if (entry["id"] !== targetId) return false;
278
+ consume(entry);
207
279
  if (typeof entry["parentId"] !== "string") return true;
208
280
  targetId = entry["parentId"];
209
281
  return false;
210
282
  };
211
283
 
212
- try {
213
- let position = size;
214
- let partial = Buffer.alloc(0);
215
- while (position > 0) {
216
- const length = Math.min(READ_CHUNK_BYTES, position);
217
- position -= length;
218
- const chunk = Buffer.allocUnsafe(length);
219
- const { bytesRead } = await file.read(chunk, 0, length, position);
220
- const data = Buffer.concat([chunk.subarray(0, bytesRead), partial]);
221
- let lineEnd = data["length"];
222
- for (let index = data["length"] - 1; index >= 0; index -= 1) {
223
- if (data[index] !== 0x0a) continue;
224
- if (inspect(data["subarray"](index + 1, lineEnd))) return result();
225
- lineEnd = index;
226
- }
227
- partial = data["subarray"](0, lineEnd);
284
+ let position = size;
285
+ const boundary = cached?.size ?? 0;
286
+ /** @type {Buffer[]} Fragments in reverse file order; join only at a newline. */
287
+ let fragments = [];
288
+ /** @param {Buffer} prefix */
289
+ const finishLine = (prefix) => {
290
+ if (!fragments.length) return inspect(prefix);
291
+ fragments.push(prefix);
292
+ const line = Buffer.concat(fragments.reverse());
293
+ fragments = [];
294
+ return inspect(line);
295
+ };
296
+ while (position > boundary) {
297
+ const length = Math.min(READ_CHUNK_BYTES, position - boundary);
298
+ position -= length;
299
+ const chunk = Buffer.allocUnsafe(length);
300
+ const { bytesRead } = await file.read(chunk, 0, length, position);
301
+ let lineEnd = bytesRead;
302
+ for (let index = bytesRead - 1; index >= 0; index -= 1) {
303
+ if (chunk[index] !== 0x0a) continue;
304
+ if (finishLine(chunk.subarray(index + 1, lineEnd))) return summary();
305
+ lineEnd = index;
228
306
  }
229
- inspect(partial);
230
- return result();
231
- } finally {
232
- await file.close();
307
+ if (lineEnd) fragments.push(chunk.subarray(0, lineEnd));
308
+ }
309
+ if (finishLine(Buffer.alloc(0))) return summary();
310
+ if (cached) {
311
+ if (targetId !== undefined && targetId !== cached.summary.leaf)
312
+ return sessionView(file, size, undefined);
313
+ leaf ??= cached.summary.leaf;
314
+ for (const entry of cached.summary.entries) consume(entry);
233
315
  }
316
+ return summary();
234
317
  }
235
318
 
236
319
  /** @param {string | undefined} path @returns {Promise<import("../types.js").SessionView>} */
@@ -241,20 +324,57 @@ export async function readSessionView(path) {
241
324
  try {
242
325
  metadata = await stat(expanded);
243
326
  } catch (error) {
244
- if (error instanceof Error && "code" in error && error.code === "ENOENT")
327
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
328
+ sessionCache.delete(expanded);
245
329
  return {};
330
+ }
246
331
  throw error;
247
332
  }
248
333
  const cached = sessionCache.get(expanded);
249
- if (cached?.size === metadata.size && cached.mtimeMs === metadata.mtimeMs)
250
- return cached.result;
251
- const result = await sessionView(expanded, metadata.size);
252
- sessionCache.set(expanded, {
253
- size: metadata.size,
254
- mtimeMs: metadata.mtimeMs,
255
- result,
256
- });
257
- return result;
334
+ const sameFile = cached?.ino === metadata.ino && cached.dev === metadata.dev;
335
+ if (
336
+ sameFile &&
337
+ cached.size === metadata.size &&
338
+ cached.mtimeMs === metadata.mtimeMs &&
339
+ cached.ctimeMs === metadata.ctimeMs
340
+ )
341
+ return cached.summary.result;
342
+ const file = await open(expanded, "r");
343
+ try {
344
+ metadata = await file.stat();
345
+ const candidate =
346
+ sameFile && cached.terminated && cached.size < metadata.size
347
+ ? cached
348
+ : undefined;
349
+ const fingerprinted = await fingerprint(file, metadata.size, candidate);
350
+ const summary = await sessionView(
351
+ file,
352
+ metadata.size,
353
+ fingerprinted.prefixMatches ? candidate : undefined,
354
+ );
355
+ const after = await file.stat();
356
+ // Never publish a cache built across a concurrent append, rewrite or truncation.
357
+ if (
358
+ fingerprinted.complete &&
359
+ after.size === metadata.size &&
360
+ after.mtimeMs === metadata.mtimeMs &&
361
+ after.ctimeMs === metadata.ctimeMs
362
+ ) {
363
+ sessionCache.set(expanded, {
364
+ size: metadata.size,
365
+ mtimeMs: metadata.mtimeMs,
366
+ ctimeMs: metadata.ctimeMs,
367
+ ino: metadata.ino,
368
+ dev: metadata.dev,
369
+ digest: fingerprinted.digest,
370
+ terminated: fingerprinted.terminated,
371
+ summary,
372
+ });
373
+ } else sessionCache.delete(expanded);
374
+ return summary.result;
375
+ } finally {
376
+ await file.close();
377
+ }
258
378
  }
259
379
 
260
380
  /** Native session identity only; never create or load an entire transcript.
@@ -1,5 +1,5 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- import { activityAttemptId } from "../activity.js";
2
+ import { activityAttemptId, activityTask } from "../activity.js";
3
3
  import { injectAgentEvent } from "../messages/events.js";
4
4
  import type { WorkAttempt } from "../monitor-state.js";
5
5
  import type {
@@ -143,6 +143,17 @@ export class SettlementDelivery {
143
143
  });
144
144
  return;
145
145
  }
146
+ // Notice-only turns can deliberately end without a report. Settle them
147
+ // silently, but keep assigned work and actionable events visible.
148
+ if (
149
+ settlement.status !== "blocked" &&
150
+ !blockedMessage &&
151
+ !activityTask(record.activity) &&
152
+ reply?.stopReason === "stop" &&
153
+ !reply.text.trim() &&
154
+ !settlement.extensionMessages?.length
155
+ )
156
+ return;
146
157
  injectAgentEvent(this.pi, lifecycle.context, {
147
158
  agent: settlement.agent,
148
159
  agentToolName: "agents",
@@ -143,6 +143,7 @@ export async function runSetupProcess(
143
143
  signal.removeEventListener("abort", abort);
144
144
  await cleanup;
145
145
  if (cleanupError)
146
+ // oxlint-disable-next-line no-unsafe-finally -- Cleanup failure must remain visible, even when the primary operation failed.
146
147
  throw new Error(
147
148
  `Setup process cleanup failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`,
148
149
  { cause: cleanupError },
@@ -28,13 +28,12 @@ export async function registerSharedAgentContext(
28
28
  });
29
29
  let relationships:
30
30
  | ReturnType<
31
- typeof import("@howaboua/pi-codex-conversion/agent-relationship")["connectCodexAgentRelationships"]
31
+ (typeof import("@howaboua/pi-codex-conversion/agent-relationship"))["connectCodexAgentRelationships"]
32
32
  >
33
33
  | undefined;
34
34
  try {
35
- const relationshipApi = await import(
36
- "@howaboua/pi-codex-conversion/agent-relationship"
37
- );
35
+ const relationshipApi =
36
+ await import("@howaboua/pi-codex-conversion/agent-relationship");
38
37
  relationships = relationshipApi.connectCodexAgentRelationships(pi);
39
38
  } catch (error) {
40
39
  const failure = error as { code?: string; message?: string };
@@ -45,6 +45,7 @@ export interface SpawnOwnership {
45
45
  terminal: string;
46
46
  sessionFile: string;
47
47
  agent?: string;
48
+ supervised?: boolean;
48
49
  launch?: Static<typeof SavedLaunch>;
49
50
  aliases?: string[];
50
51
  }
@@ -77,6 +78,9 @@ export function spawnedChildren(ctx: ExtensionContext): SpawnOwnership[] {
77
78
  ...("agent" in value && typeof value.agent === "string"
78
79
  ? { agent: value.agent }
79
80
  : {}),
81
+ ...("supervised" in value && typeof value.supervised === "boolean"
82
+ ? { supervised: value.supervised }
83
+ : {}),
80
84
  ...("aliases" in value &&
81
85
  Array.isArray(value.aliases) &&
82
86
  value.aliases.every((alias) => typeof alias === "string")
@@ -95,6 +99,25 @@ export function spawnedChildren(ctx: ExtensionContext): SpawnOwnership[] {
95
99
  return [...children.values()];
96
100
  }
97
101
 
102
+ /** Terminal closure ends a live watch, not the parent's saved delegation policy. */
103
+ export function setChildSupervision(
104
+ pi: ExtensionAPI,
105
+ ctx: ExtensionContext,
106
+ machine: string,
107
+ panel: Pick<PaneInfo, "pane_id" | "agent_session">,
108
+ supervised: boolean,
109
+ ): void {
110
+ const file = sessionPath(panel);
111
+ for (const child of spawnedChildren(ctx)) {
112
+ if (
113
+ child.session === machine &&
114
+ (child.pane === panel.pane_id || (file && child.sessionFile === file)) &&
115
+ (child.supervised !== false) !== supervised
116
+ )
117
+ pi.appendEntry(ENTRY, { ...child, supervised } satisfies SpawnOwnership);
118
+ }
119
+ }
120
+
98
121
  // Capture before launch. A context switch must never adopt a completed spawn.
99
122
  export function prepareSpawnOwnership(
100
123
  pi: ExtensionAPI,
package/src/ssh-setup.ts CHANGED
@@ -44,6 +44,7 @@ export function sshSetupItems(draft: SshSetupDraft): SettingItem[] {
44
44
 
45
45
  export function sshSetupArgs(draft: SshSetupDraft): string[] {
46
46
  const { target, label, session } = draft;
47
+ // oxlint-disable-next-line no-control-regex -- Intentionally matches terminal controls or rejects control characters at the boundary.
47
48
  if (!target || /^[-\s]|[\s\x00-\x1f\x7f]/.test(target))
48
49
  throw new Error(
49
50
  "Enter an SSH alias or user@host, without spaces or options.",
@@ -20,6 +20,27 @@ interface OwnedTarget {
20
20
  runtime: ConnectedMachine;
21
21
  panel: PaneInfo;
22
22
  resumed: boolean;
23
+ restoreSupervision?: true;
24
+ }
25
+
26
+ function ownedTarget(
27
+ runtime: ConnectedMachine,
28
+ panel: PaneInfo,
29
+ resumed: boolean,
30
+ child?: SpawnOwnership,
31
+ ): OwnedTarget {
32
+ return {
33
+ runtime,
34
+ panel,
35
+ resumed,
36
+ ...(child &&
37
+ child.supervised !== false &&
38
+ !runtime.monitor
39
+ .list()
40
+ .some((record) => record.terminalId === panel.terminal_id)
41
+ ? { restoreSupervision: true as const }
42
+ : {}),
43
+ };
23
44
  }
24
45
 
25
46
  /** Parent-owned saved sessions, not a general session launcher or delivery retry. */
@@ -42,6 +63,7 @@ export class WorkerResumer {
42
63
  const selected = machine
43
64
  ? this.fleet.connected(machine).machine
44
65
  : undefined;
66
+ const children = spawnedChildren(ctx);
45
67
  // A current native address/name always wins over a saved routing alias.
46
68
  if (!target.startsWith("/")) {
47
69
  const runtime = this.fleet.connected(machine);
@@ -50,20 +72,30 @@ export class WorkerResumer {
50
72
  const live = exact
51
73
  ? [exact]
52
74
  : snapshot.agents.filter((panel) => panel.name === target);
53
- if (live.length)
54
- return {
75
+ if (live.length) {
76
+ const panel = await resolvePiAgent(
77
+ runtime.client,
78
+ target,
79
+ runtime.local ? process.env["HC_TERMINAL_ID"] : "",
80
+ );
81
+ const machineId = runtime.local
82
+ ? this.fleet.localMachine()
83
+ : runtime.machine;
84
+ return ownedTarget(
55
85
  runtime,
56
- panel: await resolvePiAgent(
57
- runtime.client,
58
- target,
59
- runtime.local ? process.env["HC_TERMINAL_ID"] : "",
86
+ panel,
87
+ false,
88
+ children.find(
89
+ (child) =>
90
+ child.session === machineId &&
91
+ child.sessionFile === sessionPath(panel),
60
92
  ),
61
- resumed: false,
62
- };
93
+ );
94
+ }
63
95
  }
64
96
  const candidates: { child: SpawnOwnership; runtime: ConnectedMachine }[] =
65
97
  [];
66
- for (const child of spawnedChildren(ctx)) {
98
+ for (const child of children) {
67
99
  const direct =
68
100
  child.agent === target ||
69
101
  child.pane === target ||
@@ -166,7 +198,7 @@ export class WorkerResumer {
166
198
  throw new Error(
167
199
  "Worker identity changed; resolve its current session before sending",
168
200
  );
169
- return { runtime, panel: live[0], resumed: false };
201
+ return ownedTarget(runtime, live[0], false, child);
170
202
  }
171
203
  if (!allowResume)
172
204
  throw new Error("Worker is already closed; no session was resumed");
@@ -223,7 +255,7 @@ export class WorkerResumer {
223
255
  started.agent,
224
256
  agent,
225
257
  );
226
- return { runtime, panel: started.agent, resumed: true };
258
+ return ownedTarget(runtime, started.agent, true, child);
227
259
  } catch (error) {
228
260
  return rollbackStartedAgent(runtime.client, started, error);
229
261
  }
@@ -77,9 +77,9 @@ export function registerWorkerService(
77
77
  state: !panel
78
78
  ? "closed"
79
79
  : (panel.agent_status !== "idle" && panel.agent_status !== "done") ||
80
- panel.interactive_ready !== true ||
81
- panel.launch_pending ||
82
- (record &&
80
+ panel.interactive_ready !== true ||
81
+ panel.launch_pending ||
82
+ (record &&
83
83
  (record.activity.phase !== "settled" ||
84
84
  activityTask(record.activity)))
85
85
  ? "working"
package/biome.json DELETED
@@ -1,31 +0,0 @@
1
- {
2
- "$schema": "https://biomejs.dev/schemas/2.6.6/schema.json",
3
- "vcs": {
4
- "enabled": true,
5
- "clientKind": "git",
6
- "useIgnoreFile": true
7
- },
8
- "files": {
9
- "includes": [
10
- "**",
11
- "!node_modules",
12
- "!dist",
13
- "!coverage",
14
- "!package-lock.json"
15
- ]
16
- },
17
- "formatter": {
18
- "enabled": true,
19
- "indentStyle": "tab"
20
- },
21
- "linter": {
22
- "enabled": false
23
- },
24
- "javascript": {
25
- "formatter": {
26
- "quoteStyle": "double",
27
- "semicolons": "always",
28
- "trailingCommas": "all"
29
- }
30
- }
31
- }