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