@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,67 @@
1
+ import type { AssistantReader } from "../session-reader.js";
2
+ import type { SessionView } from "../types.js";
3
+ import { object } from "./protocol.js";
4
+ import type { RemoteCoreEndpoint } from "./remote-endpoint.js";
5
+ import { remoteExec } from "./remote-exec.js";
6
+
7
+ export class CoreRemoteReader implements AssistantReader {
8
+ private readonly endpoint: RemoteCoreEndpoint;
9
+ constructor(endpoint: RemoteCoreEndpoint) {
10
+ this.endpoint = endpoint;
11
+ }
12
+ async view(path?: string): Promise<SessionView> {
13
+ if (!path) return {};
14
+ return object(
15
+ await remoteExec(this.endpoint.host, this.endpoint.machine, {
16
+ op: "view",
17
+ path,
18
+ }),
19
+ ) as SessionView;
20
+ }
21
+ async latest(path?: string) {
22
+ return (await this.view(path)).assistant;
23
+ }
24
+ async watch(
25
+ paths: string[],
26
+ onChange: (path: string) => void,
27
+ onError: (error: Error) => void,
28
+ signal: AbortSignal,
29
+ ): Promise<() => void> {
30
+ const lifetime = new AbortController();
31
+ const abort = () => lifetime.abort();
32
+ signal.addEventListener("abort", abort, { once: true });
33
+ if (signal.aborted) abort();
34
+ const close = () => {
35
+ signal.removeEventListener("abort", abort);
36
+ lifetime.abort();
37
+ };
38
+ void (async () => {
39
+ try {
40
+ while (!lifetime.signal.aborted) {
41
+ const changed = await remoteExec(
42
+ this.endpoint.host,
43
+ this.endpoint.machine,
44
+ { op: "watch", paths },
45
+ { signal: lifetime.signal },
46
+ );
47
+ if (lifetime.signal.aborted) break;
48
+ if (
49
+ !Array.isArray(changed) ||
50
+ !changed.every(
51
+ (path) => typeof path === "string" && paths.includes(path),
52
+ )
53
+ )
54
+ throw new Error("Remote session watch returned invalid paths");
55
+ // A bounded long-poll cannot promise continuity between processes.
56
+ for (const path of changed.length ? changed : paths) onChange(path);
57
+ }
58
+ } catch (error) {
59
+ if (!lifetime.signal.aborted)
60
+ onError(error instanceof Error ? error : new Error(String(error)));
61
+ } finally {
62
+ close();
63
+ }
64
+ })();
65
+ return close;
66
+ }
67
+ }
@@ -0,0 +1,191 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { CoreClient } from "./client.js";
3
+ import { object } from "./protocol.js";
4
+ import { type CoreMachine, remoteExec } from "./remote-exec.js";
5
+
6
+ // Fleet closes synchronously and can immediately construct a replacement owner.
7
+ // Retain only live/closing routes, including starts not yet acknowledged by Core.
8
+ const routes = new Map<string, CoreContextRelay>();
9
+ // Match context-relay.mjs: sixfold Notes escaping plus envelope headroom.
10
+ const RELAY_PAYLOAD_BYTES = 6_250_000;
11
+
12
+ /** Owns the reverse route, its bounded polling and all host-side handlers. */
13
+ export class CoreContextRelay {
14
+ private readonly client: CoreClient;
15
+ private readonly machine: CoreMachine;
16
+ private readonly token = randomBytes(32).toString("hex");
17
+ private readonly controller = new AbortController();
18
+ private readonly incoming = new Map<string, AbortController>();
19
+ private pathValue: string | undefined;
20
+ private failed: Error | undefined;
21
+ private closed = false;
22
+ private closing: Promise<void> | undefined;
23
+ private starting: Promise<void> | undefined;
24
+ private route: string | undefined;
25
+ private readonly socket: string;
26
+ private onFailure: ((error: Error) => void) | undefined;
27
+ constructor(socket: string, machine: CoreMachine) {
28
+ this.socket = socket;
29
+ this.client = new CoreClient(socket);
30
+ this.machine = machine;
31
+ }
32
+ start(
33
+ threadId: string,
34
+ handle: (request: unknown, signal: AbortSignal) => Promise<unknown>,
35
+ onFailure: (error: Error) => void,
36
+ ): Promise<void> {
37
+ if (this.starting || this.closed)
38
+ return Promise.reject(
39
+ new Error("Shared context relay is already started or closed"),
40
+ );
41
+ this.route = JSON.stringify([this.socket, this.machine.id, threadId]);
42
+ const previous = routes.get(this.route);
43
+ routes.set(this.route, this);
44
+ this.starting = this.open(threadId, handle, onFailure, previous);
45
+ return this.starting;
46
+ }
47
+ private async open(
48
+ threadId: string,
49
+ handle: (request: unknown, signal: AbortSignal) => Promise<unknown>,
50
+ onFailure: (error: Error) => void,
51
+ previous: CoreContextRelay | undefined,
52
+ ): Promise<void> {
53
+ await previous?.close();
54
+ this.controller.signal.throwIfAborted();
55
+ this.onFailure = onFailure;
56
+ const path = await remoteExec(
57
+ this.client,
58
+ this.machine,
59
+ {
60
+ op: "relay-start",
61
+ threadId,
62
+ routeId: createHash("sha256")
63
+ .update(this.machine.id)
64
+ .digest("hex")
65
+ .slice(0, 32),
66
+ relayToken: this.token,
67
+ },
68
+ // Accepted machine.exec is not cancelled by closing its local socket.
69
+ // Finish this bounded start so close can remove its actual daemon.
70
+ );
71
+ if (typeof path !== "string")
72
+ throw new Error("Invalid shared context relay path");
73
+ this.pathValue = path;
74
+ if (this.closed) return;
75
+ void this.poll(handle).catch((error: unknown) => {
76
+ this.fail(error);
77
+ });
78
+ }
79
+ path(): string {
80
+ if (this.failed)
81
+ throw new Error(
82
+ `Shared context relay disconnected: ${this.failed.message}. Open /herdr → Status to retry sharing`,
83
+ );
84
+ if (!this.pathValue || this.controller.signal.aborted)
85
+ throw new Error(
86
+ "Shared context relay is unavailable; open /herdr → Status to retry sharing",
87
+ );
88
+ return this.pathValue;
89
+ }
90
+ private call(request: object, signal?: AbortSignal) {
91
+ return remoteExec(
92
+ this.client,
93
+ this.machine,
94
+ {
95
+ op: "context",
96
+ path: this.pathValue,
97
+ request: { ...request, relayToken: this.token },
98
+ },
99
+ { timeoutMs: 25_000, ...(signal ? { signal } : {}) },
100
+ );
101
+ }
102
+ private async poll(
103
+ handle: (request: unknown, signal: AbortSignal) => Promise<unknown>,
104
+ ) {
105
+ while (!this.controller.signal.aborted) {
106
+ const batch = object(
107
+ await this.call({ action: "poll" }, this.controller.signal),
108
+ );
109
+ if (!Array.isArray(batch["requests"]) || !Array.isArray(batch["active"]))
110
+ throw new Error("Invalid shared context relay batch");
111
+ const active = batch["active"];
112
+ for (const [id, controller] of this.incoming)
113
+ if (!active.includes(id)) controller.abort();
114
+ for (const value of batch["requests"]) {
115
+ const entry = object(value);
116
+ const id = entry["id"];
117
+ if (typeof id !== "string" || this.incoming.has(id))
118
+ throw new Error("Invalid shared context relay request");
119
+ const controller = new AbortController();
120
+ this.incoming.set(id, controller);
121
+ void this.respond(id, entry["request"], controller, handle)
122
+ .catch((error: unknown) => {
123
+ this.fail(error);
124
+ })
125
+ .finally(() => this.incoming.delete(id));
126
+ }
127
+ }
128
+ if (this.failed) throw this.failed;
129
+ }
130
+ private async respond(
131
+ id: string,
132
+ request: unknown,
133
+ controller: AbortController,
134
+ handle: (request: unknown, signal: AbortSignal) => Promise<unknown>,
135
+ ) {
136
+ let reply: object;
137
+ try {
138
+ controller.signal.throwIfAborted();
139
+ const result = await handle(request, controller.signal);
140
+ reply = { ok: true, result };
141
+ } catch (error) {
142
+ reply = {
143
+ ok: false,
144
+ error: error instanceof Error ? error.message : String(error),
145
+ };
146
+ }
147
+ if (controller.signal.aborted || this.controller.signal.aborted) return;
148
+ if (Buffer.byteLength(JSON.stringify(reply)) > RELAY_PAYLOAD_BYTES)
149
+ reply = {
150
+ ok: false,
151
+ error: "Shared context response is too large; narrow the request",
152
+ };
153
+ await this.call({ action: "reply", id, ...reply }, this.controller.signal);
154
+ }
155
+ private fail(error: unknown): void {
156
+ if (this.closed) return;
157
+ this.failed = error instanceof Error ? error : new Error(String(error));
158
+ void this.close();
159
+ this.onFailure?.(this.failed);
160
+ }
161
+ close(): Promise<void> {
162
+ if (this.closing) return this.closing;
163
+ this.closed = true;
164
+ this.controller.abort();
165
+ for (const controller of this.incoming.values()) controller.abort();
166
+ this.incoming.clear();
167
+ // A separate bounded connection can close the accepted remote daemon.
168
+ // If the machine disappeared, its 30-second lease performs cleanup.
169
+ this.closing = (async () => {
170
+ await this.starting?.catch(() => {});
171
+ if (this.pathValue)
172
+ await remoteExec(
173
+ this.client,
174
+ this.machine,
175
+ { op: "relay-close", path: this.pathValue, relayToken: this.token },
176
+ { timeoutMs: 10_000 },
177
+ );
178
+ })()
179
+ .catch(async () => {
180
+ // A failed close cannot prove removal. Keep replacement starts
181
+ // behind the daemon's 30-second no-poll lease, not a stale owner.
182
+ await new Promise((resolve) => setTimeout(resolve, 31_000));
183
+ })
184
+ .finally(() => {
185
+ this.client.close();
186
+ if (this.route && routes.get(this.route) === this)
187
+ routes.delete(this.route);
188
+ });
189
+ return this.closing;
190
+ }
191
+ }
@@ -0,0 +1,124 @@
1
+ import type { CoreClient } from "./client.js";
2
+ import { focusCoreWindow } from "./focus-window.js";
3
+ import { object } from "./protocol.js";
4
+ import { RemoteCoreEndpoint } from "./remote-endpoint.js";
5
+ import { terminalPane, terminalSnapshot } from "./terminal.js";
6
+
7
+ function unavailableFocus(): Error {
8
+ return Object.assign(
9
+ new Error(
10
+ "Focus is unavailable: the Herdr window cannot confirm which Core it controls. Use hc attach with the terminal address on this Core; messages and supervision remain available.",
11
+ ),
12
+ { code: "SHEPHERDR_DELIVERY_REJECTED" },
13
+ );
14
+ }
15
+
16
+ /** Translate legacy connection operations to Core without owning connection lifetime. */
17
+ export async function dispatchCoreRequest(
18
+ core: CoreClient | RemoteCoreEndpoint,
19
+ method: string,
20
+ params: Record<string, unknown>,
21
+ timeoutMs: number,
22
+ ): Promise<unknown> {
23
+ const options = { timeoutMs };
24
+ switch (method) {
25
+ case "ping":
26
+ return core.request("hello", {}, options);
27
+ case "session.snapshot":
28
+ return {
29
+ snapshot: terminalSnapshot(
30
+ await core.request("terminal.list", {}, options),
31
+ ),
32
+ };
33
+ case "agent.get": {
34
+ const listing = object(await core.request("terminal.list", {}, options));
35
+ const snapshot = terminalSnapshot(listing);
36
+ const terminals = listing["terminals"];
37
+ // Include finished and non-Pi terminals: an address must not redirect.
38
+ const exact =
39
+ Array.isArray(terminals) &&
40
+ terminals.some(
41
+ (terminal) => object(terminal)["address"] === params["target"],
42
+ );
43
+ const matches = exact
44
+ ? []
45
+ : snapshot.agents.filter((agent) => agent.name === params["target"]);
46
+ if (matches.length > 1)
47
+ throw new Error("Agent name is ambiguous; use its terminal address");
48
+ return {
49
+ agent: terminalPane(
50
+ await core.request(
51
+ "terminal.get",
52
+ { terminal: matches[0]?.terminal_id ?? params["target"] },
53
+ options,
54
+ ),
55
+ ),
56
+ };
57
+ }
58
+ case "pane.get":
59
+ case "pane.current":
60
+ return {
61
+ pane: terminalPane(
62
+ await core.request(
63
+ "terminal.get",
64
+ { terminal: params["pane_id"] ?? params["caller_pane_id"] },
65
+ options,
66
+ ),
67
+ ),
68
+ };
69
+ case "agent.read": {
70
+ const result = object(
71
+ await core.request(
72
+ "terminal.read",
73
+ {
74
+ terminal: params["target"],
75
+ lines: params["source"] === "visible" ? 0 : params["lines"],
76
+ },
77
+ options,
78
+ ),
79
+ );
80
+ return {
81
+ read: {
82
+ text: result["text"],
83
+ truncated: result["complete"] === false,
84
+ },
85
+ };
86
+ }
87
+ case "agent.focus":
88
+ if (core instanceof RemoteCoreEndpoint) throw unavailableFocus();
89
+ if (typeof params["target"] !== "string")
90
+ throw new Error("Use the exact local terminal address");
91
+ return focusCoreWindow(core, params["target"]);
92
+ case "workspace.close":
93
+ case "tab.close":
94
+ throw new Error(
95
+ "Window-location cleanup is unavailable through Core; close only the created terminal by its exact address",
96
+ );
97
+ case "terminal.close":
98
+ case "pane.close": {
99
+ const terminal = params["pane_id"] ?? params["id"];
100
+ if (typeof terminal !== "string" || !/^t[0-9a-z]+$/.test(terminal))
101
+ throw new Error(
102
+ "Cleanup requires an exact local Core terminal address",
103
+ );
104
+ const current = object(
105
+ await core.request("terminal.get", { terminal }, options),
106
+ );
107
+ if (current["address"] !== terminal)
108
+ throw new Error(
109
+ "Core terminal identity changed; resolve the target again",
110
+ );
111
+ if (current["state"] === "live")
112
+ await core.request("terminal.kill", { terminal }, options);
113
+ else if (current["state"] !== "finished")
114
+ throw new Error(
115
+ "Core terminal state is unknown; inspect it before cleanup",
116
+ );
117
+ return core.request("terminal.rm", { terminal }, options);
118
+ }
119
+ default:
120
+ throw new Error(
121
+ `Action ${method} is unavailable through Core; use Core terminal operations or the Herdr window commands`,
122
+ );
123
+ }
124
+ }
@@ -0,0 +1,177 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import {
3
+ RolledBackAgentLaunchError,
4
+ type StartAgentParams,
5
+ type StartedAgent,
6
+ UnstartedAgentLaunchError,
7
+ } from "../launch-contract.js";
8
+ import type { CoreConnection } from "./backend.js";
9
+ import { piExecutable } from "./pi-executable.mjs";
10
+ import { object } from "./protocol.js";
11
+ import { RemoteCoreEndpoint } from "./remote-endpoint.js";
12
+ import { remoteExec } from "./remote-exec.js";
13
+ import { terminalPane, terminalSnapshot } from "./terminal.js";
14
+
15
+ export async function startCoreAgent(
16
+ client: CoreConnection,
17
+ params: StartAgentParams,
18
+ cwd: string,
19
+ _label: string,
20
+ args: string[],
21
+ ): Promise<StartedAgent> {
22
+ if (params.placement === "pane")
23
+ throw new Error(
24
+ "Core cannot launch a program inside an existing terminal without terminal input. Use terminal placement for a background worker or new_tab/new_workspace for a Herdr window location.",
25
+ );
26
+ const labels: Record<string, string> = {};
27
+ if (params.placement === "new_tab") {
28
+ const snapshot = terminalSnapshot(
29
+ await client.core.request("terminal.list"),
30
+ );
31
+ if (
32
+ !params.workspace ||
33
+ !snapshot.workspaces.some(
34
+ (space) => space.workspace_id === params.workspace,
35
+ )
36
+ )
37
+ throw new UnstartedAgentLaunchError(
38
+ "new_tab requires a space ID advertised by a live terminal on this Core; use list to find it, or choose new_workspace/terminal placement",
39
+ );
40
+ labels["herdr.space"] = params.workspace;
41
+ labels["herdr.tab"] = `tb${randomUUID().replaceAll("-", "")}`;
42
+ } else if (params.placement === "new_workspace") {
43
+ labels["herdr.space"] = `sp${randomUUID().replaceAll("-", "")}`;
44
+ labels["herdr.tab"] = `tb${randomUUID().replaceAll("-", "")}`;
45
+ } else if (params.placement !== "terminal") {
46
+ throw new UnstartedAgentLaunchError(
47
+ "Choose terminal, new_tab or new_workspace placement for Core",
48
+ );
49
+ }
50
+ const executable =
51
+ client.core instanceof RemoteCoreEndpoint
52
+ ? await remoteExec(client.core.host, client.core.machine, {
53
+ op: "pi-executable",
54
+ cwd,
55
+ })
56
+ : await piExecutable(cwd);
57
+ if (typeof executable !== "string" || !executable)
58
+ throw new Error("Could not resolve Pi on the target machine");
59
+ const result = object(
60
+ await client.core.request("terminal.run", {
61
+ argv: [executable, ...args],
62
+ name: params.name,
63
+ cwd,
64
+ parent: process.env["HC_TERMINAL_ID"],
65
+ outlive_parent: true,
66
+ no_notify: true,
67
+ // Labels request adoption only by a window connected to this Core.
68
+ labels,
69
+ env: process.env,
70
+ }),
71
+ );
72
+ const terminal = result["address"];
73
+ if (typeof terminal !== "string" || !/^t[0-9a-z]+$/.test(terminal))
74
+ throw new Error(
75
+ "Core launch returned no local terminal address; inspect Core terminals before retrying",
76
+ );
77
+ const cleanup = { method: "terminal.close" as const, id: terminal };
78
+ try {
79
+ await client.core.request("terminal.label", {
80
+ terminal,
81
+ labels: { "pi.shepherdr.name": params.name },
82
+ });
83
+ const agent = await waitReady(client, terminal);
84
+ return { agent, id: terminal, cleanup };
85
+ } catch (error) {
86
+ try {
87
+ await client.request(cleanup.method, { id: cleanup.id });
88
+ } catch (cleanupError) {
89
+ throw new Error(
90
+ `${String(error)}; cleanup failed: ${String(cleanupError)}`,
91
+ { cause: error },
92
+ );
93
+ }
94
+ throw new RolledBackAgentLaunchError(error);
95
+ }
96
+ }
97
+
98
+ async function waitReady(client: CoreConnection, terminal: string) {
99
+ const abort = new AbortController();
100
+ let chain = Promise.resolve();
101
+ let resolve!: (agent: ReturnType<typeof terminalPane>) => void;
102
+ let reject!: (error: unknown) => void;
103
+ const ready = new Promise<ReturnType<typeof terminalPane>>((yes, no) => {
104
+ resolve = yes;
105
+ reject = no;
106
+ });
107
+ const inspect = (value: unknown) => {
108
+ const record = object(value);
109
+ if (record["state"] !== "live")
110
+ throw new Error(
111
+ `Core terminal ${terminal} exited before publishing its Pi session; inspect its output`,
112
+ );
113
+ const agent = terminalPane(record);
114
+ if (agent.agent_status === "blocked")
115
+ throw new Error(
116
+ `Core terminal ${terminal} is blocked during startup; inspect its output`,
117
+ );
118
+ if (agent.interactive_ready) resolve(agent);
119
+ };
120
+ const timer = setTimeout(
121
+ () =>
122
+ reject(
123
+ new Error(
124
+ `Timed out waiting for ${terminal} to publish its Pi session; inspect its output`,
125
+ ),
126
+ ),
127
+ 30_000,
128
+ );
129
+ try {
130
+ const subscribed = client.core
131
+ .subscribe(
132
+ { terminal },
133
+ (message) => {
134
+ if (message.method === "snapshot" || message.method === "missed") {
135
+ // Remote mirrors may not contain an acknowledged launch yet.
136
+ if (message.terminals.length === 0)
137
+ chain = chain
138
+ .then(async () =>
139
+ inspect(
140
+ await client.core.request(
141
+ "terminal.get",
142
+ { terminal },
143
+ { signal: abort.signal },
144
+ ),
145
+ ),
146
+ )
147
+ .catch(reject);
148
+ for (const record of message.terminals) inspect(record);
149
+ } else if (message.method === "event") {
150
+ chain = chain
151
+ .then(async () =>
152
+ inspect(
153
+ await client.core.request(
154
+ "terminal.get",
155
+ { terminal },
156
+ { signal: abort.signal },
157
+ ),
158
+ ),
159
+ )
160
+ .catch(reject);
161
+ }
162
+ },
163
+ { signal: abort.signal },
164
+ )
165
+ .then((sub) => {
166
+ void sub.closed.then((error) => {
167
+ if (error) reject(error);
168
+ });
169
+ return sub;
170
+ });
171
+ const [, agent] = await Promise.all([subscribed, ready]);
172
+ return agent;
173
+ } finally {
174
+ clearTimeout(timer);
175
+ abort.abort();
176
+ }
177
+ }
@@ -0,0 +1,68 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+
3
+ /** Core observes only status reports written by the program in its terminal. */
4
+ export function registerCoreStatus(pi: ExtensionAPI): void {
5
+ if (
6
+ !process.env["HC_TERMINAL_ID"] ||
7
+ !process.env["HC_TERMINAL_SOCKET"] ||
8
+ !process.stdout.isTTY
9
+ )
10
+ return;
11
+ let active = false;
12
+ let running = false;
13
+ let failed = false;
14
+ let blocked = 0;
15
+ let last = "";
16
+ const publish = (state: string) => {
17
+ if (!active || state === last) return;
18
+ last = state;
19
+ process.stdout.write(`\x1b]7501;state=${state}:app=pi\x1b\\`);
20
+ };
21
+ const current = () =>
22
+ publish(blocked ? "blocked" : running ? "working" : "idle");
23
+ pi.events.on("herdr:blocked", (value: unknown) => {
24
+ if (
25
+ !active ||
26
+ typeof value !== "object" ||
27
+ value === null ||
28
+ !("active" in value) ||
29
+ typeof value.active !== "boolean"
30
+ )
31
+ return;
32
+ blocked = value.active ? blocked + 1 : Math.max(0, blocked - 1);
33
+ current();
34
+ });
35
+ pi.on("session_start", (_event, ctx) => {
36
+ active = ctx.mode === "tui";
37
+ blocked = 0;
38
+ running = !ctx.isIdle();
39
+ failed = false;
40
+ last = "";
41
+ current();
42
+ });
43
+ pi.on("before_agent_start", () => {
44
+ running = true;
45
+ failed = false;
46
+ current();
47
+ });
48
+ pi.on("agent_start", () => {
49
+ running = true;
50
+ current();
51
+ });
52
+ pi.on("agent_end", (event) => {
53
+ const reply = event.messages.findLast(
54
+ (message) => message.role === "assistant",
55
+ );
56
+ failed = reply?.role === "assistant" && reply.stopReason === "error";
57
+ });
58
+ pi.on("agent_settled", (event) => {
59
+ running = false;
60
+ publish(
61
+ blocked ? "blocked" : event.aborted ? "idle" : failed ? "error" : "done",
62
+ );
63
+ });
64
+ pi.on("session_shutdown", () => {
65
+ publish("clear");
66
+ active = false;
67
+ });
68
+ }