@operad-io/chat 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/src/index.ts CHANGED
@@ -1,32 +1,101 @@
1
1
  /** The chat plugin: a long conversation with an agent, and how a message is answered. */
2
2
 
3
+ import { messageOf } from "@operad-io/engine";
3
4
  import pkg from "../package.json" with { type: "json" };
4
- import { defineFlow, definePlugin, type ActionArgsSchema, type ActionContext, type ActionTypeDefinition } from "@operad-io/engine";
5
+ import { defineFlow, definePlugin, formatElapsed, isRecord, modelIds, type ActionArgsSchema, type ActionContext, type ActionTypeDefinition, type HarnessCapabilities, type HarnessEfforts,type HarnessModels, type JsonValue, type ObjectStore, type PluginFact, type RunControl, type StoredObject, type UsageTokens } from "@operad-io/engine";
6
+ import { ACCESS_LEVELS, isAccessLevel, updateLiveAccessLevel, type AccessLevel } from "@operad-io/access-match";
7
+ import { stopKeptWorkers } from "@operad-io/engine/platform";
5
8
  import {
6
9
  CHAT_FILTERS,
7
10
  CHAT_SOURCES,
8
11
  OTHER_SOURCE,
9
12
  CHAT_TYPE,
10
13
  chatData,
14
+ chatFacts,
11
15
  chatRef,
16
+ ACCESS_ACTION_REQUEST,
17
+ ACCESS_FACT,
18
+ ACCESS_LEVEL_INFO,
19
+ accessLevelPath,
12
20
  CLOSED_FACT,
21
+ COMMAND_FACT,
22
+ costText,
23
+ effectiveEffort,
13
24
  EFFORT_FACT,
25
+ firstOutputMs,
26
+ lastReplyOutcome,
27
+ latestRunOf,
14
28
  MESSAGE_EVENT,
15
29
  MESSAGE_FACT,
30
+ MESSAGE_CHANGE_FACT,
16
31
  attachmentOf,
17
32
  MODEL_FACT,
18
33
  newMessageId,
34
+ readChat,
35
+ STOP_FACT,
36
+ stoppedRunAfter,
37
+ takenIds,
38
+ unanswered,
39
+ writingReplyNow,
40
+ type AccessChangedData,
41
+ type ChatData,
19
42
  type ClosedData,
43
+ type CommandData,
20
44
  type EffortChangedData,
45
+ type Message,
21
46
  type ModelChangedData,
47
+ type MessageChangeData,
22
48
  type MessageData,
49
+ type StopData,
50
+ type WritingReply,
23
51
  } from "./model.ts";
24
- import { runReply } from "./reply.ts";
52
+ import { keepInterrupted, runReply, withLevelFileDeny, WORKTREE_ALLOW_ALWAYS, WORKTREE_ALLOW_ONCE, WORKTREE_CHOICES, WORKTREE_DENY, WORKTREE_REPLY_EVENT, WORKTREE_YES, worktreeChoiceInfo } from "./reply.ts";
53
+ import { syncQueuedLocked, withQueueLock } from "./queue.ts";
54
+ import { chatCommands, findCommand, helpText, parseCommand, runCommand } from "./command.ts";
55
+ import { readChatSkills } from "./skills.ts";
25
56
  import { chatViews } from "./views.ts";
26
57
 
58
+ export { ACCESS_LEVEL_INFO } from "./model.ts";
59
+
27
60
  /** How many rounds one reply run may take before it stops (each round is one visit). */
28
61
  export const REPLY_MAX_VISITS = 20;
29
62
 
63
+ /** The chat an action runs on; it fails when the chat is gone. */
64
+ async function storedChat(ctx: ActionContext): Promise<StoredObject> {
65
+ const stored = await ctx.store.get(CHAT_TYPE, ctx.object.id);
66
+ if (stored === undefined) throw new Error(`there is no chat ${ctx.object.id}`);
67
+ return stored;
68
+ }
69
+
70
+ /** The chat an action runs on, when it is still open; it fails with `reason` otherwise. */
71
+ async function openChat(ctx: ActionContext, reason: string): Promise<StoredObject> {
72
+ const stored = await storedChat(ctx);
73
+ if (chatData(stored.data).closed) throw new Error(`chat ${ctx.object.id} is closed; ${reason}`);
74
+ return stored;
75
+ }
76
+
77
+ /** Reads the chat again and puts its data changed, when the change still applies. */
78
+ async function changeChat(
79
+ ctx: ActionContext,
80
+ cause: string,
81
+ change: (data: Readonly<Record<string, unknown>>) => Readonly<Record<string, unknown>> | undefined,
82
+ ): Promise<void> {
83
+ const fresh = await ctx.store.get(CHAT_TYPE, ctx.object.id);
84
+ if (fresh === undefined) return;
85
+ const data = change(fresh.data);
86
+ if (data === undefined) return;
87
+ await ctx.store.put(CHAT_TYPE, ctx.object.id, data, cause);
88
+ }
89
+
90
+ /** Ends the kept worker of a chat, if the agent keeps one. */
91
+ async function endKeptWorker(home: string, chat: ChatData, id: string): Promise<void> {
92
+ await stopKeptWorkers({
93
+ home,
94
+ name: chat.harness,
95
+ filter: { scope: `${CHAT_TYPE}:${id}` },
96
+ });
97
+ }
98
+
30
99
  /** The flow a message starts: answer, and go round again while messages came meanwhile. */
31
100
  export const replyFlow = defineFlow({
32
101
  name: "chat:reply",
@@ -43,9 +112,18 @@ export const replyFlow = defineFlow({
43
112
  more: "reply",
44
113
  waiting: "person",
45
114
  failed: "failed",
46
- interrupted: "cancelled",
115
+ interrupted: "keep",
47
116
  },
48
117
  },
118
+ {
119
+ // A reply a crash, stop or restart interrupted keeps what its log
120
+ // finished and one line saying so, so /retry can continue it.
121
+ id: "keep",
122
+ kind: "plugin",
123
+ params: { use: "chat/keep", params: {} },
124
+ replay: "safe",
125
+ next: { done: "cancelled", failed: "cancelled" },
126
+ },
49
127
  {
50
128
  // A question ran out of grace. The answer sends the run back to the
51
129
  // reply, which continues the session with it.
@@ -53,11 +131,17 @@ export const replyFlow = defineFlow({
53
131
  kind: "wait_person",
54
132
  params: {
55
133
  prompt: "The agent asked a question.",
56
- choices: ["allow_once", "reject_once", "yes", "no"],
57
- lateChoices: ["allow_always"],
134
+ choices: [...WORKTREE_CHOICES],
135
+ choiceInfo: worktreeChoiceInfo(),
136
+ // The older yes/no and the internal names still answer an item opened before this.
137
+ lateChoices: ["allow_once", "allow_always", "reject_once", "yes", "no"],
58
138
  },
59
139
  replay: "safe",
60
140
  next: {
141
+ [WORKTREE_ALLOW_ONCE]: "reply",
142
+ [WORKTREE_ALLOW_ALWAYS]: "reply",
143
+ [WORKTREE_DENY]: "reply",
144
+ [WORKTREE_YES]: "reply",
61
145
  allow_once: "reply",
62
146
  allow_always: "reply",
63
147
  reject_once: "reply",
@@ -73,7 +157,14 @@ export const replyFlow = defineFlow({
73
157
  });
74
158
 
75
159
  /** What {@link sendMessage} needs of an action's context. */
76
- export type SendContext = Pick<ActionContext, "facts" | "emit" | "actor">;
160
+ export type SendContext = Pick<ActionContext, "facts" | "emit" | "actor"> & {
161
+ /** The event source for a message a plugin writes itself; absent uses the client's. */
162
+ readonly source?: string | undefined;
163
+ /** The store the chat lives in, so its row can show the queue at once. */
164
+ readonly store?: ActionContext["store"] | undefined;
165
+ /** The operad home, for the queue lock. */
166
+ readonly home?: string | undefined;
167
+ };
77
168
 
78
169
  /**
79
170
  * Records a user message on chat `chatId` and, when events can be routed, starts
@@ -86,12 +177,13 @@ export async function sendMessage(
86
177
  note: string,
87
178
  ref?: string,
88
179
  files: readonly string[] = [],
180
+ instruction?: string,
89
181
  ): Promise<string> {
90
182
  const via = ctx.actor.via;
91
- // The message records who sent it as it is; the event uses a known source, or
92
- // `other` for a client this plugin does not know, so it is still answered.
183
+ // The message records who sent it as it is; the event uses the source its
184
+ // caller names, else a known client source, else `other`, so it is still answered.
93
185
  const known = CHAT_SOURCES.find((name) => name === via);
94
- const source = known ?? OTHER_SOURCE;
186
+ const source = ctx.source ?? known ?? OTHER_SOURCE;
95
187
  const id = newMessageId();
96
188
  const message: MessageData = {
97
189
  id,
@@ -100,9 +192,15 @@ export async function sendMessage(
100
192
  text: note,
101
193
  attachments: files.map((path) => attachmentOf(path)),
102
194
  source: { kind: via, ref: ref ?? null },
195
+ ...(instruction === undefined || instruction.length === 0 ? {} : { instruction }),
103
196
  };
104
197
  // The message is a fact first; the event is what starts the answer.
105
- await ctx.facts.append({ type: MESSAGE_FACT, object: chatRef(chatId), data: message });
198
+ const record = async (): Promise<void> => {
199
+ await ctx.facts.append({ type: MESSAGE_FACT, object: chatRef(chatId), data: message });
200
+ if (ctx.store !== undefined) await syncQueuedLocked(ctx.store, chatId, "action:chat/send");
201
+ };
202
+ if (ctx.home === undefined || ctx.store === undefined) await record();
203
+ else await withQueueLock(ctx.home, chatId, record);
106
204
  if (ctx.emit === undefined) return `recorded ${id}; it is answered when operad serve runs`;
107
205
  await ctx.emit({ source, type: MESSAGE_EVENT, key: id, object: `${CHAT_TYPE}:${chatId}` });
108
206
  return `sent ${id}`;
@@ -136,32 +234,143 @@ const sendAction: ActionTypeDefinition = {
136
234
  why: (object) =>
137
235
  chatData(object.data).closed ? `${object.id} is closed; it takes no messages` : undefined,
138
236
  async run(ctx, args) {
139
- const stored = await ctx.store.get(CHAT_TYPE, ctx.object.id);
140
- if (stored === undefined) throw new Error(`there is no chat ${ctx.object.id}`);
141
- if (chatData(stored.data).closed) {
142
- throw new Error(`chat ${ctx.object.id} is closed; it takes no messages`);
143
- }
237
+ await openChat(ctx, "it takes no messages");
144
238
  const input = args as {
145
239
  readonly note?: string;
146
240
  readonly ref?: string;
147
241
  readonly attachments?: readonly string[];
148
242
  };
149
243
  const files = input.attachments ?? [];
150
- if ((input.note ?? "").trim().length === 0 && files.length === 0) {
244
+ const text = input.note ?? "";
245
+ if (text.trim().length === 0 && files.length === 0) {
151
246
  throw new Error("a message needs text or an attachment; pass --note <text>");
152
247
  }
153
- return sendMessage(ctx, ctx.object.id, input.note ?? "", input.ref, files);
248
+ // A command is text alone: attachments mean a message, never a command.
249
+ const parsed = files.length === 0 ? parseCommand(text) : undefined;
250
+ const command = parsed === undefined ? undefined : findCommand(chatCommands(ctx.actions ?? []), parsed.name);
251
+ if (parsed !== undefined && command !== undefined) {
252
+ const result = await runCommand(ctx, command, parsed.rest);
253
+ const data: CommandData = {
254
+ from: { via: ctx.actor.via, id: ctx.actor.id },
255
+ command: parsed.text,
256
+ outcome: result.outcome,
257
+ ok: result.ok,
258
+ };
259
+ await ctx.facts.append({ type: COMMAND_FACT, object: chatRef(ctx.object.id), data });
260
+ return result.outcome;
261
+ }
262
+ return sendMessage(ctx, ctx.object.id, text, input.ref, files);
263
+ },
264
+ };
265
+
266
+ /** The message an action on the queue names, when it is still there to change. */
267
+ async function queuedMessage(
268
+ ctx: ActionContext,
269
+ messageId: string,
270
+ action: "withdrawn" | "changed",
271
+ ): Promise<Message> {
272
+ const read = readChat(ctx.store, ctx.object.id);
273
+ const message = read.messages.find((item) => item.id === messageId);
274
+ if (message === undefined || message.role !== "user") {
275
+ throw new Error(`chat ${ctx.object.id} has no queued message ${messageId}`);
276
+ }
277
+ if (takenIds(read.facts).has(messageId)) {
278
+ throw new Error(`message ${messageId} was taken by a run; it can no longer be ${action}`);
279
+ }
280
+ return message;
281
+ }
282
+
283
+ const withdrawAction: ActionTypeDefinition = {
284
+ name: "withdraw",
285
+ on: CHAT_TYPE,
286
+ args: {
287
+ type: "object",
288
+ properties: {
289
+ message: {
290
+ type: "string",
291
+ minLength: 1,
292
+ description: "The id of the queued message to withdraw.",
293
+ },
294
+ },
295
+ required: ["message"],
296
+ additionalProperties: false,
297
+ },
298
+ when: (state) => !chatData(state).closed,
299
+ why: (object) =>
300
+ chatData(object.data).closed ? `${object.id} is closed; it has no queued message` : undefined,
301
+ async run(ctx, args) {
302
+ await openChat(ctx, "it has no queued message");
303
+ const messageId = (args as { readonly message: string }).message;
304
+ return withQueueLock(ctx.home, ctx.object.id, async () => {
305
+ await queuedMessage(ctx, messageId, "withdrawn");
306
+ const change: MessageChangeData = {
307
+ id: messageId,
308
+ kind: "withdraw",
309
+ by: { via: ctx.actor.via, id: ctx.actor.id },
310
+ };
311
+ await ctx.facts.append({ type: MESSAGE_CHANGE_FACT, object: chatRef(ctx.object.id), data: change });
312
+ await syncQueuedLocked(ctx.store, ctx.object.id, "action:chat/withdraw");
313
+ return `withdrew message ${messageId}`;
314
+ });
315
+ },
316
+ };
317
+
318
+ const editAction: ActionTypeDefinition = {
319
+ name: "edit",
320
+ on: CHAT_TYPE,
321
+ args: {
322
+ type: "object",
323
+ properties: {
324
+ message: {
325
+ type: "string",
326
+ minLength: 1,
327
+ description: "The id of the queued message to change.",
328
+ },
329
+ text: {
330
+ type: "string",
331
+ description: "The text it now has. Its attachments stay.",
332
+ },
333
+ },
334
+ required: ["message", "text"],
335
+ additionalProperties: false,
336
+ },
337
+ when: (state) => !chatData(state).closed,
338
+ why: (object) =>
339
+ chatData(object.data).closed ? `${object.id} is closed; it has no queued message` : undefined,
340
+ async run(ctx, args) {
341
+ await openChat(ctx, "it has no queued message");
342
+ const input = args as { readonly message: string; readonly text: string };
343
+ return withQueueLock(ctx.home, ctx.object.id, async () => {
344
+ const message = await queuedMessage(ctx, input.message, "changed");
345
+ if (input.text.trim().length === 0 && message.attachments.length === 0) {
346
+ throw new Error("a message needs text or an attachment; pass --text <text>");
347
+ }
348
+ if (message.text === input.text) return `message ${input.message} already reads that`;
349
+ const change: MessageChangeData = {
350
+ id: input.message,
351
+ kind: "text",
352
+ by: { via: ctx.actor.via, id: ctx.actor.id },
353
+ text: input.text,
354
+ };
355
+ await ctx.facts.append({ type: MESSAGE_CHANGE_FACT, object: chatRef(ctx.object.id), data: change });
356
+ await syncQueuedLocked(ctx.store, ctx.object.id, "action:chat/edit");
357
+ return `changed message ${input.message}`;
358
+ });
154
359
  },
155
360
  };
156
361
 
157
- /** The models the chat's agent lists, as the enum of `chat:model`. */
158
- function modelArgs(models: readonly string[]): ActionArgsSchema {
362
+ /** The models the chat's agent lists, as the enum and descriptions of `chat:model`. */
363
+ function modelArgs(models: HarnessModels | undefined, chat: ChatData | undefined): ActionArgsSchema {
364
+ const list = modelIds(models);
365
+ const current = chat?.model ?? chat?.lastModel ?? models?.default ?? undefined;
159
366
  return {
160
367
  type: "object",
161
368
  properties: {
162
369
  model: {
163
370
  type: "string",
164
- ...(models.length === 0 ? {} : { enum: [...models] }),
371
+ ...(list.length === 0 ? {} : { enum: [...list] }),
372
+ ...(models?.info === undefined ? {} : { info: models.info }),
373
+ ...(current === undefined || current.length === 0 ? {} : { current }),
165
374
  description: "The model the next reply uses.",
166
375
  },
167
376
  },
@@ -173,25 +382,27 @@ function modelArgs(models: readonly string[]): ActionArgsSchema {
173
382
  const modelAction: ActionTypeDefinition = {
174
383
  name: "model",
175
384
  on: CHAT_TYPE,
176
- args: modelArgs([]),
177
- argsFor: (object, env) => modelArgs(env.models?.[chatData(object.data).harness]?.list ?? []),
385
+ command: "Change the model the next reply uses.",
386
+ args: modelArgs(undefined, undefined),
387
+ argsFor: (object, env) => {
388
+ const chat = chatData(object.data);
389
+ return modelArgs(env.models?.[chat.harness], chat);
390
+ },
178
391
  when: (state, env) =>
179
- !chatData(state).closed && (env.models?.[chatData(state).harness]?.list.length ?? 0) > 0,
392
+ !chatData(state).closed && modelIds(env.models?.[chatData(state).harness]).length > 0,
180
393
  why: (object, env) => {
181
394
  const chat = chatData(object.data);
182
395
  if (chat.closed) return `${object.id} is closed; its model cannot change`;
183
- if ((env.models?.[chat.harness]?.list.length ?? 0) === 0) {
396
+ if (modelIds(env.models?.[chat.harness]).length === 0) {
184
397
  return `the agent "${chat.harness}" offers no model to pick`;
185
398
  }
186
399
  return undefined;
187
400
  },
188
401
  async run(ctx, args) {
189
- const stored = await ctx.store.get(CHAT_TYPE, ctx.object.id);
190
- if (stored === undefined) throw new Error(`there is no chat ${ctx.object.id}`);
402
+ const stored = await openChat(ctx, "its model cannot change");
191
403
  const chat = chatData(stored.data);
192
- if (chat.closed) throw new Error(`chat ${ctx.object.id} is closed; its model cannot change`);
193
404
  const model = (args as { readonly model: string }).model;
194
- const offered = ctx.models[chat.harness]?.list ?? [];
405
+ const offered = modelIds(ctx.models[chat.harness]);
195
406
  if (!offered.includes(model)) {
196
407
  throw new Error(
197
408
  `the agent "${chat.harness}" cannot use the model "${model}"; it offers: ${offered.join(", ") || "none"}`,
@@ -209,22 +420,24 @@ const modelAction: ActionTypeDefinition = {
209
420
  data: changed,
210
421
  });
211
422
  // Read again: a reply may have moved the session while the fact was written.
212
- const fresh = await ctx.store.get(CHAT_TYPE, ctx.object.id);
213
- if (fresh !== undefined) {
214
- await ctx.store.put(CHAT_TYPE, ctx.object.id, { ...fresh.data, model }, "action:chat/model");
215
- }
423
+ await changeChat(ctx, "action:chat/model", (data) => ({ ...data, model }));
216
424
  return `chat ${ctx.object.id} now uses ${model}; the next reply uses it`;
217
425
  },
218
426
  };
219
427
 
220
428
  /** The efforts the chat's agent lists, as the enum of `chat:effort`. */
221
- function effortArgs(efforts: readonly string[]): ActionArgsSchema {
429
+ function effortArgs(efforts: HarnessEfforts | undefined, chat: ChatData | undefined): ActionArgsSchema {
430
+ const list = efforts?.list ?? [];
431
+ const current = chat === undefined ? undefined : effectiveEffort(chat, efforts);
432
+ const fallback = efforts?.default ?? undefined;
222
433
  return {
223
434
  type: "object",
224
435
  properties: {
225
436
  effort: {
226
437
  type: "string",
227
- ...(efforts.length === 0 ? {} : { enum: [...efforts] }),
438
+ ...(list.length === 0 ? {} : { enum: [...list] }),
439
+ ...(current === undefined || current.length === 0 ? {} : { current }),
440
+ ...(fallback === undefined || fallback.length === 0 ? {} : { default: fallback }),
228
441
  description: "The effort the next reply uses.",
229
442
  },
230
443
  },
@@ -236,8 +449,12 @@ function effortArgs(efforts: readonly string[]): ActionArgsSchema {
236
449
  const effortAction: ActionTypeDefinition = {
237
450
  name: "effort",
238
451
  on: CHAT_TYPE,
239
- args: effortArgs([]),
240
- argsFor: (object, env) => effortArgs(env.efforts?.[chatData(object.data).harness]?.list ?? []),
452
+ command: "Change the effort the next reply uses.",
453
+ args: effortArgs(undefined, undefined),
454
+ argsFor: (object, env) => {
455
+ const chat = chatData(object.data);
456
+ return effortArgs(env.efforts?.[chat.harness], chat);
457
+ },
241
458
  when: (state, env) =>
242
459
  !chatData(state).closed && (env.efforts?.[chatData(state).harness]?.list.length ?? 0) > 0,
243
460
  why: (object, env) => {
@@ -249,10 +466,8 @@ const effortAction: ActionTypeDefinition = {
249
466
  return undefined;
250
467
  },
251
468
  async run(ctx, args) {
252
- const stored = await ctx.store.get(CHAT_TYPE, ctx.object.id);
253
- if (stored === undefined) throw new Error(`there is no chat ${ctx.object.id}`);
469
+ const stored = await openChat(ctx, "its effort cannot change");
254
470
  const chat = chatData(stored.data);
255
- if (chat.closed) throw new Error(`chat ${ctx.object.id} is closed; its effort cannot change`);
256
471
  const effort = (args as { readonly effort: string }).effort;
257
472
  const offered = ctx.efforts[chat.harness];
258
473
  const list = offered?.list ?? [];
@@ -273,49 +488,357 @@ const effortAction: ActionTypeDefinition = {
273
488
  data: changed,
274
489
  });
275
490
  // Read again: a reply may have moved the session while the fact was written.
276
- const fresh = await ctx.store.get(CHAT_TYPE, ctx.object.id);
277
- if (fresh !== undefined) {
278
- const fallback = offered?.default;
279
- await ctx.store.put(
280
- CHAT_TYPE,
281
- ctx.object.id,
282
- {
283
- ...fresh.data,
284
- effort,
285
- ...(fallback === undefined || fallback === null ? {} : { effortDefault: fallback }),
286
- },
287
- "action:chat/effort",
491
+ const fallback = offered?.default;
492
+ await changeChat(ctx, "action:chat/effort", (data) => ({
493
+ ...data,
494
+ effort,
495
+ ...(fallback === undefined || fallback === null ? {} : { effortDefault: fallback }),
496
+ }));
497
+ return `chat ${ctx.object.id} now uses effort ${effort}; the next reply uses it`;
498
+ },
499
+ };
500
+
501
+ function accessArgs(): ActionArgsSchema {
502
+ return {
503
+ type: "object",
504
+ properties: {
505
+ level: {
506
+ type: "string",
507
+ title: "Access",
508
+ enum: [...ACCESS_LEVELS],
509
+ oneOf: ACCESS_LEVELS.map((level) => ({
510
+ const: level,
511
+ title: ACCESS_LEVEL_INFO[level].title,
512
+ description: ACCESS_LEVEL_INFO[level].description,
513
+ })),
514
+ description: "How much the agent may do without asking in this chat.",
515
+ },
516
+ },
517
+ required: ["level"],
518
+ additionalProperties: false,
519
+ };
520
+ }
521
+
522
+ /**
523
+ * Prepares a change of the level in the plugin that owns what the level applies
524
+ * to: a repository chat opens its worktree before it becomes writable. The
525
+ * action is marked on the in-memory chat only while it is called, so no client
526
+ * offers it. An action that cannot prepare the change refuses it, so the level
527
+ * stays as it was.
528
+ */
529
+ async function prepareAccess(
530
+ ctx: ActionContext,
531
+ chat: ChatData,
532
+ chatId: string,
533
+ level: AccessLevel,
534
+ ): Promise<void> {
535
+ if (chat.accessAction === undefined) return;
536
+ if (ctx.act === undefined) {
537
+ throw new Error(`chat ${chatId} cannot change its access here`);
538
+ }
539
+ const original = ctx.object.data;
540
+ const marked: Record<string, unknown> = { ...original, [ACCESS_ACTION_REQUEST]: true };
541
+ Object.defineProperty(ctx.object, "data", { value: marked, configurable: true, writable: true });
542
+ try {
543
+ await ctx.act(chat.accessAction, { level });
544
+ } finally {
545
+ Object.defineProperty(ctx.object, "data", { value: original, configurable: true, writable: true });
546
+ }
547
+ }
548
+
549
+ /** Why an agent cannot carry a level, in a plain sentence; undefined when it can or its abilities are not known. */
550
+ export function levelRefusal(
551
+ agent: string,
552
+ level: string,
553
+ capabilities: Readonly<Record<string, HarnessCapabilities>> | undefined,
554
+ ): string | undefined {
555
+ const declared = capabilities?.[agent];
556
+ if (declared === undefined) return undefined;
557
+ const carried = declared.accessLevels ?? [];
558
+ if (carried.includes(level)) return undefined;
559
+ return `the agent "${agent}" cannot carry the access level "${level}"; it carries ${carried.length === 0 ? "none" : carried.join(", ")}`;
560
+ }
561
+
562
+ const accessAction: ActionTypeDefinition = {
563
+ name: "access",
564
+ on: CHAT_TYPE,
565
+ command: "Change what the agent may do without asking.",
566
+ args: accessArgs(),
567
+ when: (state) => !chatData(state).closed,
568
+ why: (object) =>
569
+ chatData(object.data).closed ? `${object.id} is closed; its access cannot change` : undefined,
570
+ async run(ctx, args) {
571
+ const stored = await openChat(ctx, "its access cannot change");
572
+ const chat = chatData(stored.data);
573
+ const level = (args as { readonly level?: unknown }).level;
574
+ if (!isAccessLevel(level)) {
575
+ throw new Error(`the access level must be one of ${ACCESS_LEVELS.join(", ")}`);
576
+ }
577
+ // An agent that cannot carry the level is refused now, not at the next reply.
578
+ const refusal = levelRefusal(chat.harness, level, ctx.capabilities);
579
+ if (refusal !== undefined) throw new Error(refusal);
580
+ const from = chat.accessLevel ?? chat.accessDefault ?? "ask";
581
+ if (from === level && chat.accessChosen === true) return `chat ${ctx.object.id} already uses access level ${level}`;
582
+ if (from === level) {
583
+ // Naming the level it already follows is a choice: the chat keeps it when the setting moves.
584
+ await changeChat(ctx, "action:chat/access", (data) => ({ ...data, accessLevel: level, accessChosen: true }));
585
+ return `chat ${ctx.object.id} already uses access level ${level}`;
586
+ }
587
+ await prepareAccess(ctx, chat, ctx.object.id, level);
588
+ const changed: AccessChangedData = {
589
+ by: { via: ctx.actor.via, id: ctx.actor.id },
590
+ from,
591
+ to: level,
592
+ };
593
+ await ctx.facts.append({ type: ACCESS_FACT, object: chatRef(ctx.object.id), data: changed });
594
+ // Read again: a reply may have moved the session while the fact was written.
595
+ await changeChat(ctx, "action:chat/access", (data) => ({ ...data, accessLevel: level, accessChosen: true }));
596
+ // A reply already running reads this file again for each call. The file
597
+ // keeps the base profile, so the new level adds or removes only its own asks.
598
+ const levelPath = accessLevelPath(ctx.home, ctx.object.id);
599
+ try {
600
+ await updateLiveAccessLevel(levelPath, level, withLevelFileDeny(chat.access, levelPath));
601
+ } catch (error) {
602
+ await ctx.logger.write(
603
+ `the live access level could not be written: ${messageOf(error)}`,
288
604
  );
289
605
  }
290
- return `chat ${ctx.object.id} now uses effort ${effort}; the next reply uses it`;
606
+ return `chat ${ctx.object.id} now uses access level ${level}; replies follow it`;
291
607
  },
292
608
  };
293
609
 
294
610
  const closeAction: ActionTypeDefinition = {
295
611
  name: "close",
296
612
  on: CHAT_TYPE,
613
+ command: "Close this chat.",
297
614
  confirm: true,
298
615
  ends: true,
299
616
  when: (state) => !chatData(state).closed,
300
617
  why: (object) =>
301
618
  chatData(object.data).closed ? `${object.id} is closed; nothing to close` : undefined,
302
619
  async run(ctx) {
303
- const stored = await ctx.store.get(CHAT_TYPE, ctx.object.id);
304
- if (stored === undefined) throw new Error(`there is no chat ${ctx.object.id}`);
620
+ const stored = await storedChat(ctx);
305
621
  if (chatData(stored.data).closed) return `chat ${ctx.object.id} is closed; nothing to close`;
306
622
  const closed: ClosedData = {
307
623
  by: { via: ctx.actor.via, id: ctx.actor.id },
308
624
  };
625
+ const chat = chatData(stored.data);
309
626
  await ctx.facts.append({ type: CLOSED_FACT, object: chatRef(ctx.object.id), data: closed });
310
627
  // Read again: a reply may have moved the session while the fact was written.
311
- const fresh = await ctx.store.get(CHAT_TYPE, ctx.object.id);
312
- if (fresh !== undefined && !chatData(fresh.data).closed) {
313
- await ctx.store.put(CHAT_TYPE, ctx.object.id, { ...fresh.data, closed: true }, "action:chat/close");
314
- }
628
+ await changeChat(ctx, "action:chat/close", (data) =>
629
+ chatData(data).closed ? undefined : { ...data, closed: true },
630
+ );
631
+ await endKeptWorker(ctx.home, chat, ctx.object.id);
315
632
  return `closed ${ctx.object.id}`;
316
633
  },
317
634
  };
318
635
 
636
+ const stopAction: ActionTypeDefinition = {
637
+ name: "stop",
638
+ on: CHAT_TYPE,
639
+ command: "Stop the reply being written.",
640
+ when: (state) => !chatData(state).closed,
641
+ why: (object) =>
642
+ chatData(object.data).closed ? `${object.id} is closed; there is no reply to stop` : undefined,
643
+ async run(ctx) {
644
+ const stored = await openChat(ctx, "there is no reply to stop");
645
+ const chat = chatData(stored.data);
646
+ const runId = latestRunOf(chatFacts(ctx.store, ctx.object.id));
647
+ if (runId === undefined) return "no reply is running";
648
+ if (ctx.runs === undefined) throw new Error("this client cannot stop a reply");
649
+ const stopped = await ctx.runs.cancel(runId);
650
+ if (stopped !== true) return "no reply is running";
651
+ const data: StopData = {
652
+ runId,
653
+ by: { via: ctx.actor.via, id: ctx.actor.id },
654
+ };
655
+ await ctx.facts.append({ type: STOP_FACT, object: chatRef(ctx.object.id), data });
656
+ await endKeptWorker(ctx.home, chat, ctx.object.id);
657
+ return "stopped the reply; what was written stays in the transcript. Messages that arrived meanwhile are not answered by themselves; send /retry to answer the last message";
658
+ },
659
+ };
660
+
661
+ /** A token count: whole below 10k, then in k with one decimal. */
662
+ function tokenCount(count: number): string {
663
+ return count < 10_000 ? String(count) : `${(count / 1000).toFixed(1)}k`;
664
+ }
665
+
666
+ /** The token usage part of a status line, or that no agent reported it. */
667
+ function statusTokens(tokens: UsageTokens | undefined, incomplete = false): string {
668
+ if (tokens === undefined) return "tokens unknown";
669
+ return `${incomplete ? "at least " : ""}${tokenCount(tokens.input)} in / ${tokenCount(tokens.output)} out tokens`;
670
+ }
671
+
672
+ /** When a running reply began, in UTC, to the second. */
673
+ function statusClock(at: number): string {
674
+ return new Date(at).toISOString().slice(0, 19).replace("T", " ");
675
+ }
676
+
677
+ /** What `/status` says: a few lines read from the chat's record and its agent's declared effort. */
678
+ function statusText(
679
+ chat: ChatData,
680
+ messages: readonly Message[],
681
+ facts: readonly PluginFact[],
682
+ writing: WritingReply | undefined,
683
+ effort: string | undefined,
684
+ ): string {
685
+ const last = [...messages].reverse().find((message) => message.role === "assistant");
686
+ const model = chat.model ?? chat.lastModel;
687
+ const waiting = unanswered(messages, facts).length;
688
+ const first = firstOutputMs(last?.timings);
689
+ const lastUsage =
690
+ last === undefined
691
+ ? []
692
+ : [
693
+ last.costMicros === undefined
694
+ ? "cost unknown"
695
+ : costText(last.costMicros, last.costQuality),
696
+ statusTokens(last.tokens),
697
+ ...(first === undefined ? [] : [`first output ${formatElapsed(first)}`]),
698
+ ];
699
+ return [
700
+ `Agent: ${chat.harness}`,
701
+ `Model: ${model ?? "unknown"}`,
702
+ `Effort: ${effort ?? "unknown"}`,
703
+ `Reply: ${writing === undefined ? "not writing" : `writing since ${statusClock(writing.since)}`}`,
704
+ `Waiting: ${waiting} ${waiting === 1 ? "message" : "messages"}`,
705
+ `Cost: ${chat.costMicros === undefined ? "unknown" : costText(chat.costMicros, chat.costQuality)} · ${statusTokens(chat.tokens, chat.tokensIncomplete === true)}`,
706
+ `Last reply: ${last === undefined ? "none" : lastUsage.join(" · ")}`,
707
+ ].join("\n");
708
+ }
709
+
710
+ const statusAction: ActionTypeDefinition = {
711
+ name: "status",
712
+ on: CHAT_TYPE,
713
+ command: "Show where this chat stands and what it has used.",
714
+ when: (state) => !chatData(state).closed,
715
+ why: (object) =>
716
+ chatData(object.data).closed ? `${object.id} is closed; there is no status to show` : undefined,
717
+ async run(ctx) {
718
+ const stored = await openChat(ctx, "there is no status to show");
719
+ const read = readChat(ctx.store, ctx.object.id);
720
+ const facts = read.facts;
721
+ const messages = read.messages;
722
+ const entries = read.entries;
723
+ const writing = await writingReplyNow(facts, messages, entries, ctx.runs);
724
+ const chat = chatData(stored.data);
725
+ return statusText(
726
+ chat,
727
+ messages,
728
+ facts,
729
+ writing,
730
+ effectiveEffort(chat, ctx.efforts[chat.harness]),
731
+ );
732
+ },
733
+ };
734
+
735
+ /** Why `chat:retry` would start no reply now; absent when it would start one. */
736
+ type RetryRefusal = "closed" | "finished" | "no-attempt" | "writing";
737
+
738
+ /** What `chat:retry` would do now: start a reply for `runId`, or why it starts none. */
739
+ interface RetryCheck {
740
+ readonly refused?: RetryRefusal | undefined;
741
+ /** The attempt a retry answers again, so a repeated command starts no second reply. */
742
+ readonly runId?: string | undefined;
743
+ }
744
+
745
+ /**
746
+ * Whether `chat:retry` would start a reply now, read the same way by the
747
+ * action's offer, its `why` and its run: the chat is open, a message waits for
748
+ * a reply, the last attempt failed, was stopped or was interrupted, and no
749
+ * reply is being written. A stop records its fact before the reply's own
750
+ * stopping finishes, so that fact counts before the stopped half reply is in
751
+ * the record.
752
+ */
753
+ async function retryCheck(
754
+ store: ObjectStore,
755
+ id: string,
756
+ chat: ChatData,
757
+ runs?: Pick<RunControl, "active"> | undefined,
758
+ ): Promise<RetryCheck> {
759
+ if (chat.closed) return { refused: "closed" };
760
+ const read = readChat(store, id);
761
+ const messages = read.messages;
762
+ const facts = read.facts;
763
+ if (unanswered(messages, facts).length === 0) return { refused: "finished" };
764
+ const entries = read.entries;
765
+ let last = lastReplyOutcome(messages, entries);
766
+ if (last.kind !== "failed" && last.kind !== "stopped") {
767
+ const lastUser = [...messages].reverse().find((message) => message.role === "user");
768
+ const stoppedRun = lastUser === undefined ? undefined : stoppedRunAfter(facts, lastUser.sequence);
769
+ if (stoppedRun !== undefined) last = { kind: "stopped", runId: stoppedRun };
770
+ }
771
+ if (last.kind === "normal") return { refused: "finished" };
772
+ if (last.kind !== "failed" && last.kind !== "stopped") return { refused: "no-attempt" };
773
+ if ((await writingReplyNow(facts, messages, entries, runs)) !== undefined) return { refused: "writing" };
774
+ return last.runId === undefined ? {} : { runId: last.runId };
775
+ }
776
+
777
+ /** The line a refused `chat:retry` answers with, for its `why` and its run alike. */
778
+ function retryRefusalLine(refused: RetryRefusal, id: string): string {
779
+ switch (refused) {
780
+ case "closed":
781
+ return `chat ${id} is closed; there is nothing to retry`;
782
+ case "finished":
783
+ return "the last reply finished normally; there is nothing to retry";
784
+ case "no-attempt":
785
+ return "the last reply has not failed or stopped; there is nothing to retry";
786
+ case "writing":
787
+ return `chat ${id} is writing a reply; retry is offered once it ends`;
788
+ }
789
+ }
790
+
791
+ const retryAction: ActionTypeDefinition = {
792
+ name: "retry",
793
+ on: CHAT_TYPE,
794
+ command: "Answer the last message again after a reply failed, was stopped or was interrupted.",
795
+ // The offer answers the same question the run does: would this start a reply?
796
+ when: async (state, env) =>
797
+ env.object !== undefined &&
798
+ (await retryCheck(env.store, env.object.id, chatData(state), env.runs)).refused === undefined,
799
+ why: async (object, env) => {
800
+ const refused = (await retryCheck(env.store, object.id, chatData(object.data), env.runs)).refused;
801
+ return refused === undefined ? undefined : retryRefusalLine(refused, object.id);
802
+ },
803
+ async run(ctx) {
804
+ const stored = await ctx.store.get(CHAT_TYPE, ctx.object.id);
805
+ if (stored === undefined) throw new Error(`there is no chat ${ctx.object.id}`);
806
+ // The offer said a reply would start; a reply may have begun since, so the
807
+ // run asks the same question again.
808
+ const check = await retryCheck(ctx.store, ctx.object.id, chatData(stored.data), ctx.runs);
809
+ if (check.refused !== undefined) throw new Error(retryRefusalLine(check.refused, ctx.object.id));
810
+ if (ctx.emit === undefined) {
811
+ throw new Error("the reply cannot be started here; operad serve is not running");
812
+ }
813
+ const known = CHAT_SOURCES.find((name) => name === ctx.actor.via);
814
+ const source = known ?? OTHER_SOURCE;
815
+ const key = check.runId === undefined ? newMessageId() : `retry:${check.runId}`;
816
+ await ctx.emit({
817
+ source,
818
+ type: MESSAGE_EVENT,
819
+ key,
820
+ object: `${CHAT_TYPE}:${ctx.object.id}`,
821
+ });
822
+ return "retrying the last message";
823
+ },
824
+ };
825
+
826
+ const helpAction: ActionTypeDefinition = {
827
+ name: "help",
828
+ on: CHAT_TYPE,
829
+ command: "What you can type with `/`.",
830
+ when: (state) => !chatData(state).closed,
831
+ why: (object) =>
832
+ chatData(object.data).closed ? `${object.id} is closed; it takes no commands` : undefined,
833
+ async run(ctx) {
834
+ const skills = await readChatSkills(
835
+ chatData(ctx.object.data),
836
+ async (type, id) => ctx.store.get(type, id),
837
+ );
838
+ return helpText(chatCommands(ctx.actions ?? []), skills);
839
+ },
840
+ };
841
+
319
842
  /** Builds the chat plugin. */
320
843
  export function createChatPlugin() {
321
844
  return definePlugin({
@@ -328,6 +851,7 @@ export function createChatPlugin() {
328
851
  properties: {
329
852
  speaker: {
330
853
  type: "string",
854
+ title: "Speaker name",
331
855
  minLength: 1,
332
856
  default: "Operad Bot",
333
857
  editable: true,
@@ -338,6 +862,14 @@ export function createChatPlugin() {
338
862
  additionalProperties: false,
339
863
  },
340
864
  steps: [
865
+ {
866
+ name: "keep",
867
+ resumable: false,
868
+ // The chat's `refresh` step and the after step it names are named by data.
869
+ callsNamedByData: true,
870
+ results: ["done", "failed"],
871
+ run: keepInterrupted,
872
+ },
341
873
  {
342
874
  name: "reply",
343
875
  // The harness's question comes back as `resumeSession` and `askAnswer`.
@@ -353,14 +885,25 @@ export function createChatPlugin() {
353
885
  flows: [replyFlow],
354
886
  // A message from a client or a channel is answered without anyone starting
355
887
  // the answer; a user rule for the same source and type replaces these.
356
- rules: [...CHAT_SOURCES, OTHER_SOURCE].map((source) => ({
357
- source,
358
- type: MESSAGE_EVENT,
359
- start: { flow: "chat:reply" },
360
- object: "$event.object",
361
- mode: "auto" as const,
362
- })),
363
- actions: [sendAction, modelAction, effortAction, closeAction],
888
+ rules: [
889
+ ...[...CHAT_SOURCES, OTHER_SOURCE].map((source) => ({
890
+ source,
891
+ type: MESSAGE_EVENT,
892
+ start: { flow: "chat:reply" },
893
+ object: "$event.object",
894
+ mode: "auto" as const,
895
+ })),
896
+ // The plugin that owns the working directory opened the chat's worktree;
897
+ // answer the message that asked the worktree question again there.
898
+ {
899
+ source: "operad",
900
+ type: WORKTREE_REPLY_EVENT,
901
+ start: { flow: "chat:reply" },
902
+ object: "$event.object",
903
+ mode: "auto" as const,
904
+ },
905
+ ],
906
+ actions: [sendAction, withdrawAction, editAction, modelAction, effortAction, accessAction, stopAction, retryAction, statusAction, closeAction, helpAction],
364
907
  views: { [CHAT_TYPE]: chatViews },
365
908
  });
366
909
  }
@@ -368,6 +911,10 @@ export function createChatPlugin() {
368
911
  export default createChatPlugin();
369
912
 
370
913
  export * from "./model.ts";
914
+ export * from "./notes.ts";
915
+ export * from "./command.ts";
916
+ export * from "./queue.ts";
371
917
  export * from "./reply.ts";
918
+ export * from "./skills.ts";
372
919
  export * from "./views.ts";
373
920
  export * from "./tail.ts";