@wheatley-ai/cli 0.0.0 → 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/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
- const { accepted } = await client.request("chat.command", {
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 { DAEMON_SOCKET_FILE } from "../core/daemon.js";
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
- /** Resolves `true` if a daemon accepts connections on the Unix socket of `home`. */
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(path.join(home, DAEMON_SOCKET_FILE));
41
+ const socket = createConnection(daemonSocket(home).path);
40
42
  socket.once("connect", () => {
41
43
  socket.destroy();
42
44
  resolve(true);
@@ -1,10 +1,9 @@
1
- import path from "node:path";
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: path.join(flags.home, DAEMON_SOCKET_FILE) }
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
@@ -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. A command reply arrives like a Run reply, with source
229
- * `command`.
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 false;
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
- return run === undefined ? false : await this.stopRun(run.runId);
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 false;
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
+ };
@@ -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 `attach`, the Agent start, or the Control Server listener fails. The Deployment and the attached
23
- * services are closed before the promise rejects.
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.agent(name);
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: options.socketPath === null
61
- ? undefined
62
- : (options.socketPath ??
63
- path.join(options.homeDir, DAEMON_SOCKET_FILE)),
72
+ socketPath,
64
73
  version: options.version,
65
74
  });
66
75
  }
@@ -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);
@@ -60,10 +60,11 @@ const mergeResults = (results) => {
60
60
  */
61
61
  export const createRouter = (sources) => {
62
62
  const fanOut = async (request, ctx) => {
63
- const calls = sources.runningAgents().flatMap((name) => {
64
- const handler = handlerIn(sources.agent(name), request.method);
65
- return handler === undefined ? [] : [{ handler, name }];
66
- });
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
  }
@@ -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
- const defaultSetTimer = (callback, delayMs) => {
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.