@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,96 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { realpathSync, statSync } from "node:fs";
|
|
3
|
+
import { lstat, mkdir } from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
/** The Unix socket of the Control Server inside the Deployment home. */
|
|
6
|
+
export const DAEMON_SOCKET_FILE = "daemon.sock";
|
|
7
|
+
/** The size of `sun_path` in `struct sockaddr_un`: 104 bytes on macOS and the BSDs, 108 bytes on Linux. */
|
|
8
|
+
const SUN_PATH_BYTES = {
|
|
9
|
+
darwin: 104,
|
|
10
|
+
freebsd: 104,
|
|
11
|
+
linux: 108,
|
|
12
|
+
openbsd: 104,
|
|
13
|
+
};
|
|
14
|
+
const DEFAULT_SUN_PATH_BYTES = 104;
|
|
15
|
+
/** The hex characters of the home hash in a fallback socket name. */
|
|
16
|
+
const HOME_HASH_LENGTH = 16;
|
|
17
|
+
/** The mode of the folder of a fallback socket: the owner only. */
|
|
18
|
+
const PRIVATE_DIR_MODE = 0o700;
|
|
19
|
+
/** A file mode is a multiple of this value if its six lowest bits, the group and other permissions, are all zero. */
|
|
20
|
+
const GROUP_AND_OTHER_BITS_MODULUS = 0o100;
|
|
21
|
+
/** The base of the fallback folder if the systemd user runtime folder does not exist. */
|
|
22
|
+
const SHARED_TMP_DIR = "/tmp";
|
|
23
|
+
/** The longest socket path in bytes. `sun_path` also holds the closing NUL byte. */
|
|
24
|
+
const maxSocketPathBytes = () => (SUN_PATH_BYTES[process.platform] ?? DEFAULT_SUN_PATH_BYTES) - 1;
|
|
25
|
+
const fits = (socketPath) => Buffer.byteLength(socketPath) <= maxSocketPathBytes();
|
|
26
|
+
const isOpenToOthers = (mode) => mode % GROUP_AND_OTHER_BITS_MODULUS !== 0;
|
|
27
|
+
const isDirectory = (dir) => {
|
|
28
|
+
try {
|
|
29
|
+
return statSync(dir).isDirectory();
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
/** The home with symlinks resolved. A home that does not exist yet keeps its absolute path. */
|
|
36
|
+
const canonicalHome = (home) => {
|
|
37
|
+
const resolved = path.resolve(home);
|
|
38
|
+
try {
|
|
39
|
+
return realpathSync.native(resolved);
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return resolved;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* The fallback folder comes from the file system, not from environment variables, so a daemon and a client with
|
|
47
|
+
* different `XDG_RUNTIME_DIR` or `TMPDIR` values agree on it.
|
|
48
|
+
*/
|
|
49
|
+
const fallbackDirOf = () => {
|
|
50
|
+
const uid = process.getuid?.();
|
|
51
|
+
const runtimeDir = `/run/user/${uid}`;
|
|
52
|
+
const base = uid !== undefined && process.platform === "linux" && isDirectory(runtimeDir)
|
|
53
|
+
? runtimeDir
|
|
54
|
+
: SHARED_TMP_DIR;
|
|
55
|
+
return path.join(base, `wheatley-${uid ?? "user"}`);
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* The Unix socket of the Control Server for a Deployment home. The daemon listens on it, and every client connects to
|
|
59
|
+
* it.
|
|
60
|
+
*
|
|
61
|
+
* Invariants: the path is `<home>/daemon.sock` if that path fits in `sun_path`. Else it is
|
|
62
|
+
* `<base>/wheatley-<uid>/<hash>.sock`. The base is `/run/user/<uid>` on Linux if that folder exists, else `/tmp`. The
|
|
63
|
+
* hash comes from the home with symlinks resolved. The result depends only on the home and the file system, so every
|
|
64
|
+
* spelling of one home gives the same result in every process of the user.
|
|
65
|
+
*
|
|
66
|
+
* Errors: does not throw.
|
|
67
|
+
*/
|
|
68
|
+
export const daemonSocket = (home) => {
|
|
69
|
+
const canonical = canonicalHome(home);
|
|
70
|
+
const inHome = path.join(canonical, DAEMON_SOCKET_FILE);
|
|
71
|
+
if (fits(inHome)) {
|
|
72
|
+
return { fallbackDir: undefined, path: inHome };
|
|
73
|
+
}
|
|
74
|
+
const fallbackDir = fallbackDirOf();
|
|
75
|
+
const hash = createHash("sha256")
|
|
76
|
+
.update(canonical)
|
|
77
|
+
.digest("hex")
|
|
78
|
+
.slice(0, HOME_HASH_LENGTH);
|
|
79
|
+
return { fallbackDir, path: path.join(fallbackDir, `${hash}.sock`) };
|
|
80
|
+
};
|
|
81
|
+
/**
|
|
82
|
+
* Creates the owner-only folder `dir` if it is missing, and checks that only the current user can access it.
|
|
83
|
+
*
|
|
84
|
+
* Ordering: call it with `daemonSocket(home).fallbackDir` before the daemon listens on the fallback socket.
|
|
85
|
+
*
|
|
86
|
+
* Errors: rejects if `dir` is not a folder, belongs to another user, or allows access by the group or other users.
|
|
87
|
+
*/
|
|
88
|
+
export const prepareDaemonSocketDir = async (dir) => {
|
|
89
|
+
await mkdir(dir, { mode: PRIVATE_DIR_MODE, recursive: true });
|
|
90
|
+
const info = await lstat(dir);
|
|
91
|
+
const uid = process.getuid?.();
|
|
92
|
+
const ownedByOthers = uid !== undefined && info.uid !== uid;
|
|
93
|
+
if (!info.isDirectory() || ownedByOthers || isOpenToOthers(info.mode)) {
|
|
94
|
+
throw new Error(`The socket folder ${dir} must be a folder that only the current user can access`);
|
|
95
|
+
}
|
|
96
|
+
};
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
2
|
+
import { parseDuration } from "@wheatley-ai/protocol";
|
|
3
|
+
import { daemonSocket, prepareDaemonSocketDir } from "./daemon-socket.js";
|
|
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
|
+
/** How long `close` waits for active Runs before it stops the Agents. */
|
|
14
|
+
export const DEFAULT_DRAIN_TIMEOUT = "30s";
|
|
15
|
+
const DRAIN_POLL_MS = 100;
|
|
16
|
+
/** The socket path of the options, or `undefined` if they disable the socket. Prepares a default fallback folder. */
|
|
17
|
+
const resolveSocketPath = async (options) => {
|
|
18
|
+
if (options.socketPath !== undefined) {
|
|
19
|
+
return options.socketPath ?? undefined;
|
|
20
|
+
}
|
|
21
|
+
const socket = daemonSocket(options.homeDir);
|
|
22
|
+
if (socket.fallbackDir !== undefined) {
|
|
23
|
+
await prepareDaemonSocketDir(socket.fallbackDir);
|
|
24
|
+
}
|
|
25
|
+
return socket.path;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Starts a Deployment and its Control Server. The router sends Deployment methods to the Deployment, and Agent methods
|
|
29
|
+
* to the core handlers and hosted modules of the named Agent.
|
|
30
|
+
*
|
|
31
|
+
* Errors: rejects if the fallback socket folder is not owner-only (see `prepareDaemonSocketDir`), or if `attach`, the
|
|
32
|
+
* Agent start, or the Control Server listener fails. The Deployment and the attached services are closed before the
|
|
33
|
+
* promise rejects.
|
|
34
|
+
*/
|
|
35
|
+
export const startDaemon = async (options) => {
|
|
36
|
+
const deployment = await Deployment.create(options);
|
|
37
|
+
const snapshot = await deployment.config.read();
|
|
38
|
+
const settings = snapshot.config.daemon;
|
|
39
|
+
const agentRpc = new WeakMap();
|
|
40
|
+
const router = createRouter({
|
|
41
|
+
agent: async (name) => {
|
|
42
|
+
const agent = await deployment.waitForAgent(name);
|
|
43
|
+
const cached = agentRpc.get(agent);
|
|
44
|
+
if (cached !== undefined) {
|
|
45
|
+
return cached;
|
|
46
|
+
}
|
|
47
|
+
const maps = [
|
|
48
|
+
createAgentRpc(agent, deployment.agentDir(name)),
|
|
49
|
+
...agent.moduleRpc,
|
|
50
|
+
];
|
|
51
|
+
agentRpc.set(agent, maps);
|
|
52
|
+
return maps;
|
|
53
|
+
},
|
|
54
|
+
deployment: [createDeploymentRpc(deployment)],
|
|
55
|
+
runningAgents: () => deployment.agentNames.filter((name) => deployment.health(name).state === "running"),
|
|
56
|
+
});
|
|
57
|
+
let attached;
|
|
58
|
+
let server;
|
|
59
|
+
try {
|
|
60
|
+
// The daemon checks the socket folder before any service or Agent starts, so a bad folder fails fast.
|
|
61
|
+
const socketPath = await resolveSocketPath(options);
|
|
62
|
+
attached = await options.attach?.(deployment);
|
|
63
|
+
await deployment.start();
|
|
64
|
+
server = await ControlServer.listen({
|
|
65
|
+
allowedOrigins: settings?.allowedOrigins ?? [],
|
|
66
|
+
events: deployment.events,
|
|
67
|
+
host: options.host ?? settings?.host ?? DEFAULT_DAEMON_HOST,
|
|
68
|
+
log: deployment.logs.logger("control-server"),
|
|
69
|
+
port: options.port ?? settings?.port ?? DEFAULT_DAEMON_PORT,
|
|
70
|
+
router,
|
|
71
|
+
staticDir: options.staticDir,
|
|
72
|
+
socketPath,
|
|
73
|
+
version: options.version,
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
await deployment.close();
|
|
78
|
+
await attached?.close();
|
|
79
|
+
throw error;
|
|
80
|
+
}
|
|
81
|
+
const drainMs = parseDuration(settings?.drainTimeout ?? DEFAULT_DRAIN_TIMEOUT);
|
|
82
|
+
return {
|
|
83
|
+
close: async () => {
|
|
84
|
+
await server.close();
|
|
85
|
+
const deadline = Date.now() + drainMs;
|
|
86
|
+
while (Date.now() < deadline &&
|
|
87
|
+
deployment.status().agents.some((agent) => agent.activeRuns > 0)) {
|
|
88
|
+
// oxlint-disable-next-line no-await-in-loop -- The drain waits for Runs to end one poll at a time.
|
|
89
|
+
await delay(DRAIN_POLL_MS);
|
|
90
|
+
}
|
|
91
|
+
await deployment.close();
|
|
92
|
+
await attached?.close();
|
|
93
|
+
},
|
|
94
|
+
deployment,
|
|
95
|
+
server,
|
|
96
|
+
};
|
|
97
|
+
};
|
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
import { mkdir, rename, rm, stat } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { PROTOCOL_VERSION } from "@wheatley-ai/protocol";
|
|
4
|
+
import { SeamError } from "../contracts/errors.js";
|
|
5
|
+
import { systemClock } from "../contracts/module.js";
|
|
6
|
+
import { Agent } from "./agent/agent.js";
|
|
7
|
+
import { gatedModels } from "./agent/gated-models.js";
|
|
8
|
+
import { builtinOnlyCatalog } from "./builtin-catalog.js";
|
|
9
|
+
import { ConcurrencyGate, DEFAULT_PROVIDER_CONCURRENCY, } from "./concurrency-gate.js";
|
|
10
|
+
import { FileConfigStore } from "./config/config-store.js";
|
|
11
|
+
import { pendingRestarts } from "./config/pending-restart.js";
|
|
12
|
+
import { EventBus } from "./events.js";
|
|
13
|
+
import { LogStore } from "./logger.js";
|
|
14
|
+
import { createProviderModels } from "./models.js";
|
|
15
|
+
import { defaultSetTimer, Supervisor } from "./supervisor.js";
|
|
16
|
+
/** The folder of the Agents inside the Deployment home. */
|
|
17
|
+
export const AGENTS_DIR = "agents";
|
|
18
|
+
/** The folder that `agents.delete` with `data: "archive"` moves Agent folders into. */
|
|
19
|
+
export const ARCHIVE_DIR = "archive";
|
|
20
|
+
/** The longest time that `waitForAgent` waits for the start, stop, or restart of an Agent to finish. */
|
|
21
|
+
const AGENT_START_WAIT_MS = 30_000;
|
|
22
|
+
/** The health fields of an Agent that is not running. */
|
|
23
|
+
const IDLE_STATUS = {
|
|
24
|
+
activeRuns: 0,
|
|
25
|
+
frontends: [],
|
|
26
|
+
mcpServers: [],
|
|
27
|
+
plugins: [],
|
|
28
|
+
skillWarnings: [],
|
|
29
|
+
};
|
|
30
|
+
const exists = async (target) => {
|
|
31
|
+
try {
|
|
32
|
+
await stat(target);
|
|
33
|
+
return true;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* One running Wheatley installation: the Config Store, the Supervisor of its Agents, the Concurrency Gate, the event
|
|
41
|
+
* bus, and the log buffer (ADR 0001, ADR 0004).
|
|
42
|
+
*
|
|
43
|
+
* Agent lifecycle calls (`createAgent`, `renameAgent`, `deleteAgent`) check `expectedRevision` through the Config Store
|
|
44
|
+
* first and change nothing if it fails.
|
|
45
|
+
*/
|
|
46
|
+
export class Deployment {
|
|
47
|
+
homeDir;
|
|
48
|
+
events = new EventBus();
|
|
49
|
+
logs;
|
|
50
|
+
config;
|
|
51
|
+
gate;
|
|
52
|
+
#options;
|
|
53
|
+
#clock;
|
|
54
|
+
#supervisor;
|
|
55
|
+
#applied = new Map();
|
|
56
|
+
#startedAt;
|
|
57
|
+
#current;
|
|
58
|
+
#daemonConfig;
|
|
59
|
+
constructor(options, config, initial) {
|
|
60
|
+
this.#options = options;
|
|
61
|
+
this.homeDir = options.homeDir;
|
|
62
|
+
this.config = config;
|
|
63
|
+
this.#clock = options.clock ?? systemClock;
|
|
64
|
+
this.#startedAt = this.#clock.now();
|
|
65
|
+
this.#current = initial;
|
|
66
|
+
this.#daemonConfig = initial;
|
|
67
|
+
this.logs = new LogStore({
|
|
68
|
+
clock: this.#clock,
|
|
69
|
+
events: this.events,
|
|
70
|
+
redact: config.secrets.redact,
|
|
71
|
+
write: options.writeLog,
|
|
72
|
+
});
|
|
73
|
+
this.gate = new ConcurrencyGate((provider) => this.#current.providers?.[provider]?.maxConcurrent ??
|
|
74
|
+
DEFAULT_PROVIDER_CONCURRENCY);
|
|
75
|
+
this.#supervisor = new Supervisor({
|
|
76
|
+
clock: this.#clock,
|
|
77
|
+
events: this.events,
|
|
78
|
+
log: this.logs.logger("supervisor"),
|
|
79
|
+
open: this.#openAgent,
|
|
80
|
+
setTimer: options.setTimer,
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Reads `config.yaml` and creates the Deployment without starting any Agent. Errors: rejects with
|
|
85
|
+
* `SeamError("config_invalid")` if `config.yaml` is invalid.
|
|
86
|
+
*/
|
|
87
|
+
static async create(options) {
|
|
88
|
+
const config = options.configStore ??
|
|
89
|
+
(await FileConfigStore.open({
|
|
90
|
+
env: options.env,
|
|
91
|
+
homeDir: options.homeDir,
|
|
92
|
+
}));
|
|
93
|
+
const snapshot = await config.read();
|
|
94
|
+
await mkdir(path.join(options.homeDir, AGENTS_DIR), { recursive: true });
|
|
95
|
+
return new Deployment(options, config, snapshot.config);
|
|
96
|
+
}
|
|
97
|
+
/** `create`, then `start`. */
|
|
98
|
+
static async open(options) {
|
|
99
|
+
const deployment = await Deployment.create(options);
|
|
100
|
+
await deployment.start();
|
|
101
|
+
return deployment;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Starts every Agent in `config.yaml`, all at once, and resolves when each is `running` or `degraded`. An Agent that
|
|
105
|
+
* fails to start does not stop the others.
|
|
106
|
+
*/
|
|
107
|
+
start = async () => {
|
|
108
|
+
await Promise.all(Object.keys(this.#current.agents).map(async (name) => await this.#supervisor.start(name)));
|
|
109
|
+
};
|
|
110
|
+
/** The Agent folder of `name`. */
|
|
111
|
+
agentDir = (name) => path.join(this.homeDir, AGENTS_DIR, name);
|
|
112
|
+
/** The names of every Agent that `config.yaml` lists or the Supervisor knows, sorted. */
|
|
113
|
+
get agentNames() {
|
|
114
|
+
return [
|
|
115
|
+
...new Set([
|
|
116
|
+
...Object.keys(this.#current.agents),
|
|
117
|
+
...this.#supervisor.names,
|
|
118
|
+
]),
|
|
119
|
+
].toSorted();
|
|
120
|
+
}
|
|
121
|
+
/** The running Agent `name`. Throws `agent_not_found` for an unknown Agent and `agent_unavailable` otherwise. */
|
|
122
|
+
agent = (name) => {
|
|
123
|
+
const state = this.#supervisor.get(name);
|
|
124
|
+
if (state === undefined && this.#current.agents[name] === undefined) {
|
|
125
|
+
throw new SeamError("agent_not_found", `Unknown Agent: ${name}`);
|
|
126
|
+
}
|
|
127
|
+
if (state?.instance === undefined) {
|
|
128
|
+
throw new SeamError("agent_unavailable", `Agent ${name} is ${state?.state ?? "stopped"}`);
|
|
129
|
+
}
|
|
130
|
+
return state.instance;
|
|
131
|
+
};
|
|
132
|
+
/**
|
|
133
|
+
* The Agent `name` for a request that can wait for it, for example `chat.send` while `/restart` runs.
|
|
134
|
+
*
|
|
135
|
+
* Ordering: it returns a running Agent at once. Otherwise it waits until every queued start, stop, and restart of the
|
|
136
|
+
* Agent finishes, at most `AGENT_START_WAIT_MS`, and then behaves as `agent`.
|
|
137
|
+
*
|
|
138
|
+
* Errors: throws `agent_not_found` at once for an unknown Agent. Throws `agent_unavailable` if the Agent is not running
|
|
139
|
+
* after the wait, for example `degraded` or `stopped`, or if the wait times out while it is still `starting`.
|
|
140
|
+
*/
|
|
141
|
+
waitForAgent = async (name) => {
|
|
142
|
+
const state = this.#supervisor.get(name);
|
|
143
|
+
if (state?.instance !== undefined) {
|
|
144
|
+
return state.instance;
|
|
145
|
+
}
|
|
146
|
+
if (state === undefined && this.#current.agents[name] === undefined) {
|
|
147
|
+
throw new SeamError("agent_not_found", `Unknown Agent: ${name}`);
|
|
148
|
+
}
|
|
149
|
+
const timedOut = Promise.withResolvers();
|
|
150
|
+
const setTimer = this.#options.setTimer ?? defaultSetTimer;
|
|
151
|
+
const cancel = setTimer(() => {
|
|
152
|
+
timedOut.resolve(undefined);
|
|
153
|
+
}, AGENT_START_WAIT_MS);
|
|
154
|
+
try {
|
|
155
|
+
await Promise.race([this.#supervisor.settled(name), timedOut.promise]);
|
|
156
|
+
}
|
|
157
|
+
finally {
|
|
158
|
+
cancel();
|
|
159
|
+
}
|
|
160
|
+
return this.agent(name);
|
|
161
|
+
};
|
|
162
|
+
/** Health of one Agent. Throws `SeamError("agent_not_found")`. */
|
|
163
|
+
health = (name) => {
|
|
164
|
+
const state = this.#supervisor.get(name);
|
|
165
|
+
if (state === undefined && this.#current.agents[name] === undefined) {
|
|
166
|
+
throw new SeamError("agent_not_found", `Unknown Agent: ${name}`);
|
|
167
|
+
}
|
|
168
|
+
const status = state?.instance?.status() ?? IDLE_STATUS;
|
|
169
|
+
const pending = pendingRestarts(this.#appliedConfig(), this.#current);
|
|
170
|
+
return {
|
|
171
|
+
activeRuns: status.activeRuns,
|
|
172
|
+
frontends: [...status.frontends],
|
|
173
|
+
lastError: state?.lastError ?? null,
|
|
174
|
+
mcpServers: [...status.mcpServers],
|
|
175
|
+
name,
|
|
176
|
+
pendingRestart: pending.some((item) => item.kind !== "daemon" && item.agent === name),
|
|
177
|
+
plugins: [...status.plugins],
|
|
178
|
+
restartBackoffMs: state?.restartBackoffMs ?? null,
|
|
179
|
+
skillWarnings: [...status.skillWarnings],
|
|
180
|
+
state: state?.state ?? "stopped",
|
|
181
|
+
};
|
|
182
|
+
};
|
|
183
|
+
/** Deployment health for `system.status`. */
|
|
184
|
+
status = () => {
|
|
185
|
+
const now = this.#clock.now();
|
|
186
|
+
return {
|
|
187
|
+
agents: this.agentNames.map((name) => this.health(name)),
|
|
188
|
+
concurrency: this.gate.pressure(),
|
|
189
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
190
|
+
startedAt: new Date(this.#startedAt).toISOString(),
|
|
191
|
+
uptimeMs: Math.max(0, now - this.#startedAt),
|
|
192
|
+
version: this.#options.version,
|
|
193
|
+
};
|
|
194
|
+
};
|
|
195
|
+
startAgent = async (name) => {
|
|
196
|
+
this.#requireConfigured(name);
|
|
197
|
+
return await this.#supervisor.start(name);
|
|
198
|
+
};
|
|
199
|
+
stopAgent = async (name) => {
|
|
200
|
+
this.#requireKnown(name);
|
|
201
|
+
return await this.#supervisor.stop(name);
|
|
202
|
+
};
|
|
203
|
+
restartAgent = async (name) => {
|
|
204
|
+
this.#requireConfigured(name);
|
|
205
|
+
return await this.#supervisor.restart(name);
|
|
206
|
+
};
|
|
207
|
+
/** `config.get`: the current file, its revision, and the changes that wait for a restart. */
|
|
208
|
+
getConfig = async () => {
|
|
209
|
+
const snapshot = await this.config.read();
|
|
210
|
+
this.#current = snapshot.config;
|
|
211
|
+
return {
|
|
212
|
+
config: snapshot.config,
|
|
213
|
+
pendingRestart: pendingRestarts(this.#appliedConfig(), snapshot.config),
|
|
214
|
+
raw: snapshot.raw,
|
|
215
|
+
revision: snapshot.revision,
|
|
216
|
+
};
|
|
217
|
+
};
|
|
218
|
+
/**
|
|
219
|
+
* `config.save`: writes the config, starts Agents that the save added, stops Agents that it removed, and with
|
|
220
|
+
* `restart: "affected"` restarts every Agent with a pending change. Emits `config.changed`.
|
|
221
|
+
*/
|
|
222
|
+
saveConfig = async (input, expectedRevision, restart) => {
|
|
223
|
+
const snapshot = await this.config.save(input, expectedRevision);
|
|
224
|
+
await this.#apply(snapshot.config);
|
|
225
|
+
if (restart === "affected") {
|
|
226
|
+
const affected = new Set(pendingRestarts(this.#appliedConfig(), snapshot.config).flatMap((item) => (item.kind === "daemon" ? [] : [item.agent])));
|
|
227
|
+
await Promise.all([...affected].map(async (name) => await this.#supervisor.restart(name)));
|
|
228
|
+
}
|
|
229
|
+
return this.#changed(snapshot.revision);
|
|
230
|
+
};
|
|
231
|
+
/** `agents.create`: adds the Agent to `config.yaml` and starts it. Throws `conflict` for an existing name. */
|
|
232
|
+
createAgent = async (name, config, expectedRevision) => {
|
|
233
|
+
const current = await this.config.read();
|
|
234
|
+
if (current.config.agents[name] !== undefined ||
|
|
235
|
+
this.#supervisor.get(name) !== undefined) {
|
|
236
|
+
throw new SeamError("conflict", `Agent ${name} already exists`);
|
|
237
|
+
}
|
|
238
|
+
const snapshot = await this.config.save({
|
|
239
|
+
config: {
|
|
240
|
+
...current.config,
|
|
241
|
+
agents: { ...current.config.agents, [name]: config },
|
|
242
|
+
},
|
|
243
|
+
}, expectedRevision);
|
|
244
|
+
await this.#apply(snapshot.config);
|
|
245
|
+
return { revision: this.#changed(snapshot.revision).revision };
|
|
246
|
+
};
|
|
247
|
+
/**
|
|
248
|
+
* `agents.rename`: stops the Agent, moves its folder, renames it in `config.yaml`, and starts it under the new name.
|
|
249
|
+
* If the config write fails, it moves the folder back and starts the Agent under its old name.
|
|
250
|
+
*/
|
|
251
|
+
renameAgent = async (name, newName, expectedRevision) => {
|
|
252
|
+
const current = await this.config.read();
|
|
253
|
+
const agentConfig = current.config.agents[name];
|
|
254
|
+
if (agentConfig === undefined) {
|
|
255
|
+
throw new SeamError("agent_not_found", `Unknown Agent: ${name}`);
|
|
256
|
+
}
|
|
257
|
+
if (current.config.agents[newName] !== undefined ||
|
|
258
|
+
(await exists(this.agentDir(newName)))) {
|
|
259
|
+
throw new SeamError("conflict", `Agent ${newName} already exists`);
|
|
260
|
+
}
|
|
261
|
+
if (current.revision !== expectedRevision) {
|
|
262
|
+
throw new SeamError("revision_conflict", "config.yaml changed since it was read", {
|
|
263
|
+
revision: current.revision,
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
const agents = Object.fromEntries(Object.entries(current.config.agents).map(([key, value]) => [
|
|
267
|
+
key === name ? newName : key,
|
|
268
|
+
value,
|
|
269
|
+
]));
|
|
270
|
+
await this.#supervisor.remove(name);
|
|
271
|
+
this.#applied.delete(name);
|
|
272
|
+
const moved = await exists(this.agentDir(name));
|
|
273
|
+
if (moved) {
|
|
274
|
+
await rename(this.agentDir(name), this.agentDir(newName));
|
|
275
|
+
}
|
|
276
|
+
try {
|
|
277
|
+
const snapshot = await this.config.save({ config: { ...current.config, agents } }, expectedRevision);
|
|
278
|
+
await this.#apply(snapshot.config);
|
|
279
|
+
return { revision: this.#changed(snapshot.revision).revision };
|
|
280
|
+
}
|
|
281
|
+
catch (error) {
|
|
282
|
+
if (moved) {
|
|
283
|
+
await rename(this.agentDir(newName), this.agentDir(name));
|
|
284
|
+
}
|
|
285
|
+
await this.#supervisor.start(name);
|
|
286
|
+
throw error;
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
/** `agents.delete`: removes the Agent from `config.yaml`, stops it, and keeps, archives, or deletes its folder. */
|
|
290
|
+
deleteAgent = async (params) => {
|
|
291
|
+
const current = await this.config.read();
|
|
292
|
+
if (current.config.agents[params.agent] === undefined) {
|
|
293
|
+
throw new SeamError("agent_not_found", `Unknown Agent: ${params.agent}`);
|
|
294
|
+
}
|
|
295
|
+
const agents = Object.fromEntries(Object.entries(current.config.agents).filter(([key]) => key !== params.agent));
|
|
296
|
+
const snapshot = await this.config.save({ config: { ...current.config, agents } }, params.expectedRevision);
|
|
297
|
+
await this.#apply(snapshot.config);
|
|
298
|
+
const dir = this.agentDir(params.agent);
|
|
299
|
+
if (params.data === "delete") {
|
|
300
|
+
await rm(dir, { force: true, recursive: true });
|
|
301
|
+
}
|
|
302
|
+
else if (params.data === "archive" && (await exists(dir))) {
|
|
303
|
+
const stamp = new Date(this.#clock.now())
|
|
304
|
+
.toISOString()
|
|
305
|
+
.replaceAll(":", "-");
|
|
306
|
+
const archiveDir = path.join(this.homeDir, ARCHIVE_DIR);
|
|
307
|
+
await mkdir(archiveDir, { recursive: true });
|
|
308
|
+
await rename(dir, path.join(archiveDir, `${params.agent}-${stamp}`));
|
|
309
|
+
}
|
|
310
|
+
return { revision: this.#changed(snapshot.revision).revision };
|
|
311
|
+
};
|
|
312
|
+
/** Stops every Agent. */
|
|
313
|
+
close = async () => {
|
|
314
|
+
await this.#supervisor.stopAll();
|
|
315
|
+
};
|
|
316
|
+
#requireKnown = (name) => {
|
|
317
|
+
if (this.#supervisor.get(name) === undefined &&
|
|
318
|
+
this.#current.agents[name] === undefined) {
|
|
319
|
+
throw new SeamError("agent_not_found", `Unknown Agent: ${name}`);
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
#requireConfigured = (name) => {
|
|
323
|
+
if (this.#current.agents[name] === undefined) {
|
|
324
|
+
throw new SeamError("agent_not_found", `Unknown Agent: ${name}`);
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
/** Starts Agents that `config` added and stops Agents that it removed. */
|
|
328
|
+
#apply = async (config) => {
|
|
329
|
+
this.#current = config;
|
|
330
|
+
const removed = this.#supervisor.names.filter((name) => config.agents[name] === undefined);
|
|
331
|
+
const added = Object.keys(config.agents).filter((name) => this.#supervisor.get(name) === undefined);
|
|
332
|
+
await Promise.all(removed.map(async (name) => {
|
|
333
|
+
await this.#supervisor.remove(name);
|
|
334
|
+
this.#applied.delete(name);
|
|
335
|
+
}));
|
|
336
|
+
await Promise.all(added.map(async (name) => await this.#supervisor.start(name)));
|
|
337
|
+
};
|
|
338
|
+
#changed = (revision) => {
|
|
339
|
+
const pendingRestart = pendingRestarts(this.#appliedConfig(), this.#current);
|
|
340
|
+
this.events.emit("config.changed", { pendingRestart, revision });
|
|
341
|
+
return { pendingRestart, revision };
|
|
342
|
+
};
|
|
343
|
+
#appliedConfig = () => ({
|
|
344
|
+
agents: new Map([...this.#applied.entries()].filter(([name]) => this.#supervisor.get(name)?.instance !== undefined)),
|
|
345
|
+
daemon: this.#daemonConfig,
|
|
346
|
+
});
|
|
347
|
+
#openAgent = async (name, controls) => {
|
|
348
|
+
const snapshot = await this.config.read();
|
|
349
|
+
this.#current = snapshot.config;
|
|
350
|
+
const config = snapshot.config.agents[name];
|
|
351
|
+
if (config === undefined) {
|
|
352
|
+
throw new SeamError("agent_not_found", `Unknown Agent: ${name}`);
|
|
353
|
+
}
|
|
354
|
+
const providers = snapshot.config.providers ?? {};
|
|
355
|
+
const createModels = this.#options.models ?? createProviderModels;
|
|
356
|
+
const base = await createModels(snapshot.config, this.config.secrets);
|
|
357
|
+
const models = gatedModels(base, this.gate, (provider) => this.#current.providers?.[provider]?.baseUrl);
|
|
358
|
+
const agent = await Agent.open({
|
|
359
|
+
...this.#options.agentServices?.(name, config),
|
|
360
|
+
agentDir: this.agentDir(name),
|
|
361
|
+
clock: this.#clock,
|
|
362
|
+
config,
|
|
363
|
+
events: this.events,
|
|
364
|
+
extensions: this.#options.extensions ?? builtinOnlyCatalog,
|
|
365
|
+
homeDir: this.homeDir,
|
|
366
|
+
log: this.logs.logger("agent", name),
|
|
367
|
+
models,
|
|
368
|
+
name,
|
|
369
|
+
onFailed: controls.onFailed,
|
|
370
|
+
onRestartRequested: controls.onRestartRequested,
|
|
371
|
+
secrets: this.config.secrets,
|
|
372
|
+
});
|
|
373
|
+
this.#applied.set(name, {
|
|
374
|
+
config,
|
|
375
|
+
provider: providers[config.model.provider],
|
|
376
|
+
});
|
|
377
|
+
return agent;
|
|
378
|
+
};
|
|
379
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** The message of a thrown value: `Error.message` for an `Error`, otherwise the value as a string. */
|
|
2
|
+
export const errorMessage = (
|
|
3
|
+
// oxlint-disable-next-line anti-slop/no-unknown-parameters -- A caught value has no type, and this helper only reads its message.
|
|
4
|
+
error) => (error instanceof Error ? error.message : String(error));
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Deployment-wide event bus. Modules emit through it as an `EventSink`, and each Control Server connection
|
|
3
|
+
* listens and filters by its subscriptions. Listeners run synchronously in subscription order. A throwing listener is
|
|
4
|
+
* skipped, so one connection cannot block another.
|
|
5
|
+
*/
|
|
6
|
+
export class EventBus {
|
|
7
|
+
#listeners = new Set();
|
|
8
|
+
emit = (name, payload) => {
|
|
9
|
+
for (const listener of this.#listeners) {
|
|
10
|
+
try {
|
|
11
|
+
listener(name, payload);
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
// A listener failure must not reach the emitter or other listeners.
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
/** Adds a listener and returns the function that removes it. */
|
|
19
|
+
listen = (listener) => {
|
|
20
|
+
this.#listeners.add(listener);
|
|
21
|
+
return () => {
|
|
22
|
+
this.#listeners.delete(listener);
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { isJsonValue } from "@wheatley-ai/protocol";
|
|
2
|
+
/** The number of records that `logs.tail` can return. */
|
|
3
|
+
export const LOG_BUFFER_SIZE = 2000;
|
|
4
|
+
const LEVEL_ORDER = {
|
|
5
|
+
debug: 0,
|
|
6
|
+
error: 3,
|
|
7
|
+
info: 1,
|
|
8
|
+
warn: 2,
|
|
9
|
+
};
|
|
10
|
+
const isJsonObject = (value) => isJsonValue(value) &&
|
|
11
|
+
typeof value === "object" &&
|
|
12
|
+
value !== null &&
|
|
13
|
+
!Array.isArray(value);
|
|
14
|
+
const redactFields = (fields, redact) => {
|
|
15
|
+
try {
|
|
16
|
+
const parsed = JSON.parse(redact(JSON.stringify(fields)));
|
|
17
|
+
return isJsonObject(parsed) ? parsed : undefined;
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Keeps the last `LOG_BUFFER_SIZE` diagnostic records of the daemon for `logs.tail`, and emits each record as a
|
|
25
|
+
* `log.record` event. Records never contain secret values: messages and fields pass through `redact` first.
|
|
26
|
+
*/
|
|
27
|
+
export class LogStore {
|
|
28
|
+
#options;
|
|
29
|
+
#records = [];
|
|
30
|
+
#seq = 0;
|
|
31
|
+
constructor(options) {
|
|
32
|
+
this.#options = options;
|
|
33
|
+
}
|
|
34
|
+
/** Returns a `Logger` that tags its records with `module` and, if given, `agent`. */
|
|
35
|
+
logger = (module, agent) => {
|
|
36
|
+
const log = (level) => (message, fields) => {
|
|
37
|
+
this.#record(level, module, agent, message, fields);
|
|
38
|
+
};
|
|
39
|
+
return {
|
|
40
|
+
debug: log("debug"),
|
|
41
|
+
error: log("error"),
|
|
42
|
+
info: log("info"),
|
|
43
|
+
warn: log("warn"),
|
|
44
|
+
};
|
|
45
|
+
};
|
|
46
|
+
/** Returns the newest matching records, oldest first. */
|
|
47
|
+
tail = (filter) => {
|
|
48
|
+
const minimum = LEVEL_ORDER[filter.level ?? "debug"];
|
|
49
|
+
const matching = this.#records.filter((record) => LEVEL_ORDER[record.level] >= minimum &&
|
|
50
|
+
(filter.agent === undefined || record.agent === filter.agent) &&
|
|
51
|
+
(filter.module === undefined || record.module === filter.module));
|
|
52
|
+
return matching.slice(-filter.limit);
|
|
53
|
+
};
|
|
54
|
+
#record = (level, module, agent, message, fields) => {
|
|
55
|
+
if (LEVEL_ORDER[level] < LEVEL_ORDER[this.#options.minLevel ?? "info"]) {
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
const { redact } = this.#options;
|
|
59
|
+
const safeFields = fields === undefined ? undefined : redactFields(fields, redact);
|
|
60
|
+
const record = {
|
|
61
|
+
at: new Date(this.#options.clock.now()).toISOString(),
|
|
62
|
+
level,
|
|
63
|
+
message: redact(message),
|
|
64
|
+
module,
|
|
65
|
+
seq: this.#seq,
|
|
66
|
+
};
|
|
67
|
+
if (agent !== undefined) {
|
|
68
|
+
record.agent = agent;
|
|
69
|
+
}
|
|
70
|
+
if (safeFields !== undefined) {
|
|
71
|
+
record.fields = safeFields;
|
|
72
|
+
}
|
|
73
|
+
this.#seq += 1;
|
|
74
|
+
this.#records.push(record);
|
|
75
|
+
if (this.#records.length > LOG_BUFFER_SIZE) {
|
|
76
|
+
this.#records.shift();
|
|
77
|
+
}
|
|
78
|
+
this.#options.write?.(record);
|
|
79
|
+
this.#options.events.emit("log.record", { record });
|
|
80
|
+
};
|
|
81
|
+
}
|