@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,95 @@
1
+ import { decode, isJsonValue, METHOD_NAMES, methods, RpcError, RpcErrorCode, } from "@wheatley-ai/protocol";
2
+ const handlerIn = (maps, method) => {
3
+ for (const map of maps) {
4
+ const handler = map[method];
5
+ if (handler !== undefined) {
6
+ return handler;
7
+ }
8
+ }
9
+ return undefined;
10
+ };
11
+ /** True if the params name an Agent, so the request goes to that Agent's handlers. */
12
+ const namesAgent = (params) => "agent" in params && typeof params.agent === "string";
13
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
14
+ /** True if a params schema has an `agent` property that is not required. */
15
+ const hasOptionalAgent = (schema) => {
16
+ if (!isObject(schema) ||
17
+ schema.properties === undefined ||
18
+ !isObject(schema.properties)) {
19
+ return false;
20
+ }
21
+ const { required } = schema;
22
+ return (schema.properties.agent !== undefined &&
23
+ !(Array.isArray(required) && required.includes("agent")));
24
+ };
25
+ /**
26
+ * The methods whose `agent` param is optional, such as `approvals.list`. A request without `agent` goes to every
27
+ * running Agent.
28
+ */
29
+ const FAN_OUT_METHODS = new Set(METHOD_NAMES.filter((method) => {
30
+ const schema = structuredClone(methods[method].params);
31
+ return isJsonValue(schema) && hasOptionalAgent(schema);
32
+ }));
33
+ const isJsonArray = (value) => Array.isArray(value);
34
+ /** True if `value` matches the result schema of `method`. */
35
+ const isResultOf = (method, value) => isJsonValue(value) && decode(methods[method].result, value).ok;
36
+ /** Merges the results of one method from several Agents: arrays concatenate, booleans combine with OR. */
37
+ const mergeResults = (results) => {
38
+ const merged = {};
39
+ for (const result of results) {
40
+ for (const [key, value] of Object.entries(result)) {
41
+ const previous = merged[key];
42
+ if (isJsonArray(value) && isJsonArray(previous)) {
43
+ merged[key] = [...previous, ...value];
44
+ }
45
+ else if (value === true || previous === undefined) {
46
+ merged[key] = value;
47
+ }
48
+ }
49
+ }
50
+ return merged;
51
+ };
52
+ /**
53
+ * Routes JSON-RPC requests to module handlers (see `RpcHandlerMap` for the rules):
54
+ * 1. A Deployment-wide handler of the method.
55
+ * 2. With `params.agent`, the handler of that Agent's modules.
56
+ * 3. Without `params.agent`, for a method whose `agent` param is optional, every running Agent that handles it. The
57
+ * router sets `agent` on each call and merges the results.
58
+ *
59
+ * Errors: throws `RpcError` `MethodNotFound` if no module handles the method, and passes handler errors through.
60
+ */
61
+ export const createRouter = (sources) => {
62
+ const fanOut = async (request, ctx) => {
63
+ const calls = sources.runningAgents().flatMap((name) => {
64
+ const handler = handlerIn(sources.agent(name), request.method);
65
+ return handler === undefined ? [] : [{ handler, name }];
66
+ });
67
+ const results = await Promise.all(calls.map(async ({ handler, name }) => await handler({ ...request.params, agent: name }, ctx)));
68
+ const objects = results.flatMap((result) => isJsonValue(result) && isObject(result) ? [result] : []);
69
+ const merged = mergeResults(objects);
70
+ if (!isResultOf(request.method, merged)) {
71
+ throw new RpcError(RpcErrorCode.InternalError, "Internal error");
72
+ }
73
+ return merged;
74
+ };
75
+ return {
76
+ /** Runs the handler of one request and resolves with its result. */
77
+ dispatch: async (request, ctx) => {
78
+ const deploymentHandler = handlerIn(sources.deployment, request.method);
79
+ if (deploymentHandler !== undefined) {
80
+ return await deploymentHandler(request.params, ctx);
81
+ }
82
+ if (namesAgent(request.params)) {
83
+ const handler = handlerIn(sources.agent(request.params.agent), request.method);
84
+ if (handler === undefined) {
85
+ throw new RpcError(RpcErrorCode.MethodNotFound, `Method not available: ${request.method}`);
86
+ }
87
+ return await handler(request.params, ctx);
88
+ }
89
+ if (!FAN_OUT_METHODS.has(request.method)) {
90
+ throw new RpcError(RpcErrorCode.MethodNotFound, `Method not available: ${request.method}`);
91
+ }
92
+ return await fanOut(request, ctx);
93
+ },
94
+ };
95
+ };
@@ -0,0 +1,170 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { decodeClientMessage, encodeError, encodeEvent, encodeResult, eventTopic, PROTOCOL_VERSION, RpcError, RpcErrorCode, } from "@wheatley-ai/protocol";
3
+ import { SeamError, toRpcError } from "../../contracts/errors.js";
4
+ import { errorMessage } from "../error-message.js";
5
+ /** The Agent that an event belongs to, or `undefined` for a Deployment-wide event. */
6
+ const eventAgent = (name, payload) => {
7
+ if (hasAgent(payload)) {
8
+ return payload.agent;
9
+ }
10
+ return name === "log.record" && hasRecordAgent(payload)
11
+ ? payload.record.agent
12
+ : undefined;
13
+ };
14
+ const hasAgent = (payload) => "agent" in payload && typeof payload.agent === "string";
15
+ const hasRecordAgent = (payload) => "record" in payload && typeof payload.record.agent === "string";
16
+ const matches = (subscription, topic, agent) => (subscription.topics === undefined || subscription.topics.has(topic)) &&
17
+ (subscription.agents === undefined ||
18
+ agent === undefined ||
19
+ subscription.agents.has(agent));
20
+ const errorObject = (error, log, method) => {
21
+ if (error instanceof RpcError) {
22
+ return error.toObject();
23
+ }
24
+ if (error instanceof SeamError) {
25
+ return toRpcError(error).toObject();
26
+ }
27
+ log.error("A JSON-RPC handler failed", {
28
+ error: error.message,
29
+ method,
30
+ });
31
+ return { code: RpcErrorCode.InternalError, message: "Internal error" };
32
+ };
33
+ const rawText = (data) => {
34
+ if (Array.isArray(data)) {
35
+ return Buffer.concat(data).toString("utf-8");
36
+ }
37
+ return Buffer.from(data instanceof ArrayBuffer ? new Uint8Array(data) : data).toString("utf-8");
38
+ };
39
+ /**
40
+ * One WebSocket connection: its `system.hello` state, its event subscriptions, and the ordering rule of ADR 0005.
41
+ *
42
+ * Ordering: while any request of the connection runs, the connection holds back events, and sends them after the
43
+ * response. Thus a client never sees the events of a Run before the reply to the request that started it.
44
+ */
45
+ export class Connection {
46
+ id = randomUUID();
47
+ #socket;
48
+ #options;
49
+ #abort = new AbortController();
50
+ #subscriptions = new Map();
51
+ #held = [];
52
+ #stopListening;
53
+ #inFlight = 0;
54
+ #greeted = false;
55
+ constructor(socket, options) {
56
+ this.#socket = socket;
57
+ this.#options = options;
58
+ this.#stopListening = options.events.listen(this.#onEvent);
59
+ socket.on("message", (data) => {
60
+ void this.#onMessage(rawText(data));
61
+ });
62
+ socket.on("close", () => {
63
+ this.#abort.abort(new Error("The connection closed"));
64
+ this.#stopListening();
65
+ });
66
+ }
67
+ #send = (text) => {
68
+ if (this.#socket.readyState === this.#socket.OPEN) {
69
+ this.#socket.send(text);
70
+ }
71
+ };
72
+ #onEvent = (name, payload) => {
73
+ const topic = eventTopic(name);
74
+ const agent = eventAgent(name, payload);
75
+ if (![...this.#subscriptions.values()].some((subscription) => matches(subscription, topic, agent))) {
76
+ return;
77
+ }
78
+ const text = encodeEvent(name, payload);
79
+ if (this.#inFlight > 0) {
80
+ this.#held.push(text);
81
+ }
82
+ else {
83
+ this.#send(text);
84
+ }
85
+ };
86
+ #onMessage = async (text) => {
87
+ const decoded = decodeClientMessage(text);
88
+ if (!decoded.ok) {
89
+ this.#send(encodeError(decoded.id, decoded.error));
90
+ return;
91
+ }
92
+ this.#inFlight += 1;
93
+ try {
94
+ this.#send(await this.#respond(decoded.request));
95
+ }
96
+ finally {
97
+ this.#inFlight -= 1;
98
+ if (this.#inFlight === 0) {
99
+ for (const event of this.#held.splice(0)) {
100
+ this.#send(event);
101
+ }
102
+ }
103
+ }
104
+ };
105
+ #respond = async (request) => {
106
+ try {
107
+ if (request.method === "system.hello") {
108
+ this.#hello(request.params.protocolVersion);
109
+ return encodeResult(request.id, "system.hello", {
110
+ protocolVersion: PROTOCOL_VERSION,
111
+ wheatleyVersion: this.#options.version,
112
+ });
113
+ }
114
+ if (!this.#greeted) {
115
+ return encodeError(request.id, {
116
+ code: RpcErrorCode.InvalidRequest,
117
+ message: "The first request of a connection must be system.hello",
118
+ });
119
+ }
120
+ if (request.method === "events.subscribe") {
121
+ const subscriptionId = randomUUID();
122
+ this.#subscriptions.set(subscriptionId, {
123
+ agents: request.params.agents === undefined
124
+ ? undefined
125
+ : new Set(request.params.agents),
126
+ topics: request.params.topics === undefined
127
+ ? undefined
128
+ : new Set(request.params.topics),
129
+ });
130
+ return encodeResult(request.id, "events.subscribe", { subscriptionId });
131
+ }
132
+ if (request.method === "events.unsubscribe") {
133
+ return encodeResult(request.id, "events.unsubscribe", {
134
+ removed: this.#subscriptions.delete(request.params.subscriptionId),
135
+ });
136
+ }
137
+ return await this.#dispatch(request.id, request);
138
+ }
139
+ catch (error) {
140
+ return encodeError(request.id, errorObject(error instanceof Error ? error : new Error(String(error)), this.#options.log, request.method));
141
+ }
142
+ };
143
+ /** Accepts `system.hello`. Throws `ProtocolMismatch` for another protocol version. */
144
+ #hello = (protocolVersion) => {
145
+ if (protocolVersion !== PROTOCOL_VERSION) {
146
+ throw new RpcError(RpcErrorCode.ProtocolMismatch, `The daemon speaks protocol version ${PROTOCOL_VERSION}, and the client speaks ${protocolVersion}`, { protocolVersion: PROTOCOL_VERSION });
147
+ }
148
+ this.#greeted = true;
149
+ };
150
+ #dispatch = async (id, request) => {
151
+ const ctx = {
152
+ connectionId: this.id,
153
+ signal: this.#abort.signal,
154
+ };
155
+ const result = await this.#options.router.dispatch(request, ctx);
156
+ try {
157
+ return encodeResult(id, request.method, result);
158
+ }
159
+ catch (error) {
160
+ this.#options.log.error("A JSON-RPC result does not match its schema", {
161
+ error: errorMessage(error),
162
+ method: request.method,
163
+ });
164
+ return encodeError(id, {
165
+ code: RpcErrorCode.InternalError,
166
+ message: "Internal error",
167
+ });
168
+ }
169
+ };
170
+ }
@@ -0,0 +1,152 @@
1
+ import { once } from "node:events";
2
+ import { chmod, rm } from "node:fs/promises";
3
+ import { createServer } from "node:http";
4
+ import { isIPv4 } from "node:net";
5
+ import { WebSocketServer } from "ws";
6
+ import { errorMessage } from "../error-message.js";
7
+ import { Connection } from "./connection.js";
8
+ import { serveStaticFile } from "./static-files.js";
9
+ /** The WebSocket path of the JSON-RPC protocol (ADR 0005). */
10
+ export const WS_PATH = "/ws";
11
+ /** The file mode of the Unix socket: the owner only (ADR 0002). */
12
+ export const SOCKET_FILE_MODE = 0o600;
13
+ /** Hosts whose origins count as the listener's own. */
14
+ const LOOPBACK_HOSTS = ["localhost", "127.0.0.1", "[::1]"];
15
+ /** True for a host name or address that only the local machine can reach: `localhost`, `127.0.0.0/8`, or `::1`. */
16
+ export const isLoopbackHost = (host) => {
17
+ const bare = host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
18
+ return (bare.toLowerCase() === "localhost" ||
19
+ bare === "::1" ||
20
+ (isIPv4(bare) && bare.startsWith("127.")));
21
+ };
22
+ /**
23
+ * The localhost Control Server: HTTP plus the JSON-RPC WebSocket at `/ws` (ADR 0005). It listens on a loopback TCP
24
+ * port and, if set, on an owner-only Unix socket.
25
+ *
26
+ * Browser requests must come from the listener's own origin or from `allowedOrigins`. The server rejects every other
27
+ * `Origin` with `403`, so a web page cannot drive the daemon. Clients without an `Origin` header, such as the CLI, pass.
28
+ */
29
+ export class ControlServer {
30
+ #options;
31
+ #wss = new WebSocketServer({ noServer: true });
32
+ #servers = [];
33
+ #connections = new Map();
34
+ #port = 0;
35
+ constructor(options) {
36
+ this.#options = options;
37
+ }
38
+ /** Starts to listen. Rejects if the port or the socket path is not available. */
39
+ static async listen(options) {
40
+ const server = new ControlServer(options);
41
+ const tcp = server.#createHttpServer(true);
42
+ tcp.listen(options.port, options.host);
43
+ await onceListening(tcp);
44
+ server.#port = portOf(tcp);
45
+ if (!isLoopbackHost(options.host)) {
46
+ options.log.warn("The Control Server listens on a host that is not loopback. The protocol has no login: limit access with a firewall, a proxy, or a loopback port mapping.", { host: options.host });
47
+ }
48
+ if (options.socketPath !== undefined) {
49
+ await rm(options.socketPath, { force: true });
50
+ const unix = server.#createHttpServer(false);
51
+ unix.listen(options.socketPath);
52
+ await onceListening(unix);
53
+ await chmod(options.socketPath, SOCKET_FILE_MODE);
54
+ }
55
+ return server;
56
+ }
57
+ /** The TCP port. */
58
+ get port() {
59
+ return this.#port;
60
+ }
61
+ /** The WebSocket URL on the TCP listener. */
62
+ get url() {
63
+ const host = this.#options.host.includes(":")
64
+ ? `[${this.#options.host}]`
65
+ : this.#options.host;
66
+ return `ws://${host}:${this.#port}${WS_PATH}`;
67
+ }
68
+ /** Closes every connection and both listeners. */
69
+ close = async () => {
70
+ for (const socket of this.#connections.keys()) {
71
+ socket.terminate();
72
+ }
73
+ await Promise.all(this.#servers.map(async (server) => {
74
+ server.closeAllConnections();
75
+ const closed = once(server, "close");
76
+ server.close();
77
+ await closed;
78
+ }));
79
+ this.#wss.close();
80
+ if (this.#options.socketPath !== undefined) {
81
+ await rm(this.#options.socketPath, { force: true });
82
+ }
83
+ };
84
+ #createHttpServer = (checkOrigin) => {
85
+ const server = createServer((request, response) => {
86
+ void this.#serveHttp(request, response);
87
+ });
88
+ server.on("upgrade", (request, socket, head) => {
89
+ this.#upgrade(request, socket, head, checkOrigin);
90
+ });
91
+ this.#servers.push(server);
92
+ return server;
93
+ };
94
+ #serveHttp = async (request, response) => {
95
+ const { staticDir } = this.#options;
96
+ try {
97
+ if (staticDir !== undefined &&
98
+ (await serveStaticFile(staticDir, request, response))) {
99
+ return;
100
+ }
101
+ }
102
+ catch (error) {
103
+ this.#options.log.warn("A dashboard file could not be served", {
104
+ error: errorMessage(error),
105
+ });
106
+ }
107
+ const status = request.method === "GET" && request.url === "/" ? 200 : 404;
108
+ response.writeHead(status, {
109
+ "content-type": "text/plain; charset=utf-8",
110
+ });
111
+ response.end(status === 200
112
+ ? `Wheatley daemon. Connect with JSON-RPC over WebSocket at ${WS_PATH}.\n`
113
+ : "Not found\n");
114
+ };
115
+ #allowedOrigin = (origin) => {
116
+ const own = [this.#options.host, ...LOOPBACK_HOSTS].map((host) => {
117
+ const bracketed = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
118
+ return `http://${bracketed}:${this.#port}`;
119
+ });
120
+ return (own.includes(origin) || this.#options.allowedOrigins.includes(origin));
121
+ };
122
+ #upgrade = (request, socket, head, checkOrigin) => {
123
+ const { pathname } = new URL(request.url ?? "/", "http://localhost");
124
+ const { origin } = request.headers;
125
+ if (pathname !== WS_PATH) {
126
+ socket.end("HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n");
127
+ return;
128
+ }
129
+ if (checkOrigin && origin !== undefined && !this.#allowedOrigin(origin)) {
130
+ this.#options.log.warn("Rejected a WebSocket from a foreign origin", {
131
+ origin,
132
+ });
133
+ socket.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n");
134
+ return;
135
+ }
136
+ this.#wss.handleUpgrade(request, socket, head, (ws) => {
137
+ this.#connections.set(ws, new Connection(ws, this.#options));
138
+ ws.on("close", () => {
139
+ this.#connections.delete(ws);
140
+ });
141
+ });
142
+ };
143
+ }
144
+ const onceListening = async (server) => {
145
+ // `once` rejects if the server emits `error` first, for example for a port in use.
146
+ await once(server, "listening");
147
+ };
148
+ const isAddressInfo = (address) => address !== null && typeof address === "object";
149
+ const portOf = (server) => {
150
+ const address = server.address();
151
+ return isAddressInfo(address) ? address.port : 0;
152
+ };
@@ -0,0 +1,79 @@
1
+ import { readFile, stat } from "node:fs/promises";
2
+ import path from "node:path";
3
+ /** The dashboard entry file. Paths without a file extension fall back to it, so the SPA can route itself. */
4
+ const INDEX_FILE = "index.html";
5
+ const CONTENT_TYPES = new Map([
6
+ [".css", "text/css; charset=utf-8"],
7
+ [".html", "text/html; charset=utf-8"],
8
+ [".ico", "image/x-icon"],
9
+ [".js", "text/javascript; charset=utf-8"],
10
+ [".json", "application/json; charset=utf-8"],
11
+ [".map", "application/json; charset=utf-8"],
12
+ [".png", "image/png"],
13
+ [".svg", "image/svg+xml"],
14
+ [".txt", "text/plain; charset=utf-8"],
15
+ [".webp", "image/webp"],
16
+ [".woff", "font/woff"],
17
+ [".woff2", "font/woff2"],
18
+ ]);
19
+ const contentTypeOf = (file) => CONTENT_TYPES.get(path.extname(file).toLowerCase()) ??
20
+ "application/octet-stream";
21
+ const isFile = async (file) => {
22
+ try {
23
+ const info = await stat(file);
24
+ return info.isFile();
25
+ }
26
+ catch {
27
+ return false;
28
+ }
29
+ };
30
+ /**
31
+ * Resolves the file for a URL path inside `root`, or `undefined`. A path that leaves `root` resolves `undefined`. A
32
+ * path without a file extension resolves the SPA entry.
33
+ */
34
+ const resolveFile = async (root, urlPath) => {
35
+ let decoded;
36
+ try {
37
+ decoded = decodeURIComponent(urlPath);
38
+ }
39
+ catch {
40
+ return undefined;
41
+ }
42
+ const target = path.resolve(root, `.${path.posix.normalize(decoded)}`);
43
+ const inside = target === root || target.startsWith(`${root}${path.sep}`);
44
+ if (!inside) {
45
+ return undefined;
46
+ }
47
+ if (await isFile(target)) {
48
+ return target;
49
+ }
50
+ const entry = path.join(root, INDEX_FILE);
51
+ const isRoute = path.extname(target) === "";
52
+ return isRoute && (await isFile(entry)) ? entry : undefined;
53
+ };
54
+ /**
55
+ * Serves `GET` and `HEAD` requests from the bundled dashboard folder. Resolves `false` if no file matches, so the
56
+ * caller can answer with its own response.
57
+ *
58
+ * The dashboard is static and holds no data. It reads everything over `/ws`, where the Control Server checks the
59
+ * browser `Origin`.
60
+ */
61
+ export const serveStaticFile = async (root, request, response) => {
62
+ if (request.method !== "GET" && request.method !== "HEAD") {
63
+ return false;
64
+ }
65
+ const { pathname } = new URL(request.url ?? "/", "http://localhost");
66
+ const file = await resolveFile(path.resolve(root), pathname);
67
+ if (file === undefined) {
68
+ return false;
69
+ }
70
+ const body = await readFile(file);
71
+ response.writeHead(200, {
72
+ "cache-control": path.basename(file) === INDEX_FILE ? "no-cache" : "max-age=3600",
73
+ "content-length": body.byteLength,
74
+ "content-type": contentTypeOf(file),
75
+ "x-content-type-options": "nosniff",
76
+ });
77
+ response.end(request.method === "HEAD" ? undefined : body);
78
+ return true;
79
+ };