@howaboua/pi-shepherdr 0.1.1 → 0.1.3

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.
@@ -1,104 +1,242 @@
1
- import { readFile, stat } from "node:fs/promises";
2
- import type { LatestAssistant } from "./types.js";
1
+ import { open, stat } from "node:fs/promises";
2
+ import type {
3
+ LatestAssistant,
4
+ LatestUser,
5
+ PendingAsk,
6
+ SessionView,
7
+ } from "./types.js";
3
8
 
4
- interface SessionNode {
5
- assistant?: LatestAssistant;
6
- parentId?: string;
9
+ const READ_CHUNK_BYTES = 64 * 1024;
10
+
11
+ function record(value: unknown): Record<string, unknown> | undefined {
12
+ return typeof value === "object" && value !== null && !Array.isArray(value)
13
+ ? (value as Record<string, unknown>)
14
+ : undefined;
7
15
  }
8
16
 
9
- function latestAssistantFromLines(
10
- lines: string[],
17
+ function assistantFromMessage(
18
+ id: string,
19
+ message: Record<string, unknown>,
11
20
  ): LatestAssistant | undefined {
12
- const nodes = new Map<string, SessionNode>();
13
- let leafId: string | undefined;
14
- for (const line of lines) {
21
+ if (message["role"] !== "assistant") return undefined;
22
+ const text: string[] = [];
23
+ if (typeof message["content"] === "string") {
24
+ text.push(message["content"]);
25
+ } else if (Array.isArray(message["content"])) {
26
+ for (const value of message["content"]) {
27
+ const part = record(value);
28
+ if (part?.["type"] === "text" && typeof part["text"] === "string") {
29
+ text.push(part["text"]);
30
+ }
31
+ }
32
+ }
33
+ const joined = text.join("");
34
+ const stopReason =
35
+ typeof message["stopReason"] === "string"
36
+ ? message["stopReason"]
37
+ : undefined;
38
+ if (!joined && stopReason !== "error") return undefined;
39
+ return {
40
+ id,
41
+ text: joined,
42
+ ...(stopReason ? { stopReason } : {}),
43
+ };
44
+ }
45
+
46
+ function userFromMessage(
47
+ id: string,
48
+ message: Record<string, unknown>,
49
+ ): LatestUser | undefined {
50
+ if (message["role"] !== "user") return undefined;
51
+ const text: string[] = [];
52
+ if (typeof message["content"] === "string") {
53
+ text.push(message["content"]);
54
+ } else if (Array.isArray(message["content"])) {
55
+ for (const value of message["content"]) {
56
+ const part = record(value);
57
+ if (part?.["type"] === "text" && typeof part["text"] === "string") {
58
+ text.push(part["text"]);
59
+ }
60
+ }
61
+ }
62
+ const joined = text.join("");
63
+ return joined ? { id, text: joined } : undefined;
64
+ }
65
+
66
+ function askChoice(
67
+ value: unknown,
68
+ ): PendingAsk["prompts"][number]["choices"][number] | undefined {
69
+ const choice = record(value);
70
+ if (!choice || typeof choice["label"] !== "string") return undefined;
71
+ return {
72
+ label: choice["label"],
73
+ ...(typeof choice["description"] === "string"
74
+ ? { description: choice["description"] }
75
+ : {}),
76
+ };
77
+ }
78
+
79
+ function askPrompt(value: unknown): PendingAsk["prompts"][number] | undefined {
80
+ const prompt = record(value);
81
+ if (!prompt || typeof prompt["title"] !== "string") return undefined;
82
+ return {
83
+ title: prompt["title"],
84
+ multiple: prompt["multiple"] === true,
85
+ choices: (Array.isArray(prompt["choices"]) ? prompt["choices"] : [])
86
+ .map(askChoice)
87
+ .filter((choice): choice is NonNullable<typeof choice> =>
88
+ Boolean(choice),
89
+ ),
90
+ ...(typeof prompt["body"] === "string" ? { body: prompt["body"] } : {}),
91
+ };
92
+ }
93
+
94
+ function askCall(value: unknown): PendingAsk | undefined {
95
+ const part = record(value);
96
+ if (
97
+ !part ||
98
+ part["type"] !== "toolCall" ||
99
+ part["name"] !== "ask" ||
100
+ typeof part["id"] !== "string"
101
+ ) {
102
+ return undefined;
103
+ }
104
+ const args = record(part["arguments"]);
105
+ if (!args) return undefined;
106
+ const prompts = (Array.isArray(args["prompts"]) ? args["prompts"] : [])
107
+ .map(askPrompt)
108
+ .filter((prompt): prompt is NonNullable<typeof prompt> => Boolean(prompt));
109
+ if (prompts.length === 0) return undefined;
110
+ return {
111
+ toolCallId: part["id"],
112
+ handoff: args["handoff"] === true,
113
+ prompts,
114
+ };
115
+ }
116
+
117
+ function resolvedToolCallId(
118
+ message: Record<string, unknown>,
119
+ ): string | undefined {
120
+ if (message["role"] !== "toolResult" && message["role"] !== "tool") {
121
+ return undefined;
122
+ }
123
+ const value = message["toolCallId"] ?? message["tool_call_id"];
124
+ return typeof value === "string" ? value : undefined;
125
+ }
126
+
127
+ async function readSessionView(
128
+ path: string,
129
+ size: number,
130
+ ): Promise<SessionView> {
131
+ const file = await open(path, "r");
132
+ let targetId: string | undefined;
133
+ let assistant: LatestAssistant | undefined;
134
+ let assistantDepth: number | undefined;
135
+ let ask: PendingAsk | undefined;
136
+ let depth = 0;
137
+ let user: LatestUser | undefined;
138
+ let userDepth: number | undefined;
139
+ const resolved = new Set<string>();
140
+ const result = (): SessionView => ({
141
+ ...(assistant ? { assistant } : {}),
142
+ ...(ask ? { ask } : {}),
143
+ ...(user ? { user } : {}),
144
+ ...(assistantDepth !== undefined && userDepth !== undefined
145
+ ? { assistantAfterUser: assistantDepth < userDepth }
146
+ : {}),
147
+ });
148
+ const inspect = (line: Buffer): boolean => {
149
+ if (line.length === 0) return false;
15
150
  let entry: Record<string, unknown>;
16
151
  try {
17
- entry = JSON.parse(line) as Record<string, unknown>;
152
+ entry = JSON.parse(line.toString("utf8")) as Record<string, unknown>;
18
153
  } catch {
19
- continue;
154
+ return false;
20
155
  }
21
- if (typeof entry["id"] !== "string") continue;
22
- const node: SessionNode = {
23
- ...(typeof entry["parentId"] === "string"
24
- ? { parentId: entry["parentId"] }
25
- : {}),
26
- };
27
- const message = entry["message"];
28
- if (
29
- typeof message === "object" &&
30
- message !== null &&
31
- "role" in message &&
32
- message.role === "assistant"
33
- ) {
34
- const text: string[] = [];
35
- if ("content" in message && typeof message.content === "string") {
36
- text.push(message.content);
37
- } else if ("content" in message && Array.isArray(message.content)) {
38
- for (const part of message.content) {
39
- if (
40
- typeof part === "object" &&
41
- part !== null &&
42
- "type" in part &&
43
- part.type === "text" &&
44
- "text" in part &&
45
- typeof part.text === "string"
46
- ) {
47
- text.push(part.text);
48
- }
49
- }
156
+ const id = entry["id"];
157
+ if (typeof id !== "string") return false;
158
+ targetId ??= id;
159
+ if (id !== targetId) return false;
160
+ const currentDepth = depth;
161
+ depth += 1;
162
+ const message = record(entry["message"]);
163
+ if (message) {
164
+ const resolvedId = resolvedToolCallId(message);
165
+ if (resolvedId) resolved.add(resolvedId);
166
+ if (!assistant) {
167
+ assistant = assistantFromMessage(id, message);
168
+ if (assistant) assistantDepth = currentDepth;
169
+ }
170
+ if (!user) {
171
+ user = userFromMessage(id, message);
172
+ if (user) userDepth = currentDepth;
50
173
  }
51
- const joined = text.join("");
52
- const stopReason =
53
- "stopReason" in message && typeof message.stopReason === "string"
54
- ? message.stopReason
55
- : undefined;
56
- if (joined || stopReason === "error") {
57
- node.assistant = {
58
- id: entry["id"],
59
- text: joined,
60
- ...(stopReason ? { stopReason } : {}),
61
- };
174
+ if (
175
+ !ask &&
176
+ message["role"] === "assistant" &&
177
+ Array.isArray(message["content"])
178
+ ) {
179
+ ask = [...message["content"]]
180
+ .reverse()
181
+ .map(askCall)
182
+ .find(
183
+ (candidate) =>
184
+ candidate !== undefined && !resolved.has(candidate.toolCallId),
185
+ );
62
186
  }
63
187
  }
64
- nodes.set(entry["id"], node);
65
- leafId = entry["id"];
66
- }
188
+ const parentId = entry["parentId"];
189
+ if (typeof parentId !== "string") return true;
190
+ targetId = parentId;
191
+ return false;
192
+ };
67
193
 
68
- const visited = new Set<string>();
69
- let current = leafId;
70
- while (current && !visited.has(current)) {
71
- visited.add(current);
72
- const node = nodes.get(current);
73
- if (!node) break;
74
- if (node.assistant) return node.assistant;
75
- current = node.parentId;
194
+ try {
195
+ let position = size;
196
+ let partial = Buffer.alloc(0);
197
+ while (position > 0) {
198
+ const length = Math.min(READ_CHUNK_BYTES, position);
199
+ position -= length;
200
+ const chunk = Buffer.allocUnsafe(length);
201
+ const { bytesRead } = await file.read(chunk, 0, length, position);
202
+ const data = Buffer.concat([chunk.subarray(0, bytesRead), partial]);
203
+ let lineEnd = data.length;
204
+ for (let index = data.length - 1; index >= 0; index -= 1) {
205
+ if (data[index] !== 0x0a) continue;
206
+ if (inspect(data.subarray(index + 1, lineEnd))) {
207
+ return result();
208
+ }
209
+ lineEnd = index;
210
+ }
211
+ partial = data.subarray(0, lineEnd);
212
+ }
213
+ inspect(partial);
214
+ return result();
215
+ } finally {
216
+ await file.close();
76
217
  }
77
- return undefined;
78
218
  }
79
219
 
80
220
  export class SessionReader {
81
221
  private readonly cache = new Map<
82
222
  string,
83
- { mtimeMs: number; result: LatestAssistant | undefined; size: number }
223
+ { mtimeMs: number; result: SessionView; size: number }
84
224
  >();
85
225
 
86
- async latest(path?: string): Promise<LatestAssistant | undefined> {
87
- if (!path) return undefined;
226
+ async view(path?: string): Promise<SessionView> {
227
+ if (!path) return {};
88
228
  let metadata;
89
229
  try {
90
230
  metadata = await stat(path);
91
231
  } catch (error) {
92
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
232
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return {};
93
233
  throw error;
94
234
  }
95
235
  const cached = this.cache.get(path);
96
236
  if (cached?.size === metadata.size && cached.mtimeMs === metadata.mtimeMs) {
97
237
  return cached.result;
98
238
  }
99
- const result = latestAssistantFromLines(
100
- (await readFile(path, "utf8")).split("\n"),
101
- );
239
+ const result = await readSessionView(path, metadata.size);
102
240
  this.cache.set(path, {
103
241
  mtimeMs: metadata.mtimeMs,
104
242
  result,
@@ -106,4 +244,13 @@ export class SessionReader {
106
244
  });
107
245
  return result;
108
246
  }
247
+
248
+ async latest(path?: string): Promise<LatestAssistant | undefined> {
249
+ return (await this.view(path)).assistant;
250
+ }
251
+ }
252
+
253
+ export interface AssistantReader {
254
+ latest(path?: string): Promise<LatestAssistant | undefined>;
255
+ view(path?: string): Promise<SessionView>;
109
256
  }