@wheatley-ai/cli 0.0.0-stage → 0.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 (209) hide show
  1. package/LICENSE +15 -0
  2. package/bin/wheatley.js +2 -0
  3. package/dist/approvals/gate.js +278 -0
  4. package/dist/approvals/module.js +21 -0
  5. package/dist/approvals/policy.js +30 -0
  6. package/dist/approvals/preview.js +17 -0
  7. package/dist/approvals/prompt.js +98 -0
  8. package/dist/approvals/rpc.js +16 -0
  9. package/dist/approvals/store.js +159 -0
  10. package/dist/cli/ask.js +94 -0
  11. package/dist/cli/chat.js +180 -0
  12. package/dist/cli/client.js +104 -0
  13. package/dist/cli/daemon.js +35 -0
  14. package/dist/cli/init.js +72 -0
  15. package/dist/cli/io.js +45 -0
  16. package/dist/cli/main.js +204 -0
  17. package/dist/cli/session.js +87 -0
  18. package/dist/cli/status.js +46 -0
  19. package/dist/contracts/approval-gate.js +1 -0
  20. package/dist/contracts/config-store.js +1 -0
  21. package/dist/contracts/delivery-outbox.js +1 -0
  22. package/dist/contracts/errors.js +28 -0
  23. package/dist/contracts/extension-catalog.js +1 -0
  24. package/dist/contracts/maintenance-runner.js +1 -0
  25. package/dist/contracts/memory-store.js +1 -0
  26. package/dist/contracts/module.js +7 -0
  27. package/dist/contracts/tool-names.js +43 -0
  28. package/dist/contracts/trigger-runtime.js +1 -0
  29. package/dist/contracts/webhook-ingress.js +2 -0
  30. package/dist/core/agent/agent-store.js +300 -0
  31. package/dist/core/agent/agent.js +1020 -0
  32. package/dist/core/agent/gated-models.js +89 -0
  33. package/dist/core/agent/pi-adapter.js +401 -0
  34. package/dist/core/agent/policy-gate.js +44 -0
  35. package/dist/core/builtin-catalog.js +20 -0
  36. package/dist/core/concurrency-gate.js +87 -0
  37. package/dist/core/config/atomic-file.js +61 -0
  38. package/dist/core/config/config-store.js +138 -0
  39. package/dist/core/config/pending-restart.js +53 -0
  40. package/dist/core/config/secret-references.js +69 -0
  41. package/dist/core/config/secret-store.js +147 -0
  42. package/dist/core/config/validate.js +55 -0
  43. package/dist/core/config/yaml-patch.js +57 -0
  44. package/dist/core/daemon.js +88 -0
  45. package/dist/core/deployment.js +347 -0
  46. package/dist/core/error-message.js +4 -0
  47. package/dist/core/events.js +25 -0
  48. package/dist/core/logger.js +81 -0
  49. package/dist/core/models.js +27 -0
  50. package/dist/core/module.js +42 -0
  51. package/dist/core/rpc/agent-handlers.js +82 -0
  52. package/dist/core/rpc/deployment-handlers.js +63 -0
  53. package/dist/core/rpc/router.js +95 -0
  54. package/dist/core/server/connection.js +170 -0
  55. package/dist/core/server/control-server.js +152 -0
  56. package/dist/core/server/static-files.js +79 -0
  57. package/dist/core/supervisor.js +206 -0
  58. package/dist/core/tool-routing.js +41 -0
  59. package/dist/dashboard/assets/index-3COz_MZq.css +2 -0
  60. package/dist/dashboard/assets/index-RnxedkKh.js +11 -0
  61. package/dist/dashboard/assets/sheet-presentation-U1UUymXc.js +1 -0
  62. package/dist/dashboard/index.html +13 -0
  63. package/dist/db/database.js +16 -0
  64. package/dist/db/migrations.js +184 -0
  65. package/dist/frontends/discord/approvals.js +199 -0
  66. package/dist/frontends/discord/attachments.js +115 -0
  67. package/dist/frontends/discord/binding.js +489 -0
  68. package/dist/frontends/discord/config.js +107 -0
  69. package/dist/frontends/discord/discord-runtime.js +52 -0
  70. package/dist/frontends/discord/errors.js +61 -0
  71. package/dist/frontends/discord/live-runs.js +189 -0
  72. package/dist/frontends/discord/module.js +39 -0
  73. package/dist/frontends/discord/recent-ids.js +20 -0
  74. package/dist/frontends/slack/approval-blocks.js +98 -0
  75. package/dist/frontends/slack/attachments.js +102 -0
  76. package/dist/frontends/slack/background-tasks.js +20 -0
  77. package/dist/frontends/slack/binding.js +405 -0
  78. package/dist/frontends/slack/bounded.js +9 -0
  79. package/dist/frontends/slack/chat-id.js +17 -0
  80. package/dist/frontends/slack/config.js +80 -0
  81. package/dist/frontends/slack/delivery-errors.js +81 -0
  82. package/dist/frontends/slack/inbound.js +76 -0
  83. package/dist/frontends/slack/live-progress.js +190 -0
  84. package/dist/frontends/slack/manifest.js +66 -0
  85. package/dist/frontends/slack/outbound.js +160 -0
  86. package/dist/frontends/slack/schemas.js +99 -0
  87. package/dist/frontends/slack/signature.js +30 -0
  88. package/dist/frontends/slack/slack-client.js +60 -0
  89. package/dist/frontends/slack/slack-frontend.js +38 -0
  90. package/dist/frontends/slack/state-store.js +112 -0
  91. package/dist/frontends/telegram/approvals.js +134 -0
  92. package/dist/frontends/telegram/attachments.js +126 -0
  93. package/dist/frontends/telegram/binding.js +144 -0
  94. package/dist/frontends/telegram/chat-key.js +43 -0
  95. package/dist/frontends/telegram/client.js +88 -0
  96. package/dist/frontends/telegram/config.js +93 -0
  97. package/dist/frontends/telegram/delivery.js +215 -0
  98. package/dist/frontends/telegram/frontend.js +42 -0
  99. package/dist/frontends/telegram/grammy-client.js +122 -0
  100. package/dist/frontends/telegram/http-status.js +6 -0
  101. package/dist/frontends/telegram/inbound.js +149 -0
  102. package/dist/frontends/telegram/live.js +182 -0
  103. package/dist/frontends/telegram/markdown.js +103 -0
  104. package/dist/frontends/telegram/recent-set.js +18 -0
  105. package/dist/frontends/telegram/serial-queue.js +23 -0
  106. package/dist/index.js +7 -0
  107. package/dist/mcp/content.js +61 -0
  108. package/dist/mcp/mcp-module.js +35 -0
  109. package/dist/mcp/mcp-tool-provider.js +93 -0
  110. package/dist/mcp/server-connection.js +297 -0
  111. package/dist/memory/consolidation.js +260 -0
  112. package/dist/memory/format.js +5 -0
  113. package/dist/memory/migrations.js +76 -0
  114. package/dist/memory/module.js +69 -0
  115. package/dist/memory/names.js +20 -0
  116. package/dist/memory/rows.js +22 -0
  117. package/dist/memory/rpc.js +49 -0
  118. package/dist/memory/snapshots.js +12 -0
  119. package/dist/memory/store.js +281 -0
  120. package/dist/memory/tools.js +158 -0
  121. package/dist/node_modules/@wheatley-ai/protocol/dist/config.d.ts +252 -0
  122. package/dist/node_modules/@wheatley-ai/protocol/dist/config.js +110 -0
  123. package/dist/node_modules/@wheatley-ai/protocol/dist/domain.d.ts +512 -0
  124. package/dist/node_modules/@wheatley-ai/protocol/dist/domain.js +441 -0
  125. package/dist/node_modules/@wheatley-ai/protocol/dist/duration.d.ts +8 -0
  126. package/dist/node_modules/@wheatley-ai/protocol/dist/duration.js +28 -0
  127. package/dist/node_modules/@wheatley-ai/protocol/dist/events.d.ts +234 -0
  128. package/dist/node_modules/@wheatley-ai/protocol/dist/events.js +124 -0
  129. package/dist/node_modules/@wheatley-ai/protocol/dist/index.d.ts +11 -0
  130. package/dist/node_modules/@wheatley-ai/protocol/dist/index.js +11 -0
  131. package/dist/node_modules/@wheatley-ai/protocol/dist/json-rpc.d.ts +81 -0
  132. package/dist/node_modules/@wheatley-ai/protocol/dist/json-rpc.js +157 -0
  133. package/dist/node_modules/@wheatley-ai/protocol/dist/json.d.ts +14 -0
  134. package/dist/node_modules/@wheatley-ai/protocol/dist/json.js +23 -0
  135. package/dist/node_modules/@wheatley-ai/protocol/dist/limits.d.ts +17 -0
  136. package/dist/node_modules/@wheatley-ai/protocol/dist/limits.js +17 -0
  137. package/dist/node_modules/@wheatley-ai/protocol/dist/methods.d.ts +1107 -0
  138. package/dist/node_modules/@wheatley-ai/protocol/dist/methods.js +201 -0
  139. package/dist/node_modules/@wheatley-ai/protocol/dist/rpc-error.d.ts +45 -0
  140. package/dist/node_modules/@wheatley-ai/protocol/dist/rpc-error.js +44 -0
  141. package/dist/node_modules/@wheatley-ai/protocol/dist/validation.d.ts +20 -0
  142. package/dist/node_modules/@wheatley-ai/protocol/dist/validation.js +11 -0
  143. package/dist/node_modules/@wheatley-ai/protocol/package.json +14 -0
  144. package/dist/node_modules/@wheatley-ai/sdk/dist/chunk.d.ts +11 -0
  145. package/dist/node_modules/@wheatley-ai/sdk/dist/chunk.js +162 -0
  146. package/dist/node_modules/@wheatley-ai/sdk/dist/commands.d.ts +48 -0
  147. package/dist/node_modules/@wheatley-ai/sdk/dist/commands.js +39 -0
  148. package/dist/node_modules/@wheatley-ai/sdk/dist/delivery-error.d.ts +29 -0
  149. package/dist/node_modules/@wheatley-ai/sdk/dist/delivery-error.js +27 -0
  150. package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.d.ts +236 -0
  151. package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.js +2 -0
  152. package/dist/node_modules/@wheatley-ai/sdk/dist/index.d.ts +10 -0
  153. package/dist/node_modules/@wheatley-ai/sdk/dist/index.js +7 -0
  154. package/dist/node_modules/@wheatley-ai/sdk/dist/json.d.ts +9 -0
  155. package/dist/node_modules/@wheatley-ai/sdk/dist/json.js +2 -0
  156. package/dist/node_modules/@wheatley-ai/sdk/dist/logger.d.ts +18 -0
  157. package/dist/node_modules/@wheatley-ai/sdk/dist/logger.js +2 -0
  158. package/dist/node_modules/@wheatley-ai/sdk/dist/plugin.d.ts +48 -0
  159. package/dist/node_modules/@wheatley-ai/sdk/dist/plugin.js +5 -0
  160. package/dist/node_modules/@wheatley-ai/sdk/dist/schema.d.ts +69 -0
  161. package/dist/node_modules/@wheatley-ai/sdk/dist/schema.js +3 -0
  162. package/dist/node_modules/@wheatley-ai/sdk/dist/tool.d.ts +69 -0
  163. package/dist/node_modules/@wheatley-ai/sdk/dist/tool.js +3 -0
  164. package/dist/node_modules/@wheatley-ai/sdk/package.json +11 -0
  165. package/dist/ops/backup.js +185 -0
  166. package/dist/ops/cli.js +195 -0
  167. package/dist/ops/command-runner.js +34 -0
  168. package/dist/ops/dashboard-assets.js +37 -0
  169. package/dist/ops/migrate.js +63 -0
  170. package/dist/ops/module.js +47 -0
  171. package/dist/ops/paths.js +55 -0
  172. package/dist/ops/service.js +376 -0
  173. package/dist/ops/update.js +145 -0
  174. package/dist/plugins/contributions.js +89 -0
  175. package/dist/plugins/guards.js +111 -0
  176. package/dist/plugins/load.js +76 -0
  177. package/dist/plugins/module.js +31 -0
  178. package/dist/plugins/provider.js +349 -0
  179. package/dist/plugins/schema.js +69 -0
  180. package/dist/skills/disclosure.js +142 -0
  181. package/dist/skills/discovery.js +120 -0
  182. package/dist/skills/fs-errors.js +8 -0
  183. package/dist/skills/read-skill-tool.js +3 -0
  184. package/dist/skills/skill-file.js +90 -0
  185. package/dist/skills/skills.js +140 -0
  186. package/dist/tools/builtin-tools.js +61 -0
  187. package/dist/tools/input.js +45 -0
  188. package/dist/tools/paths.js +6 -0
  189. package/dist/tools/read-file.js +65 -0
  190. package/dist/tools/shell.js +156 -0
  191. package/dist/tools/write-file.js +58 -0
  192. package/dist/triggers/delivery-codec.js +99 -0
  193. package/dist/triggers/delivery-outbox.js +313 -0
  194. package/dist/triggers/due-timer.js +14 -0
  195. package/dist/triggers/errors.js +2 -0
  196. package/dist/triggers/migrations.js +91 -0
  197. package/dist/triggers/module.js +104 -0
  198. package/dist/triggers/rpc.js +35 -0
  199. package/dist/triggers/schedule.js +52 -0
  200. package/dist/triggers/sql-row.js +59 -0
  201. package/dist/triggers/trigger-runtime.js +445 -0
  202. package/dist/triggers/trigger-tools.js +207 -0
  203. package/dist/triggers/webhook-ingress.js +216 -0
  204. package/dist/wiring/agent-services.js +144 -0
  205. package/dist/wiring/catalog.js +81 -0
  206. package/dist/wiring/daemon.js +83 -0
  207. package/dist/wiring/frontend-host.js +268 -0
  208. package/package.json +50 -3
  209. package/README.md +0 -3
@@ -0,0 +1,445 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { TriggerScheduleSchema } from "@wheatley-ai/protocol";
3
+ import { Type } from "typebox";
4
+ import { Value } from "typebox/value";
5
+ import { SeamError } from "../contracts/errors.js";
6
+ import { armDueTimer } from "./due-timer.js";
7
+ import { errorText } from "./errors.js";
8
+ import { assertValidSchedule, initialFireAt, nextCronTick, } from "./schedule.js";
9
+ import { blobColumn, enumColumn, integerColumn, optionalIntegerColumn, textColumn, } from "./sql-row.js";
10
+ /**
11
+ * A `cron` tick that the scheduler reaches later than this counts as missed and is skipped, for example after the host
12
+ * slept.
13
+ */
14
+ const CRON_GRACE_MS = 60_000;
15
+ /** The wait before the runtime tries again to start a webhook or `once` firing whose start failed. */
16
+ const START_RETRY_MS = 5000;
17
+ /** How long the runtime keeps the record of a Trigger Run for `isDeliverySuppressed`. */
18
+ const RUN_RECORD_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
19
+ const TRIGGER_COLUMNS = `id, name, prompt, schedule_json, target_binding_id, target_chat_id, conversation_mode, paused,
20
+ created_by, created_at, last_fired_at, next_fire_at`;
21
+ const decoder = new TextDecoder();
22
+ const iso = (epochMs) => new Date(epochMs).toISOString();
23
+ const isoOrNull = (epochMs) => epochMs === null ? null : iso(epochMs);
24
+ const parseSchedule = (json) => {
25
+ const value = JSON.parse(json);
26
+ if (!Value.Check(TriggerScheduleSchema, value)) {
27
+ throw new TypeError("Stored Trigger schedule is invalid");
28
+ }
29
+ return value;
30
+ };
31
+ const CONVERSATION_MODES = [
32
+ "per_firing",
33
+ "shared",
34
+ ];
35
+ const CREATORS = ["agent", "operator"];
36
+ const toTrigger = (row) => {
37
+ const paused = integerColumn(row, "paused") === 1;
38
+ return {
39
+ conversationMode: enumColumn(row, "conversation_mode", CONVERSATION_MODES),
40
+ createdAt: iso(integerColumn(row, "created_at")),
41
+ createdBy: enumColumn(row, "created_by", CREATORS),
42
+ id: textColumn(row, "id"),
43
+ lastFiredAt: isoOrNull(optionalIntegerColumn(row, "last_fired_at")),
44
+ name: textColumn(row, "name"),
45
+ nextFireAt: paused
46
+ ? null
47
+ : isoOrNull(optionalIntegerColumn(row, "next_fire_at")),
48
+ paused,
49
+ prompt: textColumn(row, "prompt"),
50
+ schedule: parseSchedule(textColumn(row, "schedule_json")),
51
+ target: {
52
+ bindingId: textColumn(row, "target_binding_id"),
53
+ chatId: textColumn(row, "target_chat_id"),
54
+ },
55
+ };
56
+ };
57
+ const HeadersSchema = Type.Record(Type.String(), Type.String());
58
+ const parseHeaders = (json) => {
59
+ const value = JSON.parse(json);
60
+ if (!Value.Check(HeadersSchema, value)) {
61
+ throw new TypeError("Stored webhook headers are invalid");
62
+ }
63
+ return value;
64
+ };
65
+ const assertActorMayChange = (actor, schedule) => {
66
+ if (actor === "agent" && schedule.kind === "webhook") {
67
+ throw new SeamError("forbidden", "Only the Operator manages webhook Triggers");
68
+ }
69
+ };
70
+ /**
71
+ * The `TriggerRuntime` of one Agent over `agent.sqlite` (ADR 0010), with its scheduler.
72
+ *
73
+ * The scheduler runs between `start` and `stop`. Before `start`, the runtime stores Triggers and webhook events but
74
+ * fires nothing on schedule. `start` skips every `cron` tick that passed while the Agent was down, fires each overdue
75
+ * `once` Trigger one time, and fires the stored webhook events in arrival order.
76
+ *
77
+ * Scheduled firings and webhook firings run one at a time, in due order. `fire` starts a Run at once.
78
+ */
79
+ export class SqliteTriggerRuntime {
80
+ #options;
81
+ #starts = new Set();
82
+ #timer;
83
+ #webhookRetry;
84
+ #queue = Promise.resolve();
85
+ #running = false;
86
+ constructor(options) {
87
+ this.#options = options;
88
+ }
89
+ list = async () => await Promise.try(() => this.#db
90
+ .prepare(`SELECT ${TRIGGER_COLUMNS} FROM triggers_definitions ORDER BY seq`)
91
+ .all()
92
+ .map(toTrigger));
93
+ get = async (triggerId) => await Promise.try(() => this.#read(triggerId));
94
+ create = async (input, actor) => await Promise.try(() => this.#create(input, actor));
95
+ update = async (triggerId, patch, actor) => await Promise.try(() => this.#update(triggerId, patch, actor));
96
+ delete = async (triggerId, actor) => await Promise.try(() => this.#delete(triggerId, actor));
97
+ fire = async (triggerId) => await this.#fire(this.#require(triggerId), undefined);
98
+ webhookTokenSecret = async (triggerId) => await Promise.try(() => {
99
+ const trigger = this.#read(triggerId);
100
+ return trigger?.schedule.kind === "webhook" && !trigger.paused
101
+ ? trigger.schedule.tokenSecret
102
+ : undefined;
103
+ });
104
+ acceptWebhookEvent = async (triggerId, event) => {
105
+ const secret = await this.webhookTokenSecret(triggerId);
106
+ if (secret === undefined) {
107
+ throw new SeamError("not_found", `No active webhook Trigger ${triggerId}`);
108
+ }
109
+ const eventId = randomUUID();
110
+ this.#db
111
+ .prepare("INSERT INTO triggers_webhook_events (id, trigger_id, received_at, headers_json, body) VALUES (?, ?, ?, ?, ?)")
112
+ .run(eventId, triggerId, event.receivedAt, JSON.stringify(event.headers), event.body);
113
+ this.#enqueue(this.#drainWebhookEvents);
114
+ return { eventId };
115
+ };
116
+ isDeliverySuppressed = async (runId) => {
117
+ await this.#settleStarts();
118
+ return (this.#db
119
+ .prepare("SELECT 1 FROM triggers_runs WHERE run_id = ? AND suppressed = 1")
120
+ .get(runId) !== undefined);
121
+ };
122
+ /**
123
+ * Marks the Trigger Run `runId` so that `isDeliverySuppressed` resolves `true`. It backs the `suppress_delivery` Tool.
124
+ *
125
+ * Waits for Run starts in progress first, because a Run can call the Tool before `TriggerRunner.start` resolves.
126
+ * Resolves `false` if no Trigger started the Run.
127
+ */
128
+ suppressDelivery = async (runId) => {
129
+ await this.#settleStarts();
130
+ const { changes } = this.#db
131
+ .prepare("UPDATE triggers_runs SET suppressed = 1 WHERE run_id = ?")
132
+ .run(runId);
133
+ return Number(changes) > 0;
134
+ };
135
+ /**
136
+ * Starts the scheduler. It skips missed `cron` ticks, fires overdue `once` Triggers one time, and fires stored webhook
137
+ * events. Resolves after the first scheduler pass started. Calling it twice does nothing.
138
+ */
139
+ start = async () => {
140
+ await Promise.try(() => {
141
+ if (this.#running) {
142
+ return;
143
+ }
144
+ this.#running = true;
145
+ this.#db
146
+ .prepare("DELETE FROM triggers_runs WHERE started_at < ?")
147
+ .run(this.#now() - RUN_RECORD_RETENTION_MS);
148
+ this.#skipMissedCronTicks();
149
+ this.#enqueue(this.#drainWebhookEvents);
150
+ this.#enqueue(this.#runDue);
151
+ });
152
+ };
153
+ /** Stops the scheduler and waits for the scheduler work in progress. Repeated calls do nothing. */
154
+ stop = async () => {
155
+ this.#running = false;
156
+ clearTimeout(this.#timer);
157
+ clearTimeout(this.#webhookRetry);
158
+ this.#timer = undefined;
159
+ this.#webhookRetry = undefined;
160
+ await this.#queue;
161
+ };
162
+ get #db() {
163
+ return this.#options.db;
164
+ }
165
+ #now = () => this.#options.clock.now();
166
+ #read = (triggerId) => {
167
+ const row = this.#db
168
+ .prepare(`SELECT ${TRIGGER_COLUMNS} FROM triggers_definitions WHERE id = ?`)
169
+ .get(triggerId);
170
+ return row === undefined ? undefined : toTrigger(row);
171
+ };
172
+ #require = (triggerId) => {
173
+ const trigger = this.#read(triggerId);
174
+ if (trigger === undefined) {
175
+ throw new SeamError("not_found", `Unknown Trigger ${triggerId}`);
176
+ }
177
+ return trigger;
178
+ };
179
+ #create = (input, actor) => {
180
+ assertActorMayChange(actor, input.schedule);
181
+ assertValidSchedule(input.schedule);
182
+ const id = randomUUID();
183
+ const now = this.#now();
184
+ this.#db
185
+ .prepare(`INSERT INTO triggers_definitions (${TRIGGER_COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?)`)
186
+ .run(id, input.name, input.prompt, JSON.stringify(input.schedule), input.target.bindingId, input.target.chatId, input.conversationMode ?? "per_firing", input.paused === true ? 1 : 0, actor, now, initialFireAt(input.schedule, now));
187
+ const trigger = this.#require(id);
188
+ this.#changed("created", id, trigger);
189
+ this.#rearm();
190
+ return trigger;
191
+ };
192
+ #update = (triggerId, patch, actor) => {
193
+ const current = this.#require(triggerId);
194
+ const schedule = patch.schedule ?? current.schedule;
195
+ const paused = patch.paused ?? current.paused;
196
+ assertActorMayChange(actor, current.schedule);
197
+ assertActorMayChange(actor, schedule);
198
+ assertValidSchedule(schedule);
199
+ const nextFireAt = this.#nextFireAtAfterUpdate(current, patch);
200
+ const target = patch.target ?? current.target;
201
+ this.#db
202
+ .prepare(`UPDATE triggers_definitions SET name = ?, prompt = ?, schedule_json = ?, target_binding_id = ?,
203
+ target_chat_id = ?, conversation_mode = ?, paused = ?, next_fire_at = ? WHERE id = ?`)
204
+ .run(patch.name ?? current.name, patch.prompt ?? current.prompt, JSON.stringify(schedule), target.bindingId, target.chatId, patch.conversationMode ?? current.conversationMode, paused ? 1 : 0, nextFireAt, triggerId);
205
+ const updated = this.#require(triggerId);
206
+ this.#changed("updated", triggerId, updated);
207
+ this.#rearm();
208
+ return updated;
209
+ };
210
+ #delete = (triggerId, actor) => {
211
+ const current = this.#read(triggerId);
212
+ if (current === undefined) {
213
+ return false;
214
+ }
215
+ assertActorMayChange(actor, current.schedule);
216
+ this.#db
217
+ .prepare("DELETE FROM triggers_definitions WHERE id = ?")
218
+ .run(triggerId);
219
+ this.#changed("deleted", triggerId);
220
+ this.#rearm();
221
+ return true;
222
+ };
223
+ #storedNextFireAt = (triggerId) => {
224
+ const row = this.#db
225
+ .prepare("SELECT next_fire_at FROM triggers_definitions WHERE id = ?")
226
+ .get(triggerId);
227
+ return row === undefined
228
+ ? null
229
+ : optionalIntegerColumn(row, "next_fire_at");
230
+ };
231
+ /**
232
+ * A new schedule starts over. A `cron` Trigger that resumes skips the ticks of its pause. An overdue `once` Trigger
233
+ * that resumes fires one time.
234
+ */
235
+ #nextFireAtAfterUpdate = (current, patch) => {
236
+ const now = this.#now();
237
+ if (patch.schedule !== undefined) {
238
+ return initialFireAt(patch.schedule, now);
239
+ }
240
+ const resumes = current.paused && patch.paused === false;
241
+ if (resumes && current.schedule.kind === "cron") {
242
+ return nextCronTick(current.schedule, now);
243
+ }
244
+ return this.#storedNextFireAt(current.id);
245
+ };
246
+ /** Emits `trigger.changed`. A `deleted` change has no `trigger`. */
247
+ #changed = (change, triggerId, trigger) => {
248
+ const payload = {
249
+ agent: this.#options.agentName,
250
+ change,
251
+ triggerId,
252
+ };
253
+ if (trigger !== undefined) {
254
+ payload.trigger = trigger;
255
+ }
256
+ this.#options.events.emit("trigger.changed", payload);
257
+ };
258
+ #settleStarts = async () => {
259
+ await Promise.allSettled(this.#starts);
260
+ };
261
+ /** Starts a Run for one firing, records it for `suppress_delivery`, and emits `fired`. */
262
+ #fire = async (trigger, event) => {
263
+ const firedAt = this.#now();
264
+ const firingId = randomUUID();
265
+ const body = event === undefined ? "" : `\n\n${decoder.decode(event.body)}`;
266
+ const firing = {
267
+ firingId,
268
+ prompt: `${trigger.prompt}${body}`,
269
+ target: trigger.target,
270
+ trigger: { ...trigger, lastFiredAt: iso(firedAt) },
271
+ };
272
+ const started = this.#options.runner.start(firing);
273
+ this.#starts.add(started);
274
+ try {
275
+ const { runId } = await started;
276
+ this.#db
277
+ .prepare("INSERT OR IGNORE INTO triggers_runs (run_id, trigger_id, firing_id, started_at) VALUES (?, ?, ?, ?)")
278
+ .run(runId, trigger.id, firingId, firedAt);
279
+ this.#db
280
+ .prepare("UPDATE triggers_definitions SET last_fired_at = ? WHERE id = ?")
281
+ .run(firedAt, trigger.id);
282
+ this.#changed("fired", trigger.id, this.#read(trigger.id) ?? firing.trigger);
283
+ return { runId };
284
+ }
285
+ finally {
286
+ this.#starts.delete(started);
287
+ }
288
+ };
289
+ /** Runs `work` after the scheduler work queued before it. A failure does not stop later work. */
290
+ #enqueue = (work) => {
291
+ const previous = this.#queue;
292
+ this.#queue = (async () => {
293
+ await previous;
294
+ if (!this.#running) {
295
+ return;
296
+ }
297
+ try {
298
+ await work();
299
+ }
300
+ catch (error) {
301
+ this.#options.log.error("Trigger scheduler work failed", {
302
+ error: errorText(error),
303
+ });
304
+ }
305
+ })();
306
+ };
307
+ /** Moves every overdue `cron` Trigger to its next future tick without a firing. */
308
+ #skipMissedCronTicks = () => {
309
+ const now = this.#now();
310
+ const rows = this.#db
311
+ .prepare(`SELECT ${TRIGGER_COLUMNS} FROM triggers_definitions WHERE next_fire_at IS NOT NULL AND next_fire_at <= ?`)
312
+ .all(now);
313
+ for (const row of rows) {
314
+ const trigger = toTrigger(row);
315
+ if (trigger.schedule.kind === "cron") {
316
+ this.#db
317
+ .prepare("UPDATE triggers_definitions SET next_fire_at = ? WHERE id = ?")
318
+ .run(nextCronTick(trigger.schedule, now), trigger.id);
319
+ this.#options.log.info("Skipped missed cron ticks", {
320
+ triggerId: trigger.id,
321
+ });
322
+ }
323
+ }
324
+ };
325
+ /** Fires every due scheduled Trigger in due order, then arms the timer for the next one. */
326
+ #runDue = async () => {
327
+ clearTimeout(this.#timer);
328
+ this.#timer = undefined;
329
+ const now = this.#now();
330
+ const rows = this.#db
331
+ .prepare(`SELECT ${TRIGGER_COLUMNS} FROM triggers_definitions
332
+ WHERE paused = 0 AND next_fire_at IS NOT NULL AND next_fire_at <= ? ORDER BY next_fire_at, seq`)
333
+ .all(now);
334
+ for (const row of rows) {
335
+ const dueAt = integerColumn(row, "next_fire_at");
336
+ // oxlint-disable-next-line no-await-in-loop -- Scheduled firings start one at a time, in due order.
337
+ await this.#runDueTrigger(toTrigger(row), dueAt, now);
338
+ }
339
+ this.#rearm();
340
+ };
341
+ /**
342
+ * Advances one due Trigger and fires it. The schedule state changes only if it still has the `dueAt` value that the
343
+ * pass read, so a concurrent `update` wins.
344
+ */
345
+ #runDueTrigger = async (trigger, dueAt, now) => {
346
+ const { schedule } = trigger;
347
+ const next = schedule.kind === "cron" ? nextCronTick(schedule, now) : null;
348
+ const { changes } = this.#db
349
+ .prepare("UPDATE triggers_definitions SET next_fire_at = ? WHERE id = ? AND next_fire_at = ?")
350
+ .run(next, trigger.id, dueAt);
351
+ if (Number(changes) === 0) {
352
+ return;
353
+ }
354
+ if (schedule.kind === "cron" && now - dueAt > CRON_GRACE_MS) {
355
+ this.#options.log.info("Skipped a missed cron tick", {
356
+ triggerId: trigger.id,
357
+ });
358
+ return;
359
+ }
360
+ if (schedule.kind === "cron" && this.#options.runner.isActive(trigger.id)) {
361
+ this.#options.log.info("Skipped a cron tick that overlaps an active Run", {
362
+ triggerId: trigger.id,
363
+ });
364
+ return;
365
+ }
366
+ try {
367
+ await this.#fire(trigger, undefined);
368
+ }
369
+ catch (error) {
370
+ this.#options.log.error("A scheduled Trigger failed to start a Run", {
371
+ error: errorText(error),
372
+ triggerId: trigger.id,
373
+ });
374
+ if (schedule.kind === "once") {
375
+ this.#retryOnce(trigger.id);
376
+ }
377
+ }
378
+ };
379
+ /**
380
+ * Schedules a `once` firing whose start failed again after `START_RETRY_MS`, so that a reminder is not lost. A
381
+ * concurrent `update` that set a new fire time wins.
382
+ */
383
+ #retryOnce = (triggerId) => {
384
+ this.#db
385
+ .prepare("UPDATE triggers_definitions SET next_fire_at = ? WHERE id = ? AND next_fire_at IS NULL")
386
+ .run(this.#now() + START_RETRY_MS, triggerId);
387
+ };
388
+ /** Fires the stored webhook events in arrival order. On a failed start, it keeps the event and tries again later. */
389
+ #drainWebhookEvents = async () => {
390
+ while (this.#running) {
391
+ const row = this.#db
392
+ .prepare(`SELECT id, trigger_id, received_at, headers_json, body FROM triggers_webhook_events ORDER BY seq LIMIT 1`)
393
+ .get();
394
+ if (row === undefined) {
395
+ return;
396
+ }
397
+ const eventId = textColumn(row, "id");
398
+ const trigger = this.#read(textColumn(row, "trigger_id"));
399
+ const event = {
400
+ body: blobColumn(row, "body"),
401
+ headers: parseHeaders(textColumn(row, "headers_json")),
402
+ receivedAt: integerColumn(row, "received_at"),
403
+ };
404
+ try {
405
+ if (trigger !== undefined) {
406
+ // oxlint-disable-next-line no-await-in-loop -- Webhook events run in arrival order.
407
+ await this.#fire(trigger, event);
408
+ }
409
+ }
410
+ catch (error) {
411
+ this.#options.log.error("A webhook Trigger failed to start a Run", {
412
+ error: errorText(error),
413
+ eventId,
414
+ });
415
+ this.#scheduleWebhookRetry();
416
+ return;
417
+ }
418
+ this.#db
419
+ .prepare("DELETE FROM triggers_webhook_events WHERE id = ?")
420
+ .run(eventId);
421
+ }
422
+ };
423
+ #scheduleWebhookRetry = () => {
424
+ clearTimeout(this.#webhookRetry);
425
+ this.#webhookRetry = setTimeout(() => {
426
+ this.#webhookRetry = undefined;
427
+ this.#enqueue(this.#drainWebhookEvents);
428
+ }, START_RETRY_MS);
429
+ this.#webhookRetry.unref();
430
+ };
431
+ /** Arms the timer for the earliest scheduled firing. */
432
+ #rearm = () => {
433
+ if (!this.#running) {
434
+ return;
435
+ }
436
+ clearTimeout(this.#timer);
437
+ const row = this.#db
438
+ .prepare("SELECT min(next_fire_at) AS due FROM triggers_definitions WHERE paused = 0 AND next_fire_at IS NOT NULL")
439
+ .get();
440
+ this.#timer = armDueTimer(row === undefined ? null : optionalIntegerColumn(row, "due"), this.#now(), () => {
441
+ this.#timer = undefined;
442
+ this.#enqueue(this.#runDue);
443
+ });
444
+ };
445
+ }
@@ -0,0 +1,207 @@
1
+ import { parseDuration, TRIGGER_NAME_MAX_LENGTH } from "@wheatley-ai/protocol";
2
+ import { Type } from "typebox";
3
+ import { Value } from "typebox/value";
4
+ import { canonicalToolName } from "../contracts/tool-names.js";
5
+ import { errorText } from "./errors.js";
6
+ const ChatTargetSchema = Type.Object({
7
+ bindingId: Type.String({ minLength: 1 }),
8
+ chatId: Type.String({ minLength: 1 }),
9
+ }, { additionalProperties: false });
10
+ const ScheduleInputSchema = Type.Union([
11
+ Type.Object({
12
+ kind: Type.Literal("cron"),
13
+ schedule: Type.String({
14
+ description: "A 5-field cron expression: minute hour day-of-month month day-of-week, for example `0 8 * * 1-5`.",
15
+ minLength: 1,
16
+ }),
17
+ timezone: Type.String({
18
+ description: "An IANA time zone, for example `Europe/Berlin`.",
19
+ minLength: 1,
20
+ }),
21
+ }, { additionalProperties: false }),
22
+ Type.Object({
23
+ at: Type.String({
24
+ description: "An ISO 8601 date and time with an offset, for example `2026-12-01T09:00:00+01:00`.",
25
+ pattern: String.raw `^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$`,
26
+ }),
27
+ kind: Type.Literal("once"),
28
+ }, { additionalProperties: false }),
29
+ Type.Object({
30
+ delay: Type.String({
31
+ description: "A delay from now, for example `90s`, `15m`, `2h`, or `1d`.",
32
+ pattern: "^[0-9]+(ms|s|m|h|d)$",
33
+ }),
34
+ kind: Type.Literal("once"),
35
+ }, { additionalProperties: false }),
36
+ ]);
37
+ const ScheduleTriggerInputSchema = Type.Object({
38
+ conversationMode: Type.Optional(Type.Union([Type.Literal("per_firing"), Type.Literal("shared")], {
39
+ description: "`per_firing` (default) starts a new Conversation for each firing. `shared` keeps one Conversation.",
40
+ })),
41
+ name: Type.String({ maxLength: TRIGGER_NAME_MAX_LENGTH, minLength: 1 }),
42
+ prompt: Type.String({
43
+ description: "The instruction that each firing runs.",
44
+ minLength: 1,
45
+ }),
46
+ schedule: ScheduleInputSchema,
47
+ target: Type.Optional(Type.Object(ChatTargetSchema.properties, {
48
+ additionalProperties: false,
49
+ description: "The Chat that receives the result. The default is the current Chat.",
50
+ })),
51
+ }, { additionalProperties: false });
52
+ const EmptyInputSchema = Type.Object({}, { additionalProperties: false });
53
+ const CancelTriggerInputSchema = Type.Object({ triggerId: Type.String({ minLength: 1 }) }, { additionalProperties: false });
54
+ /** The Trigger Tools hold no resources, so `close` resolves at once. */
55
+ const NOTHING_TO_CLOSE = Promise.resolve();
56
+ const textResult = (text) => ({
57
+ content: [{ text, type: "text" }],
58
+ });
59
+ const errorResult = (text) => ({
60
+ content: [{ text, type: "text" }],
61
+ isError: true,
62
+ });
63
+ const jsonResult = (value) => textResult(JSON.stringify(value, null, 2));
64
+ const summary = (trigger) => ({
65
+ conversationMode: trigger.conversationMode,
66
+ createdBy: trigger.createdBy,
67
+ id: trigger.id,
68
+ lastFiredAt: trigger.lastFiredAt,
69
+ name: trigger.name,
70
+ nextFireAt: trigger.nextFireAt,
71
+ paused: trigger.paused,
72
+ prompt: trigger.prompt,
73
+ schedule: trigger.schedule,
74
+ target: trigger.target,
75
+ });
76
+ /** Converts Tool schedule input into a stored schedule. Throws a `RangeError` for an unreadable time. */
77
+ const toSchedule = (input, now) => {
78
+ if (input.kind === "cron") {
79
+ return input;
80
+ }
81
+ const at = "at" in input ? Date.parse(input.at) : now + parseDuration(input.delay);
82
+ if (Number.isNaN(at)) {
83
+ throw new RangeError(`Invalid time: ${"at" in input ? input.at : input.delay}`);
84
+ }
85
+ return { at: new Date(at).toISOString(), kind: "once" };
86
+ };
87
+ const defineTriggerTool = (tool) => tool;
88
+ const scheduleTrigger = defineTriggerTool({
89
+ defaultAction: "allow",
90
+ description: "Schedule a reminder or recurring task. A `cron` schedule repeats in a time zone. A `once` schedule fires one " +
91
+ "time at `at` or after `delay`. The result goes to the current Chat unless you set `target`.",
92
+ execute: async (input, ctx, { clock, runtime }) => {
93
+ const target = input.target ?? ctx.chat;
94
+ if (target === null) {
95
+ return errorResult("This Run has no Chat. Set `target` to the Chat that receives the result.");
96
+ }
97
+ const trigger = await runtime.create({
98
+ conversationMode: input.conversationMode ?? "per_firing",
99
+ name: input.name,
100
+ prompt: input.prompt,
101
+ schedule: toSchedule(input.schedule, clock.now()),
102
+ target,
103
+ }, "agent");
104
+ return jsonResult(summary(trigger));
105
+ },
106
+ inputSchema: ScheduleTriggerInputSchema,
107
+ name: "schedule_trigger",
108
+ });
109
+ const listTriggers = defineTriggerTool({
110
+ defaultAction: "allow",
111
+ description: "List every Trigger of this Agent with its schedule, next fire time, and target Chat.",
112
+ execute: async (_input, _ctx, { runtime }) => {
113
+ const triggers = await runtime.list();
114
+ return jsonResult(triggers.map(summary));
115
+ },
116
+ inputSchema: EmptyInputSchema,
117
+ name: "list_triggers",
118
+ });
119
+ const cancelTrigger = defineTriggerTool({
120
+ defaultAction: "allow",
121
+ description: "Delete a `cron` or `once` Trigger by ID. Only the Operator can delete `webhook` Triggers.",
122
+ execute: async (input, _ctx, { runtime }) => {
123
+ const deleted = await runtime.delete(input.triggerId, "agent");
124
+ return deleted
125
+ ? textResult(`Deleted Trigger ${input.triggerId}.`)
126
+ : errorResult(`No Trigger has the ID ${input.triggerId}.`);
127
+ },
128
+ inputSchema: CancelTriggerInputSchema,
129
+ name: "cancel_trigger",
130
+ });
131
+ const suppressDelivery = defineTriggerTool({
132
+ defaultAction: "allow",
133
+ description: "In a Run that a Trigger started, do not send the final reply to the target Chat, for example when a check " +
134
+ "found nothing to report.",
135
+ execute: async (_input, ctx, deps) => {
136
+ const suppressed = await deps.suppressDelivery(ctx.runId);
137
+ return suppressed
138
+ ? textResult("The final reply of this Run will not be delivered.")
139
+ : errorResult("suppress_delivery works only in a Run that a Trigger started.");
140
+ },
141
+ inputSchema: EmptyInputSchema,
142
+ name: "suppress_delivery",
143
+ });
144
+ const isJsonSchema = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
145
+ /** Copies a TypeBox schema into plain JSON Schema for the model provider. */
146
+ const plainSchema = (schema) => {
147
+ const plain = structuredClone(schema);
148
+ if (!isJsonSchema(plain)) {
149
+ throw new TypeError("A Tool schema is not a JSON object");
150
+ }
151
+ return plain;
152
+ };
153
+ /** Binds a Tool to its dependencies. `run` checks the input against the Tool's schema first. */
154
+ const bind = (tool, deps) => ({
155
+ descriptor: {
156
+ defaultAction: tool.defaultAction,
157
+ description: tool.description,
158
+ inputSchema: plainSchema(tool.inputSchema),
159
+ name: canonicalToolName({ kind: "builtin" }, tool.name),
160
+ source: "builtin",
161
+ },
162
+ run: async (input, ctx) => {
163
+ if (!Value.Check(tool.inputSchema, input)) {
164
+ const issues = Value.Errors(tool.inputSchema, input)
165
+ .map((error) => `${error.instancePath || "/"} ${error.message}`)
166
+ .join("; ");
167
+ return errorResult(`Invalid input for ${tool.name}: ${issues}`);
168
+ }
169
+ return await tool.execute(input, ctx, deps);
170
+ },
171
+ });
172
+ /**
173
+ * Creates the `ToolProvider` of the built-in Trigger Tools: `schedule_trigger`, `list_triggers`, `cancel_trigger`, and
174
+ * `suppress_delivery` (ADR 0010). The Permission Policy governs every call. Agents cannot create, change, or delete
175
+ * `webhook` Triggers through these Tools.
176
+ */
177
+ export const createTriggerToolProvider = (deps) => {
178
+ const tools = new Map([
179
+ bind(scheduleTrigger, deps),
180
+ bind(listTriggers, deps),
181
+ bind(cancelTrigger, deps),
182
+ bind(suppressDelivery, deps),
183
+ ].map((tool) => [tool.descriptor.name, tool]));
184
+ const descriptors = [...tools.values()].map((tool) => tool.descriptor);
185
+ return {
186
+ close: async () => {
187
+ await NOTHING_TO_CLOSE;
188
+ },
189
+ execute: async (name, input, ctx) => {
190
+ const tool = tools.get(name);
191
+ if (tool === undefined) {
192
+ return errorResult(`Unknown Tool: ${name}`);
193
+ }
194
+ if (ctx.signal.aborted) {
195
+ return errorResult(`${name} was aborted`);
196
+ }
197
+ try {
198
+ return await tool.run(input, ctx);
199
+ }
200
+ catch (error) {
201
+ return errorResult(errorText(error));
202
+ }
203
+ },
204
+ health: () => [],
205
+ tools: () => descriptors,
206
+ };
207
+ };