@kingcrab/pi-imessage 1.2.1 → 1.2.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.
@@ -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.
@@ -8,15 +8,17 @@ export const Sessions = defineDoc({
8
8
  initial: () => ({ items: [] }),
9
9
  checkpointWhen: () => false,
10
10
  });
11
- /** Explicit health checks reuse one tool-less conversation and never deliver to a chat. */
11
+ /** Explicit health checks create a fresh tool-less conversation each time and never deliver to a chat. */
12
12
  export async function submitHealth(harness, defaults) {
13
13
  const key = JSON.stringify(["health", "model-health"]);
14
14
  const id = await harness.commit(async (tx) => {
15
15
  const sessions = await tx.doc(Sessions);
16
- const found = sessions.items.find((item) => item.key === key);
17
- const id = found?.conversationId ?? (await tx.createConversation({ ownership: { kind: "ownerless" } })).id;
16
+ const id = (await tx.createConversation({ ownership: { kind: "ownerless" } })).id;
18
17
  await configure(tx, id, { ...defaults, tools: [], instructions: "Reply OK. Do not use tools." });
19
- if (!found)
18
+ const found = sessions.items.find((item) => item.key === key);
19
+ if (found)
20
+ found.conversationId = id;
21
+ else
20
22
  sessions.items.push({
21
23
  key,
22
24
  label: "model-health",
@@ -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",
@@ -11,6 +11,11 @@ export const WebResults = defineDoc({
11
11
  initial: () => ({ queries: {} }),
12
12
  checkpointWhen: () => false,
13
13
  });
14
+ const FETCH_CONTENT_HEADERS = {
15
+ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
16
+ Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
17
+ "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
18
+ };
14
19
  async function fetchBounded(url, options = {}) {
15
20
  const parsed = new URL(url);
16
21
  if (!["http:", "https:"].includes(parsed.protocol) || parsed.username || parsed.password)
@@ -75,7 +80,10 @@ export function webExtension(apiKey = process.env.BRAVE_API_KEY ?? process.env.B
75
80
  parameters: Type.Object({ url: Type.String() }),
76
81
  replay: "safe",
77
82
  async execute(args, _api, context) {
78
- const result = await fetchBounded(args.url, { signal: context.abortSignal });
83
+ const result = await fetchBounded(args.url, {
84
+ headers: FETCH_CONTENT_HEADERS,
85
+ signal: context.abortSignal,
86
+ });
79
87
  const text = result.type.includes("pdf")
80
88
  ? (await extractText(new Uint8Array(result.bytes), { mergePages: true })).text
81
89
  : result.type.includes("html")
@@ -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
@@ -590,22 +590,30 @@ function renderScheduled() {
590
590
  if (!runs.length) body.append(element("p", "No executions yet.", "empty"));
591
591
  return body;
592
592
  }
593
- for (const job of data.jobs || []) {
593
+ function formatTokens(count) {
594
+ if (typeof count !== "number" || count <= 0) return "0 tok";
595
+ if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M tok`;
596
+ if (count >= 1_000) return `${(count / 1_000).toFixed(1)}k tok`;
597
+ return `${count} tok`;
598
+ }
599
+ const jobs = (data.jobs || [])
600
+ .filter((job) => job.enabled)
601
+ .toSorted((a, b) => (b.tokens || 0) - (a.tokens || 0));
602
+ for (const job of jobs) {
594
603
  const details = element("details", undefined, "schedule-row");
595
604
  details.id = `schedule-history-${job.id}`;
596
605
  const latest = job.runs?.[0];
597
- const status = !job.enabled
598
- ? "disabled"
599
- : ["aborted", "faulted", "failed", "missing"].includes(job.status)
600
- ? job.status
601
- : latest
602
- ? [latest.status, latest.delivery].filter(Boolean).join(" / ")
603
- : "enabled";
606
+ const status = ["aborted", "faulted", "failed", "missing"].includes(job.status)
607
+ ? job.status
608
+ : latest
609
+ ? [latest.status, latest.delivery].filter(Boolean).join(" / ")
610
+ : "enabled";
604
611
  const lastRun = latest ? time(latest.input?.startedAt, job.timezone) : "No executions yet";
605
612
  const cadence = job.time !== undefined ? `daily ${job.time}` : `every ${job.intervalMs / 3600000}h`;
606
613
  const summary = element("summary", undefined, "schedule-summary");
607
614
  summary.append(
608
615
  element("span", job.name, "schedule-name"),
616
+ element("span", formatTokens(job.tokens), "schedule-tokens"),
609
617
  element(
610
618
  "span",
611
619
  `${cadence} / Next: ${time(job.nextAt, job.timezone)} (${job.timezone})`,
@@ -617,11 +625,19 @@ function renderScheduled() {
617
625
  details.append(summary, history(job.runs || [], job.conversationId, job.timezone));
618
626
  view.append(details);
619
627
  }
620
- if (!data.jobs?.length) view.append(element("p", "No scheduled tasks.", "empty"));
628
+ if (!jobs.length) view.append(element("p", "No scheduled tasks.", "empty"));
621
629
  }
622
630
 
623
631
  function renderTasks() {
624
632
  view.replaceChildren();
633
+ if (!conversationId)
634
+ view.append(
635
+ element(
636
+ "p",
637
+ "5 most recently active chats. Open a chat's Task tree link to view an older conversation.",
638
+ "meta",
639
+ ),
640
+ );
625
641
  const children = new Map();
626
642
  const conversations = new Map(data.conversations.map((conversation) => [conversation.id, conversation]));
627
643
  const chatNames = new Map(
@@ -727,7 +743,7 @@ function setupToolbar() {
727
743
  if (page === "/chat" || page === "/tasks") {
728
744
  if (conversationId) {
729
745
  toolbar.className = "toolbar";
730
- toolbar.append(page === "/chat" ? link("< Messages", "/") : link("< All conversations", "/tasks"));
746
+ toolbar.append(page === "/chat" ? link("< Messages", "/") : link("< Recent conversations", "/tasks"));
731
747
  }
732
748
  } else if (page === "/memory") {
733
749
  const records = Array.isArray(data) ? memoryRows() : data.records;
@@ -1,11 +1,49 @@
1
1
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
+ import { UsageDoc, } from "@earendil-works/pi-durable";
2
3
  import { DirectSends } from "../agent/direct-send.js";
3
4
  import { EXECUTION_KIND, Schedules } from "../agent/scheduling.js";
5
+ function sumUsageTokens(usage) {
6
+ let total = 0;
7
+ for (const bucket of [usage.models, usage.tools]) {
8
+ for (const item of Object.values(bucket)) {
9
+ total += item.totalTokens || item.input + item.output + item.cacheRead + item.cacheWrite;
10
+ }
11
+ }
12
+ return total;
13
+ }
4
14
  /** Native occurrence tasks are the execution history; this view keeps no parallel log. */
5
- export function readSchedules(harness) {
6
- return harness.commit(async (tx) => {
15
+ export async function readSchedules(harness) {
16
+ const { jobs, conversationsByRoot } = await harness.commit(async (tx) => {
7
17
  const schedules = await tx.doc(Schedules);
8
18
  const sends = await tx.doc(DirectSends);
19
+ const roots = new Set(schedules.items.map((schedule) => schedule.conversationId));
20
+ const conversationsByRoot = new Map(schedules.items.map((schedule) => [schedule.conversationId, [schedule.conversationId]]));
21
+ if (roots.size > 0) {
22
+ const ownerOf = new Map();
23
+ let cursor;
24
+ do {
25
+ const page = await tx.scanConversations({}, 500, cursor);
26
+ for (const conversation of page.items) {
27
+ if (conversation.owner)
28
+ ownerOf.set(conversation.id, conversation.owner.conversationId);
29
+ }
30
+ cursor = page.next;
31
+ } while (cursor);
32
+ for (const id of ownerOf.keys()) {
33
+ if (roots.has(id))
34
+ continue;
35
+ const seen = new Set([id]);
36
+ let current = ownerOf.get(id);
37
+ while (current !== undefined && !seen.has(current)) {
38
+ if (roots.has(current)) {
39
+ conversationsByRoot.get(current)?.push(id);
40
+ break;
41
+ }
42
+ seen.add(current);
43
+ current = ownerOf.get(current);
44
+ }
45
+ }
46
+ }
9
47
  const jobs = [];
10
48
  for (const schedule of schedules.items) {
11
49
  const task = await tx.task(schedule.taskId);
@@ -49,15 +87,27 @@ export function readSchedules(harness) {
49
87
  status: task?.state.outcome?.status ?? task?.state.status ?? "missing",
50
88
  phase: state?.phase,
51
89
  nextAt: state?.phase === "sleep" ? state.at : undefined,
90
+ tokens: 0,
52
91
  runs,
53
92
  });
54
93
  }
55
- return {
56
- jobs,
57
- recent: jobs
58
- .flatMap((job) => job.runs.map((run) => ({ ...run, jobId: job.id, name: job.name })))
59
- .sort((a, b) => b.id - a.id)
60
- .slice(0, 10),
61
- };
94
+ return { jobs, conversationsByRoot };
62
95
  }, BACKGROUND_CONTEXT);
96
+ for (const job of jobs) {
97
+ let tokens = 0;
98
+ for (const id of conversationsByRoot.get(job.conversationId) ?? [job.conversationId]) {
99
+ const state = await harness.snapshot(UsageDoc, id, BACKGROUND_CONTEXT);
100
+ if (state)
101
+ tokens += sumUsageTokens(state);
102
+ }
103
+ job.tokens = tokens;
104
+ }
105
+ jobs.sort((a, b) => b.tokens - a.tokens);
106
+ return {
107
+ jobs,
108
+ recent: jobs
109
+ .flatMap((job) => job.runs.map((run) => ({ ...run, jobId: job.id, name: job.name })))
110
+ .sort((a, b) => b.id - a.id)
111
+ .slice(0, 10),
112
+ };
63
113
  }
@@ -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", () => {
@@ -447,8 +447,11 @@ body.page-logs .native-state {
447
447
 
448
448
  .schedule-summary {
449
449
  display: grid;
450
- grid-template-columns: 16px minmax(160px, 1fr) minmax(400px, 2fr) minmax(240px, 1.2fr) minmax(100px, 0.6fr);
451
- min-width: 980px;
450
+ grid-template-columns: 16px minmax(160px, 1fr) minmax(88px, 0.5fr) minmax(380px, 2fr) minmax(220px, 1.2fr) minmax(
451
+ 100px,
452
+ 0.6fr
453
+ );
454
+ min-width: 1060px;
452
455
  align-items: center;
453
456
  gap: 10px;
454
457
  padding: 12px 16px;
@@ -469,6 +472,7 @@ body.page-logs .native-state {
469
472
  }
470
473
 
471
474
  .schedule-name,
475
+ .schedule-tokens,
472
476
  .schedule-next,
473
477
  .schedule-last,
474
478
  .schedule-status {
@@ -478,6 +482,7 @@ body.page-logs .native-state {
478
482
  white-space: nowrap;
479
483
  }
480
484
 
485
+ .schedule-tokens,
481
486
  .schedule-next,
482
487
  .schedule-last,
483
488
  .schedule-status {
@@ -485,6 +490,10 @@ body.page-logs .native-state {
485
490
  white-space: nowrap;
486
491
  }
487
492
 
493
+ .schedule-tokens {
494
+ text-align: right;
495
+ }
496
+
488
497
  [hidden] {
489
498
  display: none;
490
499
  }
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/docs/install.md CHANGED
@@ -97,6 +97,11 @@ temporary HOME/workspace without models or Messages.
97
97
  `.github/workflows/publish.yml` uses the existing npm trusted publisher with
98
98
  GitHub OIDC, Node 24 and `id-token: write`; no local npm login or token is needed.
99
99
  It runs the full checks, tests and package smoke before publishing with provenance.
100
+ After `npm publish` succeeds, a separate `release` job with `contents: write`
101
+ creates the GitHub Release as `github-actions[bot]` if it does not already exist,
102
+ using the annotated tag message when present (create annotated tags with
103
+ `--cleanup=verbatim` so Markdown headings are preserved) or GitHub's generated
104
+ notes otherwise.
100
105
  Future releases push a matching `v<package-version>` tag. To publish an existing
101
106
  version after fixing packaging, dispatch the workflow on main with that exact
102
107
  version; never move an already published GitHub tag.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kingcrab/pi-imessage",
3
- "version": "1.2.1",
3
+ "version": "1.2.3",
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
  },