@kingcrab/pi-imessage 1.2.2 → 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.
@@ -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",
@@ -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")
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,7 +625,7 @@ 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() {
@@ -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
  }
@@ -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/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.2",
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": {