@kingcrab/pi-imessage 0.0.42 → 1.0.0

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.
Files changed (183) hide show
  1. package/README.md +101 -108
  2. package/dist/agent/behavior.js +79 -0
  3. package/dist/agent/chats.js +67 -0
  4. package/dist/agent/commands.js +163 -0
  5. package/dist/agent/compaction.js +51 -0
  6. package/dist/agent/deliver.js +139 -0
  7. package/dist/agent/direct-send.js +68 -0
  8. package/dist/agent/harness.js +79 -0
  9. package/dist/agent/health.js +32 -0
  10. package/dist/agent/models.js +69 -0
  11. package/dist/agent/progress-format.js +87 -0
  12. package/dist/agent/progress.js +135 -0
  13. package/dist/agent/prompt.js +79 -0
  14. package/dist/agent/replies.js +9 -0
  15. package/dist/agent/run.js +159 -0
  16. package/dist/agent/scheduling.js +290 -0
  17. package/dist/agent/time.js +18 -0
  18. package/dist/cli.js +88 -191
  19. package/dist/config/settings.js +60 -0
  20. package/dist/extensions/browser.js +326 -0
  21. package/dist/extensions/final-text.js +23 -0
  22. package/dist/extensions/memory.js +109 -0
  23. package/dist/extensions/message.js +33 -0
  24. package/dist/extensions/read-image.js +72 -0
  25. package/dist/extensions/schedules.js +41 -0
  26. package/dist/extensions/subagent.js +54 -0
  27. package/dist/extensions/web.js +99 -0
  28. package/dist/extensions/workspace.js +98 -0
  29. package/dist/main.js +571 -74
  30. package/dist/transport/attachments.js +37 -0
  31. package/dist/transport/http.js +110 -0
  32. package/dist/{rich-text.js → transport/rich-text.js} +25 -13
  33. package/dist/{send.js → transport/send.js} +13 -13
  34. package/dist/transport/watch.js +124 -0
  35. package/dist/web/app.js +748 -0
  36. package/dist/web/history.js +87 -0
  37. package/dist/web/memory.js +81 -0
  38. package/dist/web/page.js +28 -0
  39. package/dist/web/schedules.js +74 -0
  40. package/dist/web/server.js +348 -0
  41. package/dist/web/style.css +543 -0
  42. package/dist/web/tasks.js +63 -0
  43. package/docs/adr/0001-durable-owns-state.md +11 -0
  44. package/docs/adr/0002-module-layering.md +11 -0
  45. package/docs/adr/0003-replies-at-most-once.md +11 -0
  46. package/docs/adr/0004-native-extensions.md +11 -0
  47. package/docs/adr/0005-history-migration.md +11 -0
  48. package/docs/adr/0006-jsonl-storage.md +11 -0
  49. package/docs/adr/0007-images-by-path.md +11 -0
  50. package/docs/adr/0008-compaction-and-run.md +11 -0
  51. package/docs/adr/0009-one-shot-cutover.md +11 -0
  52. package/docs/adr/0010-test-budget.md +11 -0
  53. package/docs/adr/0011-reconcile-unsent-answers.md +24 -0
  54. package/docs/adr/0012-run-in-owned-conversation.md +22 -0
  55. package/docs/adr/0013-thin-adapters-around-durable.md +18 -0
  56. package/docs/adr/0014-ephemeral-private-storage.md +13 -0
  57. package/docs/adr/0015-ordinary-stop-keeps-native-inbox.md +21 -0
  58. package/docs/adr/0016-process-http-transport.md +21 -0
  59. package/docs/adr/0017-browser-cli-owned-scope.md +22 -0
  60. package/docs/adr/0018-tasks-without-prompt-api.md +19 -0
  61. package/docs/adr/0019-remove-scheduled-services.md +41 -0
  62. package/docs/adr/0020-chat-task-progress.md +41 -0
  63. package/docs/adr/0021-readable-progress-without-link-previews.md +33 -0
  64. package/docs/adr/0022-progress-admission-and-settlement.md +35 -0
  65. package/docs/adr/0023-retain-progress-type-prefixes.md +18 -0
  66. package/docs/adr/0024-status-marker-before-type-prefix.md +13 -0
  67. package/docs/adr/0025-reusable-progress-and-command-preview.md +49 -0
  68. package/docs/adr/0026-inline-command-only-requests.md +16 -0
  69. package/docs/adr/0027-command-preview-width.md +10 -0
  70. package/docs/adr/0028-command-preview-120.md +8 -0
  71. package/docs/adr/0030-shared-web-read-cache.md +33 -0
  72. package/docs/adr/0031-quiet-compaction-progress.md +32 -0
  73. package/docs/adr/0032-native-background-schedules.md +58 -0
  74. package/docs/adr/0033-operator-scheduled-run.md +23 -0
  75. package/docs/adr/0034-machine-local-schedule-time.md +36 -0
  76. package/docs/adr/0035-external-business-task-extensions.md +56 -0
  77. package/docs/adr/0036-workspace-policy-and-neutral-service-id.md +37 -0
  78. package/docs/adr/0037-restart-during-in-flight-work.md +30 -0
  79. package/docs/adr/0038-restart-any-time.md +25 -0
  80. package/docs/adr/0039-rerun-interrupted-tools.md +24 -0
  81. package/docs/adr/0040-chat-progress-notices.md +44 -0
  82. package/docs/adr/0041-restart-and-recovery.md +28 -0
  83. package/docs/adr/0042-background-schedules-and-workspace-extensions.md +44 -0
  84. package/docs/adr/0043-remove-legacy-migration.md +23 -0
  85. package/docs/adr/0044-message-channels.md +32 -0
  86. package/docs/adr/0045-chat-scheduling-tools.md +51 -0
  87. package/docs/adr/0046-selective-command-redaction.md +31 -0
  88. package/docs/adr/0047-one-scheduling-path.md +158 -0
  89. package/docs/adr/README.md +50 -0
  90. package/docs/api.md +92 -0
  91. package/docs/architecture.md +164 -0
  92. package/docs/browser.md +93 -0
  93. package/docs/memory.md +27 -0
  94. package/docs/screenshot.png +0 -0
  95. package/docs/workspace-extensions.md +133 -0
  96. package/examples/workspace-extensions/system-context/index.ts +69 -0
  97. package/examples/workspace-extensions/system-context/package.json +3 -0
  98. package/ops/README.md +267 -0
  99. package/ops/preflight.mjs +28 -0
  100. package/package.json +33 -45
  101. package/dist/agent.d.ts +0 -60
  102. package/dist/agent.d.ts.map +0 -1
  103. package/dist/agent.js +0 -715
  104. package/dist/agent.js.map +0 -1
  105. package/dist/cli.d.ts +0 -15
  106. package/dist/cli.d.ts.map +0 -1
  107. package/dist/cli.js.map +0 -1
  108. package/dist/imessage.d.ts +0 -33
  109. package/dist/imessage.d.ts.map +0 -1
  110. package/dist/imessage.js +0 -76
  111. package/dist/imessage.js.map +0 -1
  112. package/dist/logger.d.ts +0 -33
  113. package/dist/logger.d.ts.map +0 -1
  114. package/dist/logger.js +0 -104
  115. package/dist/logger.js.map +0 -1
  116. package/dist/main.d.ts +0 -5
  117. package/dist/main.d.ts.map +0 -1
  118. package/dist/main.js.map +0 -1
  119. package/dist/memory.d.ts +0 -53
  120. package/dist/memory.d.ts.map +0 -1
  121. package/dist/memory.js +0 -196
  122. package/dist/memory.js.map +0 -1
  123. package/dist/model-health.d.ts +0 -11
  124. package/dist/model-health.d.ts.map +0 -1
  125. package/dist/model-health.js +0 -67
  126. package/dist/model-health.js.map +0 -1
  127. package/dist/pipeline.d.ts +0 -27
  128. package/dist/pipeline.d.ts.map +0 -1
  129. package/dist/pipeline.js +0 -59
  130. package/dist/pipeline.js.map +0 -1
  131. package/dist/queue.d.ts +0 -23
  132. package/dist/queue.d.ts.map +0 -1
  133. package/dist/queue.js +0 -89
  134. package/dist/queue.js.map +0 -1
  135. package/dist/rich-text.d.ts +0 -26
  136. package/dist/rich-text.d.ts.map +0 -1
  137. package/dist/rich-text.js.map +0 -1
  138. package/dist/self-echo.d.ts +0 -19
  139. package/dist/self-echo.d.ts.map +0 -1
  140. package/dist/self-echo.js +0 -54
  141. package/dist/self-echo.js.map +0 -1
  142. package/dist/send.d.ts +0 -24
  143. package/dist/send.d.ts.map +0 -1
  144. package/dist/send.js.map +0 -1
  145. package/dist/settings.d.ts +0 -44
  146. package/dist/settings.d.ts.map +0 -1
  147. package/dist/settings.js +0 -80
  148. package/dist/settings.js.map +0 -1
  149. package/dist/store.d.ts +0 -57
  150. package/dist/store.d.ts.map +0 -1
  151. package/dist/store.js +0 -124
  152. package/dist/store.js.map +0 -1
  153. package/dist/tasks.d.ts +0 -95
  154. package/dist/tasks.d.ts.map +0 -1
  155. package/dist/tasks.js +0 -384
  156. package/dist/tasks.js.map +0 -1
  157. package/dist/types.d.ts +0 -93
  158. package/dist/types.d.ts.map +0 -1
  159. package/dist/types.js +0 -38
  160. package/dist/types.js.map +0 -1
  161. package/dist/watch.d.ts +0 -21
  162. package/dist/watch.d.ts.map +0 -1
  163. package/dist/watch.js +0 -219
  164. package/dist/watch.js.map +0 -1
  165. package/dist/web/data.d.ts +0 -11
  166. package/dist/web/data.d.ts.map +0 -1
  167. package/dist/web/data.js +0 -56
  168. package/dist/web/data.js.map +0 -1
  169. package/dist/web/html.d.ts +0 -5
  170. package/dist/web/html.d.ts.map +0 -1
  171. package/dist/web/html.js +0 -16
  172. package/dist/web/html.js.map +0 -1
  173. package/dist/web/index.d.ts +0 -23
  174. package/dist/web/index.d.ts.map +0 -1
  175. package/dist/web/index.js +0 -279
  176. package/dist/web/index.js.map +0 -1
  177. package/dist/web/render.d.ts +0 -11
  178. package/dist/web/render.d.ts.map +0 -1
  179. package/dist/web/render.js +0 -56
  180. package/dist/web/render.js.map +0 -1
  181. package/dist/web/templates/logs.eta +0 -75
  182. package/dist/web/templates/memory.eta +0 -91
  183. package/dist/web/templates/page.eta +0 -98
@@ -0,0 +1,79 @@
1
+ import { DefaultPackageManager, formatSkillsForPrompt, loadProjectContextFiles, loadSkills, SettingsManager, } from "@earendil-works/pi-coding-agent";
2
+ import { defineExtension, section } from "@earendil-works/pi-durable";
3
+ function preamble(workingDir) {
4
+ return `You are the user's best friend communicating via iMessage. Be concise. No emojis.
5
+
6
+ ## Context
7
+ - Plain text only. Do not use Markdown formatting, double asterisks (**like this**), or [markdown](links).
8
+ - Reply in the same language the user is writing in.
9
+ - Name sources without URLs by default to avoid iMessage link previews. Include original URLs only when the user asks for links.
10
+ - Output ONLY the final message to the user. Never include planning, reasoning, analysis or meta-commentary in the reply.
11
+
12
+ ## Environment
13
+ You are running directly on the host machine.
14
+ - Bash working directory: ${workingDir}
15
+ - Be careful with system modifications.
16
+
17
+ ## Workspace Layout
18
+ ${workingDir}/
19
+ ├── settings.json # Bot configuration
20
+ ├── extensions/<name>/ # Trusted business tools/tasks: index.ts and config.json
21
+ ├── skills/ # Your reusable CLI tools; skills/file-memory is the memory store
22
+ ├── attachments/<chat>/ # Files users shared, referenced by path in messages
23
+ └── durable/ # All conversations (JSONL); grep here to search old messages
24
+
25
+ ## Messaging
26
+ Your final answer is sent to the chat automatically. Use the send_message tool for files or extra messages.
27
+ Six-hour compaction and workspace extension schedules run as native Durable background tasks. Their deadlines and recent execution records are visible on the read-only Scheduled web page.
28
+ You can create or update a trusted workspace extension in extensions/<name>/index.ts with its config.json, using the host-pinned Durable primitives. An extension can define multiple tasks and optional daily/interval schedules. Use reload_extensions (or the user command /reload) to apply code and configuration changes without interrupting current calls or resetting saved deadlines.
29
+
30
+ ## Long-running work
31
+ - On a resumed or interrupted task, check its transcript and actual results first. An interrupted tool may already have acted: verify it instead of blindly repeating it.
32
+
33
+ ## Skills (custom CLI tools)
34
+ Create reusable tools for on-demand tasks in ${workingDir}/skills/<name>/, each with a SKILL.md:
35
+ ---
36
+ name: skill-name
37
+ description: What this skill does
38
+ ---
39
+ Usage instructions and details here.`;
40
+ }
41
+ /**
42
+ * The system prompt: product instructions, AGENTS files and skills, read once per load.
43
+ * `/reload` builds it again; the same extension name replaces the old one in place.
44
+ */
45
+ export async function loadPrompt(workingDir, agentDir) {
46
+ const settings = SettingsManager.create(workingDir, agentDir, { projectTrusted: false });
47
+ const packages = new DefaultPackageManager({ cwd: workingDir, agentDir, settingsManager: settings });
48
+ // Discover installed user resources only; never install packages or execute SDK extensions headlessly.
49
+ const resources = await packages.resolve(async (source) => {
50
+ console.warn("Prompt resource unavailable; skipping missing package", source);
51
+ return "skip";
52
+ });
53
+ const agents = loadProjectContextFiles({ cwd: workingDir, agentDir });
54
+ const loadedSkills = loadSkills({
55
+ cwd: workingDir,
56
+ agentDir,
57
+ includeDefaults: false,
58
+ skillPaths: resources.skills
59
+ .filter((resource) => resource.enabled && resource.metadata.scope === "user")
60
+ .map((resource) => resource.path),
61
+ });
62
+ for (const diagnostic of loadedSkills.diagnostics)
63
+ console.warn("Skill resource diagnostic", diagnostic);
64
+ const skills = formatSkillsForPrompt(loadedSkills.skills, "read").trim();
65
+ const text = preamble(workingDir);
66
+ return defineExtension({
67
+ name: "prompt",
68
+ sections: [
69
+ section("preamble", () => text, { tag: false }),
70
+ section("project_context", () => agents.length === 0
71
+ ? undefined
72
+ : [
73
+ "Project-specific instructions and guidelines:",
74
+ ...agents.map(({ path, content }) => `<project_instructions path="${path}">\n${content}\n</project_instructions>`),
75
+ ].join("\n\n")),
76
+ section("skills", (input) => input.agent.tools.some((tool) => tool.name === "read") ? skills || undefined : undefined),
77
+ ],
78
+ });
79
+ }
@@ -0,0 +1,9 @@
1
+ import { defineDoc } from "@earendil-works/pi-durable";
2
+ export const Deliveries = defineDoc({
3
+ kind: "imessage.deliveries",
4
+ version: 1,
5
+ scope: "conversation",
6
+ history: "latest",
7
+ fork: "initial",
8
+ initial: () => ({ answers: {} }),
9
+ });
@@ -0,0 +1,159 @@
1
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
+ import { Type } from "@earendil-works/pi-ai";
3
+ import { AssistantEntry, configure, defineDoc, defineExtension, defineTask, defineTool, GenerationTask, hook, InboxDoc, LiveDoc, section, } from "@earendil-works/pi-durable";
4
+ import { finalReplyText } from "../extensions/final-text.js";
5
+ import { Deliveries } from "./replies.js";
6
+ /** Every `/run`; ended runs stay listed so their last answers can still be delivered. */
7
+ export const Runs = defineDoc({
8
+ kind: "imessage.runs",
9
+ version: 1,
10
+ scope: "session",
11
+ initial: () => ({ items: [] }),
12
+ });
13
+ /** Model-visible notes in the chat conversation about what happened in a run. */
14
+ export const RUN_RECORD = "imessage.run-record";
15
+ export function activeRun(runs, chat) {
16
+ return runs?.find((run) => run.chat === chat && run.status === "active");
17
+ }
18
+ export function runRecord(text, now) {
19
+ return { kind: RUN_RECORD, model: [{ role: "user", content: text, timestamp: now }] };
20
+ }
21
+ const instructions = [
22
+ "This conversation is a /run: the user asked you to keep working on the task without waiting for confirmation.",
23
+ "Every final answer is sent to the chat as it is written.",
24
+ "Call end_run when the task is done, when you need the user, or when there is no unfinished task; do not invent a new task.",
25
+ ].join("\n");
26
+ async function finish(tx, taskId, stopped, now) {
27
+ const run = (await tx.doc(Runs)).items.find((item) => item.taskId === taskId);
28
+ if (!run || run.status === "ended")
29
+ return;
30
+ if (stopped) {
31
+ // Withdraw answers that were not claimed for sending; a claimed send cannot be retracted.
32
+ const deliveries = await tx.doc(Deliveries, run.conversationId);
33
+ const entries = await tx.scanEntries({
34
+ conversationId: run.conversationId,
35
+ ...(deliveries.scanned === undefined ? {} : { minEntryId: deliveries.scanned }),
36
+ }, 1000);
37
+ for (const entry of entries.items) {
38
+ const key = String(entry.id);
39
+ if (!AssistantEntry.is(entry) || !finalReplyText(entry.model?.[0]) || deliveries.answers[key])
40
+ continue;
41
+ if (deliveries.drafts?.[key] && deliveries.drafts[key].status !== "held")
42
+ continue;
43
+ deliveries.drafts ??= {};
44
+ deliveries.drafts[key] = { status: "cancelled" };
45
+ }
46
+ const drafts = deliveries.drafts ?? {};
47
+ for (const [key, draft] of Object.entries(drafts))
48
+ if (draft.status === "held")
49
+ drafts[key] = { status: "cancelled" };
50
+ run.endReason = "stopped";
51
+ }
52
+ run.endReason ??= now >= run.deadline ? "deadline" : "finished";
53
+ run.status = "ended";
54
+ // The chat conversation is idle while its run is active: ordinary messages go to the run.
55
+ await tx.appendEntry(run.chat, runRecord(`[/run ended: ${run.endReason}]`, now));
56
+ }
57
+ /** Owns the run conversation, so aborting it stops the run's work and withdraws its queued messages. */
58
+ export const RunTask = defineTask({
59
+ name: "imessage.run",
60
+ version: 1,
61
+ initial: () => ({ phase: "start" }),
62
+ phases: {
63
+ async start(task, runtime, context) {
64
+ const run = (await runtime.snapshot(Runs, context))?.items.find((item) => item.taskId === task.id);
65
+ const conversation = run && (await runtime.conversation(run.conversationId, context));
66
+ if (!conversation)
67
+ throw new Error("Run conversation is missing");
68
+ await conversation.submit({ type: "input", content: task.input.task, requestId: `run:${task.id}`, whenBusy: "steer" }, context);
69
+ await runtime.commit(() => ({ status: "running", checkpoint: { phase: "watch" } }), context);
70
+ },
71
+ async watch(task, runtime, context) {
72
+ const run = (await runtime.snapshot(Runs, context))?.items.find((item) => item.taskId === task.id);
73
+ const conversation = run && (await runtime.conversation(run.conversationId, context));
74
+ // onYield keeps the run conversation busy until end_run or the deadline; idle means the run is over.
75
+ await conversation?.waitForIdle(context);
76
+ await runtime.commit(async (tx) => {
77
+ await finish(tx, task.id, false, runtime.now());
78
+ return { status: "terminal", outcome: { status: "completed", result: null } };
79
+ }, context);
80
+ },
81
+ },
82
+ async abort(task, runtime, context) {
83
+ await runtime.commit(async (tx) => {
84
+ await finish(tx, task.id, true, runtime.now());
85
+ return { status: "terminal", outcome: { status: "aborted" } };
86
+ }, context);
87
+ },
88
+ });
89
+ /** Selected only by run conversations; its task definition resolves everywhere. */
90
+ export const RunExtension = defineExtension({
91
+ name: "run",
92
+ tasks: [RunTask],
93
+ sections: [section("run", () => instructions)],
94
+ tools: [
95
+ defineTool({
96
+ name: "end_run",
97
+ description: "End this /run when the task is done, you need the user, or nothing is left to do.",
98
+ parameters: Type.Object({ reason: Type.String() }),
99
+ replay: "safe",
100
+ async execute(args, api, context) {
101
+ await api.commit(async (tx) => {
102
+ const run = (await tx.doc(Runs)).items.find((item) => item.conversationId === api.conversationId && item.status === "active");
103
+ if (run)
104
+ run.endReason = args.reason;
105
+ }, context);
106
+ return { content: [{ type: "text", text: "The run ends after this answer." }] };
107
+ },
108
+ }),
109
+ ],
110
+ hooks: [
111
+ hook(GenerationTask, {
112
+ async onYield(_answer, api, context) {
113
+ const run = (await api.snapshot(Runs, context))?.items.find((item) => item.conversationId === api.conversationId);
114
+ if (run?.status !== "active" || run.endReason !== undefined)
115
+ return;
116
+ // The deadline only stops continuation; a turn in progress finishes.
117
+ const minutes = Math.floor((run.deadline - Date.now()) / 60000);
118
+ if (minutes < 1)
119
+ return;
120
+ return {
121
+ continue: `Continue the /run task. ${minutes} minutes left. Call end_run when it is done or you need the user.`,
122
+ };
123
+ },
124
+ }),
125
+ ],
126
+ });
127
+ /** Starts a run in a fork of the idle chat conversation, or moves the deadline of the active one. */
128
+ export function startRun(chat, chatGuid, deadline, task) {
129
+ return chat.commit(async (tx) => {
130
+ const newest = (await tx.scanEntries({ conversationId: chat.id }, 1)).items[0];
131
+ const runs = await tx.doc(Runs);
132
+ const active = activeRun(runs.items, chat.id);
133
+ if (active) {
134
+ active.deadline = deadline;
135
+ return { status: "updated", run: { ...active } };
136
+ }
137
+ const inbox = await tx.doc(InboxDoc, chat.id);
138
+ if ((await tx.doc(LiveDoc, chat.id)).run || inbox.items.length > 0)
139
+ return { status: "busy" };
140
+ const taskId = await tx.createTask(RunTask, { task }, { ownership: { kind: "conversation" } });
141
+ const ownership = { ownership: { kind: "task", taskId } };
142
+ // A fork inherits the chat's context without copying or summarizing it.
143
+ const conversation = newest
144
+ ? await tx.forkConversation(chat.id, newest.id, ownership)
145
+ : await tx.createConversation(ownership);
146
+ await configure(tx, conversation.id, { extensions: { add: [RunExtension] } });
147
+ const run = {
148
+ chatGuid,
149
+ chat: chat.id,
150
+ conversationId: conversation.id,
151
+ taskId,
152
+ deadline,
153
+ status: "active",
154
+ };
155
+ runs.items.push(run);
156
+ await tx.appendEntry(chat.id, runRecord(`[/run started: ${task}]`, Date.now()));
157
+ return { status: "started", run: { ...run } };
158
+ }, BACKGROUND_CONTEXT);
159
+ }
@@ -0,0 +1,290 @@
1
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
+ import { configure, defineDoc, defineExtension, defineTask, } from "@earendil-works/pi-durable";
3
+ import { ScheduledOutbox, validateSchedules } from "../extensions/schedules.js";
4
+ import { compactChats } from "./compaction.js";
5
+ import { dailyTime, localDate, nextDaily } from "./time.js";
6
+ export { ScheduledOutbox };
7
+ const SIX_HOURS = 6 * 3600000;
8
+ export const EXECUTION_KIND = "imessage.scheduled-execution";
9
+ export const Schedules = defineDoc({
10
+ kind: "imessage.schedules",
11
+ version: 1,
12
+ scope: "session",
13
+ initial: () => ({ items: [] }),
14
+ });
15
+ export const RunRequests = defineDoc({
16
+ kind: "imessage.schedule-requests",
17
+ version: 1,
18
+ scope: "session",
19
+ initial: () => ({ items: [] }),
20
+ });
21
+ function nextAt(schedule, previous, now) {
22
+ if (schedule.time !== undefined)
23
+ return nextDaily(schedule.time, now);
24
+ const interval = schedule.intervalMs ?? SIX_HOURS;
25
+ return previous + (Math.max(0, Math.floor((now - previous) / interval)) + 1) * interval;
26
+ }
27
+ /** Durable owns cadence and execution receipts; extensions own business tasks and documents. */
28
+ export function schedulingExtension(harness, defaults) {
29
+ let admissionReady = true;
30
+ const Execution = defineTask({
31
+ name: EXECUTION_KIND,
32
+ version: 2,
33
+ initial: () => ({ phase: "start" }),
34
+ phases: {
35
+ async start(task, runtime, context) {
36
+ const schedule = (await runtime.snapshot(Schedules, context))?.items.find((item) => item.id === task.input.jobId);
37
+ if (!schedule)
38
+ throw new Error("Scheduled job is missing");
39
+ if (schedule.id === "compact-chats") {
40
+ let admissionFailures = 0;
41
+ const tasks = await compactChats(harness, () => admissionFailures++);
42
+ await runtime.commit(() => ({ status: "running", checkpoint: { phase: "compact", tasks, admissionFailures } }), context);
43
+ return;
44
+ }
45
+ const definition = schedule.execution && runtime.registry.task(schedule.execution);
46
+ if (!definition)
47
+ throw new Error(`Missing scheduled task definition: ${schedule.execution}`);
48
+ await runtime.commit(async (tx) => {
49
+ const execution = await tx.createTask(definition, { ...task.input, config: schedule.input ?? null, chatGuid: schedule.chatGuid ?? null }, { ownership: { kind: "task", taskId: task.id } });
50
+ return {
51
+ status: "waiting",
52
+ checkpoint: { phase: "execute", execution },
53
+ on: [execution],
54
+ policy: "allSettled",
55
+ };
56
+ }, context);
57
+ },
58
+ async execute(task, runtime, context) {
59
+ const receipt = await runtime.waitForTask(task.state.checkpoint.execution, context);
60
+ await runtime.commit(() => ({ status: "terminal", outcome: receipt.state.outcome }), context);
61
+ },
62
+ async compact(task, runtime, context) {
63
+ const receipts = await Promise.all(task.state.checkpoint.tasks.map((id) => runtime.waitForTask(id, context)));
64
+ const failed = task.state.checkpoint.admissionFailures +
65
+ receipts.filter((receipt) => receipt.state.outcome.status !== "completed").length;
66
+ await runtime.commit(() => ({
67
+ status: "terminal",
68
+ outcome: failed
69
+ ? { status: "failed", error: { message: `${failed} scheduled compaction(s) failed` } }
70
+ : {
71
+ status: "completed",
72
+ result: {
73
+ summary: `${receipts.length} native compaction(s) completed; includes no-ops`,
74
+ finishedAt: runtime.now(),
75
+ },
76
+ },
77
+ }), context);
78
+ },
79
+ },
80
+ async abort(_task, runtime, context) {
81
+ await runtime.commit(() => ({ status: "terminal", outcome: { status: "aborted" } }), context);
82
+ },
83
+ });
84
+ const Scheduler = defineTask({
85
+ name: "imessage.schedule",
86
+ version: 2,
87
+ migrate(input, checkpoint) {
88
+ return { input: input, checkpoint: checkpoint };
89
+ },
90
+ initial: (input) => ({ phase: "sleep", at: input.firstAt }),
91
+ phases: {
92
+ async sleep(task, runtime, context) {
93
+ const { at } = task.state.checkpoint;
94
+ await runtime.sleep(at, context);
95
+ // Due-now work must not start between the configuration commit and registry publication.
96
+ if (!admissionReady) {
97
+ await runtime.sleep(runtime.now() + 100, context);
98
+ await runtime.commit(() => ({ status: "running", checkpoint: task.state.checkpoint }), context);
99
+ return;
100
+ }
101
+ await runtime.commit(async (tx) => {
102
+ const schedule = (await tx.doc(Schedules)).items.find((item) => item.id === task.input.jobId);
103
+ if (!schedule)
104
+ throw new Error("Scheduled job is missing");
105
+ if (task.input.requestId &&
106
+ !(await tx.doc(RunRequests)).items.find((item) => item.id === task.input.requestId)?.enabled)
107
+ return { status: "terminal", outcome: { status: "completed", result: null } };
108
+ const now = runtime.now();
109
+ const beforeToday = schedule.time !== undefined && now < dailyTime(schedule.time, now);
110
+ if (!schedule.enabled)
111
+ return task.input.requestId
112
+ ? { status: "terminal", outcome: { status: "completed", result: null } }
113
+ : { status: "running", checkpoint: { phase: "sleep", at: nextAt(schedule, at, now) } };
114
+ if (!task.input.requestId && beforeToday)
115
+ return { status: "running", checkpoint: { phase: "sleep", at: nextAt(schedule, at, now) } };
116
+ // All triggers of a job share its non-overlap boundary.
117
+ for (const status of ["pending", "running", "waiting", "completing"]) {
118
+ const existing = (await tx.scanTasks({ conversationId: schedule.conversationId, kind: EXECUTION_KIND, status }, 1)).items[0];
119
+ if (existing)
120
+ return {
121
+ status: "waiting",
122
+ checkpoint: {
123
+ phase: task.input.requestId ? "retry" : "advance",
124
+ at,
125
+ execution: existing.id,
126
+ },
127
+ on: [existing.id],
128
+ policy: "allSettled",
129
+ };
130
+ }
131
+ const execution = await tx.createTask(Execution, {
132
+ jobId: schedule.id,
133
+ dueAt: at,
134
+ startedAt: now,
135
+ date: localDate(now),
136
+ ...(task.input.requestId ? { requestId: task.input.requestId } : {}),
137
+ }, { ownership: { kind: "task", taskId: task.id } });
138
+ return {
139
+ status: "waiting",
140
+ checkpoint: { phase: "advance", at, execution },
141
+ on: [execution],
142
+ policy: "allSettled",
143
+ };
144
+ }, context);
145
+ },
146
+ async retry(task, runtime, context) {
147
+ await runtime.commit(() => ({ status: "running", checkpoint: { phase: "sleep", at: task.state.checkpoint.at } }), context);
148
+ },
149
+ async advance(task, runtime, context) {
150
+ if (task.input.requestId) {
151
+ await runtime.commit(() => ({ status: "terminal", outcome: { status: "completed", result: null } }), context);
152
+ return;
153
+ }
154
+ await runtime.commit(async (tx) => {
155
+ const schedule = (await tx.doc(Schedules)).items.find((item) => item.id === task.input.jobId);
156
+ if (!schedule)
157
+ throw new Error("Scheduled job is missing");
158
+ const execution = await tx.task(task.state.checkpoint.execution);
159
+ const outcome = execution?.state.outcome;
160
+ const result = outcome?.status === "completed" ? outcome.result : undefined;
161
+ const finishedAt = result &&
162
+ typeof result === "object" &&
163
+ !Array.isArray(result) &&
164
+ typeof result.finishedAt === "number"
165
+ ? result.finishedAt
166
+ : runtime.now();
167
+ return {
168
+ status: "running",
169
+ checkpoint: { phase: "sleep", at: nextAt(schedule, task.state.checkpoint.at, finishedAt) },
170
+ };
171
+ }, context);
172
+ },
173
+ },
174
+ async abort(_task, runtime, context) {
175
+ await runtime.commit(() => ({ status: "terminal", outcome: { status: "aborted" } }), context);
176
+ },
177
+ });
178
+ return {
179
+ extension: defineExtension({ name: "scheduling", tasks: [Scheduler, Execution] }),
180
+ /** May join a host reload commit. Existing task IDs and absolute deadlines are never reset. */
181
+ async initialize(extensions, transaction, publish) {
182
+ validateSchedules(extensions);
183
+ const timezone = new Intl.DateTimeFormat().resolvedOptions().timeZone;
184
+ const initialize = async (tx) => {
185
+ const state = await tx.doc(Schedules);
186
+ const definitions = [
187
+ {
188
+ id: "compact-chats",
189
+ name: "Chat compaction",
190
+ kind: "compaction",
191
+ enabled: true,
192
+ intervalMs: SIX_HOURS,
193
+ timezone,
194
+ extension: "scheduling",
195
+ },
196
+ ...extensions.flatMap((extension) => (extension.schedules ?? []).map(({ task, initialize, ...schedule }) => ({
197
+ ...schedule,
198
+ kind: schedule.kind ?? "custom",
199
+ extension: extension.name,
200
+ execution: task,
201
+ timezone,
202
+ initialize,
203
+ }))),
204
+ ];
205
+ for (const { initialize: initializeBusiness, ...definition } of definitions) {
206
+ const found = state.items.find((item) => item.id === definition.id);
207
+ if (found) {
208
+ // Clear old cadence when an extension switches between daily and interval scheduling.
209
+ delete found.time;
210
+ delete found.intervalMs;
211
+ delete found.input;
212
+ delete found.chatGuid;
213
+ Object.assign(found, definition);
214
+ await initializeBusiness?.(tx, found.conversationId);
215
+ continue;
216
+ }
217
+ const conversation = await tx.createConversation({ ownership: { kind: "ownerless" } });
218
+ await configure(tx, conversation.id, { ...defaults, extensions: [], tools: [] });
219
+ await initializeBusiness?.(tx, conversation.id);
220
+ const firstAt = definition.time !== undefined
221
+ ? nextDaily(definition.time, Date.now())
222
+ : Date.now() + (definition.intervalMs ?? SIX_HOURS);
223
+ const taskId = await tx.createTask(Scheduler, { jobId: definition.id, firstAt }, { conversationId: conversation.id, ownership: { kind: "conversation" }, background: true });
224
+ state.items.push({ ...definition, conversationId: conversation.id, taskId });
225
+ }
226
+ const ids = new Set(definitions.map((definition) => definition.id));
227
+ for (const item of state.items)
228
+ if (!ids.has(item.id))
229
+ item.enabled = false;
230
+ const requests = await tx.doc(RunRequests);
231
+ for (const extension of extensions)
232
+ for (const request of extension.runRequests ?? []) {
233
+ const existing = requests.items.find((item) => item.id === request.id);
234
+ if (existing) {
235
+ if (existing.jobId !== request.scheduleId || existing.requestedAt !== request.at)
236
+ throw new Error(`Run request ID already used with different configuration: ${request.id}`);
237
+ existing.enabled = true;
238
+ continue;
239
+ }
240
+ const schedule = state.items.find((item) => item.id === request.scheduleId);
241
+ if (!schedule?.enabled)
242
+ throw new Error("Run request target is unavailable");
243
+ if (schedule.manualRuns?.[request.id])
244
+ throw new Error("Run request ID belongs to a historical operator run");
245
+ const at = request.at === "now" ? Date.now() : request.at;
246
+ const taskId = await tx.createTask(Scheduler, { jobId: schedule.id, firstAt: at, requestId: request.id }, {
247
+ conversationId: schedule.conversationId,
248
+ ownership: { kind: "conversation" },
249
+ background: true,
250
+ });
251
+ requests.items.push({
252
+ id: request.id,
253
+ jobId: schedule.id,
254
+ requestedAt: request.at,
255
+ at,
256
+ taskId,
257
+ enabled: true,
258
+ });
259
+ }
260
+ const declaredRequests = new Set(extensions.flatMap((extension) => (extension.runRequests ?? []).map((request) => request.id)));
261
+ for (const request of requests.items)
262
+ if (!declaredRequests.has(request.id))
263
+ request.enabled = false;
264
+ };
265
+ admissionReady = false;
266
+ try {
267
+ if (transaction)
268
+ await initialize(transaction);
269
+ else
270
+ await harness.commit(initialize, BACKGROUND_CONTEXT);
271
+ publish?.();
272
+ }
273
+ finally {
274
+ admissionReady = true;
275
+ }
276
+ },
277
+ };
278
+ }
279
+ /** Reuse at-most-once direct-send receipts; never retry unknown external effects. */
280
+ export async function deliverScheduled(harness, send, enabled) {
281
+ for (const item of (await harness.snapshot(ScheduledOutbox, BACKGROUND_CONTEXT))?.items ?? []) {
282
+ if (!enabled(item.chatGuid))
283
+ continue;
284
+ await send(item);
285
+ await harness.commit(async (tx) => {
286
+ const outbox = await tx.doc(ScheduledOutbox);
287
+ outbox.items = outbox.items.filter((queued) => queued.requestId !== item.requestId);
288
+ }, BACKGROUND_CONTEXT);
289
+ }
290
+ }
@@ -0,0 +1,18 @@
1
+ /** Calendar dates follow the service process timezone, including an explicit TZ override. */
2
+ export function localDate(timestamp) {
3
+ const date = new Date(timestamp);
4
+ return [date.getFullYear(), date.getMonth() + 1, date.getDate()]
5
+ .map((value, index) => String(value).padStart(index === 0 ? 4 : 2, "0"))
6
+ .join("-");
7
+ }
8
+ /** Date applies local daylight-saving rules: shift gaps forward and choose the first repeated time. */
9
+ export function dailyTime(time, timestamp, dayOffset = 0) {
10
+ const date = new Date(timestamp);
11
+ const [hours, minutes] = time.split(":").map(Number);
12
+ return new Date(date.getFullYear(), date.getMonth(), date.getDate() + dayOffset, hours, minutes).getTime();
13
+ }
14
+ /** Advance by a calendar day, which need not be 24 elapsed hours. */
15
+ export function nextDaily(time, after) {
16
+ const today = dailyTime(time, after);
17
+ return today > after ? today : dailyTime(time, after, 1);
18
+ }