@howaboua/pi-shepherdr 0.2.24 → 0.2.25

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 (73) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +17 -9
  3. package/index.ts +2 -0
  4. package/package.json +5 -5
  5. package/src/agents-contract.ts +9 -6
  6. package/src/agents-discovery.ts +41 -15
  7. package/src/agents-focus.ts +15 -9
  8. package/src/agents-spawn.ts +22 -6
  9. package/src/agents-tool.ts +24 -6
  10. package/src/agents-work.ts +2 -2
  11. package/src/attachment.ts +2 -0
  12. package/src/board/host.ts +3 -1
  13. package/src/close-idle.ts +89 -0
  14. package/src/control-panel/index.ts +3 -1
  15. package/src/control-panel/items.ts +14 -2
  16. package/src/control-panel/view.ts +6 -2
  17. package/src/controller.ts +11 -2
  18. package/src/core/AGENTS.md +5 -0
  19. package/src/core/backend.ts +266 -0
  20. package/src/core/client.ts +249 -0
  21. package/src/core/context-relay.mjs +111 -0
  22. package/src/core/focus-channel-helper.mjs +165 -0
  23. package/src/core/focus-channel-stream.ts +140 -0
  24. package/src/core/focus-channel-wire.mjs +160 -0
  25. package/src/core/focus-channel.ts +213 -0
  26. package/src/core/focus-window.ts +192 -0
  27. package/src/core/pi-executable.mjs +34 -0
  28. package/src/core/protocol.ts +116 -0
  29. package/src/core/registration.ts +51 -0
  30. package/src/core/remote-endpoint.ts +119 -0
  31. package/src/core/remote-exec.ts +122 -0
  32. package/src/core/remote-helper.mjs +244 -0
  33. package/src/core/remote-reader.ts +67 -0
  34. package/src/core/remote-relay.ts +191 -0
  35. package/src/core/request.ts +124 -0
  36. package/src/core/spawn.ts +177 -0
  37. package/src/core/status.ts +68 -0
  38. package/src/core/terminal.ts +103 -0
  39. package/src/fleet/catalog.ts +83 -0
  40. package/src/fleet/connection.ts +111 -0
  41. package/src/fleet/index.ts +151 -122
  42. package/src/fleet/inspection.ts +19 -1
  43. package/src/fleet/machine.ts +3 -0
  44. package/src/fleet/monitor.ts +18 -4
  45. package/src/fleet/persistence.ts +26 -3
  46. package/src/fleet/setup.ts +54 -13
  47. package/src/herdr.ts +25 -5
  48. package/src/launch-contract.ts +48 -0
  49. package/src/launch-location.ts +151 -0
  50. package/src/launch.ts +30 -183
  51. package/src/messages/attribution.ts +15 -6
  52. package/src/messages/events.ts +10 -4
  53. package/src/messages/focus.ts +11 -2
  54. package/src/monitor-record.ts +9 -6
  55. package/src/monitor.ts +31 -0
  56. package/src/peer-commands.ts +11 -0
  57. package/src/peer-inbox-delivery.ts +171 -0
  58. package/src/peer-inbox-focus.ts +113 -0
  59. package/src/peer-inbox.ts +126 -208
  60. package/src/remote/deployment.ts +1 -1
  61. package/src/remote/shepherdr-context.mjs +1 -1
  62. package/src/remote/shepherdr-peer.mjs +18 -5
  63. package/src/remote/shepherdr-session.mjs +9 -2
  64. package/src/remote/shepherdr.mjs +1 -1
  65. package/src/settlement/collector.ts +2 -2
  66. package/src/settlement/index.ts +12 -0
  67. package/src/shared-context-host.ts +7 -3
  68. package/src/shared-context.ts +34 -2
  69. package/src/spawn-context.ts +4 -0
  70. package/src/spawn-ownership.ts +91 -0
  71. package/src/types.ts +9 -5
  72. package/src/worker-ownership.ts +92 -0
  73. package/src/worker-service.ts +12 -81
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # @howaboua/pi-shepherdr
2
2
 
3
+ ## 0.2.25
4
+
5
+ - When switching from the older Herdr TUI or another Core instance, reselect local watches.
6
+ - Added Herdr Core and Herdr app support for local and remote delegation, focus, voice transfers, shared Notes and boards, including Windows hosts.
7
+ - Added Core session discovery by terminal title, with spaces, hyphens and underscores treated alike.
8
+ - Added `/herdr close-idle` to close idle children spawned by the current session branch, leaving attached and busy sessions open.
9
+ - Spawn results now return `contextAgent` and `boardAgent` inside `sharing` instead of at the top level. The agent `target` is unchanged.
10
+ - Reduced resume delays in sessions with many delegated agents, including closed children.
11
+ - Remote sharing helpers now start only when sharing is used or restored, avoiding idle polling on unrelated machines.
12
+ - Fixed intermediate tool calls being reported as completed agent work.
13
+ - Agent guidance now distinguishes automatic background reports from blocking calls that must be awaited.
14
+ - Agent tool declarations now accept action fields discovered through help, including in native codemode.
15
+
3
16
  ## 0.2.24
4
17
 
5
18
  - - **BREAKING CHANGE:** Shared notes and history now use Notes instead of PCC. Install `@howaboua/pi-notes-compaction` and update participating hosts together to retain sharing. PCC remains optional for native parent linkage and cache affinity. Ordinary agent management requires neither extension.
package/README.md CHANGED
@@ -14,7 +14,9 @@ With Pi Codex's compatible custom developer-message API active, asynchronous wor
14
14
  pi install npm:@howaboua/pi-shepherdr
15
15
  ```
16
16
 
17
- Requires Pi 1.2.0 or newer, Node.js 22.18 or newer, Herdr 0.9 or newer and the Herdr Pi integration:
17
+ Requires Pi 1.2.0 or newer and Node.js 22.18 or newer. Run Pi inside Herdr Core 0.1.14 or newer, or the Herdr app, to use the new Herdr backend. Shepherdr reports Pi status to Core and discovers other Pi sessions with Shepherdr installed.
18
+
19
+ For the older Herdr TUI, install its Pi integration:
18
20
 
19
21
  ```bash
20
22
  herdr integration install pi
@@ -24,6 +26,10 @@ Do not load Pi Codex's example `agents.toml` custom tool alongside Shepherdr; th
24
26
 
25
27
  Pi Codex is optional. Without it, Shepherdr remains a normal Pi extension.
26
28
 
29
+ Herdr Core workers start as background terminals by default. Explicit new-tab and new-workspace placements appear when an app connected to that Core adopts them. Focus requires a Herdr app window connected to the target Core. Existing Herdr TUI sessions cannot be moved into Core.
30
+
31
+ For remote Core workers, add machines with `hc machine add` and install Node.js, Herdr Core and Shepherdr on each target. Delegation, supervision, shared context and boards work across those machines.
32
+
27
33
  ## Control panel
28
34
 
29
35
  The agent tool is always available in Pi, Code Mode and Notebook Mode. Run Pi inside Herdr to connect the fleet and start monitoring automatically. Open the control panel with:
@@ -32,17 +38,19 @@ The agent tool is always available in Pi, Code Mode and Notebook Mode. Run Pi in
32
38
  /herdr
33
39
  ```
34
40
 
35
- **Settings** contains orchestration preferences, agent command guidance and the global config path. **Status** shows machine connections and reconnect actions. **Connections** adds SSH machines through Herdr's setup flow. Agents handle discovery, attachment and detachment through the `agents` tool, not this panel.
41
+ **Settings** contains orchestration preferences, agent command guidance and the global config path. **Status** shows machine connections and reconnect actions. **Connections** adds SSH machines for the older Herdr TUI. Agents handle discovery, attachment and detachment through the `agents` tool, not this panel.
42
+
43
+ Run `/herdr close-idle` to close idle child sessions spawned by the current session branch. Attached or assigned existing sessions are never included. Busy, blocked, unavailable or unverified children stay open. Children spawned before this feature was installed have no ownership receipt and stay open too. Pi shuts down gracefully before its pane closes.
36
44
 
37
45
  `/herdr` is Shepherdr's only entry point. Outside the TUI, it reports status without changing it. An orchestration change records one visible guidance message without triggering a turn. Resumed sessions restore their last mode; new sessions start with normal guidance. The current guidance returns when a new model context no longer contains it, including turns started by worker messages. Tool availability and monitoring do not depend on this mode.
38
46
 
39
- To add a machine, enter an SSH target or alias, a label and an optional remote session under **Connections**. Herdr performs setup in the terminal and asks before installing or replacing its remote server. OpenSSH owns authentication; Shepherdr does not store credentials. Profiles remain in Herdr's existing catalog, where they can also be renamed, disabled or removed.
47
+ For the older Herdr TUI, add a machine by entering an SSH target or alias, a label and an optional remote session under **Connections**. Herdr performs setup in the terminal and asks before installing or replacing its remote server. OpenSSH owns authentication; Shepherdr does not store credentials. Profiles remain in Herdr's existing catalog, where they can also be renamed, disabled or removed.
40
48
 
41
- Shepherdr connects enabled profiles at session startup. **Status** refreshes the catalog and retries failed connections or incomplete monitoring without dropping working connections. A catalog refresh stops watches for disabled or removed profiles without stopping remote agents.
49
+ With the older TUI, Shepherdr connects enabled profiles at session startup. **Status** refreshes the catalog and retries failed connections or incomplete monitoring without dropping working connections. A catalog refresh stops watches for disabled or removed profiles without stopping remote agents.
42
50
 
43
51
  Profiles belong to the host running Pi, not the machine displaying its terminal. Omit `machine` for local agent calls. `list` and `find` search all machines unless filtered. Explicit `local` also means the host running Pi. For remote calls, use the opaque profile ID returned by `list`, not its label or hostname. Renaming a profile changes its label, not its routing identity.
44
52
 
45
- Remote machines connect over noninteractive SSH. The target needs `node` on its SSH PATH, Herdr 0.9 or newer, the Herdr Pi integration and a running Herdr session. Shepherdr installs managed transport helpers under `~/.pi/agent` on each remote, runs them only for the connection lifetime and leaves no remote daemon behind. Herdr's multi-machine UI does not expose a cross-machine automation socket, so Shepherdr still owns its remote transport and Pi transcript reads.
53
+ With the older TUI, remote machines connect over noninteractive SSH. The target needs `node` on its SSH PATH, Herdr 0.9 or newer, the Herdr Pi integration and a running Herdr session. Shepherdr installs managed transport helpers under `~/.pi/agent` on each remote, runs them only for the connection lifetime and leaves no remote daemon behind. Herdr's multi-machine UI does not expose a cross-machine automation socket, so Shepherdr still owns its remote transport and Pi transcript reads.
46
54
 
47
55
  ### Migrating from separate Shepherdr machines
48
56
 
@@ -79,15 +87,15 @@ Use `send` for messages and work updates without waiting or adding supervision.
79
87
 
80
88
  Delegation and explicit `watch` keep reporting subsequent work until `unwatch` or the agent's pane closes. Finishing or failing a task clears that task, not its watch. Follow-up messages through `send` retain completion reporting without replacing the task.
81
89
 
82
- Every `spawn` needs an `agent_type` and a concise `label`. The label names both the Herdr tab and Pi session; the routing `name` remains optional and is derived from it when omitted.
90
+ Every `spawn` needs an `agent_type` and a concise `label`. The label names the Pi session, and also names the tab in the older Herdr TUI. The routing `name` remains optional and is derived from the label when omitted.
83
91
 
84
92
  Cancelling a blocking call does not kill its worker. The waiter detaches and the eventual result returns through normal asynchronous delivery.
85
93
 
86
94
  After Pi compaction or Notes context rollover, the controller receives its supervised agents' exact machine and target, submitted tasks and follow-up instructions, and last observed status, including settled and blocked workers. Read a target for its reply or pending extension messages. This reminder does not start a turn or bypass normal turn preparation.
87
95
 
88
- Prompts sent through `agents` identify peer messages versus delegated tasks and include the sender's host, session, workspace, tab and pane identity, with current names. Reports include source workspace and tab names too. Raw `herdr agent prompt` calls bypass this attribution. These are runtime locations, not the desktop window showing a pane.
96
+ Prompts sent through `agents` identify peer messages versus delegated tasks and include the sender's host and session identity. The older TUI also includes workspace, tab and pane details. Core reports use terminal addresses and include app location IDs when available. These are runtime locations, not the desktop window showing a pane.
89
97
 
90
- Messages sent through `agents` bypass the receiving Pi editor, preserving unsent drafts. Update and reload Shepherdr on receiving agents as well as controllers. If a receiver is unavailable, delivery fails without pasting into its terminal. Raw `herdr agent prompt` still uses terminal input and does not provide this protection.
98
+ Messages sent through `agents` bypass the receiving Pi editor, preserving unsent drafts. Update and reload Shepherdr on receiving agents as well as controllers. If a receiver is unavailable, delivery fails without pasting into its terminal. On the older TUI, raw `herdr agent prompt` still uses terminal input and does not provide this protection.
91
99
 
92
100
  Messages beginning with `/` use the target Pi session's command, skill and prompt-template expansion, with sender attribution kept out of the arguments. Skills and templates retain normal task waiting. Prompt templates remain supported, but you must tell your agent which templates exist separately. When Pi Codex Conversion is installed, update and reload it too.
93
101
 
@@ -249,7 +257,7 @@ Optional profile settings:
249
257
 
250
258
  ## Advanced Herdr control
251
259
 
252
- Ordinary delegation stays inside `agents`. For workspace, tab, pane, process, focus, layout or raw-terminal operations, run `herdr --skill` and follow the installed Herdr skill. Shepherdr does not duplicate those controls.
260
+ Ordinary delegation stays inside `agents`. For terminal operations on Core, run `hc --skill`. For window operations, use `herdr-app --skill`. The older TUI provides its own guide through `herdr --skill`.
253
261
 
254
262
  Herdr still owns terminals, layout, agent processes and restored sessions. Shepherdr owns event subscriptions, remote routing, the fleet widget and purple settlement messages.
255
263
 
package/index.ts CHANGED
@@ -5,6 +5,7 @@ import { acceptFocus, registerFocusArrivals } from "./src/agents-focus.js";
5
5
  import { createAgentsTool } from "./src/agents-tool.js";
6
6
  import { AgentBoard } from "./src/board/host.js";
7
7
  import { registerAgentController } from "./src/controller.js";
8
+ import { registerCoreStatus } from "./src/core/status.js";
8
9
  import { registerDeveloperDelivery } from "./src/delivery.js";
9
10
  import { AgentFleet } from "./src/fleet/index.js";
10
11
  import { registerAgentEventRenderer } from "./src/messages/render.js";
@@ -23,6 +24,7 @@ const CODE_MODE_MODULE = `${CODE_MODE_PACKAGE}/code-mode`;
23
24
  export default async function shepherdrExtension(
24
25
  pi: ExtensionAPI,
25
26
  ): Promise<void> {
27
+ registerCoreStatus(pi);
26
28
  const workerRole = registerWorkerRole(pi);
27
29
  registerPackageChangelog(pi);
28
30
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howaboua/pi-shepherdr",
3
- "version": "0.2.24",
3
+ "version": "0.2.25",
4
4
  "description": "Persistent blocking and asynchronous Pi agents through Herdr.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -43,8 +43,8 @@
43
43
  "pack:dry": "npm pack --dry-run"
44
44
  },
45
45
  "peerDependencies": {
46
- "@howaboua/pi-notes-compaction": ">=0.0.10",
47
- "@howaboua/pi-codex-conversion": ">=4.0.5",
46
+ "@howaboua/pi-notes-compaction": ">=0.0.12",
47
+ "@howaboua/pi-codex-conversion": ">=4.0.6",
48
48
  "@earendil-works/pi-ai": ">=1.1.0",
49
49
  "@earendil-works/pi-coding-agent": ">=1.2.0",
50
50
  "@earendil-works/pi-tui": ">=1.1.0",
@@ -62,8 +62,8 @@
62
62
  "@howaboua/pi-agent-board": "0.0.4"
63
63
  },
64
64
  "devDependencies": {
65
- "@howaboua/pi-notes-compaction": "0.0.10",
66
- "@howaboua/pi-codex-conversion": "4.0.5",
65
+ "@howaboua/pi-notes-compaction": "0.0.12",
66
+ "@howaboua/pi-codex-conversion": "4.0.6",
67
67
  "@biomejs/biome": "^2.6.3",
68
68
  "@earendil-works/pi-ai": "1.4.0",
69
69
  "@earendil-works/pi-coding-agent": "1.4.0",
@@ -97,12 +97,15 @@ const AgentsRequest = Type.Object(
97
97
  { additionalProperties: false },
98
98
  );
99
99
 
100
- export const AgentsParameters = Type.Object({
101
- action: Type.Optional(StringEnum(ACTIONS)),
102
- commands: Type.Optional(Type.Literal(true)),
103
- target: Type.Optional(Type.String()),
104
- machine: Type.Optional(Type.String()),
105
- });
100
+ export const AgentsParameters = Type.Object(
101
+ {
102
+ action: Type.Optional(StringEnum(ACTIONS)),
103
+ commands: Type.Optional(Type.Literal(true)),
104
+ target: Type.Optional(Type.String()),
105
+ machine: Type.Optional(Type.String()),
106
+ },
107
+ { additionalProperties: true },
108
+ );
106
109
 
107
110
  export type AgentsParams = Static<typeof AgentsRequest>;
108
111
  export type AgentsToolParams = Static<typeof AgentsParameters>;
@@ -26,6 +26,7 @@ function describeProfiles(profiles: Map<string, AgentProfile>) {
26
26
  export async function agentsHelp(
27
27
  boardAvailable = false,
28
28
  gpt = false,
29
+ core = false,
29
30
  ): Promise<Record<string, unknown>> {
30
31
  const profiles = await loadAgentProfiles();
31
32
  return {
@@ -59,9 +60,14 @@ export async function agentsHelp(
59
60
  target: gpt
60
61
  ? "spawn/find target EXACT; /root=this family live root"
61
62
  : "Use spawn/find target exactly; /root selects this family's live root",
62
- label: gpt
63
- ? "Short tab/session name; two words IF useful"
64
- : "Short tab/session name; prefer two words when useful",
63
+ label: core
64
+ ? "Short Pi session name; app tabs use default names"
65
+ : gpt
66
+ ? "Short tab/session name; two words IF useful"
67
+ : "Short tab/session name; prefer two words when useful",
68
+ placement: core
69
+ ? "terminal (default), new_tab, new_workspace; new_tab needs space ID"
70
+ : "new_tab, new_workspace, pane",
65
71
  ...(boardAvailable
66
72
  ? {
67
73
  board_thread_id: gpt
@@ -89,8 +95,8 @@ export async function agentsHelp(
89
95
  ? "Idle target; stop selected membership; counterpart checkpoints remain readonly"
90
96
  : "Stop selected membership; retain counterpart checkpoints read-only; idle target",
91
97
  blocking: gpt
92
- ? "spawn/assign default true; profile overrides spawn; JS parallel+wait: await Promise.allSettled; false ONLY if other work continues; completion/blockage AFTER reply; NO poll/sleep"
93
- : "spawn/assign default true; profile blocking overrides spawn. In JavaScript cells, use await Promise.allSettled for parallel calls that wait for every result, including failures. Use false only to continue other work; completion/blockage arrives after your reply. No polling or sleep waits",
98
+ ? "spawn/assign default true; profile overrides spawn; await blocking calls; JS parallel: await Promise.allSettled; false ONLY if other work continues; background reports automatic→do other work/end turn, NO poll or await timers/extra Promises"
99
+ : "spawn/assign default true; profile blocking overrides spawn. Await blocking calls; use await Promise.allSettled for parallel calls, including failures. Use false only to continue other work. Background reports arrive automatically: do other work or end this turn, never poll or await timers or extra Promises for reports",
94
100
  share_context: gpt
95
101
  ? "Profile false→isolated notes/history; otherwise→controller sharing setting"
96
102
  : "Profile false isolates notes/history; otherwise follows controller sharing setting",
@@ -113,7 +119,9 @@ export async function agentsHelp(
113
119
  : {}),
114
120
  },
115
121
  profiles: describeProfiles(profiles),
116
- advanced: "herdr --skill: workspace/tab/pane/process/focus/layout/terminal",
122
+ advanced: core
123
+ ? "hc --skill: terminal processes and machines"
124
+ : "herdr --skill: workspace/tab/pane/process/focus/layout/terminal",
117
125
  };
118
126
  }
119
127
 
@@ -141,13 +149,23 @@ function compactAgent(
141
149
  machine,
142
150
  target: agent.pane_id,
143
151
  ...(agent.name ? { name: agent.name } : {}),
144
- ...(agent.label || names.panes.get(agent.pane_id)
145
- ? { label: agent.label ?? names.panes.get(agent.pane_id) }
152
+ ...(agent.label || names.panes.get(agent.pane_id) || agent.title
153
+ ? { label: agent.label || names.panes.get(agent.pane_id) || agent.title }
154
+ : {}),
155
+ ...(agent.title && (agent.label || names.panes.get(agent.pane_id))
156
+ ? { title: agent.title }
146
157
  : {}),
147
158
  status: agent.agent_status,
148
159
  cwd: agent.foreground_cwd ?? agent.cwd ?? null,
149
- workspace: names.workspaces.get(agent.workspace_id) ?? agent.workspace_id,
150
- tab: names.tabs.get(agent.tab_id) ?? agent.tab_id,
160
+ ...(agent.workspace_id
161
+ ? {
162
+ workspace:
163
+ names.workspaces.get(agent.workspace_id) ?? agent.workspace_id,
164
+ }
165
+ : {}),
166
+ ...(agent.tab_id
167
+ ? { tab: names.tabs.get(agent.tab_id) ?? agent.tab_id }
168
+ : {}),
151
169
  monitored,
152
170
  };
153
171
  }
@@ -159,11 +177,15 @@ function matchesAgent(
159
177
  ): boolean {
160
178
  if (status && agent["status"] !== status) return false;
161
179
  if (!query) return true;
162
- const haystack = Object.values(agent)
180
+ const normalize = (value: string) =>
181
+ value
182
+ .toLowerCase()
183
+ .replace(/[-_\s]+/g, " ")
184
+ .trim();
185
+ const needle = normalize(query);
186
+ return Object.values(agent)
163
187
  .filter((value) => typeof value === "string")
164
- .join("\n")
165
- .toLowerCase();
166
- return haystack.includes(query.toLowerCase());
188
+ .some((value) => normalize(value).includes(needle));
167
189
  }
168
190
 
169
191
  export async function listFleetAgents(
@@ -180,7 +202,11 @@ export async function listFleetAgents(
180
202
  .filter(
181
203
  (agent) =>
182
204
  agent.agent === "pi" &&
183
- (!machine.local || agent.pane_id !== process.env["HERDR_PANE_ID"]),
205
+ (!machine.local ||
206
+ agent.pane_id !==
207
+ (agent.backend === "core"
208
+ ? process.env["HC_TERMINAL_ID"]
209
+ : process.env["HERDR_PANE_ID"])),
184
210
  )
185
211
  .map((agent) =>
186
212
  compactAgent(
@@ -52,7 +52,9 @@ export async function focusAgent(
52
52
  const request: FocusRequest = {
53
53
  source: {
54
54
  ...(await local.client.machineIdentity()),
55
- pane: source.pane_id,
55
+ ...(source.backend === "core"
56
+ ? { backend: "core" as const }
57
+ : { pane: source.pane_id }),
56
58
  terminal: source.terminal_id,
57
59
  sessionFile,
58
60
  },
@@ -106,13 +108,7 @@ export function readFocus(value: unknown): FocusRequest {
106
108
  )
107
109
  throw new Error("Invalid focus source");
108
110
  const source = value.source as Record<string, unknown>;
109
- for (const field of [
110
- "host",
111
- "session",
112
- "pane",
113
- "terminal",
114
- "sessionFile",
115
- ] as const) {
111
+ for (const field of ["host", "session", "terminal", "sessionFile"] as const) {
116
112
  if (
117
113
  !(field in source) ||
118
114
  typeof source[field] !== "string" ||
@@ -120,6 +116,13 @@ export function readFocus(value: unknown): FocusRequest {
120
116
  )
121
117
  throw new Error("Invalid focus source");
122
118
  }
119
+ if (source["backend"] !== undefined && source["backend"] !== "core")
120
+ throw new Error("Invalid focus backend");
121
+ if (
122
+ source["backend"] !== "core" &&
123
+ (typeof source["pane"] !== "string" || !source["pane"].trim())
124
+ )
125
+ throw new Error("Invalid focus pane");
123
126
  if ("handoff" in value && typeof value.handoff !== "string")
124
127
  throw new Error("Invalid focus handoff");
125
128
  if ("voice" in value && typeof value.voice !== "boolean")
@@ -150,7 +153,10 @@ export async function acceptFocus(
150
153
  const identity = await runtime.client.machineIdentity();
151
154
  if (identity.host !== source.host || identity.session !== source.session)
152
155
  continue;
153
- const agent = await getAgent(runtime.client, source.pane);
156
+ const agent = await getAgent(
157
+ runtime.client,
158
+ source.backend === "core" ? source.terminal : source.pane!,
159
+ );
154
160
  if (
155
161
  agent.agent === "pi" &&
156
162
  agent.terminal_id === source.terminal &&
@@ -1,5 +1,6 @@
1
1
  import type {
2
2
  AgentToolUpdateCallback,
3
+ ExtensionAPI,
3
4
  ExtensionContext,
4
5
  } from "@earendil-works/pi-coding-agent";
5
6
  import {
@@ -15,6 +16,7 @@ import {
15
16
  toolResult,
16
17
  } from "./agents-work.js";
17
18
  import type { AgentBoard } from "./board/host.js";
19
+ import { CoreConnection } from "./core/backend.js";
18
20
  import type { AgentFleet, ConnectedMachine } from "./fleet/index.js";
19
21
  import { isDispatchRejected } from "./herdr-client.js";
20
22
  import {
@@ -29,8 +31,10 @@ import {
29
31
  profileAgentArgs,
30
32
  } from "./profiles.js";
31
33
  import type { SharedAgentContext } from "./shared-context.js";
34
+ import { prepareSpawnOwnership } from "./spawn-ownership.js";
32
35
 
33
36
  export async function spawnAgent(
37
+ pi: ExtensionAPI,
34
38
  fleet: AgentFleet,
35
39
  runtime: ConnectedMachine,
36
40
  params: AgentsParams,
@@ -40,6 +44,7 @@ export async function spawnAgent(
40
44
  ctx: ExtensionContext,
41
45
  board: AgentBoard,
42
46
  ) {
47
+ const recordSpawn = prepareSpawnOwnership(pi, ctx, runtime);
43
48
  const boardThreadId =
44
49
  params.board_thread_id === undefined
45
50
  ? undefined
@@ -70,9 +75,11 @@ export async function spawnAgent(
70
75
  try {
71
76
  const placement =
72
77
  params.placement ??
73
- (runtime.local && process.env["HERDR_WORKSPACE_ID"]
74
- ? "new_tab"
75
- : "new_workspace");
78
+ (runtime.client instanceof CoreConnection
79
+ ? "terminal"
80
+ : runtime.local && process.env["HERDR_WORKSPACE_ID"]
81
+ ? "new_tab"
82
+ : "new_workspace");
76
83
  const workspace =
77
84
  params.workspace ??
78
85
  (placement === "new_tab" && runtime.local
@@ -150,6 +157,7 @@ export async function spawnAgent(
150
157
  let relationshipWarning: string | undefined;
151
158
  const blocking = shouldBlockAgentSpawn(profile.blocking, params.blocking);
152
159
  try {
160
+ await recordSpawn(started.agent, agentArgs);
153
161
  relationshipWarning = (await relationship?.accept(started.agent))
154
162
  ?.warning;
155
163
  boardAgent = await boardBinding?.accept(started.agent);
@@ -183,8 +191,6 @@ export async function spawnAgent(
183
191
  }
184
192
  return toolResult(
185
193
  {
186
- ...(boardAgent ? { boardAgent } : {}),
187
- ...(shared?.agentName ? { contextAgent: shared.agentName } : {}),
188
194
  ...(dispatch.command
189
195
  ? {
190
196
  spawned: true,
@@ -204,8 +210,18 @@ export async function spawnAgent(
204
210
  target: started.id,
205
211
  name,
206
212
  status: "working",
207
- next: "Converse, do other work or reply now; completion/blockage arrives even after you reply. No polling or sleep waits",
213
+ next: "Do other work or end this turn; completion/blockage arrives automatically. Do not poll or await timers/extra Promises for reports",
208
214
  }),
215
+ ...(boardAgent || shared?.agentName
216
+ ? {
217
+ sharing: {
218
+ ...(boardAgent ? { boardAgent } : {}),
219
+ ...(shared?.agentName
220
+ ? { contextAgent: shared.agentName }
221
+ : {}),
222
+ },
223
+ }
224
+ : {}),
209
225
  },
210
226
  [dispatch.warning, shared?.warning, relationshipWarning]
211
227
  .filter(Boolean)
@@ -26,6 +26,7 @@ import {
26
26
  toolResult,
27
27
  } from "./agents-work.js";
28
28
  import type { AgentBoard } from "./board/host.js";
29
+ import { CoreConnection } from "./core/backend.js";
29
30
  import type { AgentFleet } from "./fleet/index.js";
30
31
  import { resolvePiAgent } from "./herdr.js";
31
32
  import { attributeAgentPrompt } from "./messages/attribution.js";
@@ -43,8 +44,9 @@ export function createAgentsTool(
43
44
  return defineTool({
44
45
  name: "agents",
45
46
  label: "Shepherdr",
46
- description: "Delegate to persistent agents",
47
- promptGuidelines: ["Make the first agents discovery call alone"],
47
+ description:
48
+ "Delegate to persistent agents; {} lists additional action fields",
49
+ promptGuidelines: ["Read agents help alone before first use"],
48
50
  parameters: AgentsParameters,
49
51
  executionMode: "parallel",
50
52
  async execute(_toolCallId, input: AgentsToolParams, signal, onUpdate, ctx) {
@@ -52,7 +54,16 @@ export function createAgentsTool(
52
54
  const executionSignal = signal ?? new AbortController().signal;
53
55
  const update = onUpdate ?? (() => undefined);
54
56
  if (params.action === "help" && !params.commands) {
55
- return toolResult(await agentsHelp(board.enabled(ctx), gpt()));
57
+ return toolResult(
58
+ await agentsHelp(
59
+ board.enabled(ctx),
60
+ gpt(),
61
+ Boolean(
62
+ process.env["HC_TERMINAL_ID"] &&
63
+ process.env["HC_TERMINAL_SOCKET"],
64
+ ),
65
+ ),
66
+ );
56
67
  }
57
68
  if (params.commands && params.target === undefined)
58
69
  return toolResult({ commands: commands.available() });
@@ -66,6 +77,7 @@ export function createAgentsTool(
66
77
  let runtime = fleet.connected(params.machine);
67
78
  if (params.action === "spawn") {
68
79
  return spawnAgent(
80
+ pi,
69
81
  fleet,
70
82
  runtime,
71
83
  params,
@@ -123,7 +135,13 @@ export function createAgentsTool(
123
135
  const panel = await resolvePiAgent(
124
136
  runtime.client,
125
137
  target,
126
- runtime.local ? process.env["HERDR_PANE_ID"] : "",
138
+ runtime.local
139
+ ? process.env[
140
+ runtime.client instanceof CoreConnection
141
+ ? "HC_TERMINAL_ID"
142
+ : "HERDR_PANE_ID"
143
+ ]
144
+ : "",
127
145
  );
128
146
  if (params.commands) {
129
147
  return toolResult({
@@ -149,7 +167,7 @@ export function createAgentsTool(
149
167
  watched: true,
150
168
  machine: runtime.machine,
151
169
  target: panel.pane_id,
152
- next: "Completion or blockage will be delivered automatically; do not poll",
170
+ next: "Do other work or end this turn; completion/blockage arrives automatically. Do not poll or await timers/extra Promises for reports",
153
171
  });
154
172
  }
155
173
  if (params.action === "read") {
@@ -221,7 +239,7 @@ export function createAgentsTool(
221
239
  machine: runtime.machine,
222
240
  target: panel.pane_id,
223
241
  status: "working",
224
- next: "Converse, do other work or reply now; completion/blockage arrives even after you reply. No polling or sleep waits",
242
+ next: "Do other work or end this turn; completion/blockage arrives automatically. Do not poll or await timers/extra Promises for reports",
225
243
  },
226
244
  dispatch.warning,
227
245
  );
@@ -93,13 +93,13 @@ export function settlementResult(
93
93
  `${settlement.agent.pane_id} assistant stopped with an error`
94
94
  : undefined;
95
95
  if (workerError && !options.reportWorkerError) throw new Error(workerError);
96
- const { pane, name, ...source } = agentSource(
96
+ const { pane, terminal, name, ...source } = agentSource(
97
97
  settlement.agent,
98
98
  settlement.labels,
99
99
  );
100
100
  return {
101
101
  machine,
102
- target: pane,
102
+ target: pane ?? terminal,
103
103
  ...(name ? { name } : {}),
104
104
  source,
105
105
  status: settlement.status,
package/src/attachment.ts CHANGED
@@ -97,6 +97,8 @@ export class AgentAttachment {
97
97
  "Target has different attachment choices; changing an attachment is unsupported",
98
98
  );
99
99
  let route = prior;
100
+ await runtime.prepareSharing();
101
+ await check();
100
102
  if (!route) {
101
103
  const snapshot = await runtime.client.requestContext(
102
104
  sessionContextPath(sessionFile),
package/src/board/host.ts CHANGED
@@ -78,6 +78,7 @@ export class AgentBoard {
78
78
  );
79
79
  },
80
80
  propagateEnabled: async (ctx, enabled) => {
81
+ let boardId: string | undefined;
81
82
  await Promise.all(
82
83
  children(ctx).map(async (child) => {
83
84
  try {
@@ -85,7 +86,7 @@ export class AgentBoard {
85
86
  sessionContextPath(child.sessionFile),
86
87
  {
87
88
  operation: "board-enabled",
88
- boardId: binding(ctx).boardId,
89
+ boardId: (boardId ??= binding(ctx).boardId),
89
90
  enabled,
90
91
  },
91
92
  AbortSignal.timeout(750),
@@ -156,6 +157,7 @@ export class AgentBoard {
156
157
  const segment =
157
158
  name.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64) || "agent";
158
159
  const agentName = `${own.agentName}/${segment}-${randomUUID()}`;
160
+ await runtime.prepareSharing();
159
161
  const upstream = runtime.local
160
162
  ? sessionContextPath(file)
161
163
  : runtime.client.contextRelayPath();
@@ -0,0 +1,89 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { CoreConnection } from "./core/backend.js";
3
+ import type { AgentFleet } from "./fleet/index.js";
4
+ import { getSnapshot, sessionPath } from "./herdr.js";
5
+ import { spawnedChildren } from "./spawn-ownership.js";
6
+
7
+ export async function closeIdleChildren(
8
+ fleet: AgentFleet,
9
+ ctx: ExtensionContext,
10
+ current: () => boolean,
11
+ ): Promise<string> {
12
+ let closed = 0;
13
+ let skipped = 0;
14
+ const failures: string[] = [];
15
+ for (const child of spawnedChildren(ctx)) {
16
+ if (!current()) break;
17
+ try {
18
+ const status = fleet
19
+ .statuses()
20
+ .find((value) => value.id === child.machine);
21
+ if (!status || status.status !== "connected" || status.monitoringIssue) {
22
+ skipped += 1;
23
+ continue;
24
+ }
25
+ const runtime = fleet.connected(child.machine);
26
+ const identity = await runtime.client.machineIdentity();
27
+ const snapshot = await getSnapshot(runtime.client);
28
+ const panel = snapshot.agents.find(
29
+ (value) => value.pane_id === child.pane,
30
+ );
31
+ const record = runtime.monitor
32
+ .list()
33
+ .find((value) => value.terminalId === child.terminal);
34
+ if (
35
+ !current() ||
36
+ !spawnedChildren(ctx).some(
37
+ (value) =>
38
+ value.machine === child.machine &&
39
+ value.pane === child.pane &&
40
+ value.terminal === child.terminal &&
41
+ value.sessionFile === child.sessionFile,
42
+ ) ||
43
+ identity.host !== child.host ||
44
+ identity.session !== child.session ||
45
+ !panel ||
46
+ panel.agent !== "pi" ||
47
+ panel.terminal_id !== child.terminal ||
48
+ sessionPath(panel) !== child.sessionFile ||
49
+ (runtime.local &&
50
+ panel.pane_id ===
51
+ process.env[
52
+ runtime.client instanceof CoreConnection
53
+ ? "HC_TERMINAL_ID"
54
+ : "HERDR_PANE_ID"
55
+ ]) ||
56
+ snapshot.agents.some(
57
+ (value) =>
58
+ value.pane_id !== child.pane &&
59
+ sessionPath(value) === child.sessionFile,
60
+ ) ||
61
+ panel.interactive_ready !== true ||
62
+ panel.launch_pending === true ||
63
+ (panel.agent_status !== "idle" && panel.agent_status !== "done") ||
64
+ !record ||
65
+ record.paneId !== child.pane ||
66
+ record.activity.phase !== "settled" ||
67
+ (record.activity.status !== "idle" && record.activity.status !== "done")
68
+ ) {
69
+ skipped += 1;
70
+ continue;
71
+ }
72
+ await runtime.client.sendMessage(panel, {
73
+ text: "/quit",
74
+ sender: '<herdr_sender kind="idle-close" />',
75
+ closeIfIdle: true,
76
+ });
77
+ closed += 1;
78
+ } catch (error) {
79
+ skipped += 1;
80
+ failures.push(
81
+ `${child.machine}:${child.pane}: ${error instanceof Error ? error.message : String(error)}`,
82
+ );
83
+ }
84
+ }
85
+ return [
86
+ `Closed ${closed} idle child sessions; skipped ${skipped}.`,
87
+ ...failures,
88
+ ].join("\n");
89
+ }
@@ -18,7 +18,9 @@ export function controlPanelStatus(options: PanelOptions): string {
18
18
  "Fleet inactive. Run Pi inside Herdr; open /herdr → Status to reconnect.",
19
19
  ]
20
20
  : []),
21
- "Open /herdr in TUI for Settings, Status and SSH Connections.",
21
+ process.env["HC_TERMINAL_SOCKET"]
22
+ ? "Open /herdr in TUI for Settings and Status. Manage machines in Herdr or with hc machine add."
23
+ : "Open /herdr in TUI for Settings, Status and SSH Connections.",
22
24
  ].join("\n");
23
25
  }
24
26