@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,61 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, open, readFile, rename, rm } from "node:fs/promises";
3
+ import path from "node:path";
4
+ /** Reads a UTF-8 file, or resolves `undefined` if it does not exist. */
5
+ export const readTextIfExists = async (file) => {
6
+ try {
7
+ return await readFile(file, "utf-8");
8
+ }
9
+ catch (error) {
10
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
11
+ return undefined;
12
+ }
13
+ throw error;
14
+ }
15
+ };
16
+ /**
17
+ * Replaces `file` with `text` atomically: it writes and syncs a temporary file in the same folder, then renames it.
18
+ * A reader sees the old or the new file, never a half-written one. `mode` applies to the new file.
19
+ */
20
+ export const writeFileAtomic = async (file, text, mode) => {
21
+ await mkdir(path.dirname(file), { recursive: true });
22
+ const temporary = `${file}.${randomUUID()}.tmp`;
23
+ const handle = await open(temporary, "w", mode);
24
+ try {
25
+ await handle.writeFile(text, "utf-8");
26
+ await handle.chmod(mode);
27
+ await handle.sync();
28
+ }
29
+ finally {
30
+ await handle.close();
31
+ }
32
+ try {
33
+ await rename(temporary, file);
34
+ }
35
+ catch (error) {
36
+ await rm(temporary, { force: true });
37
+ throw error;
38
+ }
39
+ };
40
+ /** Waits for `promise` and ignores its outcome. */
41
+ const settled = async (promise) => {
42
+ try {
43
+ await promise;
44
+ }
45
+ catch {
46
+ // The caller of `run` receives the error. The queue only waits for the step to end.
47
+ }
48
+ };
49
+ /** Runs async steps one at a time, in call order. A failed step does not block later steps. */
50
+ export class SerialQueue {
51
+ #tail = Promise.resolve();
52
+ run = async (step) => {
53
+ const previous = this.#tail;
54
+ const result = (async () => {
55
+ await previous;
56
+ return await step();
57
+ })();
58
+ this.#tail = settled(result);
59
+ return await result;
60
+ };
61
+ }
@@ -0,0 +1,138 @@
1
+ import { createHash } from "node:crypto";
2
+ import path from "node:path";
3
+ import { isJsonValue } from "@wheatley-ai/protocol";
4
+ import { Document, parseDocument } from "yaml";
5
+ import { SeamError } from "../../contracts/errors.js";
6
+ import { readTextIfExists, SerialQueue, writeFileAtomic, } from "./atomic-file.js";
7
+ import { secretReferences } from "./secret-references.js";
8
+ import { FileSecretStore } from "./secret-store.js";
9
+ import { parseConfigText } from "./validate.js";
10
+ import { patchDocument } from "./yaml-patch.js";
11
+ /** The file mode of `config.yaml`. It holds no secret values (ADR 0004). */
12
+ export const CONFIG_FILE_MODE = 0o644;
13
+ /** The name of the config file in the Deployment home. */
14
+ export const CONFIG_FILE_NAME = "config.yaml";
15
+ /** The name of the secrets file in the Deployment home. */
16
+ export const SECRETS_FILE_NAME = "secrets.yaml";
17
+ /** Returns the revision of `config.yaml` text: its SHA-256 hash in hex. */
18
+ export const configRevision = (raw) => createHash("sha256").update(raw).digest("hex");
19
+ const invalidConfig = (issues) => new SeamError("config_invalid", "config.yaml is invalid", {
20
+ issues: issues.map(({ message, path: issuePath }) => ({
21
+ message,
22
+ path: issuePath,
23
+ })),
24
+ });
25
+ /** A config as plain JSON. */
26
+ const configJson = (config) => {
27
+ // A JSON round trip drops fields whose value is `undefined`, which a structured clone would keep.
28
+ // oxlint-disable-next-line unicorn/prefer-structured-clone -- The clone must drop `undefined` fields.
29
+ const value = JSON.parse(JSON.stringify(config));
30
+ if (!isJsonValue(value)) {
31
+ throw new Error("The config is not JSON");
32
+ }
33
+ return value;
34
+ };
35
+ /** Applies a structured config to the current YAML text as a patch. */
36
+ const patchedText = (current, config) => {
37
+ const value = configJson(config);
38
+ const doc = parseDocument(current);
39
+ if (doc.errors.length > 0) {
40
+ // The current file is broken YAML, so no comments can be kept: write the config as a new document.
41
+ return new Document(value).toString();
42
+ }
43
+ patchDocument(doc, value);
44
+ return doc.toString();
45
+ };
46
+ const validateConfigText = async (raw) => {
47
+ await Promise.resolve();
48
+ const parsed = parseConfigText(raw);
49
+ return parsed.ok ? [] : parsed.issues;
50
+ };
51
+ const sameRule = (left, right) => left?.tool === right.tool && left.action === right.action;
52
+ /**
53
+ * The `ConfigStore` over `config.yaml` (ADR 0004). It reads the file on every `read`, so hand edits are visible. Writes
54
+ * patch the YAML document, so comments and key order stay, and replace the file atomically, one write at a time.
55
+ */
56
+ export class FileConfigStore {
57
+ secrets;
58
+ #file;
59
+ #queue = new SerialQueue();
60
+ #references;
61
+ constructor(file, secrets, references) {
62
+ this.#file = file;
63
+ this.secrets = secrets;
64
+ this.#references = references;
65
+ }
66
+ /**
67
+ * Opens the store, loads `secrets.yaml`, and reads `config.yaml` once if it exists, so that secret references are
68
+ * known. Throws `SeamError("config_invalid")` for an invalid secrets file.
69
+ */
70
+ static async open(options) {
71
+ const references = { current: new Map() };
72
+ const secrets = await FileSecretStore.open({
73
+ env: options.env,
74
+ file: path.join(options.homeDir, SECRETS_FILE_NAME),
75
+ references: () => references.current,
76
+ });
77
+ const store = new FileConfigStore(path.join(options.homeDir, CONFIG_FILE_NAME), secrets, references);
78
+ const parsed = parseConfigText(await store.#readRaw());
79
+ if (parsed.ok) {
80
+ references.current = secretReferences(parsed.config);
81
+ }
82
+ return store;
83
+ }
84
+ read = async () => {
85
+ const raw = await this.#readRaw();
86
+ const parsed = parseConfigText(raw);
87
+ if (!parsed.ok) {
88
+ throw invalidConfig(parsed.issues);
89
+ }
90
+ return this.#snapshot(raw, parsed.config);
91
+ };
92
+ validate = validateConfigText;
93
+ save = async (input, expectedRevision) => await this.#queue.run(async () => {
94
+ const current = await this.#readRaw();
95
+ const revision = configRevision(current);
96
+ if (revision !== expectedRevision) {
97
+ throw new SeamError("revision_conflict", "config.yaml changed since it was read", { revision });
98
+ }
99
+ const raw = "raw" in input ? input.raw : patchedText(current, input.config);
100
+ return await this.#write(raw);
101
+ });
102
+ prependPermissionRule = async (agent, rule) => await this.#queue.run(async () => {
103
+ const current = await this.#readRaw();
104
+ const parsed = parseConfigText(current);
105
+ if (!parsed.ok) {
106
+ throw invalidConfig(parsed.issues);
107
+ }
108
+ const agentConfig = parsed.config.agents[agent];
109
+ if (agentConfig === undefined) {
110
+ throw new SeamError("agent_not_found", `Unknown Agent: ${agent}`);
111
+ }
112
+ const policy = agentConfig.permissionPolicy ?? [];
113
+ if (sameRule(policy[0], rule)) {
114
+ return this.#snapshot(current, parsed.config);
115
+ }
116
+ const next = {
117
+ ...parsed.config,
118
+ agents: {
119
+ ...parsed.config.agents,
120
+ [agent]: { ...agentConfig, permissionPolicy: [rule, ...policy] },
121
+ },
122
+ };
123
+ return await this.#write(patchedText(current, next));
124
+ });
125
+ #write = async (raw) => {
126
+ const parsed = parseConfigText(raw);
127
+ if (!parsed.ok) {
128
+ throw invalidConfig(parsed.issues);
129
+ }
130
+ await writeFileAtomic(this.#file, raw, CONFIG_FILE_MODE);
131
+ return this.#snapshot(raw, parsed.config);
132
+ };
133
+ #readRaw = async () => (await readTextIfExists(this.#file)) ?? "";
134
+ #snapshot = (raw, config) => {
135
+ this.#references.current = secretReferences(config);
136
+ return { config, raw, revision: configRevision(raw) };
137
+ };
138
+ }
@@ -0,0 +1,53 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ const withoutFrontends = (config) => {
3
+ const { frontends: _frontends, ...rest } = config;
4
+ return rest;
5
+ };
6
+ const bindingChanges = (agent, applied, next) => {
7
+ const before = new Map((applied.frontends ?? []).map((binding) => [binding.id, binding]));
8
+ const after = new Map((next.frontends ?? []).map((binding) => [binding.id, binding]));
9
+ const ids = [...new Set([...before.keys(), ...after.keys()])].toSorted();
10
+ return ids.flatMap((bindingId) => isDeepStrictEqual(before.get(bindingId), after.get(bindingId))
11
+ ? []
12
+ : [{ agent, bindingId, kind: "binding" }]);
13
+ };
14
+ /**
15
+ * Lists the changes of `next` that wait for a restart (ADR 0004):
16
+ * - `agent` for a running Agent whose settings other than `frontends`, or whose model provider's settings, changed.
17
+ * - `binding` for each added, removed, or changed Frontend Binding of a running Agent whose other settings stayed.
18
+ * - `daemon` if the Control Server or Webhook Ingress settings changed.
19
+ *
20
+ * An Agent that is not running has nothing pending: its next start reads `config.yaml`.
21
+ */
22
+ export const pendingRestarts = (applied, next) => {
23
+ const pending = [];
24
+ for (const [agent, { config: before, provider }] of [
25
+ ...applied.agents.entries(),
26
+ ].toSorted(([left], [right]) => left.localeCompare(right))) {
27
+ const after = next.agents[agent];
28
+ if (after === undefined) {
29
+ continue;
30
+ }
31
+ const providerChanged = !isDeepStrictEqual(provider, next.providers?.[after.model.provider]);
32
+ if (providerChanged ||
33
+ !isDeepStrictEqual(withoutFrontends(before), withoutFrontends(after))) {
34
+ pending.push({ agent, kind: "agent" });
35
+ }
36
+ else {
37
+ pending.push(...bindingChanges(agent, before, after));
38
+ }
39
+ }
40
+ if (!isDeepStrictEqual(applied.daemon.daemon, next.daemon)) {
41
+ pending.push({
42
+ kind: "daemon",
43
+ reason: "The Control Server settings changed",
44
+ });
45
+ }
46
+ if (!isDeepStrictEqual(applied.daemon.webhooks, next.webhooks)) {
47
+ pending.push({
48
+ kind: "daemon",
49
+ reason: "The Webhook Ingress settings changed",
50
+ });
51
+ }
52
+ return pending;
53
+ };
@@ -0,0 +1,69 @@
1
+ import { isJsonValue } from "@wheatley-ai/protocol";
2
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3
+ const isSecretName = (value) => typeof value === "string";
4
+ /** Collects the names of every `{ secret: <name> }` object inside a JSON value. */
5
+ const secretNamesIn = (value) => {
6
+ if (Array.isArray(value)) {
7
+ return value.flatMap((item) => secretNamesIn(item));
8
+ }
9
+ if (!isRecord(value)) {
10
+ return [];
11
+ }
12
+ const own = isSecretName(value.secret) && Object.keys(value).length === 1
13
+ ? [value.secret]
14
+ : [];
15
+ return [
16
+ ...own,
17
+ ...Object.values(value).flatMap((child) => secretNamesIn(child)),
18
+ ];
19
+ };
20
+ const add = (references, names, reference) => {
21
+ for (const name of names) {
22
+ const list = references.get(name) ?? [];
23
+ if (!list.some((item) => item.kind === reference.kind &&
24
+ item.id === reference.id &&
25
+ item.agent === reference.agent)) {
26
+ list.push(reference);
27
+ }
28
+ references.set(name, list);
29
+ }
30
+ };
31
+ /**
32
+ * Lists the config entries that refer to each secret: provider API keys, Frontend Binding, MCP Server, and Plugin
33
+ * config. Trigger token secrets live in `agent.sqlite`, so the Trigger module reports them.
34
+ */
35
+ export const secretReferences = (config) => {
36
+ const references = new Map();
37
+ for (const [provider, providerConfig] of Object.entries(config.providers ?? {})) {
38
+ if (providerConfig.apiKey !== undefined) {
39
+ add(references, [providerConfig.apiKey.secret], {
40
+ id: provider,
41
+ kind: "provider",
42
+ });
43
+ }
44
+ }
45
+ for (const [agent, agentConfig] of Object.entries(config.agents)) {
46
+ for (const binding of agentConfig.frontends ?? []) {
47
+ add(references, secretNamesIn(isJsonValue(binding.config) ? binding.config : null), {
48
+ agent,
49
+ id: binding.id,
50
+ kind: "frontend",
51
+ });
52
+ }
53
+ for (const [server, serverConfig] of Object.entries(agentConfig.mcpServers ?? {})) {
54
+ add(references, secretNamesIn(isJsonValue(serverConfig) ? serverConfig : null), {
55
+ agent,
56
+ id: server,
57
+ kind: "mcp",
58
+ });
59
+ }
60
+ for (const plugin of agentConfig.plugins ?? []) {
61
+ add(references, secretNamesIn(isJsonValue(plugin.config) ? plugin.config : null), {
62
+ agent,
63
+ id: plugin.source,
64
+ kind: "plugin",
65
+ });
66
+ }
67
+ }
68
+ return references;
69
+ };
@@ -0,0 +1,147 @@
1
+ import { isMap, isScalar, parseDocument } from "yaml";
2
+ import { SeamError } from "../../contracts/errors.js";
3
+ import { readTextIfExists, SerialQueue, writeFileAtomic, } from "./atomic-file.js";
4
+ /** The file mode of `secrets.yaml`: read and write for the owner only. */
5
+ export const SECRETS_FILE_MODE = 0o600;
6
+ const SECRET_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/u;
7
+ const MIN_REDACTED_LENGTH = 4;
8
+ const REDACTED = "[redacted]";
9
+ const isText = (value) => typeof value === "string";
10
+ const invalid = (issues) => new SeamError("config_invalid", "secrets.yaml is invalid", {
11
+ issues: issues.map(({ message, path }) => ({ message, path })),
12
+ });
13
+ /** Parses `secrets.yaml`: a map of secret names to string values. An empty or missing file has no secrets. */
14
+ const parseSecrets = (raw) => {
15
+ const doc = parseDocument(raw, { prettyErrors: false });
16
+ if (doc.errors.length > 0) {
17
+ throw invalid(doc.errors.map((error) => ({ message: error.message, path: "/" })));
18
+ }
19
+ const values = new Map();
20
+ if (doc.contents === null) {
21
+ return { doc, values };
22
+ }
23
+ if (!isMap(doc.contents)) {
24
+ throw invalid([
25
+ { message: "secrets.yaml must be a map of names to values", path: "/" },
26
+ ]);
27
+ }
28
+ const issues = [];
29
+ for (const pair of doc.contents.items) {
30
+ const key = isScalar(pair.key) ? pair.key.value : pair.key;
31
+ const value = isScalar(pair.value) ? pair.value.value : pair.value;
32
+ if (!isText(key) || !SECRET_NAME.test(key)) {
33
+ issues.push({
34
+ message: `Invalid secret name: ${String(key)}`,
35
+ path: "/",
36
+ });
37
+ }
38
+ else if (isText(value)) {
39
+ values.set(key, value);
40
+ }
41
+ else {
42
+ issues.push({
43
+ message: "A secret value must be a string",
44
+ path: `/${key}`,
45
+ });
46
+ }
47
+ }
48
+ if (issues.length > 0) {
49
+ throw invalid(issues);
50
+ }
51
+ return { doc, values };
52
+ };
53
+ /**
54
+ * The `SecretStore` over `secrets.yaml` (ADR 0004). Writes keep comments, are atomic, run one at a time, and keep the
55
+ * file mode `0600`. `get` and `redact` use the values that the last `open`, `set`, or `delete` loaded.
56
+ */
57
+ export class FileSecretStore {
58
+ #options;
59
+ #queue = new SerialQueue();
60
+ #values;
61
+ constructor(options, values) {
62
+ this.#options = options;
63
+ this.#values = values;
64
+ }
65
+ /** Loads `secrets.yaml`. Throws `SeamError("config_invalid")` for a file that is not a map of string values. */
66
+ static async open(options) {
67
+ const raw = (await readTextIfExists(options.file)) ?? "";
68
+ return new FileSecretStore(options, parseSecrets(raw).values);
69
+ }
70
+ get = (name) => this.#options.env[name] ?? this.#values.get(name);
71
+ list = async () => {
72
+ await Promise.resolve();
73
+ const references = this.#options.references();
74
+ const names = new Set([
75
+ ...this.#values.keys(),
76
+ ...[...references.keys()].filter((name) => this.#options.env[name] !== undefined),
77
+ ]);
78
+ return [...names].toSorted().map((name) => ({
79
+ name,
80
+ references: [...(references.get(name) ?? [])],
81
+ source: this.#sourceOf(name),
82
+ }));
83
+ };
84
+ set = async (name, value) => {
85
+ if (!SECRET_NAME.test(name)) {
86
+ throw new SeamError("invalid_name", `Invalid secret name: ${name}`);
87
+ }
88
+ await this.#change((doc) => {
89
+ doc.set(name, value);
90
+ });
91
+ return this.#sourceOf(name);
92
+ };
93
+ delete = async (name) => {
94
+ let deleted = false;
95
+ await this.#change((doc) => {
96
+ deleted = doc.delete(name);
97
+ });
98
+ return deleted;
99
+ };
100
+ reveal = async (name) => {
101
+ await Promise.resolve();
102
+ const value = this.get(name);
103
+ if (value === undefined) {
104
+ throw new SeamError("not_found", `Unknown secret: ${name}`);
105
+ }
106
+ return value;
107
+ };
108
+ redact = (text) => {
109
+ const names = new Set([
110
+ ...this.#values.keys(),
111
+ ...this.#options.references().keys(),
112
+ ]);
113
+ const values = [...names]
114
+ .flatMap((name) => {
115
+ const value = this.get(name);
116
+ return value === undefined || value.length < MIN_REDACTED_LENGTH
117
+ ? []
118
+ : [value, JSON.stringify(value).slice(1, -1)];
119
+ })
120
+ .toSorted((left, right) => right.length - left.length);
121
+ let redacted = text;
122
+ for (const value of values) {
123
+ redacted = redacted.replaceAll(value, REDACTED);
124
+ }
125
+ return redacted;
126
+ };
127
+ /** Re-reads the file, applies `edit` to its document, writes it, and reloads the values. One change at a time. */
128
+ #change = async (edit) => {
129
+ await this.#queue.run(async () => {
130
+ const raw = (await readTextIfExists(this.#options.file)) ?? "";
131
+ const { doc } = parseSecrets(raw);
132
+ doc.contents ??= doc.createNode({});
133
+ edit(doc);
134
+ const text = doc.toString();
135
+ await writeFileAtomic(this.#options.file, text, SECRETS_FILE_MODE);
136
+ this.#values = parseSecrets(text).values;
137
+ });
138
+ };
139
+ #sourceOf = (name) => {
140
+ const inFile = this.#values.has(name);
141
+ const inEnv = this.#options.env[name] !== undefined;
142
+ if (inFile && inEnv) {
143
+ return "both";
144
+ }
145
+ return inEnv ? "env" : "file";
146
+ };
147
+ }
@@ -0,0 +1,55 @@
1
+ import { DeploymentConfigSchema, decode } from "@wheatley-ai/protocol";
2
+ import { parseDocument } from "yaml";
3
+ import { documentJson } from "./yaml-patch.js";
4
+ /** The binding ID that the Control Server reserves for the CLI and dashboard Chat. */
5
+ export const CLI_BINDING_ID = "cli";
6
+ /** Checks rules that the JSON schema cannot express: unique Frontend Binding IDs and the reserved `cli` ID. */
7
+ const semanticIssues = (config) => Object.entries(config.agents).flatMap(([agent, agentConfig]) => {
8
+ const seen = new Set();
9
+ return (agentConfig.frontends ?? []).flatMap((binding, index) => {
10
+ const path = `/agents/${agent}/frontends/${index}/id`;
11
+ if (binding.id === CLI_BINDING_ID) {
12
+ return [
13
+ {
14
+ message: `The binding ID "${CLI_BINDING_ID}" is reserved for the CLI Chat`,
15
+ path,
16
+ },
17
+ ];
18
+ }
19
+ if (seen.has(binding.id)) {
20
+ return [{ message: `Duplicate binding ID: ${binding.id}`, path }];
21
+ }
22
+ seen.add(binding.id);
23
+ return [];
24
+ });
25
+ });
26
+ /** Parses and validates `config.yaml` text. YAML syntax errors, schema errors, and rule errors become issues. */
27
+ export const parseConfigText = (raw) => {
28
+ const doc = parseDocument(raw, { prettyErrors: false });
29
+ if (doc.errors.length > 0) {
30
+ return {
31
+ issues: doc.errors.map((error) => ({
32
+ message: error.message,
33
+ path: "/",
34
+ })),
35
+ ok: false,
36
+ };
37
+ }
38
+ const value = documentJson(doc);
39
+ if (value === undefined) {
40
+ return {
41
+ issues: [
42
+ { message: "The file holds values that are not JSON", path: "/" },
43
+ ],
44
+ ok: false,
45
+ };
46
+ }
47
+ const decoded = decode(DeploymentConfigSchema, value);
48
+ if (!decoded.ok) {
49
+ return { issues: decoded.issues, ok: false };
50
+ }
51
+ const issues = semanticIssues(decoded.value);
52
+ return issues.length > 0
53
+ ? { issues, ok: false }
54
+ : { config: decoded.value, doc, ok: true };
55
+ };
@@ -0,0 +1,57 @@
1
+ import { isJsonValue } from "@wheatley-ai/protocol";
2
+ import { isMap, isNode, isScalar, isSeq } from "yaml";
3
+ /** The most alias expansions that `config.yaml` may hold, so a crafted file cannot expand into a huge value. */
4
+ const MAX_ALIAS_COUNT = 100;
5
+ const isJsonObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6
+ const isJsonArray = (value) => Array.isArray(value);
7
+ /** Returns the plain JSON value of a YAML document, or `undefined` if it holds values that JSON cannot represent. */
8
+ export const documentJson = (doc) => {
9
+ const value = doc.toJS({ maxAliasCount: MAX_ALIAS_COUNT });
10
+ return isJsonValue(value) ? value : undefined;
11
+ };
12
+ /** True if a map key is a string or a scalar node that holds a string. */
13
+ const isStringKey = (key) => typeof key === "string" || (isScalar(key) && typeof key.value === "string");
14
+ const keyText = (key) => isScalar(key) ? key.value : key;
15
+ /** Replaces `node` with a new node for `value` and keeps the comments of `node`. */
16
+ const replaceNode = (doc, node, value) => {
17
+ const created = doc.createNode(value);
18
+ created.commentBefore = node.commentBefore;
19
+ created.comment = node.comment;
20
+ created.spaceBefore = node.spaceBefore;
21
+ return created;
22
+ };
23
+ /**
24
+ * Changes `node` in place so that its value equals `value`, and returns the node to store in the parent. Unchanged
25
+ * scalars, map keys, and sequence items keep their nodes, so comments and key order stay. New map keys go to the end.
26
+ */
27
+ const patchNode = (doc, node, value) => {
28
+ if (isMap(node) && isJsonObject(value)) {
29
+ const stale = node.items.filter((pair) => !isStringKey(pair.key) || !Object.hasOwn(value, keyText(pair.key)));
30
+ for (const pair of stale) {
31
+ node.delete(pair.key);
32
+ }
33
+ for (const [key, child] of Object.entries(value)) {
34
+ const existing = node.get(key, true);
35
+ node.set(key, patchNode(doc, isNode(existing) ? existing : undefined, child));
36
+ }
37
+ return node;
38
+ }
39
+ if (isSeq(node) && isJsonArray(value)) {
40
+ node.items.splice(value.length);
41
+ for (const [index, child] of value.entries()) {
42
+ const existing = node.items[index];
43
+ node.items[index] = patchNode(doc, isNode(existing) ? existing : undefined, child);
44
+ }
45
+ return node;
46
+ }
47
+ if (isScalar(node) && node.value === value) {
48
+ return node;
49
+ }
50
+ return node === undefined
51
+ ? doc.createNode(value)
52
+ : replaceNode(doc, node, value);
53
+ };
54
+ /** Changes the YAML document `doc` so that it holds `value`, and keeps comments and key order where values stay. */
55
+ export const patchDocument = (doc, value) => {
56
+ doc.contents = patchNode(doc, doc.contents ?? undefined, value);
57
+ };
@@ -0,0 +1,88 @@
1
+ import path from "node:path";
2
+ import { setTimeout as delay } from "node:timers/promises";
3
+ import { parseDuration } from "@wheatley-ai/protocol";
4
+ import { Deployment } from "./deployment.js";
5
+ import { createAgentRpc } from "./rpc/agent-handlers.js";
6
+ import { createDeploymentRpc } from "./rpc/deployment-handlers.js";
7
+ import { createRouter } from "./rpc/router.js";
8
+ import { ControlServer } from "./server/control-server.js";
9
+ /** The default TCP host of the Control Server: loopback only (ADR 0002). */
10
+ export const DEFAULT_DAEMON_HOST = "127.0.0.1";
11
+ /** The default TCP port of the Control Server. */
12
+ export const DEFAULT_DAEMON_PORT = 7420;
13
+ /** The Unix socket of the Control Server inside the Deployment home. */
14
+ export const DAEMON_SOCKET_FILE = "daemon.sock";
15
+ /** How long `close` waits for active Runs before it stops the Agents. */
16
+ export const DEFAULT_DRAIN_TIMEOUT = "30s";
17
+ const DRAIN_POLL_MS = 100;
18
+ /**
19
+ * Starts a Deployment and its Control Server. The router sends Deployment methods to the Deployment, and Agent methods
20
+ * to the core handlers and hosted modules of the named Agent.
21
+ *
22
+ * Errors: rejects if `attach`, the Agent start, or the Control Server listener fails. The Deployment and the attached
23
+ * services are closed before the promise rejects.
24
+ */
25
+ export const startDaemon = async (options) => {
26
+ const deployment = await Deployment.create(options);
27
+ const snapshot = await deployment.config.read();
28
+ const settings = snapshot.config.daemon;
29
+ const agentRpc = new WeakMap();
30
+ const router = createRouter({
31
+ agent: (name) => {
32
+ const agent = deployment.agent(name);
33
+ const cached = agentRpc.get(agent);
34
+ if (cached !== undefined) {
35
+ return cached;
36
+ }
37
+ const maps = [
38
+ createAgentRpc(agent, deployment.agentDir(name)),
39
+ ...agent.moduleRpc,
40
+ ];
41
+ agentRpc.set(agent, maps);
42
+ return maps;
43
+ },
44
+ deployment: [createDeploymentRpc(deployment)],
45
+ runningAgents: () => deployment.agentNames.filter((name) => deployment.health(name).state === "running"),
46
+ });
47
+ let attached;
48
+ let server;
49
+ try {
50
+ attached = await options.attach?.(deployment);
51
+ await deployment.start();
52
+ server = await ControlServer.listen({
53
+ allowedOrigins: settings?.allowedOrigins ?? [],
54
+ events: deployment.events,
55
+ host: options.host ?? settings?.host ?? DEFAULT_DAEMON_HOST,
56
+ log: deployment.logs.logger("control-server"),
57
+ port: options.port ?? settings?.port ?? DEFAULT_DAEMON_PORT,
58
+ router,
59
+ staticDir: options.staticDir,
60
+ socketPath: options.socketPath === null
61
+ ? undefined
62
+ : (options.socketPath ??
63
+ path.join(options.homeDir, DAEMON_SOCKET_FILE)),
64
+ version: options.version,
65
+ });
66
+ }
67
+ catch (error) {
68
+ await deployment.close();
69
+ await attached?.close();
70
+ throw error;
71
+ }
72
+ const drainMs = parseDuration(settings?.drainTimeout ?? DEFAULT_DRAIN_TIMEOUT);
73
+ return {
74
+ close: async () => {
75
+ await server.close();
76
+ const deadline = Date.now() + drainMs;
77
+ while (Date.now() < deadline &&
78
+ deployment.status().agents.some((agent) => agent.activeRuns > 0)) {
79
+ // oxlint-disable-next-line no-await-in-loop -- The drain waits for Runs to end one poll at a time.
80
+ await delay(DRAIN_POLL_MS);
81
+ }
82
+ await deployment.close();
83
+ await attached?.close();
84
+ },
85
+ deployment,
86
+ server,
87
+ };
88
+ };