@wheatley-ai/cli 0.0.0-stage → 0.1.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.
- package/LICENSE +15 -0
- package/bin/wheatley.js +2 -0
- package/dist/approvals/gate.js +278 -0
- package/dist/approvals/module.js +21 -0
- package/dist/approvals/policy.js +30 -0
- package/dist/approvals/preview.js +17 -0
- package/dist/approvals/prompt.js +98 -0
- package/dist/approvals/rpc.js +16 -0
- package/dist/approvals/store.js +159 -0
- package/dist/cli/ask.js +94 -0
- package/dist/cli/chat.js +178 -0
- package/dist/cli/client.js +104 -0
- package/dist/cli/daemon.js +35 -0
- package/dist/cli/init.js +72 -0
- package/dist/cli/io.js +45 -0
- package/dist/cli/main.js +206 -0
- package/dist/cli/session.js +86 -0
- package/dist/cli/status.js +46 -0
- package/dist/contracts/approval-gate.js +1 -0
- package/dist/contracts/config-store.js +1 -0
- package/dist/contracts/delivery-outbox.js +1 -0
- package/dist/contracts/errors.js +28 -0
- package/dist/contracts/extension-catalog.js +1 -0
- package/dist/contracts/maintenance-runner.js +1 -0
- package/dist/contracts/memory-store.js +1 -0
- package/dist/contracts/module.js +7 -0
- package/dist/contracts/tool-names.js +43 -0
- package/dist/contracts/trigger-runtime.js +1 -0
- package/dist/contracts/webhook-ingress.js +2 -0
- package/dist/core/agent/agent-store.js +300 -0
- package/dist/core/agent/agent.js +1033 -0
- package/dist/core/agent/gated-models.js +89 -0
- package/dist/core/agent/pi-adapter.js +401 -0
- package/dist/core/agent/policy-gate.js +44 -0
- package/dist/core/builtin-catalog.js +20 -0
- package/dist/core/concurrency-gate.js +87 -0
- package/dist/core/config/atomic-file.js +72 -0
- package/dist/core/config/config-store.js +138 -0
- package/dist/core/config/pending-restart.js +53 -0
- package/dist/core/config/secret-references.js +69 -0
- package/dist/core/config/secret-store.js +147 -0
- package/dist/core/config/validate.js +55 -0
- package/dist/core/config/yaml-patch.js +57 -0
- package/dist/core/daemon-socket.js +96 -0
- package/dist/core/daemon.js +97 -0
- package/dist/core/deployment.js +379 -0
- package/dist/core/error-message.js +4 -0
- package/dist/core/events.js +25 -0
- package/dist/core/logger.js +81 -0
- package/dist/core/models.js +27 -0
- package/dist/core/module.js +42 -0
- package/dist/core/rpc/agent-handlers.js +82 -0
- package/dist/core/rpc/deployment-handlers.js +63 -0
- package/dist/core/rpc/router.js +96 -0
- package/dist/core/server/connection.js +170 -0
- package/dist/core/server/control-server.js +152 -0
- package/dist/core/server/static-files.js +79 -0
- package/dist/core/supervisor.js +215 -0
- package/dist/core/tool-routing.js +41 -0
- package/dist/dashboard/assets/index-C9Rul5vE.css +2 -0
- package/dist/dashboard/assets/index-DXzGGAxQ.js +11 -0
- package/dist/dashboard/assets/sheet-presentation-DMljN0LW.js +1 -0
- package/dist/dashboard/index.html +18 -0
- package/dist/db/database.js +16 -0
- package/dist/db/migrations.js +184 -0
- package/dist/frontends/discord/approvals.js +199 -0
- package/dist/frontends/discord/attachments.js +115 -0
- package/dist/frontends/discord/binding.js +489 -0
- package/dist/frontends/discord/config.js +107 -0
- package/dist/frontends/discord/discord-runtime.js +52 -0
- package/dist/frontends/discord/errors.js +61 -0
- package/dist/frontends/discord/live-runs.js +189 -0
- package/dist/frontends/discord/module.js +39 -0
- package/dist/frontends/discord/recent-ids.js +20 -0
- package/dist/frontends/slack/approval-blocks.js +98 -0
- package/dist/frontends/slack/attachments.js +102 -0
- package/dist/frontends/slack/background-tasks.js +20 -0
- package/dist/frontends/slack/binding.js +405 -0
- package/dist/frontends/slack/bounded.js +9 -0
- package/dist/frontends/slack/chat-id.js +17 -0
- package/dist/frontends/slack/config.js +80 -0
- package/dist/frontends/slack/delivery-errors.js +81 -0
- package/dist/frontends/slack/inbound.js +76 -0
- package/dist/frontends/slack/live-progress.js +190 -0
- package/dist/frontends/slack/manifest.js +66 -0
- package/dist/frontends/slack/outbound.js +160 -0
- package/dist/frontends/slack/schemas.js +99 -0
- package/dist/frontends/slack/signature.js +30 -0
- package/dist/frontends/slack/slack-client.js +60 -0
- package/dist/frontends/slack/slack-frontend.js +38 -0
- package/dist/frontends/slack/state-store.js +112 -0
- package/dist/frontends/telegram/approvals.js +134 -0
- package/dist/frontends/telegram/attachments.js +126 -0
- package/dist/frontends/telegram/binding.js +144 -0
- package/dist/frontends/telegram/chat-key.js +43 -0
- package/dist/frontends/telegram/client.js +88 -0
- package/dist/frontends/telegram/config.js +93 -0
- package/dist/frontends/telegram/delivery.js +215 -0
- package/dist/frontends/telegram/frontend.js +42 -0
- package/dist/frontends/telegram/grammy-client.js +122 -0
- package/dist/frontends/telegram/http-status.js +6 -0
- package/dist/frontends/telegram/inbound.js +149 -0
- package/dist/frontends/telegram/live.js +182 -0
- package/dist/frontends/telegram/markdown.js +103 -0
- package/dist/frontends/telegram/recent-set.js +18 -0
- package/dist/frontends/telegram/serial-queue.js +23 -0
- package/dist/index.js +7 -0
- package/dist/mcp/content.js +61 -0
- package/dist/mcp/mcp-module.js +35 -0
- package/dist/mcp/mcp-tool-provider.js +93 -0
- package/dist/mcp/server-connection.js +297 -0
- package/dist/memory/consolidation.js +260 -0
- package/dist/memory/format.js +5 -0
- package/dist/memory/migrations.js +76 -0
- package/dist/memory/module.js +69 -0
- package/dist/memory/names.js +20 -0
- package/dist/memory/rows.js +22 -0
- package/dist/memory/rpc.js +49 -0
- package/dist/memory/snapshots.js +12 -0
- package/dist/memory/store.js +281 -0
- package/dist/memory/tools.js +158 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/config.d.ts +262 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/config.js +120 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/domain.d.ts +512 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/domain.js +441 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/duration.d.ts +8 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/duration.js +28 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/events.d.ts +234 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/events.js +124 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/index.d.ts +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/index.js +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json-rpc.d.ts +81 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json-rpc.js +157 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json.d.ts +14 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json.js +23 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/limits.d.ts +17 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/limits.js +17 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/methods.d.ts +1107 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/methods.js +201 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/rpc-error.d.ts +45 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/rpc-error.js +44 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/validation.d.ts +20 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/validation.js +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/package.json +14 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/chunk.d.ts +11 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/chunk.js +162 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/commands.d.ts +48 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/commands.js +39 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/delivery-error.d.ts +29 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/delivery-error.js +27 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.d.ts +236 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/index.d.ts +10 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/index.js +7 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/json.d.ts +9 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/json.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/logger.d.ts +18 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/logger.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/plugin.d.ts +48 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/plugin.js +5 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/schema.d.ts +69 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/schema.js +3 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/tool.d.ts +69 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/tool.js +3 -0
- package/dist/node_modules/@wheatley-ai/sdk/package.json +11 -0
- package/dist/ops/backup.js +185 -0
- package/dist/ops/cli.js +194 -0
- package/dist/ops/command-runner.js +34 -0
- package/dist/ops/dashboard-assets.js +37 -0
- package/dist/ops/migrate.js +63 -0
- package/dist/ops/module.js +47 -0
- package/dist/ops/paths.js +55 -0
- package/dist/ops/service.js +376 -0
- package/dist/ops/update.js +145 -0
- package/dist/plugins/contributions.js +89 -0
- package/dist/plugins/guards.js +111 -0
- package/dist/plugins/load.js +76 -0
- package/dist/plugins/module.js +31 -0
- package/dist/plugins/provider.js +349 -0
- package/dist/plugins/schema.js +69 -0
- package/dist/skills/disclosure.js +142 -0
- package/dist/skills/discovery.js +120 -0
- package/dist/skills/fs-errors.js +8 -0
- package/dist/skills/read-skill-tool.js +3 -0
- package/dist/skills/skill-file.js +90 -0
- package/dist/skills/skills.js +140 -0
- package/dist/tools/builtin-tools.js +61 -0
- package/dist/tools/input.js +45 -0
- package/dist/tools/paths.js +6 -0
- package/dist/tools/read-file.js +65 -0
- package/dist/tools/shell.js +156 -0
- package/dist/tools/write-file.js +58 -0
- package/dist/triggers/delivery-codec.js +99 -0
- package/dist/triggers/delivery-outbox.js +313 -0
- package/dist/triggers/due-timer.js +14 -0
- package/dist/triggers/errors.js +2 -0
- package/dist/triggers/migrations.js +91 -0
- package/dist/triggers/module.js +106 -0
- package/dist/triggers/rpc.js +35 -0
- package/dist/triggers/schedule.js +52 -0
- package/dist/triggers/sql-row.js +59 -0
- package/dist/triggers/trigger-runtime.js +445 -0
- package/dist/triggers/trigger-tools.js +210 -0
- package/dist/triggers/webhook-ingress.js +212 -0
- package/dist/wiring/agent-services.js +151 -0
- package/dist/wiring/catalog.js +81 -0
- package/dist/wiring/daemon.js +83 -0
- package/dist/wiring/frontend-host.js +268 -0
- package/package.json +50 -3
- package/README.md +0 -3
|
@@ -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
|
+
});
|
|
@@ -0,0 +1,96 @@
|
|
|
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 handlers = await Promise.all(sources.runningAgents().map(async (name) => ({
|
|
64
|
+
handler: handlerIn(await sources.agent(name), request.method),
|
|
65
|
+
name,
|
|
66
|
+
})));
|
|
67
|
+
const calls = handlers.flatMap(({ handler, name }) => handler === undefined ? [] : [{ handler, name }]);
|
|
68
|
+
const results = await Promise.all(calls.map(async ({ handler, name }) => await handler({ ...request.params, agent: name }, ctx)));
|
|
69
|
+
const objects = results.flatMap((result) => isJsonValue(result) && isObject(result) ? [result] : []);
|
|
70
|
+
const merged = mergeResults(objects);
|
|
71
|
+
if (!isResultOf(request.method, merged)) {
|
|
72
|
+
throw new RpcError(RpcErrorCode.InternalError, "Internal error");
|
|
73
|
+
}
|
|
74
|
+
return merged;
|
|
75
|
+
};
|
|
76
|
+
return {
|
|
77
|
+
/** Runs the handler of one request and resolves with its result. */
|
|
78
|
+
dispatch: async (request, ctx) => {
|
|
79
|
+
const deploymentHandler = handlerIn(sources.deployment, request.method);
|
|
80
|
+
if (deploymentHandler !== undefined) {
|
|
81
|
+
return await deploymentHandler(request.params, ctx);
|
|
82
|
+
}
|
|
83
|
+
if (namesAgent(request.params)) {
|
|
84
|
+
const handler = handlerIn(await sources.agent(request.params.agent), request.method);
|
|
85
|
+
if (handler === undefined) {
|
|
86
|
+
throw new RpcError(RpcErrorCode.MethodNotFound, `Method not available: ${request.method}`);
|
|
87
|
+
}
|
|
88
|
+
return await handler(request.params, ctx);
|
|
89
|
+
}
|
|
90
|
+
if (!FAN_OUT_METHODS.has(request.method)) {
|
|
91
|
+
throw new RpcError(RpcErrorCode.MethodNotFound, `Method not available: ${request.method}`);
|
|
92
|
+
}
|
|
93
|
+
return await fanOut(request, ctx);
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
};
|
|
@@ -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
|
+
};
|