@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,347 @@
1
+ import { mkdir, rename, rm, stat } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { PROTOCOL_VERSION } from "@wheatley-ai/protocol";
4
+ import { SeamError } from "../contracts/errors.js";
5
+ import { systemClock } from "../contracts/module.js";
6
+ import { Agent } from "./agent/agent.js";
7
+ import { gatedModels } from "./agent/gated-models.js";
8
+ import { builtinOnlyCatalog } from "./builtin-catalog.js";
9
+ import { ConcurrencyGate, DEFAULT_PROVIDER_CONCURRENCY, } from "./concurrency-gate.js";
10
+ import { FileConfigStore } from "./config/config-store.js";
11
+ import { pendingRestarts } from "./config/pending-restart.js";
12
+ import { EventBus } from "./events.js";
13
+ import { LogStore } from "./logger.js";
14
+ import { createProviderModels } from "./models.js";
15
+ import { Supervisor } from "./supervisor.js";
16
+ /** The folder of the Agents inside the Deployment home. */
17
+ export const AGENTS_DIR = "agents";
18
+ /** The folder that `agents.delete` with `data: "archive"` moves Agent folders into. */
19
+ export const ARCHIVE_DIR = "archive";
20
+ /** The health fields of an Agent that is not running. */
21
+ const IDLE_STATUS = {
22
+ activeRuns: 0,
23
+ frontends: [],
24
+ mcpServers: [],
25
+ plugins: [],
26
+ skillWarnings: [],
27
+ };
28
+ const exists = async (target) => {
29
+ try {
30
+ await stat(target);
31
+ return true;
32
+ }
33
+ catch {
34
+ return false;
35
+ }
36
+ };
37
+ /**
38
+ * One running Wheatley installation: the Config Store, the Supervisor of its Agents, the Concurrency Gate, the event
39
+ * bus, and the log buffer (ADR 0001, ADR 0004).
40
+ *
41
+ * Agent lifecycle calls (`createAgent`, `renameAgent`, `deleteAgent`) check `expectedRevision` through the Config Store
42
+ * first and change nothing if it fails.
43
+ */
44
+ export class Deployment {
45
+ homeDir;
46
+ events = new EventBus();
47
+ logs;
48
+ config;
49
+ gate;
50
+ #options;
51
+ #clock;
52
+ #supervisor;
53
+ #applied = new Map();
54
+ #startedAt;
55
+ #current;
56
+ #daemonConfig;
57
+ constructor(options, config, initial) {
58
+ this.#options = options;
59
+ this.homeDir = options.homeDir;
60
+ this.config = config;
61
+ this.#clock = options.clock ?? systemClock;
62
+ this.#startedAt = this.#clock.now();
63
+ this.#current = initial;
64
+ this.#daemonConfig = initial;
65
+ this.logs = new LogStore({
66
+ clock: this.#clock,
67
+ events: this.events,
68
+ redact: config.secrets.redact,
69
+ write: options.writeLog,
70
+ });
71
+ this.gate = new ConcurrencyGate((provider) => this.#current.providers?.[provider]?.maxConcurrent ??
72
+ DEFAULT_PROVIDER_CONCURRENCY);
73
+ this.#supervisor = new Supervisor({
74
+ clock: this.#clock,
75
+ events: this.events,
76
+ log: this.logs.logger("supervisor"),
77
+ open: this.#openAgent,
78
+ setTimer: options.setTimer,
79
+ });
80
+ }
81
+ /**
82
+ * Reads `config.yaml` and creates the Deployment without starting any Agent. Errors: rejects with
83
+ * `SeamError("config_invalid")` if `config.yaml` is invalid.
84
+ */
85
+ static async create(options) {
86
+ const config = options.configStore ??
87
+ (await FileConfigStore.open({
88
+ env: options.env,
89
+ homeDir: options.homeDir,
90
+ }));
91
+ const snapshot = await config.read();
92
+ await mkdir(path.join(options.homeDir, AGENTS_DIR), { recursive: true });
93
+ return new Deployment(options, config, snapshot.config);
94
+ }
95
+ /** `create`, then `start`. */
96
+ static async open(options) {
97
+ const deployment = await Deployment.create(options);
98
+ await deployment.start();
99
+ return deployment;
100
+ }
101
+ /**
102
+ * Starts every Agent in `config.yaml`, all at once, and resolves when each is `running` or `degraded`. An Agent that
103
+ * fails to start does not stop the others.
104
+ */
105
+ start = async () => {
106
+ await Promise.all(Object.keys(this.#current.agents).map(async (name) => await this.#supervisor.start(name)));
107
+ };
108
+ /** The Agent folder of `name`. */
109
+ agentDir = (name) => path.join(this.homeDir, AGENTS_DIR, name);
110
+ /** The names of every Agent that `config.yaml` lists or the Supervisor knows, sorted. */
111
+ get agentNames() {
112
+ return [
113
+ ...new Set([
114
+ ...Object.keys(this.#current.agents),
115
+ ...this.#supervisor.names,
116
+ ]),
117
+ ].toSorted();
118
+ }
119
+ /** The running Agent `name`. Throws `agent_not_found` for an unknown Agent and `agent_unavailable` otherwise. */
120
+ agent = (name) => {
121
+ const state = this.#supervisor.get(name);
122
+ if (state === undefined && this.#current.agents[name] === undefined) {
123
+ throw new SeamError("agent_not_found", `Unknown Agent: ${name}`);
124
+ }
125
+ if (state?.instance === undefined) {
126
+ throw new SeamError("agent_unavailable", `Agent ${name} is ${state?.state ?? "stopped"}`);
127
+ }
128
+ return state.instance;
129
+ };
130
+ /** Health of one Agent. Throws `SeamError("agent_not_found")`. */
131
+ health = (name) => {
132
+ const state = this.#supervisor.get(name);
133
+ if (state === undefined && this.#current.agents[name] === undefined) {
134
+ throw new SeamError("agent_not_found", `Unknown Agent: ${name}`);
135
+ }
136
+ const status = state?.instance?.status() ?? IDLE_STATUS;
137
+ const pending = pendingRestarts(this.#appliedConfig(), this.#current);
138
+ return {
139
+ activeRuns: status.activeRuns,
140
+ frontends: [...status.frontends],
141
+ lastError: state?.lastError ?? null,
142
+ mcpServers: [...status.mcpServers],
143
+ name,
144
+ pendingRestart: pending.some((item) => item.kind !== "daemon" && item.agent === name),
145
+ plugins: [...status.plugins],
146
+ restartBackoffMs: state?.restartBackoffMs ?? null,
147
+ skillWarnings: [...status.skillWarnings],
148
+ state: state?.state ?? "stopped",
149
+ };
150
+ };
151
+ /** Deployment health for `system.status`. */
152
+ status = () => {
153
+ const now = this.#clock.now();
154
+ return {
155
+ agents: this.agentNames.map((name) => this.health(name)),
156
+ concurrency: this.gate.pressure(),
157
+ protocolVersion: PROTOCOL_VERSION,
158
+ startedAt: new Date(this.#startedAt).toISOString(),
159
+ uptimeMs: Math.max(0, now - this.#startedAt),
160
+ version: this.#options.version,
161
+ };
162
+ };
163
+ startAgent = async (name) => {
164
+ this.#requireConfigured(name);
165
+ return await this.#supervisor.start(name);
166
+ };
167
+ stopAgent = async (name) => {
168
+ this.#requireKnown(name);
169
+ return await this.#supervisor.stop(name);
170
+ };
171
+ restartAgent = async (name) => {
172
+ this.#requireConfigured(name);
173
+ return await this.#supervisor.restart(name);
174
+ };
175
+ /** `config.get`: the current file, its revision, and the changes that wait for a restart. */
176
+ getConfig = async () => {
177
+ const snapshot = await this.config.read();
178
+ this.#current = snapshot.config;
179
+ return {
180
+ config: snapshot.config,
181
+ pendingRestart: pendingRestarts(this.#appliedConfig(), snapshot.config),
182
+ raw: snapshot.raw,
183
+ revision: snapshot.revision,
184
+ };
185
+ };
186
+ /**
187
+ * `config.save`: writes the config, starts Agents that the save added, stops Agents that it removed, and with
188
+ * `restart: "affected"` restarts every Agent with a pending change. Emits `config.changed`.
189
+ */
190
+ saveConfig = async (input, expectedRevision, restart) => {
191
+ const snapshot = await this.config.save(input, expectedRevision);
192
+ await this.#apply(snapshot.config);
193
+ if (restart === "affected") {
194
+ const affected = new Set(pendingRestarts(this.#appliedConfig(), snapshot.config).flatMap((item) => (item.kind === "daemon" ? [] : [item.agent])));
195
+ await Promise.all([...affected].map(async (name) => await this.#supervisor.restart(name)));
196
+ }
197
+ return this.#changed(snapshot.revision);
198
+ };
199
+ /** `agents.create`: adds the Agent to `config.yaml` and starts it. Throws `conflict` for an existing name. */
200
+ createAgent = async (name, config, expectedRevision) => {
201
+ const current = await this.config.read();
202
+ if (current.config.agents[name] !== undefined ||
203
+ this.#supervisor.get(name) !== undefined) {
204
+ throw new SeamError("conflict", `Agent ${name} already exists`);
205
+ }
206
+ const snapshot = await this.config.save({
207
+ config: {
208
+ ...current.config,
209
+ agents: { ...current.config.agents, [name]: config },
210
+ },
211
+ }, expectedRevision);
212
+ await this.#apply(snapshot.config);
213
+ return { revision: this.#changed(snapshot.revision).revision };
214
+ };
215
+ /**
216
+ * `agents.rename`: stops the Agent, moves its folder, renames it in `config.yaml`, and starts it under the new name.
217
+ * If the config write fails, it moves the folder back and starts the Agent under its old name.
218
+ */
219
+ renameAgent = async (name, newName, expectedRevision) => {
220
+ const current = await this.config.read();
221
+ const agentConfig = current.config.agents[name];
222
+ if (agentConfig === undefined) {
223
+ throw new SeamError("agent_not_found", `Unknown Agent: ${name}`);
224
+ }
225
+ if (current.config.agents[newName] !== undefined ||
226
+ (await exists(this.agentDir(newName)))) {
227
+ throw new SeamError("conflict", `Agent ${newName} already exists`);
228
+ }
229
+ if (current.revision !== expectedRevision) {
230
+ throw new SeamError("revision_conflict", "config.yaml changed since it was read", {
231
+ revision: current.revision,
232
+ });
233
+ }
234
+ const agents = Object.fromEntries(Object.entries(current.config.agents).map(([key, value]) => [
235
+ key === name ? newName : key,
236
+ value,
237
+ ]));
238
+ await this.#supervisor.remove(name);
239
+ this.#applied.delete(name);
240
+ const moved = await exists(this.agentDir(name));
241
+ if (moved) {
242
+ await rename(this.agentDir(name), this.agentDir(newName));
243
+ }
244
+ try {
245
+ const snapshot = await this.config.save({ config: { ...current.config, agents } }, expectedRevision);
246
+ await this.#apply(snapshot.config);
247
+ return { revision: this.#changed(snapshot.revision).revision };
248
+ }
249
+ catch (error) {
250
+ if (moved) {
251
+ await rename(this.agentDir(newName), this.agentDir(name));
252
+ }
253
+ await this.#supervisor.start(name);
254
+ throw error;
255
+ }
256
+ };
257
+ /** `agents.delete`: removes the Agent from `config.yaml`, stops it, and keeps, archives, or deletes its folder. */
258
+ deleteAgent = async (params) => {
259
+ const current = await this.config.read();
260
+ if (current.config.agents[params.agent] === undefined) {
261
+ throw new SeamError("agent_not_found", `Unknown Agent: ${params.agent}`);
262
+ }
263
+ const agents = Object.fromEntries(Object.entries(current.config.agents).filter(([key]) => key !== params.agent));
264
+ const snapshot = await this.config.save({ config: { ...current.config, agents } }, params.expectedRevision);
265
+ await this.#apply(snapshot.config);
266
+ const dir = this.agentDir(params.agent);
267
+ if (params.data === "delete") {
268
+ await rm(dir, { force: true, recursive: true });
269
+ }
270
+ else if (params.data === "archive" && (await exists(dir))) {
271
+ const stamp = new Date(this.#clock.now())
272
+ .toISOString()
273
+ .replaceAll(":", "-");
274
+ const archiveDir = path.join(this.homeDir, ARCHIVE_DIR);
275
+ await mkdir(archiveDir, { recursive: true });
276
+ await rename(dir, path.join(archiveDir, `${params.agent}-${stamp}`));
277
+ }
278
+ return { revision: this.#changed(snapshot.revision).revision };
279
+ };
280
+ /** Stops every Agent. */
281
+ close = async () => {
282
+ await this.#supervisor.stopAll();
283
+ };
284
+ #requireKnown = (name) => {
285
+ if (this.#supervisor.get(name) === undefined &&
286
+ this.#current.agents[name] === undefined) {
287
+ throw new SeamError("agent_not_found", `Unknown Agent: ${name}`);
288
+ }
289
+ };
290
+ #requireConfigured = (name) => {
291
+ if (this.#current.agents[name] === undefined) {
292
+ throw new SeamError("agent_not_found", `Unknown Agent: ${name}`);
293
+ }
294
+ };
295
+ /** Starts Agents that `config` added and stops Agents that it removed. */
296
+ #apply = async (config) => {
297
+ this.#current = config;
298
+ const removed = this.#supervisor.names.filter((name) => config.agents[name] === undefined);
299
+ const added = Object.keys(config.agents).filter((name) => this.#supervisor.get(name) === undefined);
300
+ await Promise.all(removed.map(async (name) => {
301
+ await this.#supervisor.remove(name);
302
+ this.#applied.delete(name);
303
+ }));
304
+ await Promise.all(added.map(async (name) => await this.#supervisor.start(name)));
305
+ };
306
+ #changed = (revision) => {
307
+ const pendingRestart = pendingRestarts(this.#appliedConfig(), this.#current);
308
+ this.events.emit("config.changed", { pendingRestart, revision });
309
+ return { pendingRestart, revision };
310
+ };
311
+ #appliedConfig = () => ({
312
+ agents: new Map([...this.#applied.entries()].filter(([name]) => this.#supervisor.get(name)?.instance !== undefined)),
313
+ daemon: this.#daemonConfig,
314
+ });
315
+ #openAgent = async (name, controls) => {
316
+ const snapshot = await this.config.read();
317
+ this.#current = snapshot.config;
318
+ const config = snapshot.config.agents[name];
319
+ if (config === undefined) {
320
+ throw new SeamError("agent_not_found", `Unknown Agent: ${name}`);
321
+ }
322
+ const providers = snapshot.config.providers ?? {};
323
+ const createModels = this.#options.models ?? createProviderModels;
324
+ const base = await createModels(snapshot.config, this.config.secrets);
325
+ const models = gatedModels(base, this.gate, (provider) => this.#current.providers?.[provider]?.baseUrl);
326
+ const agent = await Agent.open({
327
+ ...this.#options.agentServices?.(name, config),
328
+ agentDir: this.agentDir(name),
329
+ clock: this.#clock,
330
+ config,
331
+ events: this.events,
332
+ extensions: this.#options.extensions ?? builtinOnlyCatalog,
333
+ homeDir: this.homeDir,
334
+ log: this.logs.logger("agent", name),
335
+ models,
336
+ name,
337
+ onFailed: controls.onFailed,
338
+ onRestartRequested: controls.onRestartRequested,
339
+ secrets: this.config.secrets,
340
+ });
341
+ this.#applied.set(name, {
342
+ config,
343
+ provider: providers[config.model.provider],
344
+ });
345
+ return agent;
346
+ };
347
+ }
@@ -0,0 +1,4 @@
1
+ /** The message of a thrown value: `Error.message` for an `Error`, otherwise the value as a string. */
2
+ export const errorMessage = (
3
+ // oxlint-disable-next-line anti-slop/no-unknown-parameters -- A caught value has no type, and this helper only reads its message.
4
+ error) => (error instanceof Error ? error.message : String(error));
@@ -0,0 +1,25 @@
1
+ /**
2
+ * The Deployment-wide event bus. Modules emit through it as an `EventSink`, and each Control Server connection
3
+ * listens and filters by its subscriptions. Listeners run synchronously in subscription order. A throwing listener is
4
+ * skipped, so one connection cannot block another.
5
+ */
6
+ export class EventBus {
7
+ #listeners = new Set();
8
+ emit = (name, payload) => {
9
+ for (const listener of this.#listeners) {
10
+ try {
11
+ listener(name, payload);
12
+ }
13
+ catch {
14
+ // A listener failure must not reach the emitter or other listeners.
15
+ }
16
+ }
17
+ };
18
+ /** Adds a listener and returns the function that removes it. */
19
+ listen = (listener) => {
20
+ this.#listeners.add(listener);
21
+ return () => {
22
+ this.#listeners.delete(listener);
23
+ };
24
+ };
25
+ }
@@ -0,0 +1,81 @@
1
+ import { isJsonValue } from "@wheatley-ai/protocol";
2
+ /** The number of records that `logs.tail` can return. */
3
+ export const LOG_BUFFER_SIZE = 2000;
4
+ const LEVEL_ORDER = {
5
+ debug: 0,
6
+ error: 3,
7
+ info: 1,
8
+ warn: 2,
9
+ };
10
+ const isJsonObject = (value) => isJsonValue(value) &&
11
+ typeof value === "object" &&
12
+ value !== null &&
13
+ !Array.isArray(value);
14
+ const redactFields = (fields, redact) => {
15
+ try {
16
+ const parsed = JSON.parse(redact(JSON.stringify(fields)));
17
+ return isJsonObject(parsed) ? parsed : undefined;
18
+ }
19
+ catch {
20
+ return undefined;
21
+ }
22
+ };
23
+ /**
24
+ * Keeps the last `LOG_BUFFER_SIZE` diagnostic records of the daemon for `logs.tail`, and emits each record as a
25
+ * `log.record` event. Records never contain secret values: messages and fields pass through `redact` first.
26
+ */
27
+ export class LogStore {
28
+ #options;
29
+ #records = [];
30
+ #seq = 0;
31
+ constructor(options) {
32
+ this.#options = options;
33
+ }
34
+ /** Returns a `Logger` that tags its records with `module` and, if given, `agent`. */
35
+ logger = (module, agent) => {
36
+ const log = (level) => (message, fields) => {
37
+ this.#record(level, module, agent, message, fields);
38
+ };
39
+ return {
40
+ debug: log("debug"),
41
+ error: log("error"),
42
+ info: log("info"),
43
+ warn: log("warn"),
44
+ };
45
+ };
46
+ /** Returns the newest matching records, oldest first. */
47
+ tail = (filter) => {
48
+ const minimum = LEVEL_ORDER[filter.level ?? "debug"];
49
+ const matching = this.#records.filter((record) => LEVEL_ORDER[record.level] >= minimum &&
50
+ (filter.agent === undefined || record.agent === filter.agent) &&
51
+ (filter.module === undefined || record.module === filter.module));
52
+ return matching.slice(-filter.limit);
53
+ };
54
+ #record = (level, module, agent, message, fields) => {
55
+ if (LEVEL_ORDER[level] < LEVEL_ORDER[this.#options.minLevel ?? "info"]) {
56
+ return;
57
+ }
58
+ const { redact } = this.#options;
59
+ const safeFields = fields === undefined ? undefined : redactFields(fields, redact);
60
+ const record = {
61
+ at: new Date(this.#options.clock.now()).toISOString(),
62
+ level,
63
+ message: redact(message),
64
+ module,
65
+ seq: this.#seq,
66
+ };
67
+ if (agent !== undefined) {
68
+ record.agent = agent;
69
+ }
70
+ if (safeFields !== undefined) {
71
+ record.fields = safeFields;
72
+ }
73
+ this.#seq += 1;
74
+ this.#records.push(record);
75
+ if (this.#records.length > LOG_BUFFER_SIZE) {
76
+ this.#records.shift();
77
+ }
78
+ this.#options.write?.(record);
79
+ this.#options.events.emit("log.record", { record });
80
+ };
81
+ }
@@ -0,0 +1,27 @@
1
+ import { InMemoryCredentialStore } from "@earendil-works/pi-ai";
2
+ import { builtinModels } from "@earendil-works/pi-ai/providers/all";
3
+ /**
4
+ * Builds pi-ai `Models` with every built-in provider. A provider entry in `config.yaml` with `apiKey` gets that secret
5
+ * as its API key credential. A provider without one uses pi-ai's own environment lookup, for example
6
+ * `ANTHROPIC_API_KEY`.
7
+ *
8
+ * Errors: rejects if a provider names an `apiKey` secret that neither `secrets.yaml` nor the environment holds.
9
+ */
10
+ export const createProviderModels = async (config, secrets) => {
11
+ const credentials = new InMemoryCredentialStore();
12
+ for (const [provider, providerConfig] of Object.entries(config.providers ?? {})) {
13
+ if (providerConfig.apiKey === undefined) {
14
+ continue;
15
+ }
16
+ const key = secrets.get(providerConfig.apiKey.secret);
17
+ if (key === undefined) {
18
+ throw new Error(`The API key secret ${providerConfig.apiKey.secret} of provider ${provider} is not set`);
19
+ }
20
+ // oxlint-disable-next-line no-await-in-loop -- The credential store serializes writes per provider anyway.
21
+ await credentials.modify(provider, async () => {
22
+ await Promise.resolve();
23
+ return { key, type: "api_key" };
24
+ });
25
+ }
26
+ return builtinModels({ credentials });
27
+ };
@@ -0,0 +1,42 @@
1
+ import { CORE_NAMESPACE, coreMigrations } from "./agent/agent-store.js";
2
+ import { Deployment } from "./deployment.js";
3
+ import { createAgentRpc } from "./rpc/agent-handlers.js";
4
+ import { createDeploymentRpc } from "./rpc/deployment-handlers.js";
5
+ export { coreMigrations } from "./agent/agent-store.js";
6
+ export { startDaemon } from "./daemon.js";
7
+ export { createAgentRpc } from "./rpc/agent-handlers.js";
8
+ export { createDeploymentRpc } from "./rpc/deployment-handlers.js";
9
+ /**
10
+ * The Deployment as a Deployment-scoped module. `create` reads `config.yaml`, `start` starts every Agent, and `stop`
11
+ * stops them. Its `rpc` serves `agents.*`, `config.*`, `secrets.*`, `system.status`, and `logs.tail`.
12
+ */
13
+ export const coreDeploymentModule = {
14
+ create: async (ctx, deps) => {
15
+ const deployment = await Deployment.create({
16
+ ...deps,
17
+ clock: ctx.clock,
18
+ homeDir: ctx.homeDir,
19
+ });
20
+ return {
21
+ api: deployment,
22
+ rpc: createDeploymentRpc(deployment),
23
+ start: deployment.start,
24
+ stop: deployment.close,
25
+ };
26
+ },
27
+ name: "core",
28
+ scope: "deployment",
29
+ };
30
+ /**
31
+ * The core methods of one Agent as an Agent-scoped module: `chat.*`, `runs.*`, and `extensions.list`. Its migrations
32
+ * are `coreMigrations`, which `Agent.open` already applies, so do not pass it to `AgentOptions.modules`.
33
+ */
34
+ export const coreAgentModule = {
35
+ create: (ctx, deps) => ({
36
+ api: deps.agent,
37
+ rpc: createAgentRpc(deps.agent, ctx.agentDir),
38
+ }),
39
+ migrations: coreMigrations,
40
+ name: CORE_NAMESPACE,
41
+ scope: "agent",
42
+ };
@@ -0,0 +1,82 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { CLI_CHAT, WORKSPACE_DIR } from "../agent/agent.js";
5
+ /** The default page size of `chat.history` and `runs.list`. */
6
+ export const DEFAULT_PAGE_SIZE = 50;
7
+ /** The folder inside the workspace that keeps files uploaded with `chat.send` and `chat.ask`. */
8
+ export const UPLOADS_DIR = "uploads";
9
+ const SAFE_FILENAME = /[^A-Za-z0-9._-]/gu;
10
+ /**
11
+ * Stores uploaded files in the Agent workspace and returns the message text with a note that lists their paths, so the
12
+ * model can read them with its Tools.
13
+ */
14
+ const withAttachments = async (agentDir, text, attachments) => {
15
+ if (attachments === undefined || attachments.length === 0) {
16
+ return text;
17
+ }
18
+ const dir = path.join(agentDir, WORKSPACE_DIR, UPLOADS_DIR);
19
+ await mkdir(dir, { recursive: true });
20
+ const lines = await Promise.all(attachments.map(async (attachment) => {
21
+ const file = path.join(dir, `${randomUUID()}-${attachment.filename.replaceAll(SAFE_FILENAME, "_")}`);
22
+ await writeFile(file, Buffer.from(attachment.data, "base64"));
23
+ return `- ${file} (${attachment.mimeType})`;
24
+ }));
25
+ return `${text}\n\nAttached files:\n${lines.join("\n")}`;
26
+ };
27
+ /**
28
+ * The core JSON-RPC handlers of one running Agent: the CLI Chat (`chat.*`), Runs (`runs.*`), and `extensions.list`.
29
+ * The router gives them only requests whose `agent` names this Agent.
30
+ */
31
+ export const createAgentRpc = (agent, agentDir) => ({
32
+ "chat.ask": async (params) => {
33
+ const sent = await agent.send(CLI_CHAT, {
34
+ interactive: params.interactive,
35
+ senderDisplayName: params.senderDisplayName,
36
+ text: await withAttachments(agentDir, params.text, params.attachments),
37
+ });
38
+ return {
39
+ conversationId: sent.conversationId,
40
+ messageId: sent.messageId,
41
+ runId: sent.runId,
42
+ };
43
+ },
44
+ "chat.command": async (params) => ({
45
+ accepted: await agent.command(CLI_CHAT, params.name, params.args),
46
+ }),
47
+ "chat.history": async (params) => await agent.history(CLI_CHAT, params.before, params.limit ?? DEFAULT_PAGE_SIZE),
48
+ "chat.send": async (params) => {
49
+ const sent = await agent.send(CLI_CHAT, {
50
+ interactive: true,
51
+ senderDisplayName: params.senderDisplayName,
52
+ text: await withAttachments(agentDir, params.text, params.attachments),
53
+ });
54
+ return { messageId: sent.messageId };
55
+ },
56
+ "extensions.list": async () => {
57
+ await Promise.resolve();
58
+ const status = agent.status();
59
+ return {
60
+ frontends: [...status.frontends],
61
+ mcpServers: [...status.mcpServers],
62
+ plugins: [...status.plugins],
63
+ skills: [...agent.extensions.skills()],
64
+ tools: agent.tools(),
65
+ };
66
+ },
67
+ "runs.get": async (params) => {
68
+ await Promise.resolve();
69
+ return agent.getRun(params.runId);
70
+ },
71
+ "runs.list": async (params) => {
72
+ await Promise.resolve();
73
+ return agent.listRuns({
74
+ activeOnly: params.status === "active",
75
+ before: params.before,
76
+ limit: params.limit ?? DEFAULT_PAGE_SIZE,
77
+ });
78
+ },
79
+ "runs.stop": async (params) => ({
80
+ stopped: await agent.stopRun(params.runId),
81
+ }),
82
+ });
@@ -0,0 +1,63 @@
1
+ /** The default number of records that `logs.tail` returns. */
2
+ export const DEFAULT_LOG_TAIL = 200;
3
+ /**
4
+ * The Deployment-wide JSON-RPC handlers: Agent lifecycle (`agents.*`), config (`config.*`), secrets (`secrets.*`),
5
+ * `system.status`, and `logs.tail`. The Control Server handles `system.hello` and `events.*` per connection.
6
+ */
7
+ export const createDeploymentRpc = (deployment) => ({
8
+ "agents.create": async (params) => await deployment.createAgent(params.agent, params.config, params.expectedRevision),
9
+ "agents.delete": async (params) => await deployment.deleteAgent(params),
10
+ "agents.get": async (params) => {
11
+ await Promise.resolve();
12
+ return deployment.health(params.agent);
13
+ },
14
+ "agents.list": async () => {
15
+ await Promise.resolve();
16
+ return {
17
+ agents: deployment.agentNames.map((name) => deployment.health(name)),
18
+ };
19
+ },
20
+ "agents.rename": async (params) => await deployment.renameAgent(params.agent, params.newName, params.expectedRevision),
21
+ "agents.restart": async (params) => ({
22
+ state: await deployment.restartAgent(params.agent),
23
+ }),
24
+ "agents.start": async (params) => ({
25
+ state: await deployment.startAgent(params.agent),
26
+ }),
27
+ "agents.stop": async (params) => ({
28
+ state: await deployment.stopAgent(params.agent),
29
+ }),
30
+ "config.get": async () => await deployment.getConfig(),
31
+ "config.save": async (params) => await deployment.saveConfig("raw" in params ? { raw: params.raw } : { config: params.config }, params.expectedRevision, params.restart ?? "none"),
32
+ "config.validate": async (params) => {
33
+ const issues = await deployment.config.validate(params.raw);
34
+ return { issues: [...issues], valid: issues.length === 0 };
35
+ },
36
+ "logs.tail": async (params) => {
37
+ await Promise.resolve();
38
+ return {
39
+ records: deployment.logs.tail({
40
+ agent: params.agent,
41
+ level: params.level,
42
+ limit: params.limit ?? DEFAULT_LOG_TAIL,
43
+ module: params.module,
44
+ }),
45
+ };
46
+ },
47
+ "secrets.delete": async (params) => ({
48
+ deleted: await deployment.config.secrets.delete(params.name),
49
+ }),
50
+ "secrets.list": async () => ({
51
+ secrets: [...(await deployment.config.secrets.list())],
52
+ }),
53
+ "secrets.reveal": async (params) => ({
54
+ value: await deployment.config.secrets.reveal(params.name),
55
+ }),
56
+ "secrets.set": async (params) => ({
57
+ source: await deployment.config.secrets.set(params.name, params.value),
58
+ }),
59
+ "system.status": async () => {
60
+ await Promise.resolve();
61
+ return deployment.status();
62
+ },
63
+ });