@operad-io/dev 0.1.0 → 0.2.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/src/chat.ts CHANGED
@@ -5,18 +5,52 @@
5
5
  * changes reach main only through a task, through integrate.
6
6
  */
7
7
 
8
- import { CHAT_TYPE, agentConditionals, type AgentChoices, chatData, createChat, sendMessage, startingEffort, startingModel, titleFromMessage } from "@operad-io/chat";
9
- import type {
10
- ActionArgsSchema,
11
- ActionTypeDefinition,
12
- JsonValue,
13
- ObjectStore,
14
- PluginStepResult,
15
- StepContext,
8
+ import { messageOf } from "@operad-io/engine";
9
+ import {
10
+ ACCESS_ACTION_REQUEST,
11
+ CHAT_TYPE,
12
+ ENTRY_FACT,
13
+ WORKTREE_EVENT,
14
+ WORKTREE_NOTE,
15
+ WORKTREE_REPLY_EVENT,
16
+ agentConditionals,
17
+ added,
18
+ type AgentChoices,
19
+ chatData,
20
+ chatRef,
21
+ createChat,
22
+ hasSkill,
23
+ isDirectory,
24
+ sendMessage,
25
+ skillsInside,
26
+ startingEffort,
27
+ startingModel,
28
+ titleFromMessage,
29
+ } from "@operad-io/chat";
30
+ import { defaultAccess } from "@operad-io/access-match";
31
+ import {
32
+ isRecord,
33
+ modelIds,
34
+ stringList,
35
+ type ActionArgsSchema,
36
+ type ActionContext,
37
+ type ActionTypeDefinition,
38
+ type HarnessModelInfo,
39
+ type JsonValue,
40
+ type ObjectStore,
41
+ type PluginBaseContext,
42
+ type PluginStepResult,
43
+ type StepContext,
16
44
  } from "@operad-io/engine";
17
- import { existsSync } from "node:fs";
45
+ import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
46
+ import { basename, join, relative, resolve, sep } from "node:path";
18
47
  import { DevError, DevRefusal, repositoryData, type RepositoryData } from "./model.ts";
19
- import { readDevSettings } from "./settings.ts";
48
+ import {
49
+ assertInsideRepository,
50
+ readDevSettings,
51
+ type DevSettings,
52
+ } from "./settings.ts";
53
+ import { git } from "./git.ts";
20
54
  import { isRegistered, prepareWorktree, workBranch, worktreePath } from "./steps.ts";
21
55
 
22
56
  /**
@@ -30,7 +64,11 @@ export const CHAT_HARNESSES = ["claude", "pi"] as const;
30
64
  export const RADIAN_NOTE =
31
65
  "radian is not offered as an agent here: it cannot stop a tool call before it starts and cannot continue a session in another directory, so it cannot keep the main clone read-only or move to a worktree; use it for a bot chat.";
32
66
 
33
- /** The access profile of a chat in the main clone: read-only, and no secrets. */
67
+ /**
68
+ * What a repository chat adds to the built-in default: read-only in the main
69
+ * clone, and no operad command. The default already holds the credential paths
70
+ * and the dangerous commands, so the chat keeps them at every level.
71
+ */
34
72
  export const CHAT_ACCESS: Readonly<Record<string, JsonValue>> = {
35
73
  readOnly: true,
36
74
  denyPaths: ["~/.ssh", "~/.gnupg", "~/.aws", "~/.config/gh"],
@@ -38,11 +76,256 @@ export const CHAT_ACCESS: Readonly<Record<string, JsonValue>> = {
38
76
  denyCommands: ["operad"],
39
77
  };
40
78
 
79
+ /** The step a repository chat calls at every reply to read its skills and access. */
80
+ export const CHAT_SETTINGS_STEP = "dev/chat_settings";
81
+
82
+ /** The action a repository chat runs before it changes its access level. */
83
+ export const CHAT_ACCESS_ACTION = "dev/chat_access";
84
+
85
+ /** The most bytes of the repository's instruction file a chat starts with. */
86
+ export const CHAT_CONTEXT_FILE_MAX_BYTES = 32 * 1024;
87
+
88
+ /** The most other agent file paths a chat starts with. */
89
+ export const CHAT_CONTEXT_PATH_MAX = 50;
90
+
91
+ /** What a repository chat's first session starts with: its place, and the same words alone. */
92
+ export interface RepositoryChatContext {
93
+ readonly [key: string]: unknown;
94
+ /** The place, the instructions and the other agent files. */
95
+ readonly text: string;
96
+ /** The place alone, for a chat that moved to its worktree after the text was built. */
97
+ readonly where: string;
98
+ }
99
+
100
+ function realPathOrUndefined(path: string): string | undefined {
101
+ try {
102
+ return realpathSync(path);
103
+ } catch {
104
+ return undefined;
105
+ }
106
+ }
107
+
108
+ function insideRoot(root: string, path: string): boolean {
109
+ const real = realPathOrUndefined(path);
110
+ return real !== undefined && (real === root || real.startsWith(`${root}${sep}`));
111
+ }
112
+
113
+ /** The instruction file at the root: `AGENTS.md`, else `CLAUDE.md`, never one outside through a link. */
114
+ function instructionFile(base: string, root: string): { readonly path: string; readonly text: string } | undefined {
115
+ for (const name of ["AGENTS.md", "CLAUDE.md"] as const) {
116
+ const path = join(base, name);
117
+ const real = realPathOrUndefined(path);
118
+ if (real === undefined || (real !== root && !real.startsWith(`${root}${sep}`))) continue;
119
+ let isFile = false;
120
+ try {
121
+ isFile = statSync(real).isFile();
122
+ } catch {
123
+ continue;
124
+ }
125
+ if (!isFile) continue;
126
+ const bytes = readFileSync(real);
127
+ if (bytes.length <= CHAT_CONTEXT_FILE_MAX_BYTES) return { path, text: bytes.toString("utf8") };
128
+ // Cut at a character boundary and then at the last line end before the limit.
129
+ let end = CHAT_CONTEXT_FILE_MAX_BYTES;
130
+ while (end > 0 && ((bytes[end] ?? 0) & 0xc0) === 0x80) end -= 1;
131
+ let text = bytes.subarray(0, end).toString("utf8");
132
+ const lineEnd = text.lastIndexOf("\n");
133
+ if (lineEnd >= 0) text = text.slice(0, lineEnd);
134
+ const note = `The file was cut at 32 KB; the whole file is at ${path}.`;
135
+ return { path, text: text.length === 0 ? note : `${text}\n\n${note}` };
136
+ }
137
+ return undefined;
138
+ }
139
+
140
+ /** Every tracked `AGENTS.md` below the root, never the root's own and never one outside through a link. */
141
+ function trackedAgentFiles(base: string, root: string): string[] {
142
+ const listed = git(base, ["ls-files", "-z"], { raw: true });
143
+ if (!listed.ok) return [];
144
+ const found: string[] = [];
145
+ for (const path of listed.out.split("\0")) {
146
+ if (path.length === 0 || path === "AGENTS.md" || basename(path) !== "AGENTS.md") continue;
147
+ const absolute = join(base, path);
148
+ if (!insideRoot(root, absolute)) continue;
149
+ const real = realPathOrUndefined(absolute);
150
+ if (real === undefined) continue;
151
+ try {
152
+ if (!statSync(real).isFile()) continue;
153
+ } catch {
154
+ continue;
155
+ }
156
+ found.push(absolute);
157
+ }
158
+ return found;
159
+ }
160
+
161
+ function insideSkill(path: string, skills: readonly string[]): boolean {
162
+ const real = realPathOrUndefined(path);
163
+ if (real === undefined) return false;
164
+ return skills.some((skill) => {
165
+ const base = realPathOrUndefined(skill);
166
+ return base !== undefined && (real === base || real.startsWith(`${base}${sep}`));
167
+ });
168
+ }
169
+
170
+ /** Every file under the root `.agents`, except those inside a skill directory the chat loads. */
171
+ function agentFiles(base: string, root: string, skills: readonly string[]): string[] {
172
+ const start = join(base, ".agents");
173
+ if (!insideRoot(root, start)) return [];
174
+ const found: string[] = [];
175
+ const seen = new Set<string>();
176
+ const walk = (path: string): void => {
177
+ const real = realPathOrUndefined(path);
178
+ if (real === undefined || (real !== root && !real.startsWith(`${root}${sep}`))) return;
179
+ let isDirectory = false;
180
+ try {
181
+ isDirectory = statSync(real).isDirectory();
182
+ } catch {
183
+ return;
184
+ }
185
+ if (isDirectory) {
186
+ if (seen.has(real)) return;
187
+ seen.add(real);
188
+ let entries;
189
+ try {
190
+ entries = readdirSync(path, { withFileTypes: true });
191
+ } catch {
192
+ return;
193
+ }
194
+ for (const entry of entries) walk(join(path, entry.name));
195
+ return;
196
+ }
197
+ let isFile = false;
198
+ try {
199
+ isFile = statSync(real).isFile();
200
+ } catch {
201
+ return;
202
+ }
203
+ if (isFile && !insideSkill(path, skills)) found.push(path);
204
+ };
205
+ walk(start);
206
+ return found;
207
+ }
208
+
209
+ /** The other agent files a chat reads by path, relative to its working directory, with no duplicates. */
210
+ function otherAgentFiles(base: string, root: string, skills: readonly string[]): string[] {
211
+ const absolute = new Set([...trackedAgentFiles(base, root), ...agentFiles(base, root, skills)]);
212
+ return [...absolute]
213
+ .map((path) => relative(base, path))
214
+ .sort((left, right) => left.localeCompare(right));
215
+ }
216
+
217
+ /**
218
+ * The text a repository chat's first session starts with: where it is, the
219
+ * repository's instruction file, and the paths of its other agent files. Built
220
+ * from the working directory the reply uses, so a worktree chat names its branch.
221
+ */
222
+ export function repositoryChatContext(input: {
223
+ readonly repository: string;
224
+ readonly cwd: string;
225
+ readonly readOnly: boolean;
226
+ readonly branch?: string | undefined;
227
+ readonly skills: readonly string[];
228
+ readonly denyCommands: readonly string[];
229
+ }): RepositoryChatContext {
230
+ const root = realPathOrUndefined(input.cwd) ?? resolve(input.cwd);
231
+ const where = [
232
+ `You are answering in an operad chat about the repository ${input.repository}, in ${input.cwd}.`,
233
+ input.readOnly
234
+ ? "This chat is read-only in the main clone. Commands that only read run at once; a call that changes a file asks the person first."
235
+ : `This chat works in its own worktree on the branch ${input.branch ?? "unknown"}. Changes reach main through a task, not by merging here.`,
236
+ ...(input.denyCommands.length === 0
237
+ ? []
238
+ : [`These commands are refused here: ${input.denyCommands.join(", ")}.`]),
239
+ ...(input.denyCommands.includes("operad")
240
+ ? ["Use the operad tools you were given to read plans, tasks and pending items."]
241
+ : []),
242
+ ].join("\n");
243
+ const parts = [where];
244
+ const instructions = instructionFile(input.cwd, root);
245
+ if (instructions !== undefined) {
246
+ parts.push(`The repository's instructions follow. Follow them.\n\n${instructions.text}`);
247
+ }
248
+ const files = otherAgentFiles(input.cwd, root, input.skills);
249
+ if (files.length > 0) {
250
+ const shown = files.slice(0, CHAT_CONTEXT_PATH_MAX);
251
+ const lines = [
252
+ "Other agent files in this repository; read the ones that apply to what you work on:",
253
+ ...shown,
254
+ ...(files.length > CHAT_CONTEXT_PATH_MAX
255
+ ? [`[${files.length - CHAT_CONTEXT_PATH_MAX} more files were left out.]`]
256
+ : []),
257
+ ];
258
+ parts.push(lines.join("\n"));
259
+ }
260
+ return { where, text: parts.join("\n\n") };
261
+ }
262
+
263
+ /** The event dev sends after a live worktree yes, so the chat answers the same message there. */
264
+ export const CHAT_REPLY_EVENT = WORKTREE_REPLY_EVENT;
265
+
41
266
  /** The directory name and branch suffix of a chat's worktree. */
42
267
  export function chatWorktreeName(chatId: string): string {
43
268
  return `chat-${chatId}`;
44
269
  }
45
270
 
271
+ interface ChatSkillList {
272
+ /** The skill directories given to the agent. */
273
+ readonly directories: string[];
274
+ /** The directories a listed path names, denied for writing. */
275
+ readonly roots: string[];
276
+ }
277
+
278
+ /**
279
+ * The skills a repository gives its chats at `base` (the main clone or the
280
+ * chat's worktree), read now. A path may be a skill itself, a directory of
281
+ * skills (such as `.agents/skills`), or a `.agents` directory, whose `skills`
282
+ * directory is read the same way. Every skill directly inside is included, so
283
+ * one added later is read at the next reply.
284
+ */
285
+ export function repositoryChatSkills(settings: DevSettings, base: string): ChatSkillList {
286
+ const directories: string[] = [];
287
+ const roots: string[] = [];
288
+ settings.skills.forEach((written, index) => {
289
+ const path = resolve(base, written);
290
+ assertInsideRepository(base, path, `skills[${index}]`);
291
+ if (hasSkill(path)) {
292
+ added(roots, path);
293
+ added(directories, path);
294
+ return;
295
+ }
296
+ const agents = isDirectory(path) && basename(path) === ".agents";
297
+ const parent = agents ? join(path, "skills") : path;
298
+ if (isDirectory(path)) added(roots, parent);
299
+ for (const skill of skillsInside(parent)) added(directories, skill);
300
+ });
301
+ return { directories, roots };
302
+ }
303
+
304
+ /**
305
+ * The access profile of a repository chat. In the main clone its skills may be
306
+ * read but not changed; in its own worktree they are repository files the chat
307
+ * changes like any other, and the change reaches main through a task.
308
+ */
309
+ export function chatAccess(skillPaths: readonly string[], readOnly: boolean): Record<string, JsonValue> {
310
+ const base = defaultAccess();
311
+ const denyPaths = [...(base.denyPaths ?? [])];
312
+ for (const path of stringList(CHAT_ACCESS.denyPaths)) if (!denyPaths.includes(path)) denyPaths.push(path);
313
+ const denyCommands = [...(base.denyCommands ?? [])];
314
+ for (const command of stringList(CHAT_ACCESS.denyCommands)) {
315
+ if (!denyCommands.includes(command)) denyCommands.push(command);
316
+ }
317
+ const protectedPaths = readOnly ? skillPaths : [];
318
+ for (const path of protectedPaths) if (!denyPaths.includes(path)) denyPaths.push(path);
319
+ return {
320
+ denyPaths,
321
+ denyCommands,
322
+ askCommands: [...(base.askCommands ?? [])],
323
+ askPaths: [...(base.askPaths ?? [])],
324
+ readOnly,
325
+ ...(protectedPaths.length === 0 ? {} : { readPaths: [...protectedPaths] }),
326
+ };
327
+ }
328
+
46
329
  /**
47
330
  * The worktree name a task opened from chat `chatId` works in. The chat must be
48
331
  * about this repository and must already have been given its worktree.
@@ -72,6 +355,7 @@ function chatArgs(
72
355
  models: readonly string[],
73
356
  efforts: readonly string[],
74
357
  agents: readonly AgentChoices[] = [],
358
+ info?: Readonly<Record<string, HarnessModelInfo>> | undefined,
75
359
  ): ActionArgsSchema {
76
360
  return {
77
361
  type: "object",
@@ -85,6 +369,7 @@ function chatArgs(
85
369
  model: {
86
370
  type: "string",
87
371
  ...(models.length === 0 ? {} : { enum: [...models] }),
372
+ ...(info === undefined ? {} : { info }),
88
373
  description: "The model the agent uses; one from that agent's list. The agent's default when left out. It can be changed later.",
89
374
  },
90
375
  effort: {
@@ -118,10 +403,15 @@ const chatAction: ActionTypeDefinition = {
118
403
  args: chatArgs([], []),
119
404
  argsFor: (_object, env) => {
120
405
  const offered = CHAT_HARNESSES.filter((name) => (env.harnesses ?? []).includes(name));
406
+ const info: Record<string, HarnessModelInfo> = {};
407
+ for (const name of offered) {
408
+ for (const [id, model] of Object.entries(env.models?.[name]?.info ?? {})) info[id] = model;
409
+ }
121
410
  return chatArgs(
122
- [...new Set(offered.flatMap((name) => env.models?.[name]?.list ?? []))],
411
+ [...new Set(offered.flatMap((name) => modelIds(env.models?.[name])))],
123
412
  [...new Set(offered.flatMap((name) => env.efforts?.[name]?.list ?? []))],
124
413
  offered.map((name) => ({ name, models: env.models?.[name], efforts: env.efforts?.[name] })),
414
+ Object.keys(info).length === 0 ? undefined : info,
125
415
  );
126
416
  },
127
417
  when: (state) => repositoryData(state).removed !== true,
@@ -151,9 +441,16 @@ const chatAction: ActionTypeDefinition = {
151
441
  model = startingModel(harness, ctx.models[harness], input.model);
152
442
  effort = startingEffort(harness, ctx.efforts[harness], input.effort);
153
443
  } catch (error) {
154
- throw new DevRefusal(error instanceof Error ? error.message : String(error));
444
+ throw new DevRefusal(messageOf(error));
155
445
  }
156
446
  const effortDefault = ctx.efforts[harness]?.default ?? undefined;
447
+ const settings = await readDevSettings(repository.path);
448
+ let skills: ChatSkillList;
449
+ try {
450
+ skills = repositoryChatSkills(settings, repository.path);
451
+ } catch (error) {
452
+ throw new DevRefusal(messageOf(error));
453
+ }
157
454
  const id = await createChat(
158
455
  ctx.store,
159
456
  {
@@ -163,7 +460,12 @@ const chatAction: ActionTypeDefinition = {
163
460
  ...(effort === undefined ? {} : { effort }),
164
461
  ...(effort === undefined || effortDefault === undefined ? {} : { effortDefault }),
165
462
  cwd: repository.path,
166
- access: CHAT_ACCESS,
463
+ access: chatAccess(skills.roots, true),
464
+ accessLevel: "plan",
465
+ accessDefault: "plan",
466
+ skills: skills.directories,
467
+ refresh: CHAT_SETTINGS_STEP,
468
+ accessAction: CHAT_ACCESS_ACTION,
167
469
  title:
168
470
  input.title ??
169
471
  (input.message === undefined ? undefined : titleFromMessage(input.message)) ??
@@ -176,31 +478,144 @@ const chatAction: ActionTypeDefinition = {
176
478
  },
177
479
  };
178
480
 
179
- /** The actions of the chat part of dev. */
180
- export const chatActions: readonly ActionTypeDefinition[] = [chatAction];
181
-
182
481
  function failed(message: string): PluginStepResult {
183
482
  return { result: "failed", data: { message } };
184
483
  }
185
484
 
186
485
  /**
187
- * Step `dev/chat_worktree`: opens `work/chat-<id>` for a chat of a repository
188
- * and moves the chat's working directory there, once. The chat is writable in
189
- * the worktree; a chat that already has one is left as it is.
486
+ * Step `dev/chat_settings`: the skills and access of a repository chat as they
487
+ * are now. The reply calls it every time, so a skill added, changed or removed
488
+ * is read at the next reply, from the main clone while the chat is read-only
489
+ * and from its worktree once it has one.
190
490
  */
191
- export async function runChatWorktree(ctx: StepContext): Promise<PluginStepResult> {
192
- const object = ctx.object;
193
- if (object === undefined || object.type !== CHAT_TYPE) return failed("this runs on a chat");
194
- const stored = await ctx.store.get(CHAT_TYPE, object.id);
195
- if (stored === undefined) return failed(`there is no chat ${object.id}`);
196
- if (typeof stored.data.worktree === "object" && stored.data.worktree !== null) {
491
+ export async function runChatSettings(ctx: StepContext, params: unknown): Promise<PluginStepResult> {
492
+ const chatId = isRecord(params) && typeof params.chat === "string" ? params.chat : undefined;
493
+ const stored = chatId === undefined ? undefined : await ctx.store.get(CHAT_TYPE, chatId);
494
+ if (stored === undefined || chatId === undefined) return failed("there is no such chat");
495
+ const chat = chatData(stored.data);
496
+ const parent = typeof chat.parent === "string" ? chat.parent : "";
497
+ const name = parent.startsWith("repo:") ? parent.slice("repo:".length) : undefined;
498
+ if (name === undefined) {
499
+ return failed(`chat ${chatId} is not a chat about a repository`);
500
+ }
501
+ const repoObject = await ctx.store.get("repo", name);
502
+ if (repoObject === undefined) return failed(`there is no repository "${name}"`);
503
+ const repository = repositoryData(repoObject.data);
504
+ let settings;
505
+ try {
506
+ settings = await readDevSettings(repository.path);
507
+ } catch (error) {
508
+ return failed(messageOf(error));
509
+ }
510
+ const cwd = chat.cwd.length > 0 ? chat.cwd : repository.path;
511
+ const hasWorktree = isRecord(stored.data.worktree);
512
+ let skills: ChatSkillList;
513
+ try {
514
+ skills = repositoryChatSkills(settings, cwd);
515
+ } catch (error) {
516
+ return failed(messageOf(error));
517
+ }
518
+ const access = chatAccess(skills.roots, !hasWorktree);
519
+ const worktree = isRecord(stored.data.worktree) ? stored.data.worktree : {};
520
+ const branch =
521
+ hasWorktree
522
+ ? typeof worktree.branch === "string"
523
+ ? worktree.branch
524
+ : workBranch(chatWorktreeName(chatId))
525
+ : undefined;
526
+ const denyCommands = Array.isArray(access.denyCommands)
527
+ ? access.denyCommands.filter((command): command is string => typeof command === "string")
528
+ : [];
529
+ const context = repositoryChatContext({
530
+ repository: name,
531
+ cwd,
532
+ readOnly: !hasWorktree,
533
+ ...(branch === undefined ? {} : { branch }),
534
+ skills: skills.directories,
535
+ denyCommands,
536
+ });
537
+ return {
538
+ result: "done",
539
+ data: {
540
+ cwd,
541
+ access,
542
+ skills: [...skills.directories],
543
+ context,
544
+ },
545
+ };
546
+ }
547
+
548
+ /**
549
+ * The action a repository chat runs before its access level changes: a chat
550
+ * still in the main clone that is raised to `edits` or `full` first gets its
551
+ * worktree, exactly as the worktree answer gives it. A chat already in its
552
+ * worktree, a bot chat and a level below `edits` need nothing. A worktree that
553
+ * cannot be opened refuses the change, so the level stays as it was. It is
554
+ * hidden from clients: the chat marks its in-memory object only while it calls
555
+ * this action.
556
+ */
557
+ export async function runChatAccess(ctx: ActionContext, args: unknown): Promise<unknown> {
558
+ const level = isRecord(args) && typeof args.level === "string" ? args.level : undefined;
559
+ if (level === undefined) throw new Error("the chat's new access level is needed");
560
+ const stored = await ctx.store.get(CHAT_TYPE, ctx.object.id);
561
+ if (stored === undefined) throw new Error(`there is no chat ${ctx.object.id}`);
562
+ if (level !== "edits" && level !== "full") return "no worktree is needed";
563
+ if (isRecord(stored.data.worktree)) {
564
+ return "the chat already has its worktree";
565
+ }
566
+ const chat = chatData(stored.data);
567
+ const parent = typeof chat.parent === "string" ? chat.parent : "";
568
+ if (!parent.startsWith("repo:")) return "a bot chat works in its own directory";
569
+ const result = await openChatWorktree(
570
+ ctx,
571
+ ctx.object.id,
572
+ ctx.runId ?? `action:dev/chat_access:${ctx.object.id}`,
573
+ "action:dev/chat_access",
574
+ );
575
+ const data = isRecord(result.data) ? result.data : {};
576
+ if (result.result !== "done") {
577
+ throw new Error(
578
+ typeof data.message === "string" && data.message.length > 0
579
+ ? data.message
580
+ : `chat ${ctx.object.id} could not open its worktree`,
581
+ );
582
+ }
583
+ return "the chat now has its worktree";
584
+ }
585
+
586
+ const chatAccessAction: ActionTypeDefinition = {
587
+ name: "chat_access",
588
+ on: CHAT_TYPE,
589
+ args: {
590
+ type: "object",
591
+ properties: { level: { type: "string" } },
592
+ required: ["level"],
593
+ additionalProperties: false,
594
+ },
595
+ when: (state) => state[ACCESS_ACTION_REQUEST] === true,
596
+ run: runChatAccess,
597
+ };
598
+
599
+ /** The actions of the chat part of dev. */
600
+ export const chatActions: readonly ActionTypeDefinition[] = [chatAction, chatAccessAction];
601
+
602
+ /** Opens a chat's worktree and records where it moved; shared by the step and the access action. */
603
+ async function openChatWorktree(
604
+ ctx: Pick<PluginBaseContext, "store" | "facts">,
605
+ chatId: string,
606
+ runId: string,
607
+ cause: string,
608
+ ): Promise<PluginStepResult> {
609
+ const stored = await ctx.store.get(CHAT_TYPE, chatId);
610
+ if (stored === undefined) return failed(`there is no chat ${chatId}`);
611
+ if (isRecord(stored.data.worktree)) {
197
612
  return { result: "done", data: { moved: false } };
198
613
  }
199
614
  const chat = chatData(stored.data);
200
615
  const parent = typeof chat.parent === "string" ? chat.parent : "";
201
616
  const name = parent.startsWith("repo:") ? parent.slice("repo:".length) : undefined;
202
617
  const repoObject = name === undefined ? undefined : await ctx.store.get("repo", name);
203
- if (repoObject === undefined) return failed(`chat ${object.id} is not a chat about a repository`);
618
+ if (repoObject === undefined) return failed(`chat ${chatId} is not a chat about a repository`);
204
619
  const repository = repositoryData(repoObject.data);
205
620
 
206
621
  let settings;
@@ -209,26 +624,87 @@ export async function runChatWorktree(ctx: StepContext): Promise<PluginStepResul
209
624
  } catch (error) {
210
625
  return failed(error instanceof DevError ? error.message : String(error));
211
626
  }
212
- const worktreeName = chatWorktreeName(object.id);
627
+ const worktreeName = chatWorktreeName(chatId);
213
628
  const prepared = prepareWorktree(repository, settings, worktreeName);
214
629
  if (prepared.kind !== "ready") {
215
- return failed(prepared.message ?? `cannot open a worktree for chat ${object.id}`);
630
+ return failed(prepared.message ?? `cannot open a worktree for chat ${chatId}`);
216
631
  }
217
632
  const path = worktreePath(repository.path, settings, worktreeName);
218
633
  const branch = workBranch(worktreeName);
219
634
 
220
635
  // Read again: the reply step may have moved the session while git ran.
221
- const fresh = await ctx.store.get(CHAT_TYPE, object.id);
222
- if (fresh === undefined) return failed(`there is no chat ${object.id}`);
223
- if (typeof fresh.data.worktree === "object" && fresh.data.worktree !== null) {
636
+ const fresh = await ctx.store.get(CHAT_TYPE, chatId);
637
+ if (fresh === undefined) return failed(`there is no chat ${chatId}`);
638
+ if (isRecord(fresh.data.worktree)) {
224
639
  return { result: "done", data: { moved: false } };
225
640
  }
226
- const access = chatData(fresh.data).access;
641
+ let skills: ChatSkillList;
642
+ try {
643
+ skills = repositoryChatSkills(settings, path);
644
+ } catch (error) {
645
+ return failed(messageOf(error));
646
+ }
647
+ const clean: Record<string, unknown> = { ...fresh.data };
648
+ // Only chat:access marks this in memory, to call its hidden action; it is never stored.
649
+ delete clean[ACCESS_ACTION_REQUEST];
227
650
  await ctx.store.put(
228
651
  CHAT_TYPE,
229
- object.id,
230
- { ...fresh.data, cwd: path, access: { ...access, readOnly: false }, worktree: { path, branch } },
231
- "step:dev/chat_worktree",
652
+ chatId,
653
+ {
654
+ ...clean,
655
+ cwd: path,
656
+ access: chatAccess(skills.roots, false),
657
+ skills: [...skills.directories],
658
+ worktree: { path, branch },
659
+ },
660
+ cause,
232
661
  );
662
+ // The transcript says where the chat moved, once. It is an entry of the
663
+ // worktree run, not of a reply, so it does not become the agent's words.
664
+ await ctx.facts.append({
665
+ type: ENTRY_FACT,
666
+ object: chatRef(chatId),
667
+ data: { runId, kind: "worktree", text: WORKTREE_NOTE },
668
+ });
233
669
  return { result: "done", data: { moved: true, path, branch } };
234
670
  }
671
+
672
+ /**
673
+ * Step `dev/chat_worktree`: opens `work/chat-<id>` for a chat of a repository
674
+ * and moves the chat's working directory there, once. The chat is writable in
675
+ * the worktree; a chat that already has one is left as it is.
676
+ */
677
+ export async function runChatWorktree(ctx: StepContext): Promise<PluginStepResult> {
678
+ const object = ctx.object;
679
+ if (object === undefined || object.type !== CHAT_TYPE) return failed("this runs on a chat");
680
+ const result = await openChatWorktree(ctx, object.id, ctx.runId, "step:dev/chat_worktree");
681
+ const data = isRecord(result.data) ? result.data : {};
682
+ // A live yes ended the reply that asked; answer the same message again now
683
+ // that the chat is writable. A yes that came after the reply ended only
684
+ // opens the worktree, so it starts no reply.
685
+ if (data.moved === true && ctx.trigger?.type === WORKTREE_EVENT && !lateWorktree(ctx)) {
686
+ await ctx.emit({
687
+ type: CHAT_REPLY_EVENT,
688
+ key: `worktree:${object.id}`,
689
+ object: `${CHAT_TYPE}:${object.id}`,
690
+ });
691
+ }
692
+ return result;
693
+ }
694
+
695
+ /** Whether the event says its yes arrived after the asking reply had ended. */
696
+ function lateWorktree(ctx: StepContext): boolean {
697
+ const path = ctx.trigger?.data;
698
+ if (path !== undefined) {
699
+ try {
700
+ const value: unknown = JSON.parse(readFileSync(path, "utf8"));
701
+ if (isRecord(value) && value.late === true) return true;
702
+ } catch {
703
+ // A missing or broken file is not the late marker; fall back to the key.
704
+ }
705
+ }
706
+ // The kernel scopes an emitted key as `<runId>:<key>`, so the reply's "late"
707
+ // arrives as `<runId>:late`. The data file is the primary marker; the key
708
+ // covers an event that carries no data.
709
+ return ctx.trigger?.key.endsWith(":late") === true;
710
+ }