@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,185 @@
|
|
|
1
|
+
import { chmod, mkdir, readdir, rename, rm } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { DatabaseSync } from "node:sqlite";
|
|
4
|
+
import { openAgentDatabase } from "../db/database.js";
|
|
5
|
+
import { AGENT_DATABASE_FILE, BACKUPS_DIR, isMissing, pathExists, } from "./paths.js";
|
|
6
|
+
/** How many backups `backupAgentDatabase` keeps per Agent, newest first. */
|
|
7
|
+
export const BACKUP_RETENTION = 5;
|
|
8
|
+
const BACKUP_FILE = /^agent-(?<stamp>\d{8}T\d{9}Z)-(?<reason>pre-migration|pre-restore)(?:-(?<seq>\d+))?\.sqlite$/u;
|
|
9
|
+
const STAMP_SEPARATORS = /[-:.]/gu;
|
|
10
|
+
const STAMP_PARTS = /^(?<year>\d{4})(?<month>\d{2})(?<day>\d{2})T(?<hour>\d{2})(?<minute>\d{2})(?<second>\d{2})(?<ms>\d{3})Z$/u;
|
|
11
|
+
const PRIVATE_DIR_MODE = 0o700;
|
|
12
|
+
const PRIVATE_FILE_MODE = 0o600;
|
|
13
|
+
const LEDGER = "wheatley_migrations";
|
|
14
|
+
const isBackupReason = (value) => value === "pre-migration" || value === "pre-restore";
|
|
15
|
+
const stampToIso = (stamp) => {
|
|
16
|
+
const parts = STAMP_PARTS.exec(stamp)?.groups;
|
|
17
|
+
if (parts === undefined) {
|
|
18
|
+
throw new Error(`Invalid backup timestamp: ${stamp}`);
|
|
19
|
+
}
|
|
20
|
+
const { year, month, day, hour, minute, second, ms } = parts;
|
|
21
|
+
return `${year}-${month}-${day}T${hour}:${minute}:${second}.${ms}Z`;
|
|
22
|
+
};
|
|
23
|
+
const parseBackup = (dir, file) => {
|
|
24
|
+
const groups = BACKUP_FILE.exec(file)?.groups;
|
|
25
|
+
const stamp = groups?.stamp;
|
|
26
|
+
const reason = groups?.reason ?? "";
|
|
27
|
+
if (stamp === undefined || !isBackupReason(reason)) {
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
return {
|
|
31
|
+
info: {
|
|
32
|
+
createdAt: stampToIso(stamp),
|
|
33
|
+
file,
|
|
34
|
+
path: path.join(dir, file),
|
|
35
|
+
reason,
|
|
36
|
+
},
|
|
37
|
+
seq: Number(groups?.seq ?? "0"),
|
|
38
|
+
stamp,
|
|
39
|
+
};
|
|
40
|
+
};
|
|
41
|
+
const newestFirst = (a, b) => b.stamp.localeCompare(a.stamp) || b.seq - a.seq;
|
|
42
|
+
/** Lists the backups of one Agent, newest first. Returns an empty list if the Agent has no `backups/` folder. */
|
|
43
|
+
export const listBackups = async (agentDir) => {
|
|
44
|
+
const dir = path.join(agentDir, BACKUPS_DIR);
|
|
45
|
+
let files = [];
|
|
46
|
+
try {
|
|
47
|
+
files = await readdir(dir);
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
if (error instanceof Error && isMissing(error)) {
|
|
51
|
+
return [];
|
|
52
|
+
}
|
|
53
|
+
throw error;
|
|
54
|
+
}
|
|
55
|
+
return files
|
|
56
|
+
.flatMap((file) => parseBackup(dir, file) ?? [])
|
|
57
|
+
.toSorted(newestFirst)
|
|
58
|
+
.map(({ info }) => info);
|
|
59
|
+
};
|
|
60
|
+
/** Picks a new file name. Two backups in the same millisecond get a sequence suffix. */
|
|
61
|
+
const nextBackupPath = async (dir, stamp, reason) => {
|
|
62
|
+
const taken = new Set(await readdir(dir));
|
|
63
|
+
let seq = 0;
|
|
64
|
+
let file = `agent-${stamp}-${reason}.sqlite`;
|
|
65
|
+
while (taken.has(file)) {
|
|
66
|
+
seq += 1;
|
|
67
|
+
file = `agent-${stamp}-${reason}-${seq}.sqlite`;
|
|
68
|
+
}
|
|
69
|
+
return path.join(dir, file);
|
|
70
|
+
};
|
|
71
|
+
const rotate = async (agentDir) => {
|
|
72
|
+
const backups = await listBackups(agentDir);
|
|
73
|
+
const stale = backups.slice(BACKUP_RETENTION);
|
|
74
|
+
await Promise.all(stale.map(async (backup) => {
|
|
75
|
+
await rm(backup.path, { force: true });
|
|
76
|
+
}));
|
|
77
|
+
return stale;
|
|
78
|
+
};
|
|
79
|
+
/**
|
|
80
|
+
* Writes a consistent snapshot of the open `agent.sqlite` handle to `<agentDir>/backups/` with `VACUUM INTO`, then
|
|
81
|
+
* deletes the oldest backups so that `BACKUP_RETENTION` remain.
|
|
82
|
+
*
|
|
83
|
+
* Invariants: backup files are owner-only (`0600`) in an owner-only folder. File names sort by time, so rotation
|
|
84
|
+
* always keeps the newest backups, including the new one.
|
|
85
|
+
*
|
|
86
|
+
* Errors: throws if `db` is inside a transaction (SQLite rejects `VACUUM` there), or for I/O errors. A failed `VACUUM INTO` leaves the existing backups unchanged.
|
|
87
|
+
*/
|
|
88
|
+
export const backupAgentDatabase = async (db, options) => {
|
|
89
|
+
if (db.isTransaction) {
|
|
90
|
+
throw new Error("Cannot back up a database inside an open transaction");
|
|
91
|
+
}
|
|
92
|
+
const dir = path.join(options.agentDir, BACKUPS_DIR);
|
|
93
|
+
await mkdir(dir, { mode: PRIVATE_DIR_MODE, recursive: true });
|
|
94
|
+
const stamp = new Date(options.clock.now())
|
|
95
|
+
.toISOString()
|
|
96
|
+
.replaceAll(STAMP_SEPARATORS, "");
|
|
97
|
+
const target = await nextBackupPath(dir, stamp, options.reason);
|
|
98
|
+
db.prepare("VACUUM INTO ?").run(target);
|
|
99
|
+
await chmod(target, PRIVATE_FILE_MODE);
|
|
100
|
+
const backup = parseBackup(dir, path.basename(target))?.info;
|
|
101
|
+
if (backup === undefined) {
|
|
102
|
+
throw new Error(`Backup file name does not parse: ${target}`);
|
|
103
|
+
}
|
|
104
|
+
return { backup, removed: await rotate(options.agentDir) };
|
|
105
|
+
};
|
|
106
|
+
const resolveBackupPath = async (agentDir, backup) => {
|
|
107
|
+
const isBareName = path.basename(backup) === backup;
|
|
108
|
+
const candidate = isBareName
|
|
109
|
+
? path.join(agentDir, BACKUPS_DIR, backup)
|
|
110
|
+
: path.resolve(backup);
|
|
111
|
+
if (!(await pathExists(candidate))) {
|
|
112
|
+
throw new Error(`Backup not found: ${candidate}`);
|
|
113
|
+
}
|
|
114
|
+
return candidate;
|
|
115
|
+
};
|
|
116
|
+
const assertRestorable = (source, file) => {
|
|
117
|
+
const integrity = source.prepare("PRAGMA integrity_check").all();
|
|
118
|
+
const isIntact = integrity.length === 1 && integrity[0]?.integrity_check === "ok";
|
|
119
|
+
if (!isIntact) {
|
|
120
|
+
throw new Error(`Backup fails the SQLite integrity check: ${file}`);
|
|
121
|
+
}
|
|
122
|
+
const hasLedger = source
|
|
123
|
+
.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = ?")
|
|
124
|
+
.get(LEDGER) !== undefined;
|
|
125
|
+
if (!hasLedger) {
|
|
126
|
+
throw new Error(`File is not a Wheatley agent.sqlite backup: ${file}`);
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
const stageBackup = (source, staging) => {
|
|
130
|
+
const db = new DatabaseSync(source, { readOnly: true });
|
|
131
|
+
try {
|
|
132
|
+
assertRestorable(db, source);
|
|
133
|
+
db.prepare("VACUUM INTO ?").run(staging);
|
|
134
|
+
}
|
|
135
|
+
finally {
|
|
136
|
+
db.close();
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
/**
|
|
140
|
+
* Replaces `<agentDir>/agent.sqlite` with a backup.
|
|
141
|
+
*
|
|
142
|
+
* Ordering: it first copies the backup to a staging file, so that rotation cannot delete the source. It then backs up
|
|
143
|
+
* the current `agent.sqlite` (reason `pre-restore`), removes its `-wal` and `-shm` files, and renames the staging file
|
|
144
|
+
* over it. The rename is atomic, so a failure leaves the current `agent.sqlite` in place.
|
|
145
|
+
*
|
|
146
|
+
* Invariant: no other process may have `agent.sqlite` open. The caller must stop the daemon first.
|
|
147
|
+
*
|
|
148
|
+
* Errors: throws if the Agent folder or the backup does not exist, or if the backup fails `PRAGMA integrity_check` or
|
|
149
|
+
* has no `wheatley_migrations` table.
|
|
150
|
+
*/
|
|
151
|
+
export const restoreAgentBackup = async (options) => {
|
|
152
|
+
if (!(await pathExists(options.agentDir))) {
|
|
153
|
+
throw new Error(`Agent folder not found: ${options.agentDir}`);
|
|
154
|
+
}
|
|
155
|
+
const source = await resolveBackupPath(options.agentDir, options.backup);
|
|
156
|
+
const target = path.join(options.agentDir, AGENT_DATABASE_FILE);
|
|
157
|
+
const staging = `${target}.restore`;
|
|
158
|
+
await rm(staging, { force: true });
|
|
159
|
+
try {
|
|
160
|
+
stageBackup(source, staging);
|
|
161
|
+
await chmod(staging, PRIVATE_FILE_MODE);
|
|
162
|
+
let safetyBackup;
|
|
163
|
+
if (await pathExists(target)) {
|
|
164
|
+
const current = openAgentDatabase(target);
|
|
165
|
+
try {
|
|
166
|
+
const result = await backupAgentDatabase(current, {
|
|
167
|
+
agentDir: options.agentDir,
|
|
168
|
+
clock: options.clock,
|
|
169
|
+
reason: "pre-restore",
|
|
170
|
+
});
|
|
171
|
+
safetyBackup = result.backup;
|
|
172
|
+
}
|
|
173
|
+
finally {
|
|
174
|
+
current.close();
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
await rm(`${target}-wal`, { force: true });
|
|
178
|
+
await rm(`${target}-shm`, { force: true });
|
|
179
|
+
await rename(staging, target);
|
|
180
|
+
return { restoredFrom: source, safetyBackup };
|
|
181
|
+
}
|
|
182
|
+
finally {
|
|
183
|
+
await rm(staging, { force: true });
|
|
184
|
+
}
|
|
185
|
+
};
|
package/dist/ops/cli.js
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import { parseArgs } from "node:util";
|
|
3
|
+
import { systemClock } from "../contracts/module.js";
|
|
4
|
+
import { listBackups, restoreAgentBackup } from "./backup.js";
|
|
5
|
+
import { processRunner } from "./command-runner.js";
|
|
6
|
+
import { agentDirFor, resolveHomeDir } from "./paths.js";
|
|
7
|
+
import { createServiceManager, packageBinScript, resolveServiceSpec, } from "./service.js";
|
|
8
|
+
import { applyUpdate, detectInstallMethod, installCommand, packageDir, planUpdate, readPackageVersion, } from "./update.js";
|
|
9
|
+
/** The ops CLI dependencies of this process. */
|
|
10
|
+
export const hostCliDeps = (isDaemonRunning, drainTimeoutMs) => ({
|
|
11
|
+
clock: systemClock,
|
|
12
|
+
env: process.env,
|
|
13
|
+
execPath: process.execPath,
|
|
14
|
+
homeDir: resolveHomeDir(),
|
|
15
|
+
isDaemonRunning,
|
|
16
|
+
platform: process.platform,
|
|
17
|
+
runner: processRunner,
|
|
18
|
+
uid: process.getuid?.() ?? 0,
|
|
19
|
+
userHome: homedir(),
|
|
20
|
+
drainTimeoutMs,
|
|
21
|
+
});
|
|
22
|
+
const EXIT_OK = 0;
|
|
23
|
+
const EXIT_FAILURE = 1;
|
|
24
|
+
const EXIT_USAGE = 2;
|
|
25
|
+
const SERVICE_USAGE = "Usage: wheatley service <install|start|stop|restart|status>";
|
|
26
|
+
const UPDATE_USAGE = "Usage: wheatley update [--check] [--manager npm|pnpm]";
|
|
27
|
+
const RESTORE_USAGE = "Usage: wheatley restore <agent> [backup]";
|
|
28
|
+
class UsageError extends Error {
|
|
29
|
+
name = "UsageError";
|
|
30
|
+
}
|
|
31
|
+
const isUsageError = (error) => error instanceof UsageError ||
|
|
32
|
+
("code" in error && String(error.code).startsWith("ERR_PARSE_ARGS"));
|
|
33
|
+
/** Turns thrown errors into exit codes, so that a command never rejects. */
|
|
34
|
+
const guarded = (usage, body) => async (args, io) => {
|
|
35
|
+
try {
|
|
36
|
+
return await body(args, io);
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
const failure = error instanceof Error ? error : new Error(String(error));
|
|
40
|
+
io.err(failure.message);
|
|
41
|
+
if (isUsageError(failure)) {
|
|
42
|
+
io.err(usage);
|
|
43
|
+
return EXIT_USAGE;
|
|
44
|
+
}
|
|
45
|
+
return EXIT_FAILURE;
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
const serviceCommand = (deps) => async (args, io) => {
|
|
49
|
+
const { positionals } = parseArgs({
|
|
50
|
+
allowPositionals: true,
|
|
51
|
+
args: [...args],
|
|
52
|
+
});
|
|
53
|
+
const [action, ...extra] = positionals;
|
|
54
|
+
if (action === undefined || extra.length > 0) {
|
|
55
|
+
throw new UsageError("Pass exactly one service action.");
|
|
56
|
+
}
|
|
57
|
+
const manager = createServiceManager(deps);
|
|
58
|
+
switch (action) {
|
|
59
|
+
case "install": {
|
|
60
|
+
const spec = await resolveServiceSpec({
|
|
61
|
+
binScript: packageBinScript(),
|
|
62
|
+
env: deps.env,
|
|
63
|
+
execPath: deps.execPath,
|
|
64
|
+
homeDir: deps.homeDir,
|
|
65
|
+
drainTimeoutMs: deps.drainTimeoutMs,
|
|
66
|
+
});
|
|
67
|
+
const result = await manager.install(spec);
|
|
68
|
+
io.out(`Installed the ${manager.kind} unit: ${result.unitPath}`);
|
|
69
|
+
for (const note of result.notes) {
|
|
70
|
+
io.out(note);
|
|
71
|
+
}
|
|
72
|
+
return EXIT_OK;
|
|
73
|
+
}
|
|
74
|
+
case "start": {
|
|
75
|
+
await manager.start();
|
|
76
|
+
io.out("Started the Wheatley service.");
|
|
77
|
+
return EXIT_OK;
|
|
78
|
+
}
|
|
79
|
+
case "stop": {
|
|
80
|
+
await manager.stop();
|
|
81
|
+
io.out("Stopped the Wheatley service.");
|
|
82
|
+
return EXIT_OK;
|
|
83
|
+
}
|
|
84
|
+
case "restart": {
|
|
85
|
+
await manager.restart();
|
|
86
|
+
io.out("Restarted the Wheatley service.");
|
|
87
|
+
return EXIT_OK;
|
|
88
|
+
}
|
|
89
|
+
case "status": {
|
|
90
|
+
const status = await manager.status();
|
|
91
|
+
io.out(`Manager: ${status.manager}`);
|
|
92
|
+
io.out(`Unit: ${status.unitPath}`);
|
|
93
|
+
io.out(`State: ${status.state}`);
|
|
94
|
+
io.out(`PID: ${status.pid ?? "-"}`);
|
|
95
|
+
return EXIT_OK;
|
|
96
|
+
}
|
|
97
|
+
default: {
|
|
98
|
+
throw new UsageError(`Unknown service action: ${action}`);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
const isPackageManager = (value) => value === "npm" || value === "pnpm";
|
|
103
|
+
const newerMajorNote = (version, manager) => `Wheatley ${version} is a new major version. wheatley update stays within the current major version. Read the release notes, then run: ${installCommand(manager, version).join(" ")}`;
|
|
104
|
+
const updateCommand = (deps) => async (args, io) => {
|
|
105
|
+
const { values } = parseArgs({
|
|
106
|
+
args: [...args],
|
|
107
|
+
options: {
|
|
108
|
+
check: { type: "boolean" },
|
|
109
|
+
manager: { type: "string" },
|
|
110
|
+
},
|
|
111
|
+
});
|
|
112
|
+
if (values.manager !== undefined && !isPackageManager(values.manager)) {
|
|
113
|
+
throw new UsageError(`Unknown package manager: ${values.manager}`);
|
|
114
|
+
}
|
|
115
|
+
const dir = packageDir();
|
|
116
|
+
const method = detectInstallMethod(deps.env, dir);
|
|
117
|
+
const plan = await planUpdate({
|
|
118
|
+
current: await readPackageVersion(dir),
|
|
119
|
+
method,
|
|
120
|
+
runner: deps.runner,
|
|
121
|
+
manager: values.manager,
|
|
122
|
+
});
|
|
123
|
+
if (plan.kind === "docker") {
|
|
124
|
+
io.out("This Wheatley runs in Docker. In the folder of docker-compose.yml, run:");
|
|
125
|
+
for (const command of plan.commands) {
|
|
126
|
+
io.out(` ${command}`);
|
|
127
|
+
}
|
|
128
|
+
return EXIT_OK;
|
|
129
|
+
}
|
|
130
|
+
const manager = values.manager ?? (method === "pnpm" ? "pnpm" : "npm");
|
|
131
|
+
const newerMajor = plan.newerMajor === undefined
|
|
132
|
+
? []
|
|
133
|
+
: [newerMajorNote(plan.newerMajor, manager)];
|
|
134
|
+
if (plan.kind === "up_to_date") {
|
|
135
|
+
io.out(`Wheatley ${plan.current} is the newest release of its major version.`);
|
|
136
|
+
for (const line of newerMajor) {
|
|
137
|
+
io.out(line);
|
|
138
|
+
}
|
|
139
|
+
return EXIT_OK;
|
|
140
|
+
}
|
|
141
|
+
if (values.check === true) {
|
|
142
|
+
io.out(`Update available: ${plan.current} -> ${plan.target}. Run: wheatley update`);
|
|
143
|
+
}
|
|
144
|
+
else {
|
|
145
|
+
io.out(`Updating Wheatley ${plan.current} -> ${plan.target}: ${plan.command.join(" ")}`);
|
|
146
|
+
await applyUpdate(plan, deps.runner);
|
|
147
|
+
io.out(`Updated Wheatley to ${plan.target}. If the daemon runs as a service, run: wheatley service restart`);
|
|
148
|
+
}
|
|
149
|
+
for (const line of newerMajor) {
|
|
150
|
+
io.out(line);
|
|
151
|
+
}
|
|
152
|
+
return EXIT_OK;
|
|
153
|
+
};
|
|
154
|
+
const restoreCommand = (deps) => async (args, io) => {
|
|
155
|
+
const { positionals } = parseArgs({
|
|
156
|
+
allowPositionals: true,
|
|
157
|
+
args: [...args],
|
|
158
|
+
});
|
|
159
|
+
const [agent, backup, ...extra] = positionals;
|
|
160
|
+
if (agent === undefined || extra.length > 0) {
|
|
161
|
+
throw new UsageError("Pass an Agent name and at most one backup.");
|
|
162
|
+
}
|
|
163
|
+
const agentDir = agentDirFor(deps.homeDir, agent);
|
|
164
|
+
if (backup === undefined) {
|
|
165
|
+
const backups = await listBackups(agentDir);
|
|
166
|
+
io.out(backups.length === 0
|
|
167
|
+
? `Agent ${agent} has no backups.`
|
|
168
|
+
: `Backups of Agent ${agent}, newest first:`);
|
|
169
|
+
for (const info of backups) {
|
|
170
|
+
io.out(` ${info.file} (${info.reason}, ${info.createdAt})`);
|
|
171
|
+
}
|
|
172
|
+
return EXIT_OK;
|
|
173
|
+
}
|
|
174
|
+
if (await deps.isDaemonRunning()) {
|
|
175
|
+
io.err("The Wheatley daemon is running and holds agent.sqlite open. Stop it first, for example: wheatley service stop");
|
|
176
|
+
return EXIT_FAILURE;
|
|
177
|
+
}
|
|
178
|
+
const result = await restoreAgentBackup({
|
|
179
|
+
agentDir,
|
|
180
|
+
backup,
|
|
181
|
+
clock: deps.clock,
|
|
182
|
+
});
|
|
183
|
+
io.out(`Restored Agent ${agent} from ${result.restoredFrom}.`);
|
|
184
|
+
if (result.safetyBackup !== undefined) {
|
|
185
|
+
io.out(`The replaced agent.sqlite is in backup ${result.safetyBackup.file}.`);
|
|
186
|
+
}
|
|
187
|
+
return EXIT_OK;
|
|
188
|
+
};
|
|
189
|
+
/** Creates the ops subcommand handlers. */
|
|
190
|
+
export const createOpsCommands = (deps) => ({
|
|
191
|
+
restore: guarded(RESTORE_USAGE, restoreCommand(deps)),
|
|
192
|
+
service: guarded(SERVICE_USAGE, serviceCommand(deps)),
|
|
193
|
+
update: guarded(UPDATE_USAGE, updateCommand(deps)),
|
|
194
|
+
});
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { once } from "node:events";
|
|
3
|
+
/** Runs commands as child processes of this process. */
|
|
4
|
+
export const processRunner = {
|
|
5
|
+
run: async (command, args, options) => {
|
|
6
|
+
const child = spawn(command, args, {
|
|
7
|
+
stdio: options?.inheritStdio === true ? "inherit" : ["ignore", "pipe", "pipe"],
|
|
8
|
+
});
|
|
9
|
+
let stdout = "";
|
|
10
|
+
let stderr = "";
|
|
11
|
+
child.stdout?.setEncoding("utf-8");
|
|
12
|
+
child.stderr?.setEncoding("utf-8");
|
|
13
|
+
child.stdout?.on("data", (chunk) => {
|
|
14
|
+
stdout += chunk;
|
|
15
|
+
});
|
|
16
|
+
child.stderr?.on("data", (chunk) => {
|
|
17
|
+
stderr += chunk;
|
|
18
|
+
});
|
|
19
|
+
// `once` rejects with the `error` event, for example `ENOENT` if the command is not installed.
|
|
20
|
+
await once(child, "close");
|
|
21
|
+
const ended = child.signalCode === null ? "" : `Terminated by ${child.signalCode}\n`;
|
|
22
|
+
return {
|
|
23
|
+
exitCode: child.exitCode ?? 1,
|
|
24
|
+
stderr: `${stderr}${ended}`,
|
|
25
|
+
stdout,
|
|
26
|
+
};
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
/** Formats a failed command for an error message. */
|
|
30
|
+
export const describeFailure = (command, args, result) => {
|
|
31
|
+
const output = result.stderr.trim() || result.stdout.trim();
|
|
32
|
+
const detail = output === "" ? "" : `: ${output}`;
|
|
33
|
+
return `${[command, ...args].join(" ")} exited with code ${result.exitCode}${detail}`;
|
|
34
|
+
};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { cp, readdir, rm, stat } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
/**
|
|
4
|
+
* The folder of the bundled dashboard assets in the compiled package: `dist/dashboard/`, next to `dist/ops/`. The
|
|
5
|
+
* Control Server serves it on `/`.
|
|
6
|
+
*/
|
|
7
|
+
export const dashboardAssetsDir = () => path.resolve(import.meta.dirname, "..", "dashboard");
|
|
8
|
+
/** The Vite build output of `packages/dashboard`, relative to `packages/wheatley`. */
|
|
9
|
+
export const DASHBOARD_BUILD_DIR = path.join("..", "dashboard", "dist");
|
|
10
|
+
const DASHBOARD_ENTRY = "index.html";
|
|
11
|
+
const countFiles = async (dir) => {
|
|
12
|
+
const entries = await readdir(dir, { recursive: true, withFileTypes: true });
|
|
13
|
+
return entries.filter((entry) => entry.isFile()).length;
|
|
14
|
+
};
|
|
15
|
+
const hasEntry = async (dir) => {
|
|
16
|
+
try {
|
|
17
|
+
const info = await stat(path.join(dir, DASHBOARD_ENTRY));
|
|
18
|
+
return info.isFile();
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Replaces `targetDir` with a copy of the dashboard build output in `sourceDir` and returns the number of copied
|
|
26
|
+
* files. `scripts/bundle-dashboard.ts` runs it after `pnpm build`, in the Docker image build and before `npm pack`.
|
|
27
|
+
*
|
|
28
|
+
* Errors: throws if `sourceDir` has no `index.html`, so a package never ships without its dashboard.
|
|
29
|
+
*/
|
|
30
|
+
export const bundleDashboardAssets = async (sourceDir, targetDir) => {
|
|
31
|
+
if (!(await hasEntry(sourceDir))) {
|
|
32
|
+
throw new Error(`No dashboard build in ${sourceDir}. Build it first: pnpm --filter @wheatley-ai/dashboard run build`);
|
|
33
|
+
}
|
|
34
|
+
await rm(targetDir, { force: true, recursive: true });
|
|
35
|
+
await cp(sourceDir, targetDir, { recursive: true });
|
|
36
|
+
return await countFiles(targetDir);
|
|
37
|
+
};
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { MigrationError, planMigrations, runMigrations, } from "../db/migrations.js";
|
|
2
|
+
import { backupAgentDatabase } from "./backup.js";
|
|
3
|
+
const causeMessage = (error) => error.cause instanceof Error
|
|
4
|
+
? `${error.message}: ${error.cause.message}`
|
|
5
|
+
: error.message;
|
|
6
|
+
const degraded = (options, error, code, backup) => {
|
|
7
|
+
const restoreHint = backup === undefined
|
|
8
|
+
? ""
|
|
9
|
+
: `. Restore the pre-migration backup with: wheatley restore ${options.agent} ${backup.file}`;
|
|
10
|
+
return {
|
|
11
|
+
agent: options.agent,
|
|
12
|
+
backup,
|
|
13
|
+
cause: error,
|
|
14
|
+
code,
|
|
15
|
+
error: `${causeMessage(error)}${restoreHint}`,
|
|
16
|
+
outcome: "degraded",
|
|
17
|
+
state: "degraded",
|
|
18
|
+
};
|
|
19
|
+
};
|
|
20
|
+
const runnerFailure = (options, error, backup) => degraded(options, error, error instanceof MigrationError ? error.code : "migration_failed", backup);
|
|
21
|
+
const isEmpty = (db) => db.prepare("SELECT 1 FROM sqlite_schema LIMIT 1").get() === undefined;
|
|
22
|
+
/**
|
|
23
|
+
* Backs up `agent.sqlite` with `VACUUM INTO` and then applies the pending migrations of every module.
|
|
24
|
+
*
|
|
25
|
+
* Ordering: plan, back up, migrate. It takes a backup only if a migration is pending and the database is not empty, so
|
|
26
|
+
* a new Agent gets no backup and an up-to-date Agent gets no extra backup on each start.
|
|
27
|
+
*
|
|
28
|
+
* Errors: it never throws for a migration or backup failure. It returns `outcome: "degraded"` instead, so that one
|
|
29
|
+
* Agent's failure cannot stop the Deployment. It does not migrate if the backup fails. If a migration fails, the
|
|
30
|
+
* migrations before it stay applied, and the report names the backup to restore.
|
|
31
|
+
*/
|
|
32
|
+
export const migrateAgentDatabase = async (db, options) => {
|
|
33
|
+
let pending = [];
|
|
34
|
+
try {
|
|
35
|
+
pending = planMigrations(db, options.namespaces);
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
const failure = error instanceof Error ? error : new Error(String(error));
|
|
39
|
+
return runnerFailure(options, failure, undefined);
|
|
40
|
+
}
|
|
41
|
+
let backup;
|
|
42
|
+
if (pending.length > 0 && !isEmpty(db)) {
|
|
43
|
+
try {
|
|
44
|
+
const result = await backupAgentDatabase(db, {
|
|
45
|
+
agentDir: options.agentDir,
|
|
46
|
+
clock: options.clock,
|
|
47
|
+
reason: "pre-migration",
|
|
48
|
+
});
|
|
49
|
+
({ backup } = result);
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
return degraded(options, new Error("Pre-migration backup failed", { cause: error }), "backup_failed", undefined);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
try {
|
|
56
|
+
const applied = runMigrations(db, options.namespaces, () => new Date(options.clock.now()));
|
|
57
|
+
return { agent: options.agent, applied, backup, outcome: "migrated" };
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
const failure = error instanceof Error ? error : new Error(String(error));
|
|
61
|
+
return runnerFailure(options, failure, backup);
|
|
62
|
+
}
|
|
63
|
+
};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { listBackups } from "./backup.js";
|
|
2
|
+
import { dashboardAssetsDir } from "./dashboard-assets.js";
|
|
3
|
+
import { migrateAgentDatabase } from "./migrate.js";
|
|
4
|
+
import { agentDirFor } from "./paths.js";
|
|
5
|
+
/** The ops module owns no `agent.sqlite` tables. */
|
|
6
|
+
export const opsMigrations = [];
|
|
7
|
+
/** The ops module serves no JSON-RPC methods: `service`, `update`, and `restore` are offline CLI commands. */
|
|
8
|
+
export const opsRpcHandlers = {};
|
|
9
|
+
/** The Deployment-scoped ops module: pre-migration backups and per-Agent degraded reports. */
|
|
10
|
+
export const opsModule = {
|
|
11
|
+
create: (ctx) => {
|
|
12
|
+
const migrateAgent = async (agent, db, namespaces) => {
|
|
13
|
+
const report = await migrateAgentDatabase(db, {
|
|
14
|
+
agent,
|
|
15
|
+
agentDir: agentDirFor(ctx.homeDir, agent),
|
|
16
|
+
clock: ctx.clock,
|
|
17
|
+
namespaces,
|
|
18
|
+
});
|
|
19
|
+
if (report.outcome === "degraded") {
|
|
20
|
+
ctx.log.error("Agent migration failed", {
|
|
21
|
+
agent,
|
|
22
|
+
backup: report.backup?.file ?? null,
|
|
23
|
+
code: report.code,
|
|
24
|
+
error: report.error,
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
else if (report.applied.length > 0) {
|
|
28
|
+
ctx.log.info("Agent migrations applied", {
|
|
29
|
+
agent,
|
|
30
|
+
applied: report.applied.length,
|
|
31
|
+
backup: report.backup?.file ?? null,
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
return report;
|
|
35
|
+
};
|
|
36
|
+
return {
|
|
37
|
+
api: {
|
|
38
|
+
dashboardAssetsDir: dashboardAssetsDir(),
|
|
39
|
+
listBackups: async (agent) => await listBackups(agentDirFor(ctx.homeDir, agent)),
|
|
40
|
+
migrateAgent,
|
|
41
|
+
},
|
|
42
|
+
rpc: opsRpcHandlers,
|
|
43
|
+
};
|
|
44
|
+
},
|
|
45
|
+
name: "ops",
|
|
46
|
+
scope: "deployment",
|
|
47
|
+
};
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { stat } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { AgentNameSchema, decode } from "@wheatley-ai/protocol";
|
|
5
|
+
/** The Agent storage file that Wheatley migrations change. */
|
|
6
|
+
export const AGENT_DATABASE_FILE = "agent.sqlite";
|
|
7
|
+
/** The folder inside an Agent folder that holds the `VACUUM INTO` backups of `agent.sqlite`. */
|
|
8
|
+
export const BACKUPS_DIR = "backups";
|
|
9
|
+
/** The environment variable that overrides the Wheatley home folder, for example `/data` in Docker. */
|
|
10
|
+
export const HOME_ENV = "WHEATLEY_HOME";
|
|
11
|
+
/** The environment variable that the Docker image sets to `1`. */
|
|
12
|
+
export const DOCKER_ENV = "WHEATLEY_DOCKER";
|
|
13
|
+
/** Returns the value of an environment variable, or `undefined` if it is unset or empty. */
|
|
14
|
+
export const envValue = (env, name) => {
|
|
15
|
+
const value = env[name];
|
|
16
|
+
return value === undefined || value === "" ? undefined : value;
|
|
17
|
+
};
|
|
18
|
+
/** Returns `true` inside the Wheatley Docker image. */
|
|
19
|
+
export const isDocker = (env) => env[DOCKER_ENV] === "1";
|
|
20
|
+
/**
|
|
21
|
+
* Returns the Wheatley home folder: `$WHEATLEY_HOME` if set, else `~/.wheatley`. The CLI and the Deployment context
|
|
22
|
+
* (`DeploymentModuleContext.homeDir`) must both use this value, so that they see the same Agent folders.
|
|
23
|
+
*/
|
|
24
|
+
export const resolveHomeDir = (env = process.env, userHome = homedir()) => {
|
|
25
|
+
const override = envValue(env, HOME_ENV);
|
|
26
|
+
return override === undefined
|
|
27
|
+
? path.join(userHome, ".wheatley")
|
|
28
|
+
: path.resolve(override);
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Returns `<home>/agents/<agent>`.
|
|
32
|
+
*
|
|
33
|
+
* Errors: throws if `agent` is not a valid Agent name, so a name cannot escape the `agents` folder.
|
|
34
|
+
*/
|
|
35
|
+
export const agentDirFor = (homeDir, agent) => {
|
|
36
|
+
if (!decode(AgentNameSchema, agent).ok) {
|
|
37
|
+
throw new Error(`Invalid Agent name: ${agent}`);
|
|
38
|
+
}
|
|
39
|
+
return path.join(homeDir, "agents", agent);
|
|
40
|
+
};
|
|
41
|
+
/** Returns `true` for a file system error with code `ENOENT`. */
|
|
42
|
+
export const isMissing = (error) => "code" in error && error.code === "ENOENT";
|
|
43
|
+
/** Resolves `true` if `target` exists. Errors: rejects for an error other than `ENOENT`, for example `EACCES`. */
|
|
44
|
+
export const pathExists = async (target) => {
|
|
45
|
+
try {
|
|
46
|
+
await stat(target);
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
if (error instanceof Error && isMissing(error)) {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
throw error;
|
|
54
|
+
}
|
|
55
|
+
};
|