@kingcrab/pi-imessage 1.2.0 → 1.2.2

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,6 +1,6 @@
1
1
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
- import { AssistantEntry, } from "@earendil-works/pi-durable";
3
- import { finalReplyText } from "../extensions/final-text.js";
2
+ import { AssistantEntry, UserEntry, } from "@earendil-works/pi-durable";
3
+ import { finalReplyText, interimText } from "../extensions/final-text.js";
4
4
  import { Chats } from "./chats.js";
5
5
  import { DirectSends } from "./direct-send.js";
6
6
  import { Deliveries } from "./replies.js";
@@ -83,29 +83,57 @@ async function deliverAnswer(harness, storage, target, answerId, send) {
83
83
  // Do not overtake an earlier in-flight send in this chat.
84
84
  if (Object.values(deliveries.answers).includes("sending"))
85
85
  return { decided: false };
86
+ // The same text already went out beside a tool call in this turn: the user has seen it.
87
+ const sends = (await tx.doc(DirectSends)).requests;
88
+ let echoed;
89
+ let turnCursor;
90
+ do {
91
+ const page = await tx.scanEntries({ conversationId, maxEntryId: answerId }, 100, turnCursor);
92
+ for (const entry of page.items) {
93
+ if (UserEntry.is(entry)) {
94
+ turnCursor = undefined;
95
+ break;
96
+ }
97
+ if (!AssistantEntry.is(entry) || interimText(entry.model?.[0]) !== text)
98
+ continue;
99
+ const status = sends.find((send) => send.chatGuid === target.chatGuid && send.requestId === `interim:${entry.id}`)?.textStatus;
100
+ if (status === "sent" || status === "sending")
101
+ echoed = status;
102
+ if (echoed)
103
+ break;
104
+ }
105
+ turnCursor = echoed ? undefined : page.next;
106
+ } while (turnCursor);
107
+ // Wait for that send to settle instead of racing it.
108
+ if (echoed === "sending")
109
+ return { decided: false };
86
110
  // Finals are claimed in order, so the only earlier unsent ones are held drafts; this answer replaces them.
87
111
  const drafts = deliveries.drafts ?? {};
88
112
  for (const [previous, draft] of Object.entries(drafts))
89
113
  if (draft.status === "held" && Number(previous) < answerId)
90
114
  drafts[previous] = { status: "superseded", replacement: answerId };
91
- deliveries.answers[key] = "sending";
92
- return { decided: decided(), text };
115
+ deliveries.answers[key] = echoed ?? "sending";
116
+ return { decided: decided(), text, echoed: echoed === "sent" };
93
117
  }, BACKGROUND_CONTEXT);
94
118
  if (!claim.text)
95
119
  return claim.decided;
96
120
  let status = "sent";
97
- try {
98
- await send(target.chatGuid, claim.text);
99
- }
100
- catch {
101
- // A throwing transport may already have sent. Never retry it automatically.
102
- status = "unknown";
121
+ if (claim.echoed)
122
+ console.log("Reply already sent as interim", conversationId, String(answerId));
123
+ else {
124
+ try {
125
+ await send(target.chatGuid, claim.text);
126
+ }
127
+ catch {
128
+ // A throwing transport may already have sent. Never retry it automatically.
129
+ status = "unknown";
130
+ }
131
+ await harness.commit(async (tx) => {
132
+ (await tx.doc(Deliveries, conversationId)).answers[String(answerId)] = status;
133
+ }, BACKGROUND_CONTEXT);
134
+ if (status === "unknown")
135
+ console.warn("Reply delivery unknown", conversationId, String(answerId));
103
136
  }
104
- await harness.commit(async (tx) => {
105
- (await tx.doc(Deliveries, conversationId)).answers[String(answerId)] = status;
106
- }, BACKGROUND_CONTEXT);
107
- if (status === "unknown")
108
- console.warn("Reply delivery unknown", conversationId, String(answerId));
109
137
  if (target.chat !== undefined) {
110
138
  // A queued write never splits a turn that is running in the chat conversation.
111
139
  const chat = await harness.conversation(target.chat, BACKGROUND_CONTEXT);
@@ -33,8 +33,8 @@ export async function openHarness(workingDir, models, extensions, policy) {
33
33
  env: () => env,
34
34
  // Consume all admitted corrections at the next native boundary, not one per turn.
35
35
  // Durable's own failure channel: faulted, parked and outdated tasks reach the service log with their type.
36
- onReport(error, info) {
37
- console.error(new Date().toISOString(), "Durable report", info, error);
36
+ onReport(report) {
37
+ console.error(new Date().toISOString(), "Durable report", report);
38
38
  },
39
39
  settings: {
40
40
  // A failed run leaves no inputs stranded until the next message.
@@ -146,53 +146,56 @@ export async function startProgress(harness, workingDir, sender) {
146
146
  if (receipt.textStatus === "unknown")
147
147
  console.warn("Progress completion delivery unknown", task.id, notice.chatGuid);
148
148
  }
149
- const unsubscribe = harness.subscribeCommits(({ changes }) => {
150
- // Change order is unspecified; queue the model's words before the notices of the calls it made.
151
- for (const change of changes) {
152
- if (change.type !== "entry")
153
- continue;
154
- const entry = change.value;
155
- pending = pending
156
- .then(() => interim(entry))
157
- .catch((error) => {
158
- console.warn("Interim delivery failed", entry.id, error);
159
- });
160
- }
161
- for (const change of changes) {
162
- if (change.type !== "task" || change.value.kind === "pi.generation")
163
- continue;
164
- const task = change.value;
165
- if (task.state.status === "terminal") {
166
- seen.delete(task.id);
167
- const notice = active.get(task.id);
168
- active.delete(task.id);
169
- if (notice) {
170
- const elapsed = performance.now() - notice.admittedAt;
171
- pending = pending
172
- .then(() => settled(task, notice, elapsed))
173
- .catch((error) => {
174
- console.warn("Progress completion notification failed", task.id, error);
175
- });
149
+ const observation = harness.observeCommits({
150
+ advance({ changes }) {
151
+ // Change order is unspecified; queue the model's words before the notices of the calls it made.
152
+ for (const change of changes) {
153
+ if (change.type !== "entry")
154
+ continue;
155
+ const entry = change.value;
156
+ pending = pending
157
+ .then(() => interim(entry))
158
+ .catch((error) => {
159
+ console.warn("Interim delivery failed", entry.id, error);
160
+ });
161
+ }
162
+ for (const change of changes) {
163
+ if (change.type !== "task" || change.value.kind === "pi.generation")
164
+ continue;
165
+ const task = change.value;
166
+ if (task.state.status === "terminal") {
167
+ seen.delete(task.id);
168
+ const notice = active.get(task.id);
169
+ active.delete(task.id);
170
+ if (notice) {
171
+ const elapsed = performance.now() - notice.admittedAt;
172
+ pending = pending
173
+ .then(() => settled(task, notice, elapsed))
174
+ .catch((error) => {
175
+ console.warn("Progress completion notification failed", task.id, error);
176
+ });
177
+ }
178
+ continue;
176
179
  }
177
- continue;
180
+ if (task.state.status !== "pending" || seen.has(task.id))
181
+ continue;
182
+ seen.add(task.id);
183
+ const notice = { admittedAt: performance.now() };
184
+ active.set(task.id, notice);
185
+ // The synchronous observer must not call Session APIs or block adoption.
186
+ pending = pending
187
+ .then(() => notify(task, notice))
188
+ .catch((error) => {
189
+ console.warn("Progress notification failed", task.id, error);
190
+ });
178
191
  }
179
- if (task.state.status !== "pending" || seen.has(task.id))
180
- continue;
181
- seen.add(task.id);
182
- const notice = { admittedAt: performance.now() };
183
- active.set(task.id, notice);
184
- // The synchronous observer must not call Session APIs or block adoption.
185
- pending = pending
186
- .then(() => notify(task, notice))
187
- .catch((error) => {
188
- console.warn("Progress notification failed", task.id, error);
189
- });
190
- }
192
+ },
193
+ end() { },
191
194
  });
192
195
  return {
193
196
  flush: () => pending,
194
197
  async close() {
195
- unsubscribe();
198
+ observation.detach();
196
199
  await pending;
197
200
  },
198
201
  };
package/dist/agent/run.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
- import { Type } from "@earendil-works/pi-ai";
3
2
  import { AssistantEntry, configure, defineDoc, defineExtension, defineTask, defineTool, GenerationTask, hook, InboxDoc, LiveDoc, section, } from "@earendil-works/pi-durable";
3
+ import { Type } from "typebox";
4
4
  import { finalReplyText } from "../extensions/final-text.js";
5
5
  import { Deliveries } from "./replies.js";
6
6
  /** Every `/run`; ended runs stay listed so their last answers can still be delivered. */
@@ -2,8 +2,8 @@ import { execFile } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
3
  import { chmod, lstat, mkdir, open, readdir, readFile, realpath, rename, writeFile } from "node:fs/promises";
4
4
  import { dirname, join, resolve } from "node:path";
5
- import { Type } from "@earendil-works/pi-ai";
6
5
  import { defineExtension, defineTool, section } from "@earendil-works/pi-durable";
6
+ import { Type } from "typebox";
7
7
  const actions = [
8
8
  "open",
9
9
  "goto",
@@ -2,8 +2,8 @@ import { execFile } from "node:child_process";
2
2
  import { readFile } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
4
  import { promisify } from "node:util";
5
- import { Type } from "@earendil-works/pi-ai";
6
5
  import { defineExtension, defineTool, section } from "@earendil-works/pi-durable";
6
+ import { Type } from "typebox";
7
7
  const run = promisify(execFile);
8
8
  /** The store's own CLI finds its data next to itself; we only pass arguments. */
9
9
  async function memoryCli(workingDir, args, signal) {
@@ -1,5 +1,5 @@
1
- import { Type } from "@earendil-works/pi-ai";
2
1
  import { defineExtension, defineTool, section } from "@earendil-works/pi-durable";
2
+ import { Type } from "typebox";
3
3
  export function messageExtension(messaging) {
4
4
  return defineExtension({
5
5
  name: "messaging",
@@ -20,6 +20,7 @@ export const ImageRead = defineExtension({
20
20
  const path = getOrThrow(await api.env.canonicalPath(args.path, context));
21
21
  return {
22
22
  output: [{ type: "text", text: imagePrefix + JSON.stringify(path) }],
23
+ structuredOutput: imagePrefix + JSON.stringify(path),
23
24
  details: { imagePath: path },
24
25
  };
25
26
  },
@@ -1,5 +1,5 @@
1
- import { Type } from "@earendil-works/pi-ai";
2
1
  import { configure, defineExtension, defineTool } from "@earendil-works/pi-durable";
2
+ import { Type } from "typebox";
3
3
  import { finalReplyText } from "./final-text.js";
4
4
  export const Subagent = defineExtension({
5
5
  name: "subagent",
@@ -1,6 +1,6 @@
1
- import { Type } from "@earendil-works/pi-ai";
2
1
  import { defineDoc, defineExtension, defineTool } from "@earendil-works/pi-durable";
3
2
  import { Defuddle } from "defuddle/node";
3
+ import { Type } from "typebox";
4
4
  import { extractText } from "unpdf";
5
5
  export const WebResults = defineDoc({
6
6
  kind: "imessage.web-results",
@@ -1,9 +1,9 @@
1
1
  import { readdir, readFile, realpath } from "node:fs/promises";
2
2
  import { createRequire } from "node:module";
3
3
  import { join, sep } from "node:path";
4
- import { Type } from "@earendil-works/pi-ai";
5
4
  import * as durable from "@earendil-works/pi-durable";
6
5
  import { configure, defineDoc, defineExtension, defineTask, defineTool, GenerationTask, hook, section, } from "@earendil-works/pi-durable";
6
+ import { Type } from "typebox";
7
7
  import { ScheduledOutbox, validateSchedules, } from "./schedules.js";
8
8
  const loadModule = createRequire(import.meta.url);
9
9
  /** A chat assistant can apply its own workspace changes through the existing host owner. */
package/dist/web/app.js CHANGED
@@ -622,6 +622,14 @@ function renderScheduled() {
622
622
 
623
623
  function renderTasks() {
624
624
  view.replaceChildren();
625
+ if (!conversationId)
626
+ view.append(
627
+ element(
628
+ "p",
629
+ "5 most recently active chats. Open a chat's Task tree link to view an older conversation.",
630
+ "meta",
631
+ ),
632
+ );
625
633
  const children = new Map();
626
634
  const conversations = new Map(data.conversations.map((conversation) => [conversation.id, conversation]));
627
635
  const chatNames = new Map(
@@ -727,7 +735,7 @@ function setupToolbar() {
727
735
  if (page === "/chat" || page === "/tasks") {
728
736
  if (conversationId) {
729
737
  toolbar.className = "toolbar";
730
- toolbar.append(page === "/chat" ? link("< Messages", "/") : link("< All conversations", "/tasks"));
738
+ toolbar.append(page === "/chat" ? link("< Messages", "/") : link("< Recent conversations", "/tasks"));
731
739
  }
732
740
  } else if (page === "/memory") {
733
741
  const records = Array.isArray(data) ? memoryRows() : data.records;
@@ -189,12 +189,18 @@ export async function startWeb(options) {
189
189
  if (url.pathname === "/events") {
190
190
  response.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-store" });
191
191
  response.write(`event: ready\ndata: ${JSON.stringify({ revision: viewRevision() })}\n\n`);
192
- const unsubscribe = options.agent.harness.subscribeCommits(() => {
193
- if (!response.write('data: {"updated":true}\n\n')) {
194
- unsubscribe();
195
- response.destroy();
196
- }
192
+ const observation = options.agent.harness.observeCommits({
193
+ advance() {
194
+ if (!response.write('data: {"updated":true}\n\n')) {
195
+ observation.detach();
196
+ response.destroy();
197
+ }
198
+ },
199
+ end() {
200
+ response.end();
201
+ },
197
202
  });
203
+ const unsubscribe = () => observation.detach();
198
204
  streams.set(response, unsubscribe);
199
205
  response.on("error", () => {
200
206
  unsubscribe();
@@ -281,7 +287,14 @@ export async function startWeb(options) {
281
287
  }
282
288
  else if (page === "/tasks") {
283
289
  value = {
284
- ...(await readTaskTree(options.agent.harness)),
290
+ ...(await readTaskTree(options.agent.harness, url.searchParams.has("conversationId")
291
+ ? (() => {
292
+ const id = url.searchParams.get("conversationId") ?? "";
293
+ if (!/^\d+$/.test(id) || !Number.isSafeInteger(Number(id)))
294
+ throw new Error("Invalid conversation ID");
295
+ return Number(id);
296
+ })()
297
+ : undefined)),
285
298
  schedules: await options.agent.harness.snapshot(Schedules, BACKGROUND_CONTEXT),
286
299
  chats: await options.agent.harness.snapshot(Chats, BACKGROUND_CONTEXT),
287
300
  sessions: await options.agent.harness.snapshot(Sessions, BACKGROUND_CONTEXT),
@@ -354,10 +367,14 @@ export async function startWeb(options) {
354
367
  }
355
368
  await send(response, 200, "text/html; charset=utf-8", renderPage(page, redact(value, compact, page !== "/memory")));
356
369
  }
357
- const unsubscribeRevision = options.agent.harness.subscribeCommits((publication) => {
358
- if (publication.changes.length)
359
- revision++;
370
+ const revisionObservation = options.agent.harness.observeCommits({
371
+ advance(publication) {
372
+ if (publication.changes.length)
373
+ revision++;
374
+ },
375
+ end() { },
360
376
  });
377
+ const unsubscribeRevision = () => revisionObservation.detach();
361
378
  await new Promise((resolve, reject) => {
362
379
  server.once("error", reject);
363
380
  server.listen(options.port ?? 7750, options.host ?? "localhost", () => {
package/dist/web/tasks.js CHANGED
@@ -1,58 +1,72 @@
1
1
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
+ import { Chats } from "../agent/chats.js";
2
3
  import { displayHistory, historyActivity } from "./history.js";
3
4
  /** Newest tasks listed per conversation; older finished ones are only flagged. */
4
5
  export const RECENT_TASKS_PER_CONVERSATION = 20;
5
- /**
6
- * Read one consistent tree, newest first: all conversations, every unfinished task, every task that owns a
7
- * conversation, their parent chains and the newest tasks of each conversation. Descending scans stop at the
8
- * window instead of reading the whole task history (earendil-works/pi#10546).
9
- */
10
- export function readTaskTree(harness) {
6
+ /** Read only the five most recently active chats, or one explicitly selected conversation. */
7
+ export function readTaskTree(harness, conversationId) {
11
8
  return harness.commit(async (tx) => {
12
9
  const conversations = [];
13
10
  const kept = new Map();
14
11
  const more = {};
15
- let cursor;
16
- do {
17
- const page = await tx.scanConversations({}, 100, cursor);
18
- for (const conversation of page.items) {
19
- const history = await tx.scanEntries({ conversationId: conversation.id }, 100);
20
- const { groupName } = displayHistory(history, 1);
21
- conversations.push({
22
- ...conversation,
23
- updatedAt: historyActivity(history),
24
- groupName: typeof groupName === "string" ? groupName : undefined,
25
- });
26
- const newest = await tx.scanTasks({ conversationId: conversation.id, order: "descending" }, RECENT_TASKS_PER_CONVERSATION + 1);
27
- for (const task of newest.items.slice(0, RECENT_TASKS_PER_CONVERSATION))
28
- kept.set(task.id, task);
29
- if (newest.items.length > RECENT_TASKS_PER_CONVERSATION)
30
- more[conversation.id] = true;
31
- if (conversation.owner && !kept.has(conversation.owner.taskId)) {
32
- const owner = await tx.task(conversation.owner.taskId);
33
- if (owner)
34
- kept.set(owner.id, owner);
12
+ const chats = await tx.doc(Chats);
13
+ const candidates = [];
14
+ for (const id of conversationId === undefined
15
+ ? chats.items.map((chat) => chat.conversationId)
16
+ : [conversationId]) {
17
+ const conversation = await tx.conversation(id);
18
+ if (!conversation)
19
+ continue;
20
+ const history = await tx.scanEntries({ conversationId: id }, 100);
21
+ const { groupName } = displayHistory(history, 1);
22
+ candidates.push({
23
+ ...conversation,
24
+ updatedAt: historyActivity(history),
25
+ groupName: typeof groupName === "string" ? groupName : undefined,
26
+ });
27
+ }
28
+ const selected = candidates
29
+ .sort((a, b) => b.updatedAt - a.updatedAt || Number(b.id) - Number(a.id))
30
+ .slice(0, 5);
31
+ const queued = new Set(selected.map((conversation) => conversation.id));
32
+ // Expand only children owned by tasks in this window, not every historical subagent.
33
+ for (const conversation of selected) {
34
+ conversations.push(conversation);
35
+ const newest = await tx.scanTasks({ conversationId: conversation.id, order: "descending" }, RECENT_TASKS_PER_CONVERSATION + 1);
36
+ const local = new Map(newest.items.slice(0, RECENT_TASKS_PER_CONVERSATION).map((task) => [task.id, task]));
37
+ if (newest.items.length > RECENT_TASKS_PER_CONVERSATION)
38
+ more[conversation.id] = true;
39
+ for (const status of ["pending", "running", "waiting", "sleeping", "completing"]) {
40
+ let cursor;
41
+ do {
42
+ const page = await tx.scanTasks({ conversationId: conversation.id, status }, 100, cursor);
43
+ for (const task of page.items)
44
+ local.set(task.id, task);
45
+ cursor = page.next;
46
+ } while (cursor);
47
+ }
48
+ for (const task of local.values()) {
49
+ for (let owner = task.owner; owner !== undefined && !local.has(owner) && !kept.has(owner);) {
50
+ const parent = await tx.task(owner);
51
+ if (!parent)
52
+ break;
53
+ local.set(parent.id, parent);
54
+ owner = parent.owner;
35
55
  }
36
56
  }
37
- cursor = page.next;
38
- } while (cursor);
39
- // Unfinished tasks can be old (sleeping schedulers); status scans are small.
40
- for (const status of ["pending", "running", "waiting", "sleeping"]) {
41
- cursor = undefined;
42
- do {
43
- const page = await tx.scanTasks({ status, order: "descending" }, 100, cursor);
44
- for (const task of page.items)
45
- kept.set(task.id, task);
46
- cursor = page.next;
47
- } while (cursor);
48
- }
49
- // A kept child needs its parent chain so the tree can place it.
50
- for (const task of [...kept.values()]) {
51
- for (let owner = task.owner; owner !== undefined && !kept.has(owner); owner = kept.get(owner)?.owner) {
52
- const parent = await tx.task(owner);
53
- if (!parent)
54
- break;
55
- kept.set(parent.id, parent);
57
+ for (const task of local.values()) {
58
+ kept.set(task.id, task);
59
+ let cursor;
60
+ do {
61
+ const page = await tx.scanConversations({ ownerTaskId: task.id }, 100, cursor);
62
+ for (const child of page.items) {
63
+ if (queued.has(child.id))
64
+ continue;
65
+ queued.add(child.id);
66
+ selected.push({ ...child, updatedAt: conversation.updatedAt, groupName: undefined });
67
+ }
68
+ cursor = page.next;
69
+ } while (cursor);
56
70
  }
57
71
  }
58
72
  const assistants = new Map();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kingcrab/pi-imessage",
3
- "version": "1.2.0",
3
+ "version": "1.2.2",
4
4
  "description": "A minimal, self-managing iMessage bot powered by Pi Durable",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -32,14 +32,15 @@
32
32
  "test": "vitest run"
33
33
  },
34
34
  "dependencies": {
35
- "@earendil-works/chord": "1.4.0",
36
- "@earendil-works/pi-ai": "1.4.0",
37
- "@earendil-works/pi-codemode": "1.4.0",
38
- "@earendil-works/pi-coding-agent": "1.4.0",
39
- "@earendil-works/pi-durable": "1.4.0",
35
+ "@earendil-works/chord": "1.5.2",
36
+ "@earendil-works/pi-ai": "1.5.2",
37
+ "@earendil-works/pi-codemode": "1.5.2",
38
+ "@earendil-works/pi-coding-agent": "1.5.2",
39
+ "@earendil-works/pi-durable": "1.5.2",
40
40
  "better-sqlite3": "13.0.3",
41
41
  "defuddle": "0.19.4",
42
42
  "sharp": "0.35.5",
43
+ "typebox": "1.3.27",
43
44
  "undici": "8.10.2",
44
45
  "unpdf": "1.8.1"
45
46
  },