@operad-io/bot 0.1.1 → 0.3.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/README.md +1 -1
- package/bot.schema.json +40 -2
- package/package.json +6 -4
- package/src/bot.ts +588 -70
- package/src/chat-watch.ts +101 -0
- package/src/create.ts +230 -0
- package/src/follow-up.ts +313 -0
- package/src/index.ts +544 -29
- package/src/login.ts +226 -0
- package/src/mcp-proposals.ts +2 -2
- package/src/proposals.ts +392 -79
- package/src/schedule.ts +1184 -0
- package/src/setup-dev.ts +282 -0
- package/src/setup-git.ts +323 -0
- package/src/setup.ts +113 -0
- package/src/tidy.ts +1021 -0
package/src/bot.ts
CHANGED
|
@@ -5,11 +5,15 @@
|
|
|
5
5
|
* a reply reads the file again, so an edit applies at once.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
import { existsSync, readdirSync, readFileSync,
|
|
8
|
+
import { closeSync, existsSync, lstatSync, mkdirSync, openSync, readSync, readdirSync, readFileSync, renameSync, rmSync } from "node:fs";
|
|
9
9
|
import { homedir } from "node:os";
|
|
10
|
-
import { isAbsolute, join, relative, resolve } from "node:path";
|
|
10
|
+
import { basename, isAbsolute, join, relative, resolve } from "node:path";
|
|
11
11
|
import { MCP_REPORT_DIR } from "./mcp-constants.ts";
|
|
12
|
-
import {
|
|
12
|
+
import { added, hasSkill, isDirectory, skillsInside } from "@operad-io/chat";
|
|
13
|
+
import { defaultAccess as builtInAccess } from "@operad-io/access-match";
|
|
14
|
+
import { readKeptWorkers, withLockFile, writeFileAtomicSync } from "@operad-io/engine/platform";
|
|
15
|
+
import { MEMORY_SKILL_DIR, ensureMemoryLayout, memoryEnabled, wikiDirectoryOfHome } from "@operad-io/memory";
|
|
16
|
+
import { configPath, isMissingFile, isRecord, prepareSettings, type ActionArgsSchema, type JsonValue, type ObjectStore } from "@operad-io/engine";
|
|
13
17
|
|
|
14
18
|
/** The object type of a bot. */
|
|
15
19
|
export const BOT_TYPE = "bot";
|
|
@@ -22,12 +26,22 @@ export const BOT_DIR = "bot";
|
|
|
22
26
|
|
|
23
27
|
const NAME = /^[a-z0-9][a-z0-9_-]*$/;
|
|
24
28
|
|
|
29
|
+
/** Refuses a name that cannot be a bot's directory under the bot home. */
|
|
30
|
+
export function validateBotName(name: string): void {
|
|
31
|
+
if (!NAME.test(name)) {
|
|
32
|
+
throw new BotError(
|
|
33
|
+
`bot "${name}": a name is lowercase letters, digits, "-" and "_", and starts with a letter or digit`,
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
25
38
|
/** The JSON Schema of the `bot` section (also shipped as `bot.schema.json`). */
|
|
26
39
|
export const BOT_SETTINGS: ActionArgsSchema = {
|
|
27
40
|
type: "object",
|
|
28
41
|
properties: {
|
|
29
42
|
bots: {
|
|
30
43
|
type: "object",
|
|
44
|
+
title: "Bots",
|
|
31
45
|
editable: true,
|
|
32
46
|
description:
|
|
33
47
|
"The bots, by name. `default` exists even when it is not written here.",
|
|
@@ -39,18 +53,25 @@ export const BOT_SETTINGS: ActionArgsSchema = {
|
|
|
39
53
|
type: "string",
|
|
40
54
|
minLength: 1,
|
|
41
55
|
description:
|
|
42
|
-
"The working directory. Without it: ~/.operad/bot
|
|
56
|
+
"The working directory. Without it: ~/.operad/bot/<name>, so the default bot is in ~/.operad/bot/default. It must be inside ~/.operad/bot or outside the operad home.",
|
|
43
57
|
},
|
|
44
58
|
harness: {
|
|
45
59
|
type: "string",
|
|
46
60
|
minLength: 1,
|
|
47
61
|
description: "The agent a new chat uses when it names none.",
|
|
48
62
|
},
|
|
63
|
+
useOwnSettings: {
|
|
64
|
+
type: "boolean",
|
|
65
|
+
title: "Use my own agent settings",
|
|
66
|
+
default: false,
|
|
67
|
+
description:
|
|
68
|
+
"The bot's agent then reads your own configuration of that agent. claude: your settings, instruction files, memory, skills, commands, subagents, plugins and MCP servers; pi: your settings, context files, skills, prompt templates and extensions, whose own code at load is not stopped by the profile; codex and radian always read their own configuration, so this switch does not change them. The bot's access profile still refuses what it refuses. Off by default.",
|
|
69
|
+
},
|
|
49
70
|
skills: {
|
|
50
71
|
type: "array",
|
|
51
72
|
items: { type: "string", minLength: 1 },
|
|
52
73
|
description:
|
|
53
|
-
"
|
|
74
|
+
"Skills given to the agent at every reply; the agent may read them but not change them. A path may be a directory with a SKILL.md, a directory whose direct subdirectories each have one (such as ~/.agents/skills), or a .agents directory (such as ~/.agents), whose skills directory is read the same way. Every skill directly inside such a directory is loaded, including one added later. A relative path is under the working directory.",
|
|
54
75
|
},
|
|
55
76
|
model: {
|
|
56
77
|
type: "string",
|
|
@@ -68,6 +89,42 @@ export const BOT_SETTINGS: ActionArgsSchema = {
|
|
|
68
89
|
description:
|
|
69
90
|
"How a chat of this bot labels the model's messages in its transcript. Without it the chat plugin's speaker is used.",
|
|
70
91
|
},
|
|
92
|
+
accessLevel: {
|
|
93
|
+
type: "string",
|
|
94
|
+
title: "Access level",
|
|
95
|
+
enum: ["plan", "ask", "edits", "full"],
|
|
96
|
+
default: "ask",
|
|
97
|
+
description:
|
|
98
|
+
"The level a chat on this bot starts at, when opened from the desktop, the CLI, the MCP server or Telegram; a chat a scheduled prompt opens starts at full. Unlike `access`, which can only tighten the profile, this can loosen it: `full` asks nothing but the deny rules. A chat that chose a level with /access keeps it; a chat that did not follows this setting. See docs/user/access.md.",
|
|
99
|
+
},
|
|
100
|
+
writeWiki: {
|
|
101
|
+
type: "boolean",
|
|
102
|
+
title: "Write the wiki",
|
|
103
|
+
description:
|
|
104
|
+
"Whether this bot may write the shared wiki. Without it the default bot writes it and every other bot only reads it. Read access is always there; a bot that may not write it has the wiki refused for writing.",
|
|
105
|
+
},
|
|
106
|
+
tidyTime: {
|
|
107
|
+
type: "string",
|
|
108
|
+
title: "Tidy time",
|
|
109
|
+
default: "03:30",
|
|
110
|
+
pattern: "^(?:[01]\\d|2[0-3]):[0-5]\\d$",
|
|
111
|
+
description:
|
|
112
|
+
"When the nightly memory check runs, as HH:MM in this machine's local time zone, between 03:00 and 03:59 by default. A missed night is caught up once after the machine wakes.",
|
|
113
|
+
},
|
|
114
|
+
runWithoutAsking: {
|
|
115
|
+
type: "boolean",
|
|
116
|
+
title: "Run without asking",
|
|
117
|
+
description:
|
|
118
|
+
"不询问直接运行. When on, the nightly memory tidy runs without a pending card; off, it waits for Run or Skip. Off by default.",
|
|
119
|
+
default: false,
|
|
120
|
+
},
|
|
121
|
+
backgroundModel: {
|
|
122
|
+
type: "string",
|
|
123
|
+
title: "Background model",
|
|
124
|
+
minLength: 1,
|
|
125
|
+
description:
|
|
126
|
+
"The model a memory tidy uses. Without it the bot's agent declares a cheap model for background work (claude: haiku); a bot with neither uses its own model, else the agent's default.",
|
|
127
|
+
},
|
|
71
128
|
mcpServers: {
|
|
72
129
|
type: "object",
|
|
73
130
|
description:
|
|
@@ -147,10 +204,16 @@ export interface BotSettings {
|
|
|
147
204
|
readonly mcpAllow?: readonly string[] | undefined;
|
|
148
205
|
readonly cwd?: string;
|
|
149
206
|
readonly harness?: string;
|
|
207
|
+
readonly useOwnSettings?: boolean | undefined;
|
|
150
208
|
readonly model?: string;
|
|
151
209
|
readonly effort?: string;
|
|
152
210
|
readonly skills?: readonly string[];
|
|
153
211
|
readonly speaker?: string;
|
|
212
|
+
readonly writeWiki?: boolean | undefined;
|
|
213
|
+
readonly tidyTime?: string | undefined;
|
|
214
|
+
readonly runWithoutAsking?: boolean | undefined;
|
|
215
|
+
readonly accessLevel?: "plan" | "ask" | "edits" | "full" | undefined;
|
|
216
|
+
readonly backgroundModel?: string | undefined;
|
|
154
217
|
readonly access?: Readonly<Record<string, JsonValue>>;
|
|
155
218
|
}
|
|
156
219
|
|
|
@@ -159,11 +222,16 @@ export interface ResolvedBot {
|
|
|
159
222
|
readonly name: string;
|
|
160
223
|
readonly cwd: string;
|
|
161
224
|
readonly harness: string | null;
|
|
225
|
+
readonly useOwnSettings: boolean;
|
|
162
226
|
readonly model: string | null;
|
|
163
227
|
readonly effort: string | null;
|
|
164
228
|
/** Absolute directories, each with a SKILL.md. */
|
|
165
229
|
readonly skills: readonly string[];
|
|
166
230
|
readonly speaker: string | null;
|
|
231
|
+
/** Whether this bot may write the shared wiki. */
|
|
232
|
+
readonly writeWiki: boolean;
|
|
233
|
+
/** The level a new chat starts at; `ask` unless the bot sets it. */
|
|
234
|
+
readonly accessLevel: "plan" | "ask" | "edits" | "full";
|
|
167
235
|
readonly access: Readonly<Record<string, JsonValue>>;
|
|
168
236
|
/** The local MCP servers the bot lists, by name. */
|
|
169
237
|
readonly mcpServers: Readonly<Record<string, McpServerSettings>>;
|
|
@@ -208,11 +276,7 @@ export function readBots(
|
|
|
208
276
|
const bots = isRecord(settings.bots) ? settings.bots : {};
|
|
209
277
|
const found: Record<string, BotSettings> = {};
|
|
210
278
|
for (const [name, value] of Object.entries(bots)) {
|
|
211
|
-
|
|
212
|
-
throw new BotError(
|
|
213
|
-
`bot "${name}": a name is lowercase letters, digits, "-" and "_", and starts with a letter or digit`,
|
|
214
|
-
);
|
|
215
|
-
}
|
|
279
|
+
validateBotName(name);
|
|
216
280
|
found[name] = value as BotSettings;
|
|
217
281
|
}
|
|
218
282
|
if (found[DEFAULT_BOT] === undefined) found[DEFAULT_BOT] = {};
|
|
@@ -225,63 +289,442 @@ function expand(path: string, base: string): string {
|
|
|
225
289
|
return isAbsolute(path) ? resolve(path) : resolve(base, path);
|
|
226
290
|
}
|
|
227
291
|
|
|
292
|
+
/** A path as the bot reads it: `~`, an absolute path, or one under `base`. */
|
|
293
|
+
export function expandPath(path: string, base: string): string {
|
|
294
|
+
return expand(path, base);
|
|
295
|
+
}
|
|
296
|
+
|
|
228
297
|
function within(path: string, directory: string): boolean {
|
|
229
298
|
const rel = relative(directory, path);
|
|
230
299
|
return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
|
|
231
300
|
}
|
|
232
301
|
|
|
302
|
+
function samePath(left: string, right: string): boolean {
|
|
303
|
+
return resolve(left) === resolve(right);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function exists(path: string): boolean {
|
|
307
|
+
try {
|
|
308
|
+
lstatSync(path);
|
|
309
|
+
return true;
|
|
310
|
+
} catch {
|
|
311
|
+
return false;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Moves one entry into a directory that may already hold the same name. Two
|
|
317
|
+
* directories are merged child by child, so a move killed halfway leaves every
|
|
318
|
+
* entry on one side or the other and the next run finishes it. A single file
|
|
319
|
+
* or link is renamed, which is atomic.
|
|
320
|
+
*/
|
|
321
|
+
function mergeInto(source: string, destination: string): void {
|
|
322
|
+
if (!exists(destination)) {
|
|
323
|
+
mkdirSync(resolve(destination, ".."), { recursive: true });
|
|
324
|
+
renameSync(source, destination);
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
const from = lstatSync(source);
|
|
328
|
+
const to = lstatSync(destination);
|
|
329
|
+
if (from.isDirectory() && to.isDirectory()) {
|
|
330
|
+
for (const name of readdirSync(source)) mergeInto(join(source, name), join(destination, name));
|
|
331
|
+
rmSync(source, { recursive: true, force: true });
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
// The new home's copy wins; the old home's copy is dropped, never written over it.
|
|
335
|
+
rmSync(source, { recursive: true, force: true });
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** What moving the default bot's old home needs from a caller. */
|
|
339
|
+
export interface BotDirectoryMigration {
|
|
340
|
+
/** Bot names whose default directory is under the old home; kept in place. */
|
|
341
|
+
readonly botNames?: readonly string[] | undefined;
|
|
342
|
+
/** Every bot's working directory, including a named `cwd` and a removed bot's. */
|
|
343
|
+
readonly botPaths?: readonly string[] | undefined;
|
|
344
|
+
/** Where claude keeps its per-directory sessions; the environment's own when absent. */
|
|
345
|
+
readonly claudeProjects?: string | undefined;
|
|
346
|
+
/** Where radian keeps session journals; the environment's own when absent. */
|
|
347
|
+
readonly radianSessionDirs?: readonly string[] | undefined;
|
|
348
|
+
/** The grant files recording a working directory; `$OPERAD_HOME/access-user.json` when absent. */
|
|
349
|
+
readonly grantFiles?: readonly string[] | undefined;
|
|
350
|
+
/** Called after each top-level entry moved; a test stops a child process here. */
|
|
351
|
+
readonly afterMove?: ((name: string) => void) | undefined;
|
|
352
|
+
/** Called after a grant file's temporary copy is written and before it replaces the file. */
|
|
353
|
+
readonly beforeGrantRename?: ((temporary: string, file: string) => void) | undefined;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** The marker that says the old default home has been handled. */
|
|
357
|
+
const MIGRATION_MARKER = ".moved-to-default";
|
|
358
|
+
|
|
359
|
+
/** What operad itself creates in the old default bot home; everything else stays there. */
|
|
360
|
+
const OWNED_ENTRIES: ReadonlySet<string> = new Set(["skills", "memory"]);
|
|
361
|
+
|
|
362
|
+
/** A marker with this content means only claude's project directory waits for a retry. */
|
|
363
|
+
const CLAUDE_PENDING = "claude";
|
|
364
|
+
|
|
365
|
+
/** The marker that says the grants which named the old home were rewritten. */
|
|
366
|
+
const GRANT_MARKER = ".grants-moved-to-default";
|
|
367
|
+
|
|
368
|
+
function markerState(marker: string): "done" | "claude" | undefined {
|
|
369
|
+
if (!existsSync(marker)) return undefined;
|
|
370
|
+
try {
|
|
371
|
+
return readFileSync(marker, "utf8").trim() === CLAUDE_PENDING ? CLAUDE_PENDING : "done";
|
|
372
|
+
} catch {
|
|
373
|
+
return "done";
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function writeMarker(marker: string, pending: boolean): void {
|
|
378
|
+
writeFileAtomicSync(marker, pending ? CLAUDE_PENDING : "");
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function writeDoneMarker(marker: string): void {
|
|
382
|
+
writeFileAtomicSync(marker, "");
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function escaped(value: string): string {
|
|
386
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
387
|
+
}
|
|
388
|
+
|
|
233
389
|
/**
|
|
234
|
-
*
|
|
235
|
-
*
|
|
236
|
-
*
|
|
237
|
-
*
|
|
238
|
-
* other than `~/.operad` is covered too.
|
|
390
|
+
* Rewrites the `cwd` of every grant made in the old default home to the new
|
|
391
|
+
* one. The file's other bytes stay as they were; a missing file, a file with
|
|
392
|
+
* no old cwd and a repeated run write nothing. The replacement is a temporary
|
|
393
|
+
* file renamed over the original, so a crash leaves the old or the new whole.
|
|
239
394
|
*/
|
|
240
|
-
|
|
395
|
+
async function migrateGrantCwds(
|
|
396
|
+
oldCwd: string,
|
|
397
|
+
newCwd: string,
|
|
398
|
+
files: readonly string[],
|
|
399
|
+
beforeRename?: ((temporary: string, file: string) => void) | undefined,
|
|
400
|
+
): Promise<boolean> {
|
|
401
|
+
const quotedOld = JSON.stringify(oldCwd);
|
|
402
|
+
const quotedNew = JSON.stringify(newCwd);
|
|
403
|
+
const pattern = new RegExp(`("cwd"\\s*:\\s*)${escaped(quotedOld)}`, "g");
|
|
404
|
+
for (const file of new Set(files)) {
|
|
405
|
+
try {
|
|
406
|
+
// The user layer's normal writer holds this same lock, so a grant added
|
|
407
|
+
// while the home moves is never dropped by the rewrite.
|
|
408
|
+
await withLockFile(
|
|
409
|
+
`${file}.lock`,
|
|
410
|
+
() => {
|
|
411
|
+
let text: string;
|
|
412
|
+
try {
|
|
413
|
+
text = readFileSync(file, "utf8");
|
|
414
|
+
} catch (error) {
|
|
415
|
+
if (isMissingFile(error)) return;
|
|
416
|
+
throw error;
|
|
417
|
+
}
|
|
418
|
+
try {
|
|
419
|
+
JSON.parse(text);
|
|
420
|
+
} catch {
|
|
421
|
+
// A file that is not JSON cannot name the old cwd; leave it as it is
|
|
422
|
+
// and count the file as handled, so every read does not parse it again.
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
const next = text.replace(pattern, (_match: string, prefix: string) => `${prefix}${quotedNew}`);
|
|
426
|
+
if (next === text) return;
|
|
427
|
+
writeFileAtomicSync(file, next, {
|
|
428
|
+
beforeRename: (temporary) => beforeRename?.(temporary, file),
|
|
429
|
+
});
|
|
430
|
+
},
|
|
431
|
+
{ label: "access user layer" },
|
|
432
|
+
);
|
|
433
|
+
} catch {
|
|
434
|
+
return false;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
return true;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** Whether a claude worker may still be writing under the old working directory. */
|
|
441
|
+
function claudeWorkerRunning(home: string): boolean {
|
|
442
|
+
try {
|
|
443
|
+
return readKeptWorkers(home, "claude").length > 0;
|
|
444
|
+
} catch {
|
|
445
|
+
return true;
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** Reads only the first line of a file, without loading the rest. */
|
|
450
|
+
function firstLine(file: string): string | undefined {
|
|
451
|
+
let descriptor: number | undefined;
|
|
452
|
+
try {
|
|
453
|
+
descriptor = openSync(file, "r");
|
|
454
|
+
const buffer = Buffer.alloc(4096);
|
|
455
|
+
const read = readSync(descriptor, buffer, 0, buffer.length, 0);
|
|
456
|
+
const text = buffer.subarray(0, read).toString("utf8");
|
|
457
|
+
const newline = text.indexOf("\n");
|
|
458
|
+
return newline < 0 ? text : text.slice(0, newline);
|
|
459
|
+
} catch {
|
|
460
|
+
return undefined;
|
|
461
|
+
} finally {
|
|
462
|
+
if (descriptor !== undefined) closeSync(descriptor);
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/** The working directories of the bots the settings name now. */
|
|
467
|
+
function configuredBotPaths(home: string): string[] {
|
|
468
|
+
const found: string[] = [];
|
|
469
|
+
try {
|
|
470
|
+
for (const [name, settings] of Object.entries(readBots(home))) {
|
|
471
|
+
if (name === DEFAULT_BOT) continue;
|
|
472
|
+
try {
|
|
473
|
+
found.push(workingDirectory(home, name, settings));
|
|
474
|
+
} catch {
|
|
475
|
+
// A bot whose directory is invalid has no path to protect here.
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
} catch {
|
|
479
|
+
// A settings file that cannot be read contributes no paths.
|
|
480
|
+
}
|
|
481
|
+
return found;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/** The top-level old-home entries that belong to some bot other than the default. */
|
|
485
|
+
function protectedEntries(
|
|
486
|
+
root: string,
|
|
487
|
+
target: string,
|
|
488
|
+
options: BotDirectoryMigration,
|
|
489
|
+
): Set<string> {
|
|
490
|
+
const found = new Set<string>();
|
|
491
|
+
const add = (path: string): void => {
|
|
492
|
+
if (!within(path, root) || samePath(path, target)) return;
|
|
493
|
+
const rel = relative(root, path);
|
|
494
|
+
if (rel === "") {
|
|
495
|
+
// A bot uses the whole old home, so no entry there is the default bot's.
|
|
496
|
+
for (const name of readdirSync(root)) found.add(name);
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
const [first] = rel.split(/[\\/]/);
|
|
500
|
+
if (first !== undefined && first.length > 0) found.add(first);
|
|
501
|
+
};
|
|
502
|
+
for (const name of options.botNames ?? []) if (name !== DEFAULT_BOT) add(join(root, name));
|
|
503
|
+
for (const path of options.botPaths ?? []) add(path);
|
|
504
|
+
return found;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/** The directory claude names for a working directory. */
|
|
508
|
+
export function claudeProjectDirectory(cwd: string): string {
|
|
509
|
+
return cwd.replace(/[^A-Za-z0-9]/g, "-");
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/** Where claude keeps its project directories. */
|
|
513
|
+
export function claudeProjectsDirectory(env: NodeJS.ProcessEnv = process.env): string {
|
|
514
|
+
const configured = env["CLAUDE_CONFIG_DIR"];
|
|
515
|
+
const root = configured !== undefined && configured.length > 0 ? configured : join(homedir(), ".claude");
|
|
516
|
+
return join(root, "projects");
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/**
|
|
520
|
+
* Claude finds a session under the project directory named for the working
|
|
521
|
+
* directory. Moving the default bot's working directory moves that project
|
|
522
|
+
* directory too, so a chat started before the move still resumes.
|
|
523
|
+
*/
|
|
524
|
+
export function migrateClaudeSessions(
|
|
525
|
+
oldCwd: string,
|
|
526
|
+
newCwd: string,
|
|
527
|
+
projects: string = claudeProjectsDirectory(),
|
|
528
|
+
): void {
|
|
529
|
+
const from = join(projects, claudeProjectDirectory(oldCwd));
|
|
530
|
+
const to = join(projects, claudeProjectDirectory(newCwd));
|
|
531
|
+
if (samePath(from, to) || !existsSync(from)) return;
|
|
532
|
+
mergeInto(from, to);
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/** The directories radian may keep its session journals in. */
|
|
536
|
+
export function radianSessionDirectories(env: NodeJS.ProcessEnv = process.env): string[] {
|
|
537
|
+
const found: string[] = [];
|
|
538
|
+
const explicit = env["RADIAN_SESSION_DIR"];
|
|
539
|
+
if (explicit !== undefined && explicit.length > 0) found.push(explicit);
|
|
540
|
+
const configured = env["RADIAN_HOME"];
|
|
541
|
+
const home = configured !== undefined && configured.length > 0 ? configured : join(homedir(), ".radian");
|
|
542
|
+
found.push(join(home, "sessions"));
|
|
543
|
+
found.push(join(homedir(), ".local", "share", "radian", "sessions"));
|
|
544
|
+
return [...new Set(found)];
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
/**
|
|
548
|
+
* Radian binds a session to the workspace in its `SessionCreated` event.
|
|
549
|
+
* Moving the default bot's old workspace rewrites that one line in every
|
|
550
|
+
* journal it belongs to, leaving the rest of the session as it was. Each
|
|
551
|
+
* rewrite uses a temporary file and a rename, so a crash leaves a whole file.
|
|
552
|
+
*/
|
|
553
|
+
export function migrateRadianSessions(
|
|
554
|
+
oldCwd: string,
|
|
555
|
+
newCwd: string,
|
|
556
|
+
directories: readonly string[] = radianSessionDirectories(),
|
|
557
|
+
): void {
|
|
558
|
+
for (const directory of new Set(directories)) {
|
|
559
|
+
if (!isDirectory(directory)) continue;
|
|
560
|
+
for (const name of readdirSync(directory)) {
|
|
561
|
+
if (!name.endsWith(".jsonl")) continue;
|
|
562
|
+
const file = join(directory, name);
|
|
563
|
+
const head = firstLine(file);
|
|
564
|
+
if (head === undefined) continue;
|
|
565
|
+
let first: unknown;
|
|
566
|
+
try {
|
|
567
|
+
first = JSON.parse(head);
|
|
568
|
+
} catch {
|
|
569
|
+
continue;
|
|
570
|
+
}
|
|
571
|
+
if (!isRecord(first) || first.event !== "SessionCreated" || !isRecord(first.data)) continue;
|
|
572
|
+
if (first.data.workspace !== oldCwd) continue;
|
|
573
|
+
// Only a journal that names the old workspace is read in full, and rewritten once.
|
|
574
|
+
const text = readFileSync(file, "utf8");
|
|
575
|
+
const newline = text.indexOf("\n");
|
|
576
|
+
const next = JSON.stringify({ ...first, data: { ...first.data, workspace: newCwd } });
|
|
577
|
+
writeFileAtomicSync(file, next + (newline < 0 ? "" : text.slice(newline)));
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/**
|
|
583
|
+
* Moves only what operad itself made in the old bot home into `default/`: the
|
|
584
|
+
* bot's `skills/` and `memory/`. Every other entry stays where it is, as does
|
|
585
|
+
* another bot's directory and a custom `cwd` for the default bot. The move can
|
|
586
|
+
* be repeated: each entry is renamed once, and directories on both sides are
|
|
587
|
+
* merged. Claude's project directory waits while a claude worker is alive, and
|
|
588
|
+
* the marker says so, so the next read retries it without rescanning journals.
|
|
589
|
+
*/
|
|
590
|
+
export async function migrateDefaultBotDir(
|
|
591
|
+
home: string,
|
|
592
|
+
options: BotDirectoryMigration = {},
|
|
593
|
+
): Promise<readonly string[]> {
|
|
594
|
+
const root = botDir(home);
|
|
595
|
+
const target = join(root, DEFAULT_BOT);
|
|
596
|
+
const marker = join(target, MIGRATION_MARKER);
|
|
597
|
+
const state = markerState(marker);
|
|
598
|
+
const rootExists = existsSync(root);
|
|
599
|
+
const grantMarker = join(target, GRANT_MARKER);
|
|
600
|
+
if (!existsSync(grantMarker)) {
|
|
601
|
+
const grants = options.grantFiles ?? [join(home, "access-user.json")];
|
|
602
|
+
if (await migrateGrantCwds(root, target, grants, options.beforeGrantRename)) writeDoneMarker(grantMarker);
|
|
603
|
+
}
|
|
604
|
+
if (state === "done") return [];
|
|
605
|
+
const moved: string[] = [];
|
|
606
|
+
if (rootExists && state === undefined) {
|
|
607
|
+
const protectedNames = protectedEntries(root, target, {
|
|
608
|
+
...options,
|
|
609
|
+
botPaths: options.botPaths ?? configuredBotPaths(home),
|
|
610
|
+
});
|
|
611
|
+
for (const entry of readdirSync(root, { withFileTypes: true })) {
|
|
612
|
+
if (entry.name === DEFAULT_BOT || protectedNames.has(entry.name)) continue;
|
|
613
|
+
if (!OWNED_ENTRIES.has(entry.name)) continue;
|
|
614
|
+
mergeInto(join(root, entry.name), join(target, entry.name));
|
|
615
|
+
moved.push(entry.name);
|
|
616
|
+
options.afterMove?.(entry.name);
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
// A home without the old directory has no journals to read. Mark it done so
|
|
620
|
+
// it never scans them later when another bot brings the directory back.
|
|
621
|
+
if (state === undefined && rootExists) migrateRadianSessions(root, target, options.radianSessionDirs);
|
|
622
|
+
const projects = options.claudeProjects ?? claudeProjectsDirectory();
|
|
623
|
+
const oldProject = join(projects, claudeProjectDirectory(root));
|
|
624
|
+
const claudePending = existsSync(oldProject) && claudeWorkerRunning(home);
|
|
625
|
+
if (!claudePending) migrateClaudeSessions(root, target, projects);
|
|
626
|
+
// Mark only after every entry and session moved, so a crash halfway runs again.
|
|
627
|
+
if (rootExists || state === CLAUDE_PENDING || state === undefined) writeMarker(marker, claudePending);
|
|
628
|
+
return moved;
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/** Whether the old default bot home has already been handled, including its grants and claude's retry. */
|
|
632
|
+
export function defaultBotHomeMigrated(home: string): boolean {
|
|
633
|
+
const target = join(botDir(home), DEFAULT_BOT);
|
|
634
|
+
return markerState(join(target, MIGRATION_MARKER)) === "done" && existsSync(join(target, GRANT_MARKER));
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/** The memory directory of a bot. */
|
|
638
|
+
export function memoryDir(cwd: string): string {
|
|
639
|
+
return join(cwd, "memory");
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
/**
|
|
643
|
+
* Makes a bot's memory directory, returning it. With the home's memory plugin
|
|
644
|
+
* enabled, its three layers are made too; nothing that is there is overwritten.
|
|
645
|
+
*/
|
|
646
|
+
export function ensureBotMemory(cwd: string, home?: string): string {
|
|
647
|
+
const memory = memoryDir(cwd);
|
|
648
|
+
mkdirSync(memory, { recursive: true });
|
|
649
|
+
if (home !== undefined && memoryEnabled(home)) ensureMemoryLayout(memory);
|
|
650
|
+
return memory;
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
/** The directories no bot may read or write: every other bot's. */
|
|
654
|
+
function siblingDirectories(home: string, ownCwd: string, defaultBot: boolean): string[] {
|
|
655
|
+
const root = botDir(home);
|
|
656
|
+
const ownIsRoot = samePath(ownCwd, root);
|
|
657
|
+
const found = new Set<string>();
|
|
658
|
+
const sibling = (path: string): boolean => {
|
|
659
|
+
if (samePath(path, ownCwd)) return false;
|
|
660
|
+
if (!ownIsRoot && (within(ownCwd, path) || within(path, ownCwd))) return false;
|
|
661
|
+
if (ownIsRoot && (samePath(path, join(root, "memory")) || samePath(path, join(root, "skills")))) return false;
|
|
662
|
+
return true;
|
|
663
|
+
};
|
|
664
|
+
// The default bot kept access to the old bot home, so only another bot's
|
|
665
|
+
// directory is denied there. Another bot still denies every entry it does
|
|
666
|
+
// not own, so the default bot's old files are not exposed to it. A bot
|
|
667
|
+
// directory has a `memory/`; a person's other old-home directory does not.
|
|
668
|
+
if (existsSync(root)) {
|
|
669
|
+
for (const entry of readdirSync(root, { withFileTypes: true })) {
|
|
670
|
+
if (!entry.isDirectory()) continue;
|
|
671
|
+
const path = join(root, entry.name);
|
|
672
|
+
if (defaultBot && !existsSync(join(path, "memory"))) continue;
|
|
673
|
+
if (sibling(path)) found.add(path);
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
for (const [name, settings] of Object.entries(readBots(home))) {
|
|
677
|
+
try {
|
|
678
|
+
const path = workingDirectory(home, name, settings);
|
|
679
|
+
if (sibling(path)) found.add(path);
|
|
680
|
+
} catch {
|
|
681
|
+
// A bot whose own directory cannot be read contributes no path here.
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
return [...found].sort();
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
/**
|
|
688
|
+
* The default access profile of a bot: the built-in default, with the operad
|
|
689
|
+
* home and the operad command added. Everything in the operad home except the
|
|
690
|
+
* bot's own directory is denied: the names that are there now, and the ones
|
|
691
|
+
* operad keeps there. Paths are absolute, so a home other than `~/.operad` is
|
|
692
|
+
* covered too. The agent reaches operad through its tools, never a shell.
|
|
693
|
+
*/
|
|
694
|
+
export function defaultAccess(home: string, wikiWrite = false): Record<string, JsonValue> {
|
|
241
695
|
const inHome = new Set(["store", "secrets", "config.json", MCP_REPORT_DIR]);
|
|
696
|
+
// The wiki is named even when it does not exist yet, so a bot's reach does
|
|
697
|
+
// not change when the memory plugin creates it. A bot that may write it has
|
|
698
|
+
// the wiki's entry in the home deny left out; one that may only read it has
|
|
699
|
+
// the entry and a read path through it.
|
|
700
|
+
const wikiName = wikiHomeName(home, wikiDirectoryOfHome(home));
|
|
701
|
+
if (wikiName !== undefined && wikiName !== BOT_DIR && !wikiWrite) inHome.add(wikiName);
|
|
702
|
+
const skipped = wikiWrite && wikiName !== undefined ? wikiName : undefined;
|
|
242
703
|
if (existsSync(home)) {
|
|
243
|
-
for (const name of readdirSync(home))
|
|
704
|
+
for (const name of readdirSync(home)) {
|
|
705
|
+
if (name !== BOT_DIR && name !== skipped) inHome.add(name);
|
|
706
|
+
}
|
|
244
707
|
}
|
|
708
|
+
const base = builtInAccess();
|
|
245
709
|
return {
|
|
246
710
|
denyPaths: [
|
|
247
|
-
|
|
248
|
-
"~/.gnupg",
|
|
249
|
-
"~/.aws",
|
|
250
|
-
"~/.config/gh",
|
|
251
|
-
"~/.radian",
|
|
252
|
-
"~/Library/Keychains",
|
|
253
|
-
"~/Library/Application Support/Google/Chrome",
|
|
254
|
-
"~/Library/Application Support/Firefox",
|
|
255
|
-
"~/Library/Safari",
|
|
256
|
-
".git/config",
|
|
257
|
-
".git/hooks",
|
|
711
|
+
...(base.denyPaths ?? []),
|
|
258
712
|
...[...inHome].sort().map((name) => join(home, name)),
|
|
259
713
|
],
|
|
260
|
-
denyCommands: [
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
"su",
|
|
264
|
-
"rm -rf /",
|
|
265
|
-
"rm -rf ~",
|
|
266
|
-
"mkfs",
|
|
267
|
-
"dd",
|
|
268
|
-
"diskutil",
|
|
269
|
-
"shutdown",
|
|
270
|
-
"reboot",
|
|
271
|
-
"launchctl",
|
|
272
|
-
"crontab -r",
|
|
273
|
-
"git push --force*",
|
|
274
|
-
"git push --delete",
|
|
275
|
-
"curl … | sh",
|
|
276
|
-
"wget … | sh",
|
|
277
|
-
"pkill",
|
|
278
|
-
"killall",
|
|
279
|
-
],
|
|
280
|
-
askCommands: ["git push", "brew install", "npm install -g", "pip install", "osascript", "open"],
|
|
281
|
-
askPaths: ["~/.zshrc", "~/.*profile"],
|
|
714
|
+
denyCommands: ["operad", ...(base.denyCommands ?? [])],
|
|
715
|
+
askCommands: [...(base.askCommands ?? [])],
|
|
716
|
+
askPaths: [...(base.askPaths ?? [])],
|
|
282
717
|
};
|
|
283
718
|
}
|
|
284
719
|
|
|
720
|
+
/** The first path segment of the wiki under the home, when it is inside it. */
|
|
721
|
+
function wikiHomeName(home: string, wiki: string): string | undefined {
|
|
722
|
+
const rel = relative(home, wiki);
|
|
723
|
+
if (rel === "" || rel.startsWith("..") || isAbsolute(rel)) return undefined;
|
|
724
|
+
const [first] = rel.split(/[\\/]/);
|
|
725
|
+
return first !== undefined && first.length > 0 ? first : undefined;
|
|
726
|
+
}
|
|
727
|
+
|
|
285
728
|
function appended(base: JsonValue | undefined, extra: unknown): JsonValue[] {
|
|
286
729
|
const list = Array.isArray(base) ? [...base] : [];
|
|
287
730
|
if (Array.isArray(extra)) {
|
|
@@ -296,13 +739,28 @@ export function accessFor(
|
|
|
296
739
|
settings: BotSettings,
|
|
297
740
|
repositories: readonly string[] = [],
|
|
298
741
|
skillPaths: readonly string[] = [],
|
|
742
|
+
readPaths: readonly string[] = [],
|
|
743
|
+
cwd?: string,
|
|
744
|
+
defaultBot = false,
|
|
299
745
|
): Record<string, JsonValue> {
|
|
300
|
-
const
|
|
746
|
+
const writeWiki = settings.writeWiki ?? defaultBot;
|
|
747
|
+
const wiki = wikiDirectoryOfHome(home);
|
|
748
|
+
const access = defaultAccess(home, writeWiki);
|
|
301
749
|
// A repository is reached through operad's tools (dev's verbs), never by
|
|
302
750
|
// touching its files, so its path is denied to the agent. Skill directories
|
|
303
751
|
// are changed only through a proposal a person confirms, so they are denied
|
|
304
|
-
//
|
|
305
|
-
|
|
752
|
+
// for writing too; `readPaths` lets the agent read them without lifting the
|
|
753
|
+
// deny (the harness still receives their paths as skills). Every other bot's
|
|
754
|
+
// directory is denied too, for reading and writing.
|
|
755
|
+
const siblings = cwd === undefined ? [] : siblingDirectories(home, cwd, defaultBot);
|
|
756
|
+
access.denyPaths = appended(access.denyPaths, [...repositories, ...skillPaths, ...siblings]);
|
|
757
|
+
// A wiki a bot may not write is refused for writing wherever it is, and a
|
|
758
|
+
// read path lets it read through that deny.
|
|
759
|
+
if (!writeWiki) {
|
|
760
|
+
access.denyPaths = appended(access.denyPaths, [wiki]);
|
|
761
|
+
access.readPaths = appended(access.readPaths, [wiki]);
|
|
762
|
+
}
|
|
763
|
+
if (readPaths.length > 0) access.readPaths = appended(access.readPaths, readPaths);
|
|
306
764
|
const own = settings.access ?? {};
|
|
307
765
|
for (const field of ["denyPaths", "denyCommands", "askCommands", "askPaths"] as const) {
|
|
308
766
|
access[field] = appended(access[field], own[field]);
|
|
@@ -313,27 +771,75 @@ export function accessFor(
|
|
|
313
771
|
return access;
|
|
314
772
|
}
|
|
315
773
|
|
|
316
|
-
/**
|
|
317
|
-
|
|
318
|
-
|
|
774
|
+
/** What one written skill path names now, without refusing one that is merely empty. */
|
|
775
|
+
export interface ListedSkills {
|
|
776
|
+
/** The skill directories directly inside it, or itself when it holds a SKILL.md. */
|
|
777
|
+
readonly directories: string[];
|
|
778
|
+
/** True when the path is a `.agents` directory, whose `skills` directory is read. */
|
|
779
|
+
readonly agents: boolean;
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
/** Reads a written skill path: a skill, a directory of skills, or a `.agents` directory. */
|
|
783
|
+
export function listedSkills(written: string, cwd: string): ListedSkills {
|
|
784
|
+
const path = expand(written, cwd);
|
|
785
|
+
if (hasSkill(path)) return { directories: [path], agents: false };
|
|
786
|
+
const agents = isDirectory(path) && basename(path) === ".agents";
|
|
787
|
+
return { directories: skillsInside(agents ? join(path, "skills") : path), agents };
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
interface SkillList {
|
|
791
|
+
/** The skill directories given to the agent. */
|
|
792
|
+
readonly directories: string[];
|
|
793
|
+
/** The directories a listed path names, denied for writing. */
|
|
794
|
+
readonly roots: string[];
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
/**
|
|
798
|
+
* The skills a bot lists, read now. A path may be a skill itself, a directory
|
|
799
|
+
* of skills (such as `~/.agents/skills`), or a `.agents` directory (such as
|
|
800
|
+
* `~/.agents`), whose `skills` directory is read the same way. Every skill
|
|
801
|
+
* directly inside is included, so one added later is read at the next reply.
|
|
802
|
+
*/
|
|
803
|
+
function skillList(settings: BotSettings, cwd: string): SkillList {
|
|
804
|
+
const directories: string[] = [];
|
|
805
|
+
const roots: string[] = [];
|
|
806
|
+
for (const written of settings.skills ?? []) {
|
|
319
807
|
const path = expand(written, cwd);
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
808
|
+
if (hasSkill(path)) {
|
|
809
|
+
added(roots, path);
|
|
810
|
+
added(directories, path);
|
|
811
|
+
continue;
|
|
323
812
|
}
|
|
324
|
-
|
|
325
|
-
|
|
813
|
+
const agents = isDirectory(path) && basename(path) === ".agents";
|
|
814
|
+
const parent = agents ? join(path, "skills") : path;
|
|
815
|
+
if (isDirectory(path)) added(roots, parent);
|
|
816
|
+
const inside = skillsInside(parent);
|
|
817
|
+
if (inside.length > 0) {
|
|
818
|
+
for (const skill of inside) added(directories, skill);
|
|
819
|
+
continue;
|
|
820
|
+
}
|
|
821
|
+
// A `.agents` directory may get its first skill after the setting is written.
|
|
822
|
+
if (agents) continue;
|
|
823
|
+
throw new BotError(`skill "${written}": there is no SKILL.md in ${path}`);
|
|
824
|
+
}
|
|
825
|
+
return { directories, roots };
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
/** The name a skill's SKILL.md gives, else its directory name. */
|
|
829
|
+
export function skillName(path: string): string {
|
|
830
|
+
try {
|
|
831
|
+
const found = /^name:\s*(\S+)/m.exec(readFileSync(join(path, "SKILL.md"), "utf8"))?.[1];
|
|
832
|
+
if (found !== undefined) return found.replace(/^["']|["']$/g, "");
|
|
833
|
+
} catch {
|
|
834
|
+
// A page can still name a skill whose SKILL.md cannot be read.
|
|
835
|
+
}
|
|
836
|
+
return basename(path);
|
|
326
837
|
}
|
|
327
838
|
|
|
328
839
|
/** The working directory of a bot; refused when it would put the operad home in reach. */
|
|
329
840
|
export function workingDirectory(home: string, name: string, settings: BotSettings): string {
|
|
330
841
|
const root = botDir(home);
|
|
331
|
-
const cwd =
|
|
332
|
-
settings.cwd === undefined
|
|
333
|
-
? name === DEFAULT_BOT
|
|
334
|
-
? root
|
|
335
|
-
: join(root, name)
|
|
336
|
-
: expand(settings.cwd, root);
|
|
842
|
+
const cwd = settings.cwd === undefined ? join(root, name) : expand(settings.cwd, root);
|
|
337
843
|
if (within(home, cwd)) {
|
|
338
844
|
throw new BotError(
|
|
339
845
|
`bot "${name}": the working directory ${cwd} is the operad home or holds it; use a subdirectory of ${root}`,
|
|
@@ -361,7 +867,7 @@ export async function repositoryPaths(store: ObjectStore): Promise<string[]> {
|
|
|
361
867
|
return found;
|
|
362
868
|
}
|
|
363
869
|
|
|
364
|
-
/** One bot as a chat uses it now;
|
|
870
|
+
/** One bot as a chat uses it now; its working directory and memory are created here. */
|
|
365
871
|
export function resolveBot(
|
|
366
872
|
home: string,
|
|
367
873
|
name: string,
|
|
@@ -369,16 +875,28 @@ export function resolveBot(
|
|
|
369
875
|
repositories: readonly string[] = [],
|
|
370
876
|
): ResolvedBot {
|
|
371
877
|
const cwd = workingDirectory(home, name, settings);
|
|
372
|
-
|
|
878
|
+
ensureBotMemory(cwd, home);
|
|
879
|
+
const list = skillList(settings, cwd);
|
|
880
|
+
const skills = [...list.directories];
|
|
881
|
+
const skillPaths = [...list.roots, join(cwd, "skills")];
|
|
882
|
+
// The memory skill is mounted for every bot while the memory plugin is
|
|
883
|
+
// enabled, so a bot that lists no skills still knows where its memory is.
|
|
884
|
+
if (memoryEnabled(home)) {
|
|
885
|
+
added(skills, MEMORY_SKILL_DIR);
|
|
886
|
+
added(skillPaths, MEMORY_SKILL_DIR);
|
|
887
|
+
}
|
|
373
888
|
return {
|
|
374
889
|
name,
|
|
375
890
|
cwd,
|
|
376
891
|
harness: settings.harness ?? null,
|
|
892
|
+
useOwnSettings: settings.useOwnSettings === true,
|
|
377
893
|
model: settings.model ?? null,
|
|
378
894
|
effort: settings.effort ?? null,
|
|
379
895
|
skills,
|
|
380
896
|
speaker: settings.speaker ?? null,
|
|
381
|
-
|
|
897
|
+
writeWiki: settings.writeWiki ?? name === DEFAULT_BOT,
|
|
898
|
+
accessLevel: settings.accessLevel ?? "ask",
|
|
899
|
+
access: accessFor(home, settings, repositories, skillPaths, skillPaths, cwd, name === DEFAULT_BOT),
|
|
382
900
|
mcpServers: settings.mcpServers ?? {},
|
|
383
901
|
};
|
|
384
902
|
}
|