@howaboua/pi-shepherdr 0.2.5 → 0.2.7

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.
@@ -0,0 +1,294 @@
1
+ // @howaboua/pi-shepherdr managed bridge
2
+ import { open, stat } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+
6
+ const READ_CHUNK_BYTES = 64 * 1024;
7
+ const sessionCache = new Map();
8
+
9
+ function expandHome(path) {
10
+ return path === "~"
11
+ ? homedir()
12
+ : path.startsWith("~/")
13
+ ? join(homedir(), path.slice(2))
14
+ : path;
15
+ }
16
+
17
+ function assistantFromMessage(id, message) {
18
+ if (message.role !== "assistant") return undefined;
19
+ const text = [];
20
+ if (typeof message.content === "string") text.push(message.content);
21
+ else if (Array.isArray(message.content)) {
22
+ for (const part of message.content) {
23
+ if (
24
+ part &&
25
+ typeof part === "object" &&
26
+ part.type === "text" &&
27
+ typeof part.text === "string"
28
+ )
29
+ text.push(part.text);
30
+ }
31
+ }
32
+ const joined = text.join("");
33
+ const stopReason =
34
+ typeof message.stopReason === "string" ? message.stopReason : undefined;
35
+ if (!joined && stopReason !== "error") return undefined;
36
+ return {
37
+ id,
38
+ text: joined,
39
+ ...(stopReason ? { stopReason } : {}),
40
+ };
41
+ }
42
+
43
+ function inputFromMessage(id, message) {
44
+ if (message.role !== "user") return undefined;
45
+ const text = [];
46
+ if (typeof message.content === "string") text.push(message.content);
47
+ else if (Array.isArray(message.content)) {
48
+ for (const part of message.content) {
49
+ if (
50
+ part &&
51
+ typeof part === "object" &&
52
+ part.type === "text" &&
53
+ typeof part.text === "string"
54
+ )
55
+ text.push(part.text);
56
+ }
57
+ }
58
+ const joined = text.join("");
59
+ return joined ? { id, text: joined } : undefined;
60
+ }
61
+
62
+ function askChoice(value) {
63
+ if (!value || typeof value !== "object" || typeof value.label !== "string")
64
+ return undefined;
65
+ return {
66
+ label: value.label,
67
+ ...(typeof value.description === "string"
68
+ ? { description: value.description }
69
+ : {}),
70
+ };
71
+ }
72
+
73
+ function askPrompt(value) {
74
+ if (!value || typeof value !== "object" || typeof value.title !== "string")
75
+ return undefined;
76
+ return {
77
+ title: value.title,
78
+ multiple: value.multiple === true,
79
+ choices: (Array.isArray(value.choices) ? value.choices : [])
80
+ .map(askChoice)
81
+ .filter(Boolean),
82
+ ...(typeof value.body === "string" ? { body: value.body } : {}),
83
+ };
84
+ }
85
+
86
+ function askCall(value) {
87
+ if (
88
+ !value ||
89
+ typeof value !== "object" ||
90
+ value.type !== "toolCall" ||
91
+ value.name !== "ask" ||
92
+ typeof value.id !== "string"
93
+ )
94
+ return undefined;
95
+ return askFromInput(value.id, value.arguments);
96
+ }
97
+
98
+ function askFromInput(toolCallId, input) {
99
+ if (!input || typeof input !== "object" || Array.isArray(input))
100
+ return undefined;
101
+ const prompts = (Array.isArray(input.prompts) ? input.prompts : [])
102
+ .map(askPrompt)
103
+ .filter(Boolean);
104
+ if (prompts.length === 0) return undefined;
105
+ return {
106
+ toolCallId,
107
+ handoff: input.handoff === true,
108
+ prompts,
109
+ };
110
+ }
111
+
112
+ function askResult(message) {
113
+ if (message.role !== "toolResult" || message.toolName !== "ask")
114
+ return undefined;
115
+ const id = message.toolCallId ?? message.tool_call_id;
116
+ if (typeof id !== "string") return undefined;
117
+ if (message.isError === true) return [id, { status: "rejected" }];
118
+ if (message.isError !== false) return [id, { status: "unknown" }];
119
+ if (message.details?.dismissed === true) return [id, { status: "rejected" }];
120
+ const rawResponses = message.details?.responses;
121
+ const rawResponseCount = Array.isArray(rawResponses)
122
+ ? rawResponses.length
123
+ : -1;
124
+ const responses = Array.isArray(rawResponses)
125
+ ? rawResponses
126
+ .map((response) => {
127
+ if (
128
+ !response ||
129
+ typeof response !== "object" ||
130
+ typeof response.id !== "string" ||
131
+ !Array.isArray(response.selections) ||
132
+ !response.selections.every(
133
+ (selection) => typeof selection === "string",
134
+ )
135
+ )
136
+ return undefined;
137
+ return {
138
+ id: response.id,
139
+ selections: response.selections,
140
+ ...(typeof response.comment === "string"
141
+ ? { comment: response.comment }
142
+ : {}),
143
+ };
144
+ })
145
+ .filter(Boolean)
146
+ : undefined;
147
+ return [
148
+ id,
149
+ {
150
+ status: "accepted",
151
+ ...(responses && responses.length === rawResponseCount
152
+ ? { responses }
153
+ : {}),
154
+ },
155
+ ];
156
+ }
157
+
158
+ async function sessionView(path, size) {
159
+ const file = await open(path, "r");
160
+ let targetId;
161
+ let assistant;
162
+ let assistantDepth;
163
+ let ask;
164
+ const askResults = new Map();
165
+ let depth = 0;
166
+ let input;
167
+ let inputDepth;
168
+ const resolved = new Set();
169
+ const result = () => ({
170
+ ...(assistant ? { assistant } : {}),
171
+ ...(ask ? { ask } : {}),
172
+ ...(askResults.size > 0
173
+ ? { askResults: Object.fromEntries(askResults) }
174
+ : {}),
175
+ ...(input ? { input } : {}),
176
+ ...(assistantDepth !== undefined && inputDepth !== undefined
177
+ ? { assistantAfterInput: assistantDepth < inputDepth }
178
+ : {}),
179
+ });
180
+ const inspect = (line) => {
181
+ if (line.length === 0) return false;
182
+ let entry;
183
+ try {
184
+ entry = JSON.parse(line.toString("utf8"));
185
+ } catch {
186
+ return false;
187
+ }
188
+ if (typeof entry.id !== "string") return false;
189
+ targetId ??= entry.id;
190
+ if (entry.id !== targetId) return false;
191
+ const currentDepth = depth;
192
+ depth += 1;
193
+ if (entry.type === "custom" && entry.customType === "pi-ask-active") {
194
+ const update = entry.data;
195
+ if (update?.version === 1 && typeof update.id === "string") {
196
+ if (update.state === "closed") resolved.add(update.id);
197
+ else if (
198
+ update.state === "active" &&
199
+ !ask &&
200
+ !resolved.has(update.id)
201
+ ) {
202
+ ask = askFromInput(update.id, update);
203
+ }
204
+ }
205
+ }
206
+ if (
207
+ !input &&
208
+ entry.type === "custom_message" &&
209
+ entry.customType === "herdr-agent-message" &&
210
+ typeof entry.content === "string" &&
211
+ entry.content
212
+ ) {
213
+ input = { id: entry.id, text: entry.content };
214
+ inputDepth = currentDepth;
215
+ }
216
+ const message = entry.message;
217
+ if (message && typeof message === "object") {
218
+ const result = askResult(message);
219
+ if (result && !askResults.has(result[0])) askResults.set(...result);
220
+ if (
221
+ (message.role === "toolResult" || message.role === "tool") &&
222
+ typeof (message.toolCallId ?? message.tool_call_id) === "string"
223
+ )
224
+ resolved.add(message.toolCallId ?? message.tool_call_id);
225
+ if (!assistant) {
226
+ assistant = assistantFromMessage(entry.id, message);
227
+ if (assistant) assistantDepth = currentDepth;
228
+ }
229
+ if (!input) {
230
+ input = inputFromMessage(entry.id, message);
231
+ if (input) inputDepth = currentDepth;
232
+ }
233
+ if (
234
+ !ask &&
235
+ message.role === "assistant" &&
236
+ Array.isArray(message.content)
237
+ )
238
+ ask = [...message.content]
239
+ .reverse()
240
+ .map(askCall)
241
+ .find(
242
+ (candidate) => candidate && !resolved.has(candidate.toolCallId),
243
+ );
244
+ }
245
+ if (typeof entry.parentId !== "string") return true;
246
+ targetId = entry.parentId;
247
+ return false;
248
+ };
249
+
250
+ try {
251
+ let position = size;
252
+ let partial = Buffer.alloc(0);
253
+ while (position > 0) {
254
+ const length = Math.min(READ_CHUNK_BYTES, position);
255
+ position -= length;
256
+ const chunk = Buffer.allocUnsafe(length);
257
+ const { bytesRead } = await file.read(chunk, 0, length, position);
258
+ const data = Buffer.concat([chunk.subarray(0, bytesRead), partial]);
259
+ let lineEnd = data.length;
260
+ for (let index = data.length - 1; index >= 0; index -= 1) {
261
+ if (data[index] !== 0x0a) continue;
262
+ if (inspect(data.subarray(index + 1, lineEnd))) return result();
263
+ lineEnd = index;
264
+ }
265
+ partial = data.subarray(0, lineEnd);
266
+ }
267
+ inspect(partial);
268
+ return result();
269
+ } finally {
270
+ await file.close();
271
+ }
272
+ }
273
+
274
+ export async function readSessionView(path) {
275
+ if (!path) return {};
276
+ const expanded = expandHome(path);
277
+ let metadata;
278
+ try {
279
+ metadata = await stat(expanded);
280
+ } catch (error) {
281
+ if (error.code === "ENOENT") return {};
282
+ throw error;
283
+ }
284
+ const cached = sessionCache.get(expanded);
285
+ if (cached?.size === metadata.size && cached.mtimeMs === metadata.mtimeMs)
286
+ return cached.result;
287
+ const result = await sessionView(expanded, metadata.size);
288
+ sessionCache.set(expanded, {
289
+ size: metadata.size,
290
+ mtimeMs: metadata.mtimeMs,
291
+ result,
292
+ });
293
+ return result;
294
+ }
@@ -1,15 +1,59 @@
1
1
  // @howaboua/pi-shepherdr managed bridge
2
- import { open, readFile, stat } from "node:fs/promises";
2
+ import { readFile, stat } from "node:fs/promises";
3
3
  import { createConnection } from "node:net";
4
4
  import { homedir } from "node:os";
5
- import { dirname, join, resolve } from "node:path";
5
+ import { join, resolve } from "node:path";
6
+ import {
7
+ listenContext,
8
+ relayContextPath,
9
+ requestContext,
10
+ } from "./shepherdr-context.mjs";
6
11
  import { sendPeerMessage } from "./shepherdr-peer.mjs";
12
+ import { readSessionView } from "./shepherdr-session.mjs";
7
13
 
8
- const BRIDGE_VERSION = 6;
14
+ const BRIDGE_VERSION = 11;
9
15
  const MAX_FRAME_BYTES = 8 * 1024 * 1024;
10
- const READ_CHUNK_BYTES = 64 * 1024;
11
16
  const subscriptions = new Map();
12
- const sessionCache = new Map();
17
+ const contextRelays = new Map();
18
+ const contextRequests = new Map();
19
+ const contextCalls = new Map();
20
+
21
+ function requestController(request, signal) {
22
+ signal.throwIfAborted();
23
+ const id = crypto.randomUUID();
24
+ return new Promise((resolve, reject) => {
25
+ const finish = (error, result) => {
26
+ if (!contextRequests.delete(id)) return;
27
+ clearTimeout(timer);
28
+ signal.removeEventListener("abort", abort);
29
+ if (error) reject(error);
30
+ else resolve(result);
31
+ };
32
+ const abort = () => {
33
+ send({ type: "context_cancel", id });
34
+ finish(
35
+ new Error(
36
+ "Shared context request cancelled; a write may have completed. Reread before retrying",
37
+ ),
38
+ );
39
+ };
40
+ const timer = setTimeout(() => {
41
+ send({ type: "context_cancel", id });
42
+ finish(
43
+ new Error(
44
+ "Shared context controller did not reply; a write may have completed. Reread before retrying",
45
+ ),
46
+ );
47
+ }, 35_000);
48
+ timer.unref();
49
+ contextRequests.set(id, {
50
+ resolve: (result) => finish(undefined, result),
51
+ reject: (error) => finish(error),
52
+ });
53
+ signal.addEventListener("abort", abort, { once: true });
54
+ send({ type: "context_request", id, request });
55
+ });
56
+ }
13
57
 
14
58
  function argument(name) {
15
59
  const index = process.argv.indexOf(`--${name}`);
@@ -228,233 +272,6 @@ function subscribe(id, requested) {
228
272
  });
229
273
  }
230
274
 
231
- function assistantFromMessage(id, message) {
232
- if (message.role !== "assistant") return undefined;
233
- const text = [];
234
- if (typeof message.content === "string") text.push(message.content);
235
- else if (Array.isArray(message.content)) {
236
- for (const part of message.content) {
237
- if (
238
- part &&
239
- typeof part === "object" &&
240
- part.type === "text" &&
241
- typeof part.text === "string"
242
- )
243
- text.push(part.text);
244
- }
245
- }
246
- const joined = text.join("");
247
- const stopReason =
248
- typeof message.stopReason === "string" ? message.stopReason : undefined;
249
- if (!joined && stopReason !== "error") return undefined;
250
- return {
251
- id,
252
- text: joined,
253
- ...(stopReason ? { stopReason } : {}),
254
- };
255
- }
256
-
257
- function inputFromMessage(id, message) {
258
- if (message.role !== "user") return undefined;
259
- const text = [];
260
- if (typeof message.content === "string") text.push(message.content);
261
- else if (Array.isArray(message.content)) {
262
- for (const part of message.content) {
263
- if (
264
- part &&
265
- typeof part === "object" &&
266
- part.type === "text" &&
267
- typeof part.text === "string"
268
- )
269
- text.push(part.text);
270
- }
271
- }
272
- const joined = text.join("");
273
- return joined ? { id, text: joined } : undefined;
274
- }
275
-
276
- function askChoice(value) {
277
- if (!value || typeof value !== "object" || typeof value.label !== "string")
278
- return undefined;
279
- return {
280
- label: value.label,
281
- ...(typeof value.description === "string"
282
- ? { description: value.description }
283
- : {}),
284
- };
285
- }
286
-
287
- function askPrompt(value) {
288
- if (!value || typeof value !== "object" || typeof value.title !== "string")
289
- return undefined;
290
- return {
291
- title: value.title,
292
- multiple: value.multiple === true,
293
- choices: (Array.isArray(value.choices) ? value.choices : [])
294
- .map(askChoice)
295
- .filter(Boolean),
296
- ...(typeof value.body === "string" ? { body: value.body } : {}),
297
- };
298
- }
299
-
300
- function askCall(value) {
301
- if (
302
- !value ||
303
- typeof value !== "object" ||
304
- value.type !== "toolCall" ||
305
- value.name !== "ask" ||
306
- typeof value.id !== "string"
307
- )
308
- return undefined;
309
- return askFromInput(value.id, value.arguments);
310
- }
311
-
312
- function askFromInput(toolCallId, input) {
313
- if (!input || typeof input !== "object" || Array.isArray(input))
314
- return undefined;
315
- const prompts = (Array.isArray(input.prompts) ? input.prompts : [])
316
- .map(askPrompt)
317
- .filter(Boolean);
318
- if (prompts.length === 0) return undefined;
319
- return {
320
- toolCallId,
321
- handoff: input.handoff === true,
322
- prompts,
323
- };
324
- }
325
-
326
- async function sessionView(path, size) {
327
- const file = await open(path, "r");
328
- let targetId;
329
- let assistant;
330
- let assistantDepth;
331
- let ask;
332
- let depth = 0;
333
- let input;
334
- let inputDepth;
335
- const resolved = new Set();
336
- const result = () => ({
337
- ...(assistant ? { assistant } : {}),
338
- ...(ask ? { ask } : {}),
339
- ...(input ? { input } : {}),
340
- ...(assistantDepth !== undefined && inputDepth !== undefined
341
- ? { assistantAfterInput: assistantDepth < inputDepth }
342
- : {}),
343
- });
344
- const inspect = (line) => {
345
- if (line.length === 0) return false;
346
- let entry;
347
- try {
348
- entry = JSON.parse(line.toString("utf8"));
349
- } catch {
350
- return false;
351
- }
352
- if (typeof entry.id !== "string") return false;
353
- targetId ??= entry.id;
354
- if (entry.id !== targetId) return false;
355
- const currentDepth = depth;
356
- depth += 1;
357
- if (entry.type === "custom" && entry.customType === "pi-ask-active") {
358
- const update = entry.data;
359
- if (update?.version === 1 && typeof update.id === "string") {
360
- if (update.state === "closed") resolved.add(update.id);
361
- else if (
362
- update.state === "active" &&
363
- !ask &&
364
- !resolved.has(update.id)
365
- ) {
366
- ask = askFromInput(update.id, update);
367
- }
368
- }
369
- }
370
- if (
371
- !input &&
372
- entry.type === "custom_message" &&
373
- entry.customType === "herdr-agent-message" &&
374
- typeof entry.content === "string" &&
375
- entry.content
376
- ) {
377
- input = { id: entry.id, text: entry.content };
378
- inputDepth = currentDepth;
379
- }
380
- const message = entry.message;
381
- if (message && typeof message === "object") {
382
- if (
383
- (message.role === "toolResult" || message.role === "tool") &&
384
- typeof (message.toolCallId ?? message.tool_call_id) === "string"
385
- )
386
- resolved.add(message.toolCallId ?? message.tool_call_id);
387
- if (!assistant) {
388
- assistant = assistantFromMessage(entry.id, message);
389
- if (assistant) assistantDepth = currentDepth;
390
- }
391
- if (!input) {
392
- input = inputFromMessage(entry.id, message);
393
- if (input) inputDepth = currentDepth;
394
- }
395
- if (
396
- !ask &&
397
- message.role === "assistant" &&
398
- Array.isArray(message.content)
399
- )
400
- ask = [...message.content]
401
- .reverse()
402
- .map(askCall)
403
- .find(
404
- (candidate) => candidate && !resolved.has(candidate.toolCallId),
405
- );
406
- }
407
- if (typeof entry.parentId !== "string") return true;
408
- targetId = entry.parentId;
409
- return false;
410
- };
411
-
412
- try {
413
- let position = size;
414
- let partial = Buffer.alloc(0);
415
- while (position > 0) {
416
- const length = Math.min(READ_CHUNK_BYTES, position);
417
- position -= length;
418
- const chunk = Buffer.allocUnsafe(length);
419
- const { bytesRead } = await file.read(chunk, 0, length, position);
420
- const data = Buffer.concat([chunk.subarray(0, bytesRead), partial]);
421
- let lineEnd = data.length;
422
- for (let index = data.length - 1; index >= 0; index -= 1) {
423
- if (data[index] !== 0x0a) continue;
424
- if (inspect(data.subarray(index + 1, lineEnd))) return result();
425
- lineEnd = index;
426
- }
427
- partial = data.subarray(0, lineEnd);
428
- }
429
- inspect(partial);
430
- return result();
431
- } finally {
432
- await file.close();
433
- }
434
- }
435
-
436
- async function view(path) {
437
- if (!path) return {};
438
- const expanded = expandHome(path);
439
- let metadata;
440
- try {
441
- metadata = await stat(expanded);
442
- } catch (error) {
443
- if (error.code === "ENOENT") return {};
444
- throw error;
445
- }
446
- const cached = sessionCache.get(expanded);
447
- if (cached?.size === metadata.size && cached.mtimeMs === metadata.mtimeMs)
448
- return cached.result;
449
- const result = await sessionView(expanded, metadata.size);
450
- sessionCache.set(expanded, {
451
- size: metadata.size,
452
- mtimeMs: metadata.mtimeMs,
453
- result,
454
- });
455
- return result;
456
- }
457
-
458
275
  async function directory(value, fallback) {
459
276
  const base = expandHome(fallback?.trim() || homedir());
460
277
  const path = resolve(base, expandHome(value?.trim() || "."));
@@ -504,6 +321,25 @@ async function handle(message) {
504
321
  if (message.op === "message") {
505
322
  return sendPeerMessage(request, message.agent, message.message);
506
323
  }
324
+ if (message.op === "context") {
325
+ const controller = new AbortController();
326
+ contextCalls.set(message.id, controller);
327
+ try {
328
+ return await requestContext(
329
+ message.path,
330
+ message.request,
331
+ controller.signal,
332
+ );
333
+ } finally {
334
+ contextCalls.delete(message.id);
335
+ }
336
+ }
337
+ if (message.op === "context_relay") {
338
+ const path = relayContextPath(message.threadId, message.routeId);
339
+ if (!contextRelays.has(path))
340
+ contextRelays.set(path, await listenContext(path, requestController));
341
+ return path;
342
+ }
507
343
  if (message.op === "subscribe") {
508
344
  await subscribe(message.id, message.subscriptions ?? []);
509
345
  return { subscribed: true };
@@ -513,7 +349,7 @@ async function handle(message) {
513
349
  subscriptions.delete(message.subscription);
514
350
  return { unsubscribed: true };
515
351
  }
516
- if (message.op === "view") return view(message.path);
352
+ if (message.op === "view") return readSessionView(message.path);
517
353
  if (message.op === "keybindings") return keybindings();
518
354
  if (message.op === "directory")
519
355
  return directory(message.value, message.fallback);
@@ -541,6 +377,25 @@ process.stdin.on("data", (chunk) => {
541
377
  send({ id: "invalid", ok: false, error: serializableError(error) });
542
378
  continue;
543
379
  }
380
+ if (message?.op === "context_cancel") {
381
+ contextCalls.get(message.id)?.abort();
382
+ continue;
383
+ }
384
+ if (message?.op === "context_reply") {
385
+ const pending = contextRequests.get(message.id);
386
+ if (pending) {
387
+ if (message.ok === true) pending.resolve(message.result);
388
+ else
389
+ pending.reject(
390
+ new Error(
391
+ typeof message.error === "string"
392
+ ? message.error
393
+ : "Shared context controller failed",
394
+ ),
395
+ );
396
+ }
397
+ continue;
398
+ }
544
399
  void handle(message).then(
545
400
  (result) => send({ id: message.id, ok: true, result }),
546
401
  (error) =>
@@ -549,11 +404,18 @@ process.stdin.on("data", (chunk) => {
549
404
  }
550
405
  });
551
406
 
552
- process.stdin.on("end", () => process.exit());
407
+ async function shutdown() {
408
+ for (const close of subscriptions.values()) close();
409
+ for (const controller of contextCalls.values()) controller.abort();
410
+ await Promise.allSettled([...contextRelays.values()].map((close) => close()));
411
+ process.exit();
412
+ }
413
+ process.stdin.on("end", () => {
414
+ void shutdown();
415
+ });
553
416
  for (const signal of ["SIGINT", "SIGTERM"]) {
554
417
  process.on(signal, () => {
555
- for (const close of subscriptions.values()) close();
556
- process.exit();
418
+ void shutdown();
557
419
  });
558
420
  }
559
421