@howaboua/pi-shepherdr 0.2.23 → 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 (96) hide show
  1. package/CHANGELOG.md +20 -18
  2. package/README.md +80 -69
  3. package/biome.json +1 -1
  4. package/index.ts +4 -2
  5. package/package.json +14 -9
  6. package/src/agents-contract.ts +9 -6
  7. package/src/agents-discovery.ts +78 -37
  8. package/src/agents-focus.ts +17 -11
  9. package/src/agents-reply.ts +1 -1
  10. package/src/agents-spawn.ts +24 -8
  11. package/src/agents-tool.ts +26 -8
  12. package/src/agents-work.ts +5 -5
  13. package/src/attachment-notes.ts +14 -2
  14. package/src/attachment-protocol.ts +21 -4
  15. package/src/attachment-routing.ts +1 -1
  16. package/src/attachment-target.ts +5 -2
  17. package/src/attachment.ts +4 -3
  18. package/src/board/host.ts +5 -3
  19. package/src/board/membership.ts +1 -1
  20. package/src/close-idle.ts +89 -0
  21. package/src/{control-panel-actions.ts → control-panel/actions.ts} +2 -2
  22. package/src/{control-panel.ts → control-panel/index.ts} +7 -5
  23. package/src/{control-panel-items.ts → control-panel/items.ts} +17 -5
  24. package/src/{control-panel-view.ts → control-panel/view.ts} +9 -5
  25. package/src/controller.ts +17 -5
  26. package/src/core/AGENTS.md +5 -0
  27. package/src/core/backend.ts +266 -0
  28. package/src/core/client.ts +249 -0
  29. package/src/core/context-relay.mjs +111 -0
  30. package/src/core/focus-channel-helper.mjs +165 -0
  31. package/src/core/focus-channel-stream.ts +140 -0
  32. package/src/core/focus-channel-wire.mjs +160 -0
  33. package/src/core/focus-channel.ts +213 -0
  34. package/src/core/focus-window.ts +192 -0
  35. package/src/core/pi-executable.mjs +34 -0
  36. package/src/core/protocol.ts +116 -0
  37. package/src/core/registration.ts +51 -0
  38. package/src/core/remote-endpoint.ts +119 -0
  39. package/src/core/remote-exec.ts +122 -0
  40. package/src/core/remote-helper.mjs +244 -0
  41. package/src/core/remote-reader.ts +67 -0
  42. package/src/core/remote-relay.ts +191 -0
  43. package/src/core/request.ts +124 -0
  44. package/src/core/spawn.ts +177 -0
  45. package/src/core/status.ts +68 -0
  46. package/src/core/terminal.ts +103 -0
  47. package/src/fleet/catalog.ts +83 -0
  48. package/src/fleet/connection.ts +111 -0
  49. package/src/fleet/index.ts +413 -0
  50. package/src/fleet/inspection.ts +159 -0
  51. package/src/fleet/machine.ts +55 -0
  52. package/src/fleet/monitor.ts +85 -0
  53. package/src/fleet/persistence.ts +65 -0
  54. package/src/fleet/reconnect.ts +75 -0
  55. package/src/fleet/setup.ts +133 -0
  56. package/src/herdr.ts +25 -5
  57. package/src/launch-contract.ts +48 -0
  58. package/src/launch-location.ts +151 -0
  59. package/src/launch.ts +30 -183
  60. package/src/messages/attachments.ts +39 -0
  61. package/src/messages/attribution.ts +84 -0
  62. package/src/messages/event-details.ts +69 -0
  63. package/src/messages/events.ts +195 -0
  64. package/src/messages/focus.ts +47 -0
  65. package/src/messages/guidance.ts +83 -0
  66. package/src/messages/render.ts +89 -0
  67. package/src/messages/voice-announcements.ts +79 -0
  68. package/src/monitor-record.ts +9 -6
  69. package/src/monitor.ts +33 -2
  70. package/src/peer-commands.ts +11 -0
  71. package/src/peer-inbox-delivery.ts +171 -0
  72. package/src/peer-inbox-focus.ts +113 -0
  73. package/src/peer-inbox.ts +127 -209
  74. package/src/remote/client.ts +127 -0
  75. package/src/remote/context-relay.ts +84 -0
  76. package/src/remote/deployment.ts +179 -0
  77. package/src/remote/focus-channels.ts +89 -0
  78. package/src/remote/shepherdr-context.mjs +1 -1
  79. package/src/remote/shepherdr-peer.mjs +18 -5
  80. package/src/remote/shepherdr-session.mjs +9 -2
  81. package/src/remote/shepherdr.mjs +1 -1
  82. package/src/remote/transport.ts +369 -0
  83. package/src/settlement/collector.ts +122 -0
  84. package/src/settlement/delivery.ts +144 -0
  85. package/src/{settlement.ts → settlement/index.ts} +35 -233
  86. package/src/shared-context-host.ts +40 -14
  87. package/src/shared-context.ts +44 -6
  88. package/src/spawn-context.ts +24 -17
  89. package/src/spawn-ownership.ts +91 -0
  90. package/src/types.ts +9 -5
  91. package/src/voice-handoff.ts +1 -1
  92. package/src/worker-ownership.ts +92 -0
  93. package/src/worker-service.ts +14 -83
  94. package/src/fleet.ts +0 -702
  95. package/src/messages.ts +0 -637
  96. package/src/remote-client.ts +0 -761
@@ -0,0 +1,159 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { CoreConnection } from "../core/backend.js";
3
+ import { getSnapshot } from "../herdr.js";
4
+ import { LOCAL_MACHINE } from "../machine-catalog.js";
5
+ import { parseMonitoredAgent } from "../monitor-record.js";
6
+ import { RemoteHerdrClient } from "../remote/client.js";
7
+ import type {
8
+ MachineStatus,
9
+ MonitoredAgent,
10
+ ScopedMonitoredAgent,
11
+ } from "../types.js";
12
+ import {
13
+ type ConnectedMachine,
14
+ errorMessage,
15
+ type MachineRuntime,
16
+ type MachineSnapshot,
17
+ } from "./machine.js";
18
+
19
+ export function listAgents(
20
+ runtimes: ReadonlyMap<string, MachineRuntime>,
21
+ ): ScopedMonitoredAgent[] {
22
+ return [...runtimes.entries()].flatMap(([machine, runtime]) => {
23
+ const values = runtime.monitor?.list() ?? runtime.pending;
24
+ return values
25
+ .map((value) => parseMonitoredAgent(value))
26
+ .filter((value): value is MonitoredAgent => value !== undefined)
27
+ .map((agent) => ({ ...agent, machine }));
28
+ });
29
+ }
30
+
31
+ export function connectedMachine(
32
+ runtimes: ReadonlyMap<string, MachineRuntime>,
33
+ context: ExtensionContext | undefined,
34
+ prepareSharing: (
35
+ machine: string,
36
+ runtime: MachineRuntime,
37
+ client: NonNullable<MachineRuntime["client"]>,
38
+ ) => Promise<void>,
39
+ machine?: string,
40
+ ): ConnectedMachine {
41
+ const name = machine?.trim() || LOCAL_MACHINE;
42
+ const runtime = runtimes.get(name);
43
+ if (!runtime) {
44
+ throw new Error(
45
+ `unknown Herdr machine ${JSON.stringify(name)}; use list to see configured machines`,
46
+ );
47
+ }
48
+ if (runtime.status !== "connected" || !runtime.client || !runtime.monitor) {
49
+ throw new Error(
50
+ `Herdr machine ${JSON.stringify(name)} is ${runtime.status}${runtime.reason ? `: ${runtime.reason}` : ""}; open /herdr → Status to reconnect`,
51
+ );
52
+ }
53
+ const remote =
54
+ runtime.client instanceof RemoteHerdrClient ||
55
+ (runtime.client instanceof CoreConnection && runtime.client.remote)
56
+ ? runtime.client
57
+ : undefined;
58
+ const client = runtime.client;
59
+ return {
60
+ prepareSharing: () => prepareSharing(name, runtime, client),
61
+ machine: name,
62
+ local: runtime.local,
63
+ client: runtime.client,
64
+ monitor: runtime.monitor,
65
+ fallbackCwd: runtime.local ? (context?.cwd ?? ".") : "~",
66
+ ...(remote
67
+ ? {
68
+ resolveDirectory: (value: string | undefined, fallback: string) =>
69
+ remote.directory(value, fallback),
70
+ }
71
+ : {}),
72
+ };
73
+ }
74
+
75
+ export async function machineSnapshots(
76
+ runtimes: ReadonlyMap<string, MachineRuntime>,
77
+ machine?: string,
78
+ ): Promise<MachineSnapshot[]> {
79
+ const selected = machine?.trim()
80
+ ? [statusFor(runtimes, machine.trim())]
81
+ : [...runtimes.keys()].map((name) => statusFor(runtimes, name));
82
+ return Promise.all(
83
+ selected.map(async (status) => {
84
+ const runtime = runtimes.get(status.id);
85
+ if (status.status !== "connected" || !runtime?.client || !runtime.monitor)
86
+ return status;
87
+ const client = runtime.client;
88
+ const monitor = runtime.monitor;
89
+ try {
90
+ const snapshot = await getSnapshot(client);
91
+ if (
92
+ runtime.status !== "connected" ||
93
+ runtime.client !== client ||
94
+ runtime.monitor !== monitor ||
95
+ runtimes.get(status.id) !== runtime
96
+ ) {
97
+ return runtimes.has(status.id)
98
+ ? statusFor(runtimes, status.id)
99
+ : status;
100
+ }
101
+ return {
102
+ ...status,
103
+ monitoredPaneIds: new Set(
104
+ monitor.list().map((record) => record.paneId),
105
+ ),
106
+ snapshot,
107
+ };
108
+ } catch (error) {
109
+ if (
110
+ runtime.status !== "connected" ||
111
+ runtime.client !== client ||
112
+ runtime.monitor !== monitor ||
113
+ runtimes.get(status.id) !== runtime
114
+ ) {
115
+ return runtimes.has(status.id)
116
+ ? statusFor(runtimes, status.id)
117
+ : status;
118
+ }
119
+ return { ...status, snapshotError: errorMessage(error) };
120
+ }
121
+ }),
122
+ );
123
+ }
124
+
125
+ export function statusFor(
126
+ runtimes: ReadonlyMap<string, MachineRuntime>,
127
+ name: string,
128
+ ): MachineStatus {
129
+ const runtime = runtimes.get(name);
130
+ if (!runtime)
131
+ throw new Error(`unknown Herdr machine ${JSON.stringify(name)}`);
132
+ return {
133
+ id: name,
134
+ local: runtime.local,
135
+ ...(runtime.config
136
+ ? {
137
+ label: runtime.config.label,
138
+ target: runtime.config.target,
139
+ session: runtime.config.session,
140
+ }
141
+ : {}),
142
+ ...(runtime.coreMachine
143
+ ? {
144
+ label: runtime.coreMachine.name,
145
+ target: runtime.coreMachine.host,
146
+ session: runtime.coreMachine.id,
147
+ }
148
+ : {}),
149
+ status: runtime.status,
150
+ ...(runtime.monitoringIssue
151
+ ? { monitoringIssue: runtime.monitoringIssue }
152
+ : {}),
153
+ ...(runtime.reason ? { reason: runtime.reason } : {}),
154
+ ...(runtime.contextRelayError
155
+ ? { contextRelayError: runtime.contextRelayError }
156
+ : {}),
157
+ ...(runtime.attempting ? { attempting: true } : {}),
158
+ };
159
+ }
@@ -0,0 +1,55 @@
1
+ import type { CoreMachine } from "../core/remote-exec.js";
2
+ import type { HerdrConnection } from "../herdr-client.js";
3
+ import type { SshMachine } from "../machine-catalog.js";
4
+ import type { AgentMonitor } from "../monitor.js";
5
+ import type {
6
+ MachineStatus,
7
+ MonitoringIssue,
8
+ SessionSnapshot,
9
+ } from "../types.js";
10
+
11
+ export interface MachineRuntime {
12
+ attempting?: boolean;
13
+ client?: HerdrConnection;
14
+ config?: SshMachine;
15
+ coreMachine?: CoreMachine;
16
+ contextRelayError?: string;
17
+ local: boolean;
18
+ monitor?: AgentMonitor;
19
+ monitoringIssue?: MonitoringIssue;
20
+ pending: unknown[];
21
+ reason?: string;
22
+ status: MachineStatus["status"];
23
+ }
24
+
25
+ export interface ConnectedMachine {
26
+ prepareSharing: () => Promise<void>;
27
+ client: HerdrConnection;
28
+ fallbackCwd: string;
29
+ local: boolean;
30
+ machine: string;
31
+ monitor: AgentMonitor;
32
+ resolveDirectory?: (
33
+ value: string | undefined,
34
+ fallback: string,
35
+ ) => Promise<string>;
36
+ }
37
+
38
+ export interface MachineSnapshot extends MachineStatus {
39
+ monitoredPaneIds?: ReadonlySet<string>;
40
+ snapshot?: SessionSnapshot;
41
+ snapshotError?: string;
42
+ }
43
+
44
+ export function errorMessage(error: unknown): string {
45
+ const message = error instanceof Error ? error.message : String(error);
46
+ return message.length <= 500 ? message : `${message.slice(0, 499)}…`;
47
+ }
48
+
49
+ function shellQuote(value: string): string {
50
+ return `'${value.replaceAll("'", `'"'"'`)}'`;
51
+ }
52
+
53
+ export function operatorPrefix(config: SshMachine): string {
54
+ return `ssh -T -o BatchMode=yes -- ${shellQuote(config.target)} herdr --session ${shellQuote(config.session)}`;
55
+ }
@@ -0,0 +1,85 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import { CoreConnection } from "../core/backend.js";
6
+ import type { HerdrConnection } from "../herdr-client.js";
7
+ import { LOCAL_MACHINE } from "../machine-catalog.js";
8
+ import { AgentMonitor } from "../monitor.js";
9
+ import { RemoteHerdrClient } from "../remote/client.js";
10
+ import {
11
+ errorMessage,
12
+ type MachineRuntime,
13
+ operatorPrefix,
14
+ } from "./machine.js";
15
+
16
+ interface FleetMonitorEvents {
17
+ isAttached(): boolean;
18
+ context(): ExtensionContext | undefined;
19
+ changed(): void;
20
+ refresh(): void;
21
+ disconnected(reason: string): void;
22
+ }
23
+
24
+ /** Owns the local/remote monitoring adapter and its warning/recovery policy. */
25
+ export function createMachineMonitor(
26
+ machine: string,
27
+ runtime: MachineRuntime,
28
+ client: HerdrConnection,
29
+ pi: ExtensionAPI,
30
+ events: FleetMonitorEvents,
31
+ ): AgentMonitor {
32
+ const selfPaneId = runtime.local
33
+ ? process.env[
34
+ client instanceof CoreConnection ? "HC_TERMINAL_ID" : "HERDR_PANE_ID"
35
+ ]
36
+ : undefined;
37
+ return new AgentMonitor(pi, {
38
+ client,
39
+ machine,
40
+ machineLabel: () =>
41
+ runtime.coreMachine?.name ?? runtime.config?.label ?? LOCAL_MACHINE,
42
+ onChange: () => events.changed(),
43
+ onRefresh: () => events.refresh(),
44
+ operatorPrefix: runtime.coreMachine
45
+ ? "hc"
46
+ : runtime.local
47
+ ? client instanceof CoreConnection
48
+ ? "hc"
49
+ : "herdr"
50
+ : operatorPrefix(runtime.config!),
51
+ onWarning: (issue) => {
52
+ if (!events.isAttached()) return;
53
+ if (!runtime.local && issue.state === "unavailable") {
54
+ events.disconnected(issue.message);
55
+ return;
56
+ }
57
+ runtime.monitoringIssue = {
58
+ ...issue,
59
+ message: errorMessage(issue.message),
60
+ };
61
+ events.refresh();
62
+ events
63
+ .context()
64
+ ?.ui.notify(
65
+ `${machine}: ${issue.message}${runtime.local ? "" : "\nOpen /herdr → Status to reconnect"}`,
66
+ "warning",
67
+ );
68
+ },
69
+ onRecovered: () => {
70
+ if (!events.isAttached() || !runtime.monitoringIssue) return;
71
+ delete runtime.monitoringIssue;
72
+ events.refresh();
73
+ if (runtime.monitor?.list().length)
74
+ events
75
+ .context()
76
+ ?.ui.notify(`Herdr monitoring restored: ${machine}`, "info");
77
+ },
78
+ reconnect: runtime.local,
79
+ ...(client instanceof RemoteHerdrClient ? { reader: client } : {}),
80
+ ...(client instanceof CoreConnection && client.reader
81
+ ? { reader: client.reader }
82
+ : {}),
83
+ ...(selfPaneId ? { selfPaneId } : {}),
84
+ });
85
+ }
@@ -0,0 +1,65 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { LOCAL_MACHINE } from "../machine-catalog.js";
3
+ export const MONITOR_STATE_TYPE = "herdr-agents-monitor-state";
4
+
5
+ export function savedAgents(
6
+ ctx: ExtensionContext,
7
+ localCoreId?: string,
8
+ ): unknown[] {
9
+ let latest: unknown[] = [];
10
+ let version: unknown;
11
+ let savedCoreId: unknown;
12
+ for (const entry of ctx.sessionManager.getBranch()) {
13
+ if (entry.type !== "custom" || entry.customType !== MONITOR_STATE_TYPE)
14
+ continue;
15
+ const data = entry.data as {
16
+ version?: unknown;
17
+ agents?: unknown;
18
+ localCoreId?: unknown;
19
+ };
20
+ if (Array.isArray(data?.agents)) {
21
+ latest = data.agents;
22
+ version = data.version;
23
+ savedCoreId = data.localCoreId;
24
+ }
25
+ }
26
+ if (latest.length > 0 && version !== 2) {
27
+ ctx.ui.notify(
28
+ "Cleared legacy Shepherdr watches; use watch to subscribe explicitly. Remote agents are unchanged.",
29
+ "warning",
30
+ );
31
+ return [];
32
+ }
33
+ if (savedCoreId === localCoreId) return latest;
34
+ const retained = latest.filter(
35
+ (value) =>
36
+ typeof value === "object" &&
37
+ value !== null &&
38
+ "machine" in value &&
39
+ typeof value.machine === "string" &&
40
+ value.machine !== LOCAL_MACHINE,
41
+ );
42
+ if (retained.length !== latest.length)
43
+ ctx.ui.notify(
44
+ "Ignored saved local agent watches from another Herdr session; watch them again in this session.",
45
+ "warning",
46
+ );
47
+ return retained;
48
+ }
49
+
50
+ export function groupSaved(values: unknown[]): Map<string, unknown[]> {
51
+ const grouped = new Map<string, unknown[]>();
52
+ for (const value of values) {
53
+ const machine =
54
+ typeof value === "object" &&
55
+ value !== null &&
56
+ "machine" in value &&
57
+ typeof value.machine === "string"
58
+ ? value.machine
59
+ : LOCAL_MACHINE;
60
+ const records = grouped.get(machine) ?? [];
61
+ records.push(value);
62
+ grouped.set(machine, records);
63
+ }
64
+ return grouped;
65
+ }
@@ -0,0 +1,75 @@
1
+ import type { MachineRuntime } from "./machine.js";
2
+
3
+ /** Explicit reconnect selection and user receipts; never schedules autonomous reconnects. */
4
+ export function connectMachines(
5
+ runtimes: ReadonlyMap<string, MachineRuntime>,
6
+ machine: string | undefined,
7
+ retrySetup: (name: string, runtime: MachineRuntime) => Promise<void>,
8
+ connectMachine: (name: string) => Promise<void>,
9
+ ): string {
10
+ const target = machine?.trim();
11
+ if (target) {
12
+ const runtime = runtimes.get(target);
13
+ if (!runtime)
14
+ throw new Error(`unknown Herdr machine ${JSON.stringify(target)}`);
15
+ if (
16
+ runtime.status === "connected" &&
17
+ (runtime.monitoringIssue || runtime.contextRelayError)
18
+ ) {
19
+ if (runtime.attempting)
20
+ return `Already retrying connection setup on ${target}`;
21
+ void retrySetup(target, runtime);
22
+ return `Retrying connection setup on ${target}`;
23
+ }
24
+ if (runtime.local) {
25
+ return `${target} is the local machine and is already connected`;
26
+ }
27
+ if (runtime.status === "connected") {
28
+ return `${target} is already connected`;
29
+ }
30
+ if (runtime.attempting || runtime.status === "connecting") {
31
+ return `${target} is already connecting`;
32
+ }
33
+ void connectMachine(target);
34
+ return `Connecting to ${target}`;
35
+ }
36
+
37
+ const retries = [...runtimes.entries()].filter(
38
+ ([, runtime]) =>
39
+ runtime.status === "connected" &&
40
+ (runtime.monitoringIssue || runtime.contextRelayError) &&
41
+ !runtime.attempting,
42
+ );
43
+ for (const [name, runtime] of retries) void retrySetup(name, runtime);
44
+ const names = [...runtimes.entries()]
45
+ .filter(
46
+ ([, runtime]) =>
47
+ !runtime.local && runtime.status !== "connected" && !runtime.attempting,
48
+ )
49
+ .map(([name]) => name);
50
+ for (const name of names) {
51
+ void connectMachine(name);
52
+ }
53
+ if (names.length > 0 || retries.length > 0) {
54
+ return [
55
+ retries.length > 0
56
+ ? `Retrying connection setup on ${retries.map(([name]) => name).join(", ")}`
57
+ : "",
58
+ names.length > 0 ? `Connecting to ${names.join(", ")}` : "",
59
+ ]
60
+ .filter(Boolean)
61
+ .join(". ");
62
+ }
63
+ const remotes = [...runtimes.entries()].filter(
64
+ ([, runtime]) => !runtime.local,
65
+ );
66
+ if (remotes.length === 0) {
67
+ return "No remote machines are configured";
68
+ }
69
+ const connecting = remotes
70
+ .filter(([, runtime]) => runtime.attempting)
71
+ .map(([name]) => name);
72
+ return connecting.length > 0
73
+ ? `Already connecting to ${connecting.join(", ")}`
74
+ : "All configured machines are connected";
75
+ }
@@ -0,0 +1,133 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { CoreConnection } from "../core/backend.js";
3
+ import { RemoteHerdrClient } from "../remote/client.js";
4
+ import { errorMessage, type MachineRuntime } from "./machine.js";
5
+
6
+ /** Explicitly requested sharing/monitor readiness; fleet supplies current-selection leases. */
7
+ export class FleetSetup {
8
+ // Concurrent publishers share one start; existing children retain its route.
9
+ private readonly relays = new WeakMap<
10
+ RemoteHerdrClient | CoreConnection,
11
+ Promise<void>
12
+ >();
13
+ private readonly refresh: () => void;
14
+ constructor(refresh: () => void) {
15
+ this.refresh = refresh;
16
+ }
17
+ private contextRelay:
18
+ | ((
19
+ ctx: ExtensionContext,
20
+ request: unknown,
21
+ signal: AbortSignal,
22
+ ) => Promise<unknown>)
23
+ | undefined;
24
+ setContextRelay(
25
+ handler: (
26
+ ctx: ExtensionContext,
27
+ request: unknown,
28
+ signal: AbortSignal,
29
+ ) => Promise<unknown>,
30
+ ): void {
31
+ this.contextRelay = handler;
32
+ }
33
+ prepareContextRelay(
34
+ name: string,
35
+ runtime: MachineRuntime,
36
+ client: RemoteHerdrClient | CoreConnection,
37
+ ctx: ExtensionContext,
38
+ isSelected: () => boolean,
39
+ ): Promise<void> {
40
+ if (!this.contextRelay)
41
+ return Promise.reject(
42
+ new Error("Context sharing is unavailable in this session"),
43
+ );
44
+ const ready = this.relays.get(client);
45
+ if (ready) return ready;
46
+ const starting = this.openContextRelay(
47
+ name,
48
+ runtime,
49
+ client,
50
+ ctx,
51
+ isSelected,
52
+ );
53
+ this.relays.set(client, starting);
54
+ return starting;
55
+ }
56
+ private async openContextRelay(
57
+ name: string,
58
+ runtime: MachineRuntime,
59
+ client: RemoteHerdrClient | CoreConnection,
60
+ ctx: ExtensionContext,
61
+ isSelected: () => boolean,
62
+ ): Promise<void> {
63
+ if (!this.contextRelay)
64
+ throw new Error("Context sharing is unavailable in this session");
65
+ const failed = (error: unknown) => {
66
+ this.relays.delete(client);
67
+ if (!isSelected()) return;
68
+ runtime.contextRelayError = errorMessage(error);
69
+ ctx.ui.notify(
70
+ `Context sharing unavailable on ${name}: ${runtime.contextRelayError}\nOpen /herdr → Status to retry sharing.`,
71
+ "warning",
72
+ );
73
+ this.refresh();
74
+ };
75
+ try {
76
+ const args = [
77
+ ctx.sessionManager.getSessionId(),
78
+ name,
79
+ (request: unknown, signal: AbortSignal) =>
80
+ this.contextRelay!(ctx, request, signal),
81
+ ] as const;
82
+ if (client instanceof CoreConnection)
83
+ await client.startContextRelay(...args, failed);
84
+ else await client.startContextRelay(...args);
85
+ if (!isSelected()) return;
86
+ delete runtime.contextRelayError;
87
+ } catch (error) {
88
+ failed(error);
89
+ throw error;
90
+ }
91
+ }
92
+
93
+ async retrySetup(
94
+ name: string,
95
+ runtime: MachineRuntime,
96
+ ctx: ExtensionContext | undefined,
97
+ isCurrent: () => boolean,
98
+ isRegistered: () => boolean,
99
+ isSelected: () => boolean,
100
+ ): Promise<void> {
101
+ const monitor = runtime.monitor;
102
+ if (!monitor || !ctx || runtime.attempting) return;
103
+ runtime.attempting = true;
104
+ this.refresh();
105
+ try {
106
+ if (
107
+ runtime.contextRelayError &&
108
+ (runtime.client instanceof RemoteHerdrClient ||
109
+ runtime.client instanceof CoreConnection)
110
+ )
111
+ await this.prepareContextRelay(
112
+ name,
113
+ runtime,
114
+ runtime.client,
115
+ ctx,
116
+ isSelected,
117
+ ).catch(() => {});
118
+ if (isCurrent() && isRegistered() && runtime.monitoringIssue)
119
+ await monitor.retryMonitoring();
120
+ } catch (error) {
121
+ if (isCurrent() && isRegistered() && runtime.monitor === monitor) {
122
+ ctx.ui.notify(
123
+ `Monitoring retry failed on ${name}: ${errorMessage(error)}`,
124
+ "warning",
125
+ );
126
+ }
127
+ } finally {
128
+ if (isRegistered() && runtime.monitor === monitor)
129
+ delete runtime.attempting;
130
+ this.refresh();
131
+ }
132
+ }
133
+ }
package/src/herdr.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { CoreConnection } from "./core/backend.js";
1
2
  import { type HerdrConnection, isHerdrErrorCode } from "./herdr-client.js";
2
3
  import type {
3
4
  AgentStatus,
@@ -49,9 +50,14 @@ export async function getPane(
49
50
  export async function getCurrentPane(
50
51
  client: HerdrConnection,
51
52
  ): Promise<PaneInfo> {
52
- const callerPaneId = process.env["HERDR_PANE_ID"];
53
+ const callerPaneId =
54
+ client instanceof CoreConnection
55
+ ? process.env["HC_TERMINAL_ID"]
56
+ : process.env["HERDR_PANE_ID"];
53
57
  if (!callerPaneId)
54
- throw new Error("HERDR_PANE_ID is required to identify the sender");
58
+ throw new Error(
59
+ "Cannot identify this terminal; run Pi inside Herdr and retry",
60
+ );
55
61
  const result = record(
56
62
  await client.request<unknown>("pane.current", {
57
63
  caller_pane_id: callerPaneId,
@@ -64,7 +70,9 @@ export async function getCurrentPane(
64
70
  export async function resolvePiAgent(
65
71
  client: HerdrConnection,
66
72
  target: string,
67
- controllingPaneId = process.env["HERDR_PANE_ID"],
73
+ controllingPaneId = client instanceof CoreConnection
74
+ ? process.env["HC_TERMINAL_ID"]
75
+ : process.env["HERDR_PANE_ID"],
68
76
  ): Promise<PaneInfo> {
69
77
  const agent = await getAgent(client, target).catch((error: unknown) => {
70
78
  if (error instanceof Error && isHerdrErrorCode(error, "agent_not_found")) {
@@ -108,10 +116,22 @@ export function sessionPath(agent: PaneInfo): string | undefined {
108
116
  export function parsePaneInfo(value: unknown, path = "pane"): PaneInfo {
109
117
  const pane = record(value, path);
110
118
  return {
119
+ ...(pane["backend"] === "core" ? { backend: "core" as const } : {}),
111
120
  pane_id: requiredString(pane, "pane_id", path),
112
121
  terminal_id: requiredString(pane, "terminal_id", path),
113
- workspace_id: requiredString(pane, "workspace_id", path),
114
- tab_id: requiredString(pane, "tab_id", path),
122
+ ...(pane["backend"] === "core"
123
+ ? {
124
+ ...(typeof pane["workspace_id"] === "string"
125
+ ? { workspace_id: pane["workspace_id"] }
126
+ : {}),
127
+ ...(typeof pane["tab_id"] === "string"
128
+ ? { tab_id: pane["tab_id"] }
129
+ : {}),
130
+ }
131
+ : {
132
+ workspace_id: requiredString(pane, "workspace_id", path),
133
+ tab_id: requiredString(pane, "tab_id", path),
134
+ }),
115
135
  agent_status: parseAgentStatus(
116
136
  pane["agent_status"],
117
137
  `${path}.agent_status`,
@@ -0,0 +1,48 @@
1
+ import type { PaneInfo } from "./types.js";
2
+
3
+ export const START_PLACEMENTS = [
4
+ "new_workspace",
5
+ "new_tab",
6
+ "pane",
7
+ "terminal",
8
+ ] as const;
9
+
10
+ export interface StartAgentParams {
11
+ cwd?: string;
12
+ label?: string;
13
+ name?: string;
14
+ pane?: string;
15
+ placement?: (typeof START_PLACEMENTS)[number];
16
+ workspace?: string;
17
+ }
18
+
19
+ export interface CreatedLocationCleanup {
20
+ id: string;
21
+ method: "tab.close" | "workspace.close" | "terminal.close";
22
+ }
23
+
24
+ export interface StartedAgent {
25
+ agent: PaneInfo;
26
+ cleanup?: CreatedLocationCleanup;
27
+ id: string;
28
+ }
29
+
30
+ export class RolledBackAgentLaunchError extends Error {
31
+ constructor(cause: unknown) {
32
+ super(cause instanceof Error ? cause.message : String(cause), { cause });
33
+ }
34
+ }
35
+
36
+ export class UnstartedAgentLaunchError extends Error {
37
+ constructor(cause: unknown) {
38
+ super(cause instanceof Error ? cause.message : String(cause), { cause });
39
+ }
40
+ }
41
+
42
+ export function requiredStartField(
43
+ value: string | undefined,
44
+ field: string,
45
+ ): string {
46
+ if (!value?.trim()) throw new Error(`${field} is required for start`);
47
+ return value.trim();
48
+ }