@howaboua/pi-shepherdr 0.2.28-core.12.1.gda85fa2e8a0f → 1.0.0

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 (55) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +34 -5
  3. package/biome.json +1 -1
  4. package/index.ts +5 -2
  5. package/package.json +19 -14
  6. package/src/agents-contract.ts +80 -61
  7. package/src/agents-discovery.ts +14 -10
  8. package/src/agents-focus.ts +7 -0
  9. package/src/agents-reply.ts +3 -12
  10. package/src/agents-spawn.ts +26 -2
  11. package/src/agents-tool.ts +57 -21
  12. package/src/agents-work.ts +9 -4
  13. package/src/ancestry-record.ts +116 -0
  14. package/src/attachment-notes.ts +3 -2
  15. package/src/attachment-protocol.ts +124 -68
  16. package/src/attachment-target.ts +8 -7
  17. package/src/attachment.ts +3 -3
  18. package/src/board/records.ts +50 -36
  19. package/src/close-idle.ts +2 -2
  20. package/src/controller.ts +5 -4
  21. package/src/core/backend.ts +26 -3
  22. package/src/core/helper-bootstrap.mjs +1 -1
  23. package/src/core/helper-core.mjs +4 -3
  24. package/src/core/helper-lifetime.mjs +199 -0
  25. package/src/core/remote-endpoint.ts +10 -3
  26. package/src/core/remote-helper.ts +3 -0
  27. package/src/core/remote-service.mjs +9 -0
  28. package/src/core/remote-transport.ts +11 -1
  29. package/src/core/spawn.ts +1 -1
  30. package/src/core/terminal-peer.mjs +26 -5
  31. package/src/core/terminal.ts +2 -1
  32. package/src/fleet/connection.ts +4 -0
  33. package/src/fleet/index.ts +24 -3
  34. package/src/launch-contract.ts +1 -0
  35. package/src/launch.ts +40 -3
  36. package/src/messages/attribution.ts +14 -5
  37. package/src/messages/focus.ts +4 -3
  38. package/src/messages/peer-sharing.ts +34 -20
  39. package/src/monitor-events.ts +10 -10
  40. package/src/monitor-extension-messages.ts +1 -0
  41. package/src/monitor.ts +5 -5
  42. package/src/profiles.ts +1 -8
  43. package/src/remote/shepherdr-session.mjs +43 -0
  44. package/src/settlement/delivery.ts +32 -14
  45. package/src/settlement/index.ts +3 -0
  46. package/src/shared-context.ts +4 -100
  47. package/src/spawn-ancestry.ts +103 -0
  48. package/src/spawn-ownership.ts +93 -5
  49. package/src/types.ts +1 -0
  50. package/src/worker-ownership.ts +41 -32
  51. package/src/worker-resume.ts +231 -0
  52. package/src/worker-role.ts +9 -35
  53. package/src/worker-service.ts +95 -59
  54. package/worker-api.ts +38 -0
  55. package/src/profile-prompt.ts +0 -32
@@ -3,55 +3,69 @@ import type {
3
3
  ExtensionAPI,
4
4
  ExtensionContext,
5
5
  } from "@earendil-works/pi-coding-agent";
6
- import { type Static, Type } from "typebox";
7
- import { Check } from "typebox/value";
6
+ import {
7
+ bool,
8
+ compile,
9
+ lit,
10
+ nul,
11
+ obj,
12
+ opt,
13
+ type Static,
14
+ str,
15
+ union,
16
+ } from "@earendil-works/pi-schema";
8
17
 
9
18
  // These are persisted transport records, not a Board engine or activation owner.
10
-
11
- const nativeId = Type.String({ pattern: "^[a-zA-Z0-9_.-]+$" });
12
- export const BindingSchema = Type.Object(
19
+ const nativeId = str({ pattern: "^[a-zA-Z0-9_.-]+$" });
20
+ export const BindingSchema = obj({
21
+ protocol: {
22
+ ...lit(1),
23
+ type: "number",
24
+ },
25
+ boardId: nativeId,
26
+ rootSessionId: nativeId,
27
+ sessionId: nativeId,
28
+ agentName: str({
29
+ pattern: "^/[a-zA-Z0-9_.-]+(?:/[a-zA-Z0-9_-]+)*$",
30
+ }),
31
+ legacyAgentName: opt(str({ pattern: "^/root(?:/[a-zA-Z0-9_-]+)*$" })),
32
+ parentSessionId: opt(nativeId),
33
+ ownerFolder: str({ minLength: 1 }),
34
+ databasePath: str({ minLength: 1 }),
35
+ enabled: bool(),
36
+ upstream: opt(str({ minLength: 1 })),
37
+ });
38
+ const checkBindingSchema = compile(BindingSchema).check;
39
+ export type BoardBinding = Static<typeof BindingSchema>;
40
+ const ChildSchema = obj(
13
41
  {
14
- protocol: Type.Literal(1),
15
- boardId: nativeId,
16
- rootSessionId: nativeId,
17
- sessionId: nativeId,
18
- agentName: Type.String({
19
- pattern: "^/[a-zA-Z0-9_.-]+(?:/[a-zA-Z0-9_-]+)*$",
20
- }),
21
- legacyAgentName: Type.Optional(
22
- Type.String({ pattern: "^/root(?:/[a-zA-Z0-9_-]+)*$" }),
23
- ),
24
- parentSessionId: Type.Optional(nativeId),
25
- ownerFolder: Type.String({ minLength: 1 }),
26
- databasePath: Type.String({ minLength: 1 }),
27
- enabled: Type.Boolean(),
28
- upstream: Type.Optional(Type.String({ minLength: 1 })),
42
+ parentSessionId: nativeId,
43
+ binding: BindingSchema,
44
+ machine: str(),
45
+ sessionFile: str({ minLength: 1 }),
29
46
  },
30
- { additionalProperties: false },
47
+ { open: true },
31
48
  );
32
- export type BoardBinding = Static<typeof BindingSchema>;
33
- const ChildSchema = Type.Object({
34
- parentSessionId: nativeId,
35
- binding: BindingSchema,
36
- machine: Type.String(),
37
- sessionFile: Type.String({ minLength: 1 }),
38
- });
49
+ const checkChildSchema = compile(ChildSchema).check;
39
50
  export type BoardChild = Static<typeof ChildSchema>;
40
51
  const BINDING = "shepherdr-board-binding";
41
52
  const MEMBER = "shepherdr-board-member";
42
53
  const CHILD = "shepherdr-board-child";
43
54
  const SETTING = "shepherdr-board-setting";
44
55
  const REMOVED = "shepherdr-board-removed";
45
- const SettingSchema = Type.Object({
46
- sessionId: nativeId,
47
- enabled: Type.Union([Type.Boolean(), Type.Null()]),
48
- });
49
-
56
+ const SettingSchema = obj(
57
+ {
58
+ sessionId: nativeId,
59
+ enabled: union([bool(), nul()]),
60
+ },
61
+ { open: true },
62
+ );
63
+ const checkSettingSchema = compile(SettingSchema).check;
50
64
  function sessionBoardSetting(ctx: ExtensionContext): boolean | undefined {
51
65
  let enabled: boolean | undefined;
52
66
  for (const entry of ctx.sessionManager.getEntries()) {
53
67
  if (entry.type !== "custom" || entry.customType !== SETTING) continue;
54
- if (!Check(SettingSchema, entry.data))
68
+ if (!checkSettingSchema(entry.data))
55
69
  throw new Error("Invalid saved board setting");
56
70
  const value = entry.data as Static<typeof SettingSchema>;
57
71
  if (value.sessionId === ctx.sessionManager.getSessionId())
@@ -61,7 +75,7 @@ function sessionBoardSetting(ctx: ExtensionContext): boolean | undefined {
61
75
  }
62
76
 
63
77
  export function parseBinding(value: unknown): BoardBinding {
64
- if (!Check(BindingSchema, value))
78
+ if (!checkBindingSchema(value))
65
79
  throw new Error("Invalid Shepherdr board binding");
66
80
  const saved = value as BoardBinding;
67
81
  assertSessionIdentity(saved.sessionId, saved.rootSessionId);
@@ -151,7 +165,7 @@ export function children(ctx: ExtensionContext): BoardChild[] {
151
165
  continue;
152
166
  }
153
167
  if (entry.type !== "custom" || entry.customType !== CHILD) continue;
154
- if (!Check(ChildSchema, entry.data))
168
+ if (!checkChildSchema(entry.data))
155
169
  throw new Error("Invalid saved board child route");
156
170
  const value = entry.data as BoardChild;
157
171
  if (
package/src/close-idle.ts CHANGED
@@ -14,14 +14,14 @@ export async function closeIdleChildren(
14
14
  for (const child of spawnedChildren(ctx)) {
15
15
  if (!current()) break;
16
16
  try {
17
+ const runtime = fleet.connected(child.machine);
17
18
  const status = fleet
18
19
  .statuses()
19
- .find((value) => value.id === child.machine);
20
+ .find((value) => value.id === runtime.machine);
20
21
  if (!status || status.status !== "connected" || status.monitoringIssue) {
21
22
  skipped += 1;
22
23
  continue;
23
24
  }
24
- const runtime = fleet.connected(child.machine);
25
25
  const identity = await runtime.client.machineIdentity();
26
26
  const snapshot = await getSnapshot(runtime.client);
27
27
  const panel = snapshot.agents.find(
package/src/controller.ts CHANGED
@@ -10,6 +10,7 @@ import {
10
10
  registerContextBriefing,
11
11
  } from "./context-briefing.js";
12
12
  import { controlPanelStatus, openControlPanel } from "./control-panel/index.js";
13
+ import { CORE_REQUIRED } from "./core/backend.js";
13
14
  import { sendPolicyMessage } from "./delivery.js";
14
15
  import type { AgentFleet } from "./fleet/index.js";
15
16
  import {
@@ -63,8 +64,7 @@ export function registerAgentController(
63
64
  if (!fleet.isActive()) {
64
65
  await activateController(fleet, ctx);
65
66
  signal.throwIfAborted();
66
- if (!fleet.isActive())
67
- throw new Error("Fleet inactive. Pi must run inside Herdr.");
67
+ if (!fleet.isActive()) throw fleet.inactiveError();
68
68
  }
69
69
  await fleet.reload();
70
70
  signal.throwIfAborted();
@@ -215,14 +215,15 @@ async function activateController(
215
215
  ctx: ExtensionContext,
216
216
  ): Promise<boolean> {
217
217
  if (!process.env["HC_TERMINAL_ID"] || !process.env["HC_TERMINAL_SOCKET"]) {
218
- ctx.ui.notify("Shepherdr requires Pi to run inside Herdr", "error");
218
+ fleet.deactivate();
219
+ ctx.ui.notify(CORE_REQUIRED, "error");
219
220
  return false;
220
221
  }
221
222
  try {
222
223
  await fleet.activate(ctx);
223
224
  return true;
224
225
  } catch (error) {
225
- fleet.deactivate();
226
+ fleet.deactivate(error instanceof Error ? error : new Error(String(error)));
226
227
  ctx.ui.notify(
227
228
  `Shepherdr could not start: ${error instanceof Error ? error.message : String(error)}`,
228
229
  "error",
@@ -12,6 +12,7 @@ import {
12
12
  sendPeerFocus,
13
13
  sendPeerMessage,
14
14
  } from "../remote/shepherdr-peer.mjs";
15
+ import { readSessionHeader } from "../remote/shepherdr-session.mjs";
15
16
  import type {
16
17
  ExtensionReply,
17
18
  FocusRequest,
@@ -28,6 +29,9 @@ import { RemoteCoreEndpoint } from "./remote-endpoint.js";
28
29
  import { CoreRemoteReader } from "./remote-reader.js";
29
30
  import { terminalPeer } from "./terminal-peer.mjs";
30
31
 
32
+ export const CORE_REQUIRED =
33
+ "Agent operations require Herdr Core 0.1.18+. Legacy Herdr TUI is unsupported. Start Pi in a fresh Core terminal. Help, current-session command discovery and /herdr settings remain available. Last legacy Shepherdr: 0.2.27, unmaintained source for forks: https://github.com/IgorWarzocha/howaboua-pi-stuff/tree/5ede06bdc32da2b513f0709966af1f32908f243c/packages/pi-shepherdr";
34
+
31
35
  export class CoreConnection {
32
36
  private readonly peer = terminalPeer((method, params) =>
33
37
  this.core.request(method, params),
@@ -42,14 +46,14 @@ export class CoreConnection {
42
46
  constructor(
43
47
  socketPath = process.env["HC_TERMINAL_SOCKET"],
44
48
  remote?: CoreMachine,
49
+ onNotice?: (message: string) => void,
45
50
  ) {
46
- if (!socketPath)
47
- throw new Error("Run Pi inside a Core terminal to connect Shepherdr");
51
+ if (!socketPath) throw new Error(CORE_REQUIRED);
48
52
  this.remote = remote;
49
53
  this.socketPath = socketPath;
50
54
  this.admission = new CoreAdmission(socketPath, remote?.id);
51
55
  this.core = remote
52
- ? new RemoteCoreEndpoint(socketPath, remote, this.admission)
56
+ ? new RemoteCoreEndpoint(socketPath, remote, this.admission, onNotice)
53
57
  : new CoreClient(socketPath);
54
58
  this.reader =
55
59
  this.core instanceof RemoteCoreEndpoint
@@ -115,6 +119,25 @@ export class CoreConnection {
115
119
  signal,
116
120
  );
117
121
  }
122
+ async sessionHeader(
123
+ path: string,
124
+ signal?: AbortSignal,
125
+ ): Promise<{ id: string; cwd: string }> {
126
+ signal?.throwIfAborted();
127
+ if (!(this.core instanceof RemoteCoreEndpoint))
128
+ return readSessionHeader(path);
129
+ const header = object(
130
+ await this.core.call(
131
+ { op: "session_header", path },
132
+ { ...(signal ? { signal } : {}) },
133
+ ),
134
+ );
135
+ if (typeof header["id"] !== "string" || typeof header["cwd"] !== "string")
136
+ throw new Error(
137
+ "Saved worker session identity is unavailable; open its saved session manually",
138
+ );
139
+ return { id: header["id"], cwd: header["cwd"] };
140
+ }
118
141
  async findSavedSessions(
119
142
  threadId: string,
120
143
  signal?: AbortSignal,
@@ -13,7 +13,7 @@ async function stop(error) {
13
13
  } catch {}
14
14
  }
15
15
  // Cleanup must finish before a replacement publishes the same context path.
16
- const deadline = setTimeout(() => process.exit(1), 2000);
16
+ const deadline = setTimeout(() => process.exit(1), 8000);
17
17
  deadline.unref();
18
18
  try {
19
19
  await runtime?.close();
@@ -4,7 +4,7 @@ import { createConnection } from "node:net";
4
4
  export function localCore(socketPath) {
5
5
  const connections = new Set();
6
6
  let closed = false;
7
- function open(method, params, receive, fail) {
7
+ function open(method, params, receive, fail, timeoutMs = 45_000) {
8
8
  if (closed) throw new Error("Core connection closed");
9
9
  const socket = createConnection(socketPath);
10
10
  connections.add(socket);
@@ -24,7 +24,7 @@ export function localCore(socketPath) {
24
24
  };
25
25
  const timer = setTimeout(
26
26
  () => failed(new Error("Core connection timed out")),
27
- 45_000,
27
+ timeoutMs,
28
28
  );
29
29
  socket.setEncoding("utf8");
30
30
  socket.on("connect", () =>
@@ -63,7 +63,7 @@ export function localCore(socketPath) {
63
63
  return finish;
64
64
  }
65
65
  return {
66
- request(method, params = {}) {
66
+ request(method, params = {}, timeoutMs) {
67
67
  return new Promise((resolve, reject) =>
68
68
  open(
69
69
  method,
@@ -75,6 +75,7 @@ export function localCore(socketPath) {
75
75
  resolve(value.result);
76
76
  },
77
77
  reject,
78
+ timeoutMs,
78
79
  ),
79
80
  );
80
81
  },
@@ -0,0 +1,199 @@
1
+ const TERMINAL = /^t[1-9][0-9bcdfghjkmnpqrstvwxyz]*$/;
2
+ const ENDED = new Set([
3
+ "holder_lost",
4
+ "stopped_by_restart",
5
+ "server_stop",
6
+ "host_shutdown",
7
+ "signaled",
8
+ ]);
9
+
10
+ function program(record) {
11
+ return Number.isSafeInteger(record.pid) && record.pid > 0
12
+ ? record.pid
13
+ : undefined;
14
+ }
15
+
16
+ /** Core's native parent links and lifetime flags are the only ownership source. */
17
+ export async function superviseParents(core, warn) {
18
+ const children = new Map();
19
+ const parents = new Map();
20
+ let active = true;
21
+ let chain = Promise.resolve();
22
+ let streamWarning;
23
+ function enqueue(work) {
24
+ chain = chain
25
+ .then(() => active && work())
26
+ .catch((error) => {
27
+ if (active)
28
+ warn(
29
+ `Automatic child shutdown could not be checked: ${error.message}. Existing agents remain available. Reconnect Core or close the children explicitly.`,
30
+ );
31
+ });
32
+ }
33
+ function forget(address) {
34
+ const child = children.get(address);
35
+ if (!child) return;
36
+ children.delete(address);
37
+ const parent = parents.get(child.record.parent);
38
+ parent?.children.delete(address);
39
+ if (parent?.children.size === 0) parents.delete(child.record.parent);
40
+ }
41
+ async function track(record, verify = true) {
42
+ if (!record || !TERMINAL.test(record.address)) return;
43
+ const previous = children.get(record.address);
44
+ if (
45
+ record.state !== "live" ||
46
+ record.die_with_parent !== true ||
47
+ typeof record.parent !== "string" ||
48
+ !record.parent.includes("/") ||
49
+ !TERMINAL.test(record.parent.split("/").at(-1)) ||
50
+ !program(record)
51
+ ) {
52
+ forget(record.address);
53
+ return;
54
+ }
55
+ if (
56
+ previous?.record.parent === record.parent &&
57
+ program(previous.record) === program(record)
58
+ ) {
59
+ previous.record = record;
60
+ return;
61
+ }
62
+ forget(record.address);
63
+ let parent = parents.get(record.parent);
64
+ if (!parent) {
65
+ parent = {
66
+ reference: record.parent,
67
+ children: new Map(),
68
+ warning: undefined,
69
+ };
70
+ parents.set(record.parent, parent);
71
+ }
72
+ const child = { record, parentProgram: undefined };
73
+ children.set(record.address, child);
74
+ parent.children.set(record.address, child);
75
+ // Read the actual parent, never infer its death from an aggregate omission.
76
+ if (verify) await check(parent);
77
+ }
78
+ async function check(parent) {
79
+ try {
80
+ const record = await core.request(
81
+ "terminal.get",
82
+ {
83
+ terminal: parent.reference,
84
+ },
85
+ 2000,
86
+ );
87
+ if (!active) return;
88
+ if (
89
+ !record ||
90
+ typeof record.address !== "string" ||
91
+ record.address.split("/").at(-1) !== parent.reference.split("/").at(-1)
92
+ )
93
+ throw new Error("Parent terminal identity was not confirmed");
94
+ const current = program(record);
95
+ const ended =
96
+ record.state === "finished" ||
97
+ (record.state === "live" &&
98
+ record.pid === null &&
99
+ ENDED.has(record.reason));
100
+ if (!ended && (record.state !== "live" || !current))
101
+ throw new Error("Parent program state is unknown");
102
+ for (const child of [...parent.children.values()]) {
103
+ if (!active) return;
104
+ if (
105
+ !ended &&
106
+ (!child.parentProgram || child.parentProgram === current)
107
+ ) {
108
+ child.parentProgram = current;
109
+ continue;
110
+ }
111
+ const target = child.record.address;
112
+ const live = await core.request(
113
+ "terminal.get",
114
+ { terminal: target },
115
+ 2000,
116
+ );
117
+ if (!active) return;
118
+ if (
119
+ live.address === target &&
120
+ live.state === "live" &&
121
+ live.parent === parent.reference &&
122
+ live.die_with_parent === true &&
123
+ program(live) === program(child.record)
124
+ )
125
+ await core.request("terminal.kill", { terminal: target }, 2000);
126
+ forget(target);
127
+ }
128
+ parent.warning = undefined;
129
+ } catch (error) {
130
+ if (!active) return;
131
+ const message = `Automatic shutdown for children of ${parent.reference} is unavailable: ${error.message}. Existing agents remain available. Reconnect the parent Core or close these children explicitly.`;
132
+ if (parent.warning !== message) warn(message);
133
+ parent.warning = message;
134
+ }
135
+ }
136
+ async function checkAll() {
137
+ await Promise.all([...parents.values()].map(check));
138
+ }
139
+ const subscription = core.subscribe(
140
+ {},
141
+ (message) => {
142
+ enqueue(async () => {
143
+ if (message.method === "snapshot" || message.method === "missed") {
144
+ const local = message.terminals.filter((record) =>
145
+ TERMINAL.test(record.address),
146
+ );
147
+ const addresses = new Set(local.map((record) => record.address));
148
+ for (const address of children.keys())
149
+ if (!addresses.has(address)) forget(address);
150
+ for (const record of local) await track(record, false);
151
+ await checkAll();
152
+ } else if (message.method === "event") {
153
+ const event = message.event;
154
+ if (TERMINAL.test(event.terminal)) {
155
+ if (["finished", "lost", "removed"].includes(event.type))
156
+ forget(event.terminal);
157
+ else if (["created", "restarted"].includes(event.type))
158
+ await track(event.data);
159
+ }
160
+ // Remote removal can mean a dropped mirror, not a dead parent.
161
+ // Every trigger is verified through a fresh, directly routed read.
162
+ if (["finished", "lost", "restarted", "removed"].includes(event.type))
163
+ await checkAll();
164
+ }
165
+ });
166
+ },
167
+ (error) => {
168
+ streamWarning = error;
169
+ if (active)
170
+ warn(
171
+ `Automatic child shutdown is unavailable: ${error.message}. Existing agents remain available. Reconnect Core or close the children explicitly.`,
172
+ );
173
+ },
174
+ );
175
+ try {
176
+ await subscription.ready;
177
+ if (streamWarning) throw streamWarning;
178
+ } catch (error) {
179
+ active = false;
180
+ subscription.close();
181
+ throw error;
182
+ }
183
+ return {
184
+ async close() {
185
+ await chain;
186
+ // Pi releases connections during shutdown, before its program exits.
187
+ // Keep observing briefly, then verify once. A lost wire is not death.
188
+ if (parents.size) {
189
+ await new Promise((resolve) => setTimeout(resolve, 1500));
190
+ enqueue(checkAll);
191
+ await chain;
192
+ }
193
+ active = false;
194
+ subscription.close();
195
+ children.clear();
196
+ parents.clear();
197
+ },
198
+ };
199
+ }
@@ -17,14 +17,17 @@ export class RemoteCoreEndpoint {
17
17
  private readonly socketPath: string;
18
18
  readonly machine: CoreMachine;
19
19
  private readonly admission: CoreAdmission;
20
+ private readonly onNotice: (message: string) => void;
20
21
  constructor(
21
22
  socketPath: string,
22
23
  machine: CoreMachine,
23
24
  admission = new CoreAdmission(socketPath, machine.id),
25
+ onNotice: (message: string) => void = () => {},
24
26
  ) {
25
27
  this.socketPath = socketPath;
26
28
  this.machine = machine;
27
29
  this.admission = admission;
30
+ this.onNotice = onNotice;
28
31
  this.host = new CoreClient(socketPath);
29
32
  }
30
33
  get bridge(): CoreRemoteTransport {
@@ -32,6 +35,7 @@ export class RemoteCoreEndpoint {
32
35
  return (this.transport ??= new CoreRemoteTransport(
33
36
  this.socketPath,
34
37
  this.machine,
38
+ this.onNotice,
35
39
  ));
36
40
  }
37
41
  close(): void {
@@ -42,9 +46,12 @@ export class RemoteCoreEndpoint {
42
46
  }
43
47
  call(input: CoreObject, options: CoreRequestOptions = {}): Promise<unknown> {
44
48
  if (
45
- ["saved_session", "find_saved_sessions", "view"].includes(
46
- String(input["op"]),
47
- )
49
+ [
50
+ "saved_session",
51
+ "find_saved_sessions",
52
+ "view",
53
+ "session_header",
54
+ ].includes(String(input["op"]))
48
55
  )
49
56
  return this.admission.run(
50
57
  "bulk",
@@ -65,6 +65,7 @@ async function sources() {
65
65
  checkpoints,
66
66
  pi,
67
67
  terminal,
68
+ lifetime,
68
69
  ] = await Promise.all([
69
70
  read("./helper-bootstrap.mjs"),
70
71
  read("./focus-channel-wire.mjs"),
@@ -78,6 +79,7 @@ async function sources() {
78
79
  read("../remote/shepherdr-checkpoints.mjs"),
79
80
  read("./pi-executable.mjs"),
80
81
  read("./terminal-peer.mjs"),
82
+ read("./helper-lifetime.mjs"),
81
83
  ]);
82
84
  const peerUrl = moduleUrl(peer);
83
85
  const savedSession = await optionalNotesSource(
@@ -113,6 +115,7 @@ async function sources() {
113
115
  watch: moduleUrl(watch),
114
116
  pi: moduleUrl(pi),
115
117
  terminal: moduleUrl(terminal),
118
+ lifetime: moduleUrl(lifetime),
116
119
  context: moduleUrl(
117
120
  context
118
121
  .replace('"./shepherdr-peer.mjs"', JSON.stringify(peerUrl))
@@ -16,6 +16,7 @@ export async function serve(input, send, fail) {
16
16
  { helperContext },
17
17
  pi,
18
18
  { terminalPeer },
19
+ { superviseParents },
19
20
  ] = await Promise.all([
20
21
  import(input.modules.core),
21
22
  import(input.modules.peer),
@@ -25,6 +26,7 @@ export async function serve(input, send, fail) {
25
26
  import(input.modules.contextHost),
26
27
  import(input.modules.pi),
27
28
  import(input.modules.terminal),
29
+ import(input.modules.lifetime),
28
30
  ]);
29
31
  const core = localCore(process.env.HC_TERMINAL_SOCKET);
30
32
  const terminals = terminalPeer((method, params) =>
@@ -35,9 +37,11 @@ export async function serve(input, send, fail) {
35
37
  let savedSession;
36
38
  let savedSessionIndex;
37
39
  let closed = false;
40
+ let lifetime;
38
41
  const close = async () => {
39
42
  if (closed) return;
40
43
  closed = true;
44
+ await lifetime?.close();
41
45
  for (const subscription of subscriptions.values()) subscription();
42
46
  subscriptions.clear();
43
47
  core.close();
@@ -52,6 +56,9 @@ export async function serve(input, send, fail) {
52
56
  throw new Error(
53
57
  "Remote Core identity changed; refresh machines before retrying",
54
58
  );
59
+ lifetime = await superviseParents(core, (message) => {
60
+ if (!closed) send({ notice: message });
61
+ });
55
62
  } catch (error) {
56
63
  await close();
57
64
  throw error;
@@ -158,6 +165,8 @@ export async function serve(input, send, fail) {
158
165
  return relay.start(message.threadId, message.routeId);
159
166
  case "view":
160
167
  return session.readSessionView(message.path);
168
+ case "session_header":
169
+ return session.readSessionHeader(message.path);
161
170
  case "directory": {
162
171
  const expand = (value) =>
163
172
  value === "~"
@@ -41,9 +41,15 @@ export class CoreRemoteTransport {
41
41
  private relayFailure: ((error: Error) => void) | undefined;
42
42
  private readonly socketPath: string;
43
43
  private readonly machine: CoreMachine;
44
- constructor(socketPath: string, machine: CoreMachine) {
44
+ private readonly onNotice: (message: string) => void;
45
+ constructor(
46
+ socketPath: string,
47
+ machine: CoreMachine,
48
+ onNotice: (message: string) => void = () => {},
49
+ ) {
45
50
  this.socketPath = socketPath;
46
51
  this.machine = machine;
52
+ this.onNotice = onNotice;
47
53
  this.relay = new ContextRelay(
48
54
  (message) => this.send(message),
49
55
  () => !!this.ended,
@@ -137,6 +143,10 @@ export class CoreRemoteTransport {
137
143
  }
138
144
  private receive(message: CoreObject): void {
139
145
  if (this.ended) return;
146
+ if (typeof message["notice"] === "string") {
147
+ this.onNotice(message["notice"]);
148
+ return;
149
+ }
140
150
  if (typeof message["subscription"] === "string") {
141
151
  this.subscriptions.get(message["subscription"])?.receive(message);
142
152
  return;
package/src/core/spawn.ts CHANGED
@@ -59,7 +59,7 @@ export async function startCoreAgent(
59
59
  name: params.name,
60
60
  cwd,
61
61
  caller: process.env["HC_TERMINAL_ID"],
62
- outlive_parent: true,
62
+ ...(params.outliveParent ? { outlive_parent: true } : {}),
63
63
  no_notify: true,
64
64
  // Labels request adoption only by a window connected to this Core.
65
65
  labels,
@@ -1,6 +1,31 @@
1
1
  /** @typedef {Pick<import('../types.js').PaneInfo, 'pane_id' | 'terminal_id' | 'agent' | 'agent_session'>} PeerTerminal */
2
2
  /** @typedef {{terminal:(address:string)=>Promise<PeerTerminal>,closeTerminal:(address:string)=>Promise<void>}} TerminalPeer */
3
3
 
4
+ /** Labels survive a kept terminal's program. Only the current Pi status owns them.
5
+ * @param {unknown} record
6
+ * @returns {string | undefined}
7
+ */
8
+ export function livePiSession(record) {
9
+ if (
10
+ !record ||
11
+ typeof record !== "object" ||
12
+ !("state" in record) ||
13
+ record.state !== "live" ||
14
+ !("status" in record) ||
15
+ !record.status ||
16
+ typeof record.status !== "object" ||
17
+ !("app" in record.status) ||
18
+ record.status.app !== "pi" ||
19
+ !("labels" in record) ||
20
+ !record.labels ||
21
+ typeof record.labels !== "object" ||
22
+ !("pi.session_file" in record.labels)
23
+ )
24
+ return undefined;
25
+ const path = record.labels["pi.session_file"];
26
+ return typeof path === "string" && path ? path : undefined;
27
+ }
28
+
4
29
  /** Native terminal identity and lifecycle shared by local and bundled peer delivery.
5
30
  * @param {(method:string,params:Record<string,unknown>)=>Promise<unknown>} request
6
31
  * @returns {TerminalPeer}
@@ -24,11 +49,7 @@ export function terminalPeer(request) {
24
49
  return {
25
50
  async terminal(address) {
26
51
  const record = await get(address);
27
- const labels = "labels" in record ? record.labels : undefined;
28
- const path =
29
- labels && typeof labels === "object" && "pi.session_file" in labels
30
- ? labels["pi.session_file"]
31
- : undefined;
52
+ const path = livePiSession(record);
32
53
  return {
33
54
  pane_id: address,
34
55
  terminal_id: address,