@howaboua/pi-shepherdr 0.2.17 → 0.2.19

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.
@@ -4,9 +4,18 @@ import { open, stat } from "node:fs/promises";
4
4
  import { homedir } from "node:os";
5
5
  import { join } from "node:path";
6
6
 
7
+ /** @param {unknown} value @returns {Record<string, unknown> | undefined} */
8
+ function record(value) {
9
+ return value && typeof value === "object" && !Array.isArray(value)
10
+ ? /** @type {Record<string, unknown>} */ (value)
11
+ : undefined;
12
+ }
13
+
7
14
  const READ_CHUNK_BYTES = 64 * 1024;
15
+ /** @type {Map<string,{mtimeMs:number,size:number,result:import("../types.js").SessionView}>} */
8
16
  const sessionCache = new Map();
9
17
 
18
+ /** @param {string} path */
10
19
  function expandHome(path) {
11
20
  return path === "~"
12
21
  ? homedir()
@@ -15,24 +24,23 @@ function expandHome(path) {
15
24
  : path;
16
25
  }
17
26
 
27
+ /** @param {string} id @param {Record<string, unknown>} message @returns {import("../types.js").LatestAssistant | undefined} */
18
28
  function assistantFromMessage(id, message) {
19
- if (message.role !== "assistant") return undefined;
29
+ if (message["role"] !== "assistant") return undefined;
20
30
  const text = [];
21
- if (typeof message.content === "string") text.push(message.content);
22
- else if (Array.isArray(message.content)) {
23
- for (const part of message.content) {
24
- if (
25
- part &&
26
- typeof part === "object" &&
27
- part.type === "text" &&
28
- typeof part.text === "string"
29
- )
30
- text.push(part.text);
31
+ if (typeof message["content"] === "string") text.push(message["content"]);
32
+ else if (Array.isArray(message["content"])) {
33
+ for (const value of message["content"]) {
34
+ const part = record(value);
35
+ if (part && part["type"] === "text" && typeof part["text"] === "string")
36
+ text.push(part["text"]);
31
37
  }
32
38
  }
33
39
  const joined = text.join("");
34
40
  const stopReason =
35
- typeof message.stopReason === "string" ? message.stopReason : undefined;
41
+ typeof message["stopReason"] === "string"
42
+ ? message["stopReason"]
43
+ : undefined;
36
44
  if (!joined && stopReason !== "error") return undefined;
37
45
  return {
38
46
  id,
@@ -41,239 +49,145 @@ function assistantFromMessage(id, message) {
41
49
  };
42
50
  }
43
51
 
52
+ /** @param {string} id @param {Record<string, unknown>} message @returns {import("../types.js").LatestInput | undefined} */
44
53
  function inputFromMessage(id, message) {
45
- if (message.role !== "user") return undefined;
54
+ if (message["role"] !== "user") return undefined;
46
55
  const text = [];
47
- if (typeof message.content === "string") text.push(message.content);
48
- else if (Array.isArray(message.content)) {
49
- for (const part of message.content) {
50
- if (
51
- part &&
52
- typeof part === "object" &&
53
- part.type === "text" &&
54
- typeof part.text === "string"
55
- )
56
- text.push(part.text);
56
+ if (typeof message["content"] === "string") text.push(message["content"]);
57
+ else if (Array.isArray(message["content"])) {
58
+ for (const value of message["content"]) {
59
+ const part = record(value);
60
+ if (part && part["type"] === "text" && typeof part["text"] === "string")
61
+ text.push(part["text"]);
57
62
  }
58
63
  }
59
64
  const joined = text.join("");
60
65
  return joined ? { id, text: joined } : undefined;
61
66
  }
62
67
 
63
- function askChoice(value) {
64
- if (!value || typeof value !== "object" || typeof value.label !== "string")
68
+ /** @param {unknown} value @returns {import("../types.js").ExtensionMessage | undefined} */
69
+ export function readExtensionMessage(value) {
70
+ if (!value || typeof value !== "object" || Array.isArray(value))
65
71
  return undefined;
66
- return {
67
- label: value.label,
68
- ...(typeof value.description === "string"
69
- ? { description: value.description }
70
- : {}),
71
- };
72
- }
73
-
74
- function askPrompt(value) {
75
- if (!value || typeof value !== "object" || typeof value.title !== "string")
76
- return undefined;
77
- return {
78
- title: value.title,
79
- multiple: value.multiple === true,
80
- choices: (Array.isArray(value.choices) ? value.choices : [])
81
- .map(askChoice)
82
- .filter(Boolean),
83
- ...(typeof value.body === "string" ? { body: value.body } : {}),
84
- };
85
- }
86
-
87
- function askCall(value) {
72
+ const data = /** @type {Record<string, unknown>} */ (value);
88
73
  if (
89
- !value ||
90
- typeof value !== "object" ||
91
- value.type !== "toolCall" ||
92
- value.name !== "ask" ||
93
- typeof value.id !== "string"
74
+ data["version"] !== 1 ||
75
+ data["state"] !== "pending" ||
76
+ typeof data["extension"] !== "string" ||
77
+ !data["extension"].trim() ||
78
+ typeof data["id"] !== "string" ||
79
+ !data["id"].trim() ||
80
+ typeof data["message"] !== "string" ||
81
+ typeof data["blocking"] !== "boolean" ||
82
+ (data["reply"] !== undefined && typeof data["reply"] !== "string")
94
83
  )
95
84
  return undefined;
96
- return askFromInput(value.id, value.arguments);
97
- }
98
-
99
- function askFromInput(toolCallId, input) {
100
- if (!input || typeof input !== "object" || Array.isArray(input))
101
- return undefined;
102
- const prompts = (Array.isArray(input.prompts) ? input.prompts : [])
103
- .map(askPrompt)
104
- .filter(Boolean);
105
- if (prompts.length === 0) return undefined;
106
85
  return {
107
- toolCallId,
108
- handoff: input.handoff === true,
109
- ...(input.delivery === "steer" ? { delivery: "steer" } : {}),
110
- prompts,
86
+ extension: data["extension"],
87
+ id: data["id"],
88
+ message: data["message"],
89
+ blocking: data["blocking"],
90
+ ...(typeof data["reply"] === "string" ? { reply: data["reply"] } : {}),
111
91
  };
112
92
  }
113
93
 
114
- function askResult(message) {
115
- if (message.role !== "toolResult" || message.toolName !== "ask")
116
- return undefined;
117
- const id = message.toolCallId ?? message.tool_call_id;
118
- if (typeof id !== "string") return undefined;
119
- if (message.details?.pending === true) return undefined;
120
- if (message.isError === true) return [id, { status: "rejected" }];
121
- if (message.isError !== false) return [id, { status: "unknown" }];
122
- if (message.details?.dismissed === true) return [id, { status: "rejected" }];
123
- const rawResponses = message.details?.responses;
124
- const rawResponseCount = Array.isArray(rawResponses)
125
- ? rawResponses.length
126
- : -1;
127
- const responses = Array.isArray(rawResponses)
128
- ? rawResponses
129
- .map((response) => {
130
- if (
131
- !response ||
132
- typeof response !== "object" ||
133
- typeof response.id !== "string" ||
134
- !Array.isArray(response.selections) ||
135
- !response.selections.every(
136
- (selection) => typeof selection === "string",
137
- )
138
- )
139
- return undefined;
140
- return {
141
- id: response.id,
142
- selections: response.selections,
143
- ...(typeof response.comment === "string"
144
- ? { comment: response.comment }
145
- : {}),
146
- };
147
- })
148
- .filter(Boolean)
149
- : undefined;
150
- return [
151
- id,
152
- {
153
- status:
154
- responses &&
155
- responses.length > 0 &&
156
- responses.length === rawResponseCount
157
- ? "accepted"
158
- : "unknown",
159
- ...(responses && responses.length === rawResponseCount
160
- ? { responses }
161
- : {}),
162
- },
163
- ];
94
+ /** @param {{extension:string,id:string}} value */
95
+ export function extensionMessageKey(value) {
96
+ return JSON.stringify([value.extension, value.id]);
164
97
  }
165
98
 
99
+ /** @param {string} path @param {number} size @returns {Promise<import("../types.js").SessionView>} */
166
100
  async function sessionView(path, size) {
167
101
  const file = await open(path, "r");
102
+ /** @type {string | undefined} */
168
103
  let targetId;
104
+ /** @type {import("../types.js").LatestAssistant | undefined} */
169
105
  let assistant;
106
+ /** @type {number | undefined} */
170
107
  let assistantDepth;
171
- let ask;
172
- const askResults = new Map();
108
+ /** @type {import("../types.js").ExtensionMessage[]} */
109
+ const extensionMessages = [];
173
110
  let depth = 0;
111
+ /** @type {import("../types.js").LatestInput | undefined} */
174
112
  let input;
113
+ /** @type {number | undefined} */
175
114
  let inputDepth;
176
115
  const resolved = new Set();
177
116
  const result = () => ({
178
117
  ...(assistant ? { assistant } : {}),
179
- ...(ask ? { ask } : {}),
180
- ...(askResults.size > 0
181
- ? { askResults: Object.fromEntries(askResults) }
182
- : {}),
118
+ ...(extensionMessages.length ? { extensionMessages } : {}),
183
119
  ...(input ? { input } : {}),
184
120
  ...(assistantDepth !== undefined && inputDepth !== undefined
185
121
  ? { assistantAfterInput: assistantDepth < inputDepth }
186
122
  : {}),
187
123
  });
124
+ /** @param {Buffer} line */
188
125
  const inspect = (line) => {
189
126
  if (line.length === 0) return false;
190
- let entry;
127
+ /** @type {unknown} */
128
+ let parsed;
191
129
  try {
192
- entry = JSON.parse(line.toString("utf8"));
130
+ parsed = JSON.parse(line.toString("utf8"));
193
131
  } catch {
194
132
  return false;
195
133
  }
196
- if (typeof entry.id !== "string") return false;
197
- targetId ??= entry.id;
198
- if (entry.id !== targetId) return false;
134
+ const entry = record(parsed);
135
+ if (!entry || typeof entry["id"] !== "string") return false;
136
+ targetId ??= entry["id"];
137
+ if (entry["id"] !== targetId) return false;
199
138
  const currentDepth = depth;
200
139
  depth += 1;
201
- if (entry.type === "custom" && entry.customType === "pi-ask-active") {
202
- const update = entry.data;
203
- if (update?.version === 1 && typeof update.id === "string") {
204
- if (update.state === "closed") resolved.add(update.id);
205
- else if (
206
- update.state === "active" &&
207
- !ask &&
208
- !resolved.has(update.id)
209
- ) {
210
- ask = askFromInput(update.id, update);
211
- }
212
- }
213
- }
214
- if (entry.type === "custom" && entry.customType === "pi-ask-pending") {
215
- const update = entry.data;
140
+ if (
141
+ entry["type"] === "custom" &&
142
+ entry["customType"] === "shepherdr-extension-message"
143
+ ) {
144
+ const update = record(entry["data"]);
216
145
  if (
217
- update?.version === 1 &&
218
- update.state === "closed" &&
219
- typeof update.id === "string"
146
+ update?.["version"] === 1 &&
147
+ typeof update["extension"] === "string" &&
148
+ update["extension"].trim() &&
149
+ typeof update["id"] === "string" &&
150
+ update["id"].trim()
220
151
  ) {
221
- resolved.add(update.id);
222
- const result = askResult({
223
- role: "toolResult",
224
- toolName: "ask",
225
- toolCallId: update.id,
226
- isError: false,
227
- details: update,
152
+ const key = extensionMessageKey({
153
+ extension: update["extension"],
154
+ id: update["id"],
228
155
  });
229
- if (result && !askResults.has(result[0])) askResults.set(...result);
156
+ if (!resolved.has(key)) {
157
+ if (update["state"] === "closed") resolved.add(key);
158
+ else {
159
+ const pending = readExtensionMessage(update);
160
+ if (pending) {
161
+ extensionMessages.push(pending);
162
+ resolved.add(key);
163
+ }
164
+ }
165
+ }
230
166
  }
231
167
  }
232
168
  if (
233
169
  !input &&
234
- entry.type === "custom_message" &&
235
- entry.customType === "herdr-agent-message" &&
236
- typeof entry.content === "string" &&
237
- entry.content
170
+ entry["type"] === "custom_message" &&
171
+ entry["customType"] === "herdr-agent-message" &&
172
+ typeof entry["content"] === "string" &&
173
+ entry["content"]
238
174
  ) {
239
- input = { id: entry.id, text: entry.content };
175
+ input = { id: entry["id"], text: entry["content"] };
240
176
  inputDepth = currentDepth;
241
177
  }
242
- const message = entry.message;
178
+ const message = record(entry["message"]);
243
179
  if (message && typeof message === "object") {
244
- const result = askResult(message);
245
- if (result && !askResults.has(result[0])) askResults.set(...result);
246
- if (
247
- (message.role === "toolResult" || message.role === "tool") &&
248
- message.details?.pending !== true &&
249
- typeof (message.toolCallId ?? message.tool_call_id) === "string"
250
- )
251
- resolved.add(message.toolCallId ?? message.tool_call_id);
252
180
  if (!assistant) {
253
- assistant = assistantFromMessage(entry.id, message);
181
+ assistant = assistantFromMessage(entry["id"], message);
254
182
  if (assistant) assistantDepth = currentDepth;
255
183
  }
256
184
  if (!input) {
257
- input = inputFromMessage(entry.id, message);
185
+ input = inputFromMessage(entry["id"], message);
258
186
  if (input) inputDepth = currentDepth;
259
187
  }
260
- if (
261
- !ask &&
262
- message.role === "assistant" &&
263
- Array.isArray(message.content)
264
- )
265
- ask = [...message.content]
266
- .reverse()
267
- .map(askCall)
268
- .find(
269
- (candidate) =>
270
- candidate &&
271
- candidate.delivery !== "steer" &&
272
- !resolved.has(candidate.toolCallId),
273
- );
274
188
  }
275
- if (typeof entry.parentId !== "string") return true;
276
- targetId = entry.parentId;
189
+ if (typeof entry["parentId"] !== "string") return true;
190
+ targetId = entry["parentId"];
277
191
  return false;
278
192
  };
279
193
 
@@ -286,13 +200,13 @@ async function sessionView(path, size) {
286
200
  const chunk = Buffer.allocUnsafe(length);
287
201
  const { bytesRead } = await file.read(chunk, 0, length, position);
288
202
  const data = Buffer.concat([chunk.subarray(0, bytesRead), partial]);
289
- let lineEnd = data.length;
290
- for (let index = data.length - 1; index >= 0; index -= 1) {
203
+ let lineEnd = data["length"];
204
+ for (let index = data["length"] - 1; index >= 0; index -= 1) {
291
205
  if (data[index] !== 0x0a) continue;
292
- if (inspect(data.subarray(index + 1, lineEnd))) return result();
206
+ if (inspect(data["subarray"](index + 1, lineEnd))) return result();
293
207
  lineEnd = index;
294
208
  }
295
- partial = data.subarray(0, lineEnd);
209
+ partial = data["subarray"](0, lineEnd);
296
210
  }
297
211
  inspect(partial);
298
212
  return result();
@@ -301,6 +215,7 @@ async function sessionView(path, size) {
301
215
  }
302
216
  }
303
217
 
218
+ /** @param {string | undefined} path @returns {Promise<import("../types.js").SessionView>} */
304
219
  export async function readSessionView(path) {
305
220
  if (!path) return {};
306
221
  const expanded = expandHome(path);
@@ -308,7 +223,8 @@ export async function readSessionView(path) {
308
223
  try {
309
224
  metadata = await stat(expanded);
310
225
  } catch (error) {
311
- if (error.code === "ENOENT") return {};
226
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
227
+ return {};
312
228
  throw error;
313
229
  }
314
230
  const cached = sessionCache.get(expanded);
@@ -11,13 +11,14 @@ import {
11
11
  } from "./shepherdr-context.mjs";
12
12
  import {
13
13
  sendPeerCommands,
14
+ sendPeerExtensionReply,
14
15
  sendPeerFocus,
15
16
  sendPeerMessage,
16
17
  } from "./shepherdr-peer.mjs";
17
18
  import { readSessionView } from "./shepherdr-session.mjs";
18
19
  import { watchSessions } from "./shepherdr-session-watch.mjs";
19
20
 
20
- const BRIDGE_VERSION = 19;
21
+ const BRIDGE_VERSION = 20;
21
22
  const MAX_FRAME_BYTES = 8 * 1024 * 1024;
22
23
  const subscriptions = new Map();
23
24
  const contextRelays = new Map();
@@ -327,6 +328,8 @@ async function handle(message) {
327
328
  if (message.op === "message") {
328
329
  return sendPeerMessage(request, message.agent, message.message);
329
330
  }
331
+ if (message.op === "extension-reply")
332
+ return sendPeerExtensionReply(request, message.agent, message.reply);
330
333
  if (message.op === "identity") {
331
334
  return { host: hostname(), session: argument("session") || "default" };
332
335
  }
@@ -17,7 +17,7 @@ import type {
17
17
  SessionView,
18
18
  } from "./types.js";
19
19
 
20
- const BRIDGE_VERSION = 19;
20
+ const BRIDGE_VERSION = 20;
21
21
  const REMOTE_HELPER = "~/.pi/agent/shepherdr.mjs";
22
22
  const REMOTE_PEER_HELPER = "~/.pi/agent/shepherdr-peer.mjs";
23
23
  const REMOTE_CHANNEL_HELPER = "~/.pi/agent/shepherdr-channel.mjs";
@@ -310,6 +310,21 @@ export class RemoteHerdrClient implements HerdrConnection, AssistantReader {
310
310
  return this.relayPath;
311
311
  }
312
312
 
313
+ async replyExtension(
314
+ agent: PaneInfo,
315
+ reply: import("./types.js").ExtensionReply,
316
+ ): Promise<string> {
317
+ const result = await this.call(
318
+ { op: "extension-reply", agent, reply },
319
+ 60_000,
320
+ );
321
+ if (typeof result !== "string")
322
+ throw new Error(
323
+ "Invalid extension reply receipt; inspect the target before retrying",
324
+ );
325
+ return result;
326
+ }
327
+
313
328
  async commands(agent: PaneInfo): Promise<import("./types.js").PeerCommand[]> {
314
329
  const result = await this.call({ op: "commands", agent }, 26_000);
315
330
  return readPeerCommands(result);