@wheatley-ai/cli 0.0.0 → 0.1.1
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/README.md +192 -0
- package/dist/cli/chat.js +2 -4
- package/dist/cli/main.js +6 -4
- package/dist/cli/session.js +2 -3
- package/dist/core/agent/agent.js +18 -5
- package/dist/core/config/atomic-file.js +11 -0
- package/dist/core/daemon-socket.js +96 -0
- package/dist/core/daemon.js +20 -11
- package/dist/core/deployment.js +33 -1
- package/dist/core/rpc/router.js +6 -5
- package/dist/core/supervisor.js +10 -1
- package/dist/dashboard/assets/{index-3COz_MZq.css → index-C9Rul5vE.css} +1 -1
- package/dist/dashboard/assets/{index-RnxedkKh.js → index-DXzGGAxQ.js} +1 -1
- package/dist/dashboard/assets/{sheet-presentation-U1UUymXc.js → sheet-presentation-DMljN0LW.js} +1 -1
- package/dist/dashboard/index.html +7 -2
- package/dist/node_modules/@wheatley-ai/protocol/dist/config.d.ts +10 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/config.js +10 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/index.d.ts +1 -1
- package/dist/node_modules/@wheatley-ai/protocol/dist/index.js +1 -1
- package/dist/node_modules/@wheatley-ai/sdk/package.json +1 -1
- package/dist/ops/cli.js +5 -6
- package/dist/triggers/module.js +3 -1
- package/dist/triggers/trigger-tools.js +5 -2
- package/dist/triggers/webhook-ingress.js +0 -4
- package/dist/wiring/agent-services.js +7 -0
- package/package.json +2 -2
package/README.md
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
# @wheatley-ai/cli
|
|
2
|
+
|
|
3
|
+
Wheatley is a personal AI assistant that you host yourself. It runs as a daemon on your machine or server and keeps working when you close the terminal. It remembers what you tell it and runs jobs on a schedule. Before it writes a file or runs a shell command, it asks you.
|
|
4
|
+
|
|
5
|
+
You can talk to it from the terminal, from the web dashboard, or from Telegram, Slack, and Discord.
|
|
6
|
+
|
|
7
|
+
This package installs the `wheatley` command. The daemon, the CLI, and the dashboard all ship in it.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
You need Node.js 26.13.1 or newer.
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
npm install -g @wheatley-ai/cli
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
pnpm works too: `pnpm add -g @wheatley-ai/cli`.
|
|
18
|
+
|
|
19
|
+
## Quick start
|
|
20
|
+
|
|
21
|
+
Create the config files. By default they go in `~/.wheatley`. Set `WHEATLEY_HOME` or pass `--home` to put them somewhere else.
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
wheatley init
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Put your API key in `~/.wheatley/secrets.yaml`:
|
|
28
|
+
|
|
29
|
+
```yaml
|
|
30
|
+
ANTHROPIC_API_KEY: sk-ant-...
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Start the daemon:
|
|
34
|
+
|
|
35
|
+
```sh
|
|
36
|
+
wheatley daemon
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Then, in another terminal:
|
|
40
|
+
|
|
41
|
+
```sh
|
|
42
|
+
wheatley ask "Summarize the README in the current folder"
|
|
43
|
+
wheatley chat
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
The dashboard is at <http://127.0.0.1:7420>.
|
|
47
|
+
|
|
48
|
+
`wheatley init` sets up Anthropic with `claude-sonnet-5-5`. For another provider, pass `--provider` and `--model`. For example, `wheatley init --provider openai --model gpt-5.4-mini` expects `OPENAI_API_KEY`.
|
|
49
|
+
|
|
50
|
+
## Run it in the background
|
|
51
|
+
|
|
52
|
+
`wheatley service` installs a user service: systemd on Linux, launchd on macOS.
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
wheatley service install
|
|
56
|
+
wheatley service start
|
|
57
|
+
wheatley service status
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## Commands
|
|
61
|
+
|
|
62
|
+
| Command | What it does |
|
|
63
|
+
| --- | --- |
|
|
64
|
+
| `wheatley init` | Create `config.yaml` and `secrets.yaml` |
|
|
65
|
+
| `wheatley daemon` | Run the daemon in the foreground |
|
|
66
|
+
| `wheatley chat` | Open an interactive chat with an agent |
|
|
67
|
+
| `wheatley ask "<prompt>"` | Send one prompt and print the reply |
|
|
68
|
+
| `wheatley status` | Show the health of the daemon and each agent |
|
|
69
|
+
| `wheatley service <action>` | `install`, `start`, `stop`, `restart`, or `status` |
|
|
70
|
+
| `wheatley update` | Update to the newest release in your major version |
|
|
71
|
+
| `wheatley restore <agent> [id]` | List or restore an agent's database backups |
|
|
72
|
+
|
|
73
|
+
Run `wheatley --help` for all the options.
|
|
74
|
+
|
|
75
|
+
With no arguments, `ask` reads the prompt from stdin:
|
|
76
|
+
|
|
77
|
+
```sh
|
|
78
|
+
{ echo "Review this diff:"; git diff; } | wheatley ask
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
If stdin is not a terminal, `ask` cannot ask for approval. It denies every tool call that needs one.
|
|
82
|
+
|
|
83
|
+
## Configuration
|
|
84
|
+
|
|
85
|
+
Wheatley reads its settings from `~/.wheatley/config.yaml`. Secrets go in `secrets.yaml`, and the config refers to them by name. If an environment variable has the same name as a secret, the variable wins.
|
|
86
|
+
|
|
87
|
+
```yaml
|
|
88
|
+
version: 1
|
|
89
|
+
|
|
90
|
+
providers:
|
|
91
|
+
anthropic:
|
|
92
|
+
apiKey:
|
|
93
|
+
secret: ANTHROPIC_API_KEY
|
|
94
|
+
|
|
95
|
+
agents:
|
|
96
|
+
default:
|
|
97
|
+
model:
|
|
98
|
+
provider: anthropic
|
|
99
|
+
id: claude-sonnet-5-5
|
|
100
|
+
|
|
101
|
+
# First match wins. Tools without a rule use their own default.
|
|
102
|
+
permissionPolicy:
|
|
103
|
+
- tool: read_file
|
|
104
|
+
action: allow
|
|
105
|
+
- tool: shell
|
|
106
|
+
action: ask
|
|
107
|
+
|
|
108
|
+
# Chat with the agent from Telegram.
|
|
109
|
+
frontends:
|
|
110
|
+
- id: phone
|
|
111
|
+
type: telegram
|
|
112
|
+
config:
|
|
113
|
+
botToken:
|
|
114
|
+
secret: TELEGRAM_BOT_TOKEN
|
|
115
|
+
allowedChatIds: [123456789]
|
|
116
|
+
|
|
117
|
+
# Give the agent the tools of an MCP server.
|
|
118
|
+
mcpServers:
|
|
119
|
+
github:
|
|
120
|
+
transport: http
|
|
121
|
+
url: https://api.githubcopilot.com/mcp/
|
|
122
|
+
headers:
|
|
123
|
+
Authorization:
|
|
124
|
+
secret: GITHUB_MCP_AUTH
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
You can define more than one agent. Each agent gets its own model, memory, schedule, and folder under `~/.wheatley/agents/<name>/`. After you edit the config, restart the agent from the dashboard or with `/restart` in a chat.
|
|
128
|
+
|
|
129
|
+
## Approvals
|
|
130
|
+
|
|
131
|
+
The file and shell tools work inside `agents/<name>/workspace`. Writing files, running shell commands, and calling MCP tools need your approval by default. When the agent wants to do one of these, the chat shows the tool and its input. You answer with one of these:
|
|
132
|
+
|
|
133
|
+
- `o`: allow it once.
|
|
134
|
+
- `c`: allow it for the rest of the conversation.
|
|
135
|
+
- `a`: allow it always. Wheatley adds an `allow` rule to your config.
|
|
136
|
+
- `d <reason>`: deny it, and tell the agent why.
|
|
137
|
+
|
|
138
|
+
An approval waits 15 minutes and then expires. Change this with `approvalTimeout` on the agent.
|
|
139
|
+
|
|
140
|
+
## Chat commands
|
|
141
|
+
|
|
142
|
+
| Command | What it does |
|
|
143
|
+
| ------------------- | ---------------------------------------------- |
|
|
144
|
+
| `/new` | Start a new conversation |
|
|
145
|
+
| `/model <id>` | Use another model for this conversation |
|
|
146
|
+
| `/compact` | Compact the conversation to save context |
|
|
147
|
+
| `/stop` | Stop the current run |
|
|
148
|
+
| `/goal <objective>` | Start a long-running task |
|
|
149
|
+
| `/status` | Show the conversation, model, and agent health |
|
|
150
|
+
| `/restart` | Restart the agent |
|
|
151
|
+
|
|
152
|
+
## What else it does
|
|
153
|
+
|
|
154
|
+
- **Memory.** Each agent keeps notes in `agents/<name>/memory/MEMORY.md` and reads them at the start of each conversation. Every day at 03:00, the agent reviews its notes. It merges duplicates and removes facts that are out of date.
|
|
155
|
+
- **Schedules.** Ask "remind me every weekday at 9 to check my email" and the agent creates a cron trigger. It can set one-off reminders too. A webhook trigger starts a run when it receives an HTTP request. You create webhook triggers in the dashboard.
|
|
156
|
+
- **Skills.** Put a folder with a `SKILL.md` in `~/.wheatley/skills/` to share it with all agents, or in `agents/<name>/skills/` for one agent.
|
|
157
|
+
- **Plugins.** Add your own tools and chat integrations in TypeScript. See [`@wheatley-ai/sdk`](https://www.npmjs.com/package/@wheatley-ai/sdk).
|
|
158
|
+
|
|
159
|
+
## Docker
|
|
160
|
+
|
|
161
|
+
If you would rather not install Node.js, use the image on the GitHub Container Registry:
|
|
162
|
+
|
|
163
|
+
```sh
|
|
164
|
+
docker volume create wheatley-data
|
|
165
|
+
docker run --rm -v wheatley-data:/data ghcr.io/sphericalkat/wheatley:latest wheatley init
|
|
166
|
+
docker run --rm -v wheatley-data:/data ghcr.io/sphericalkat/wheatley:latest \
|
|
167
|
+
sh -c 'printf "daemon:\n host: 0.0.0.0\n port: 7420\n" >> /data/config.yaml'
|
|
168
|
+
docker run --rm -v wheatley-data:/data ghcr.io/sphericalkat/wheatley:latest \
|
|
169
|
+
sh -c 'echo "ANTHROPIC_API_KEY: sk-ant-..." >> /data/secrets.yaml'
|
|
170
|
+
|
|
171
|
+
docker run -d --name wheatley --init --restart unless-stopped --stop-timeout 45 \
|
|
172
|
+
-p 127.0.0.1:7420:7420 -v wheatley-data:/data ghcr.io/sphericalkat/wheatley:latest
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
Each release gets four image tags. For release `0.1.0`, these are `0.1.0`, `0.1`, `0`, and `latest`.
|
|
176
|
+
|
|
177
|
+
## Updating
|
|
178
|
+
|
|
179
|
+
```sh
|
|
180
|
+
wheatley update --check
|
|
181
|
+
wheatley update
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
`wheatley update` stays inside your current major version. To move to a new major version, run `npm install -g @wheatley-ai/cli@latest`. Then restart the daemon, for example with `wheatley service restart`.
|
|
185
|
+
|
|
186
|
+
## Security
|
|
187
|
+
|
|
188
|
+
The daemon has no login. Anyone who can reach port 7420 can use your agents, so keep it on `127.0.0.1`, which is the default. It also rejects browser requests from other origins. If you need remote access, use an SSH tunnel or a private network such as Tailscale.
|
|
189
|
+
|
|
190
|
+
## License
|
|
191
|
+
|
|
192
|
+
ISC
|
package/dist/cli/chat.js
CHANGED
|
@@ -124,14 +124,12 @@ const handleLine = async (io, client, agent, state, line) => {
|
|
|
124
124
|
state.sent(messageId);
|
|
125
125
|
return;
|
|
126
126
|
}
|
|
127
|
-
|
|
127
|
+
// `Agent.command` sends the reply for a command that cannot run, so the CLI ignores `accepted`.
|
|
128
|
+
await client.request("chat.command", {
|
|
128
129
|
agent,
|
|
129
130
|
args: command.args,
|
|
130
131
|
name: command.name,
|
|
131
132
|
});
|
|
132
|
-
if (!accepted) {
|
|
133
|
-
io.stdout(`/${command.name} did not run.\n`);
|
|
134
|
-
}
|
|
135
133
|
};
|
|
136
134
|
/**
|
|
137
135
|
* `wheatley chat`: an interactive session in the Agent's CLI Chat (`cli` binding, Chat `default`), which the dashboard
|
package/dist/cli/main.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { createConnection } from "node:net";
|
|
2
|
-
import path from "node:path";
|
|
3
2
|
import { parseArgs } from "node:util";
|
|
4
|
-
import {
|
|
3
|
+
import { daemonSocket } from "../core/daemon-socket.js";
|
|
5
4
|
import { errorMessage } from "../core/error-message.js";
|
|
6
5
|
import { createOpsCommands, hostCliDeps } from "../ops/cli.js";
|
|
7
6
|
import { runAsk } from "./ask.js";
|
|
@@ -33,10 +32,13 @@ Options:
|
|
|
33
32
|
--host <host> daemon: the TCP host
|
|
34
33
|
--port <port> daemon: the TCP port
|
|
35
34
|
`;
|
|
36
|
-
/**
|
|
35
|
+
/**
|
|
36
|
+
* Resolves `true` if a daemon accepts connections on the Unix socket of `home` (see `daemonSocket`). Resolves `false`
|
|
37
|
+
* if the connection fails for any reason, for example a missing socket file. It does not reject.
|
|
38
|
+
*/
|
|
37
39
|
export const isDaemonRunning = async (home) => {
|
|
38
40
|
const { promise, resolve } = Promise.withResolvers();
|
|
39
|
-
const socket = createConnection(
|
|
41
|
+
const socket = createConnection(daemonSocket(home).path);
|
|
40
42
|
socket.once("connect", () => {
|
|
41
43
|
socket.destroy();
|
|
42
44
|
resolve(true);
|
package/dist/cli/session.js
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { DAEMON_SOCKET_FILE } from "../core/daemon.js";
|
|
1
|
+
import { daemonSocket } from "../core/daemon-socket.js";
|
|
3
2
|
import { errorMessage } from "../core/error-message.js";
|
|
4
3
|
import { DaemonClient } from "./client.js";
|
|
5
4
|
/** The daemon address of the flags. */
|
|
6
5
|
export const targetOf = (flags) => flags.url === undefined
|
|
7
|
-
? { socketPath:
|
|
6
|
+
? { socketPath: daemonSocket(flags.home).path }
|
|
8
7
|
: { url: flags.url };
|
|
9
8
|
/**
|
|
10
9
|
* The Agent that a command talks to: `--agent`, else the only Agent, else the Agent named `default`. Errors: rejects if
|
package/dist/core/agent/agent.js
CHANGED
|
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
|
|
|
2
2
|
import { mkdir } from "node:fs/promises";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { parseDuration, TOOL_INPUT_PREVIEW_MAX_LENGTH, TOOL_OUTPUT_PREVIEW_MAX_LENGTH, } from "@wheatley-ai/protocol";
|
|
5
|
+
import { BUILTIN_COMMANDS } from "@wheatley-ai/sdk";
|
|
5
6
|
import { SeamError } from "../../contracts/errors.js";
|
|
6
7
|
import { openAgentDatabase } from "../../db/database.js";
|
|
7
8
|
import { runMigrations } from "../../db/migrations.js";
|
|
@@ -225,8 +226,12 @@ export class Agent {
|
|
|
225
226
|
};
|
|
226
227
|
/**
|
|
227
228
|
* Runs a built-in command for `chat` (ADR 0007). Resolves `false` if the command cannot run, for example `/model`
|
|
228
|
-
* without an argument or `/stop` without an active Run.
|
|
229
|
-
*
|
|
229
|
+
* without an argument or `/stop` without an active Run.
|
|
230
|
+
*
|
|
231
|
+
* Each call sends exactly one command reply to the Chat before it resolves, also when the command cannot run, so a
|
|
232
|
+
* Frontend shows only the reply and adds no message of its own. The exception is `/goal` with an objective, which
|
|
233
|
+
* sends no command reply and replies later through the Run that it starts. A command reply arrives like a Run reply,
|
|
234
|
+
* with source `command`.
|
|
230
235
|
*/
|
|
231
236
|
command = async (chat, name, args) => {
|
|
232
237
|
switch (name) {
|
|
@@ -892,9 +897,15 @@ export class Agent {
|
|
|
892
897
|
await this.#reply(chat, "Started a new Conversation.");
|
|
893
898
|
return true;
|
|
894
899
|
};
|
|
900
|
+
/** Replies with the usage of a command that needs an argument. Resolves `false`, because the command did not run. */
|
|
901
|
+
#replyUsage = async (chat, name) => {
|
|
902
|
+
const spec = BUILTIN_COMMANDS.find((command) => command.name === name);
|
|
903
|
+
await this.#reply(chat, `Usage: /${name} ${spec?.argument ?? ""}`.trim());
|
|
904
|
+
return false;
|
|
905
|
+
};
|
|
895
906
|
#changeModel = async (chat, args) => {
|
|
896
907
|
if (args === undefined) {
|
|
897
|
-
return
|
|
908
|
+
return await this.#replyUsage(chat, "model");
|
|
898
909
|
}
|
|
899
910
|
const model = parseModelArgument(args, this.#options.config.model);
|
|
900
911
|
if (this.#options.models.getModel(model.provider, model.id) === undefined) {
|
|
@@ -922,11 +933,13 @@ export class Agent {
|
|
|
922
933
|
};
|
|
923
934
|
#stopChat = async (chat) => {
|
|
924
935
|
const run = this.#activeRunOf(chat);
|
|
925
|
-
|
|
936
|
+
const stopped = run !== undefined && (await this.stopRun(run.runId));
|
|
937
|
+
await this.#reply(chat, stopped ? "Stopped the active Run." : "No Run is active.");
|
|
938
|
+
return stopped;
|
|
926
939
|
};
|
|
927
940
|
#goal = async (chat, args) => {
|
|
928
941
|
if (args === undefined) {
|
|
929
|
-
return
|
|
942
|
+
return await this.#replyUsage(chat, "goal");
|
|
930
943
|
}
|
|
931
944
|
const conversationId = await this.#chatConversation(chat);
|
|
932
945
|
await this.#startRun({
|
|
@@ -58,4 +58,15 @@ export class SerialQueue {
|
|
|
58
58
|
this.#tail = settled(result);
|
|
59
59
|
return await result;
|
|
60
60
|
};
|
|
61
|
+
/**
|
|
62
|
+
* Resolves once no step is queued or running. It also waits for steps that callers queue while it waits. It never
|
|
63
|
+
* rejects, even if a step fails.
|
|
64
|
+
*/
|
|
65
|
+
idle = async () => {
|
|
66
|
+
const tail = this.#tail;
|
|
67
|
+
await tail;
|
|
68
|
+
if (tail !== this.#tail) {
|
|
69
|
+
await this.idle();
|
|
70
|
+
}
|
|
71
|
+
};
|
|
61
72
|
}
|
|
@@ -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
|
+
};
|
package/dist/core/daemon.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import path from "node:path";
|
|
2
1
|
import { setTimeout as delay } from "node:timers/promises";
|
|
3
2
|
import { parseDuration } from "@wheatley-ai/protocol";
|
|
3
|
+
import { daemonSocket, prepareDaemonSocketDir } from "./daemon-socket.js";
|
|
4
4
|
import { Deployment } from "./deployment.js";
|
|
5
5
|
import { createAgentRpc } from "./rpc/agent-handlers.js";
|
|
6
6
|
import { createDeploymentRpc } from "./rpc/deployment-handlers.js";
|
|
@@ -10,17 +10,27 @@ import { ControlServer } from "./server/control-server.js";
|
|
|
10
10
|
export const DEFAULT_DAEMON_HOST = "127.0.0.1";
|
|
11
11
|
/** The default TCP port of the Control Server. */
|
|
12
12
|
export const DEFAULT_DAEMON_PORT = 7420;
|
|
13
|
-
/** The Unix socket of the Control Server inside the Deployment home. */
|
|
14
|
-
export const DAEMON_SOCKET_FILE = "daemon.sock";
|
|
15
13
|
/** How long `close` waits for active Runs before it stops the Agents. */
|
|
16
14
|
export const DEFAULT_DRAIN_TIMEOUT = "30s";
|
|
17
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
|
+
};
|
|
18
27
|
/**
|
|
19
28
|
* Starts a Deployment and its Control Server. The router sends Deployment methods to the Deployment, and Agent methods
|
|
20
29
|
* to the core handlers and hosted modules of the named Agent.
|
|
21
30
|
*
|
|
22
|
-
* Errors: rejects if
|
|
23
|
-
* services are closed before the
|
|
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.
|
|
24
34
|
*/
|
|
25
35
|
export const startDaemon = async (options) => {
|
|
26
36
|
const deployment = await Deployment.create(options);
|
|
@@ -28,8 +38,8 @@ export const startDaemon = async (options) => {
|
|
|
28
38
|
const settings = snapshot.config.daemon;
|
|
29
39
|
const agentRpc = new WeakMap();
|
|
30
40
|
const router = createRouter({
|
|
31
|
-
agent: (name) => {
|
|
32
|
-
const agent = deployment.
|
|
41
|
+
agent: async (name) => {
|
|
42
|
+
const agent = await deployment.waitForAgent(name);
|
|
33
43
|
const cached = agentRpc.get(agent);
|
|
34
44
|
if (cached !== undefined) {
|
|
35
45
|
return cached;
|
|
@@ -47,6 +57,8 @@ export const startDaemon = async (options) => {
|
|
|
47
57
|
let attached;
|
|
48
58
|
let server;
|
|
49
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);
|
|
50
62
|
attached = await options.attach?.(deployment);
|
|
51
63
|
await deployment.start();
|
|
52
64
|
server = await ControlServer.listen({
|
|
@@ -57,10 +69,7 @@ export const startDaemon = async (options) => {
|
|
|
57
69
|
port: options.port ?? settings?.port ?? DEFAULT_DAEMON_PORT,
|
|
58
70
|
router,
|
|
59
71
|
staticDir: options.staticDir,
|
|
60
|
-
socketPath
|
|
61
|
-
? undefined
|
|
62
|
-
: (options.socketPath ??
|
|
63
|
-
path.join(options.homeDir, DAEMON_SOCKET_FILE)),
|
|
72
|
+
socketPath,
|
|
64
73
|
version: options.version,
|
|
65
74
|
});
|
|
66
75
|
}
|
package/dist/core/deployment.js
CHANGED
|
@@ -12,11 +12,13 @@ import { pendingRestarts } from "./config/pending-restart.js";
|
|
|
12
12
|
import { EventBus } from "./events.js";
|
|
13
13
|
import { LogStore } from "./logger.js";
|
|
14
14
|
import { createProviderModels } from "./models.js";
|
|
15
|
-
import { Supervisor } from "./supervisor.js";
|
|
15
|
+
import { defaultSetTimer, Supervisor } from "./supervisor.js";
|
|
16
16
|
/** The folder of the Agents inside the Deployment home. */
|
|
17
17
|
export const AGENTS_DIR = "agents";
|
|
18
18
|
/** The folder that `agents.delete` with `data: "archive"` moves Agent folders into. */
|
|
19
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;
|
|
20
22
|
/** The health fields of an Agent that is not running. */
|
|
21
23
|
const IDLE_STATUS = {
|
|
22
24
|
activeRuns: 0,
|
|
@@ -127,6 +129,36 @@ export class Deployment {
|
|
|
127
129
|
}
|
|
128
130
|
return state.instance;
|
|
129
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
|
+
};
|
|
130
162
|
/** Health of one Agent. Throws `SeamError("agent_not_found")`. */
|
|
131
163
|
health = (name) => {
|
|
132
164
|
const state = this.#supervisor.get(name);
|
package/dist/core/rpc/router.js
CHANGED
|
@@ -60,10 +60,11 @@ const mergeResults = (results) => {
|
|
|
60
60
|
*/
|
|
61
61
|
export const createRouter = (sources) => {
|
|
62
62
|
const fanOut = async (request, ctx) => {
|
|
63
|
-
const
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
});
|
|
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 }]);
|
|
67
68
|
const results = await Promise.all(calls.map(async ({ handler, name }) => await handler({ ...request.params, agent: name }, ctx)));
|
|
68
69
|
const objects = results.flatMap((result) => isJsonValue(result) && isObject(result) ? [result] : []);
|
|
69
70
|
const merged = mergeResults(objects);
|
|
@@ -80,7 +81,7 @@ export const createRouter = (sources) => {
|
|
|
80
81
|
return await deploymentHandler(request.params, ctx);
|
|
81
82
|
}
|
|
82
83
|
if (namesAgent(request.params)) {
|
|
83
|
-
const handler = handlerIn(sources.agent(request.params.agent), request.method);
|
|
84
|
+
const handler = handlerIn(await sources.agent(request.params.agent), request.method);
|
|
84
85
|
if (handler === undefined) {
|
|
85
86
|
throw new RpcError(RpcErrorCode.MethodNotFound, `Method not available: ${request.method}`);
|
|
86
87
|
}
|
package/dist/core/supervisor.js
CHANGED
|
@@ -4,7 +4,8 @@ import { errorMessage } from "./error-message.js";
|
|
|
4
4
|
export const RESTART_BACKOFF_INITIAL_MS = 1000;
|
|
5
5
|
/** The longest wait between restart attempts. */
|
|
6
6
|
export const RESTART_BACKOFF_MAX_MS = 60_000;
|
|
7
|
-
|
|
7
|
+
/** The `SetTimer` of production: a `setTimeout` that does not keep the process alive. */
|
|
8
|
+
export const defaultSetTimer = (callback, delayMs) => {
|
|
8
9
|
const timer = setTimeout(callback, delayMs);
|
|
9
10
|
timer.unref();
|
|
10
11
|
return () => {
|
|
@@ -51,6 +52,14 @@ export class Supervisor {
|
|
|
51
52
|
state: entry.state,
|
|
52
53
|
};
|
|
53
54
|
};
|
|
55
|
+
/**
|
|
56
|
+
* Resolves once no lifecycle call (`start`, `stop`, `restart`, `remove`, a failure, or a retry that fired) for `name`
|
|
57
|
+
* is queued or running. A pending retry timer does not count until it fires. It resolves at once for an unknown name
|
|
58
|
+
* and never rejects.
|
|
59
|
+
*/
|
|
60
|
+
settled = async (name) => {
|
|
61
|
+
await this.#entries.get(name)?.queue.idle();
|
|
62
|
+
};
|
|
54
63
|
/**
|
|
55
64
|
* Starts an Agent and resolves with its new state: `running`, or `degraded` if `open` rejected. Starting a running
|
|
56
65
|
* Agent does nothing. A degraded Agent starts at once, and its pending retry is cancelled.
|