@operad-io/chat 0.2.0 → 0.3.1

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/package.json CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "name": "@operad-io/chat",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./src/index.ts"
7
7
  },
8
8
  "dependencies": {
9
- "@operad-io/access-match": "0.2.0",
10
- "@operad-io/engine": "0.2.0",
11
- "@operad-io/harness-process": "0.2.0"
9
+ "@operad-io/access-match": "0.3.1",
10
+ "@operad-io/engine": "0.3.1",
11
+ "@operad-io/harness-process": "0.3.1"
12
12
  },
13
13
  "description": "operad: the chat plugin",
14
14
  "repository": {
@@ -17,8 +17,8 @@
17
17
  "directory": "packages/chat"
18
18
  },
19
19
  "devDependencies": {
20
- "@operad-io/harness-claude": "0.2.0",
21
- "@operad-io/harness-pi": "0.2.0"
20
+ "@operad-io/harness-claude": "0.3.1",
21
+ "@operad-io/harness-pi": "0.3.1"
22
22
  },
23
23
  "license": "MIT",
24
24
  "files": [
package/src/index.ts CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  import { messageOf } from "@operad-io/engine";
4
4
  import pkg from "../package.json" with { type: "json" };
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";
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
6
  import { ACCESS_LEVELS, isAccessLevel, updateLiveAccessLevel, type AccessLevel } from "@operad-io/access-match";
7
7
  import { stopKeptWorkers } from "@operad-io/engine/platform";
8
8
  import {
@@ -177,6 +177,7 @@ export async function sendMessage(
177
177
  note: string,
178
178
  ref?: string,
179
179
  files: readonly string[] = [],
180
+ instruction?: string,
180
181
  ): Promise<string> {
181
182
  const via = ctx.actor.via;
182
183
  // The message records who sent it as it is; the event uses the source its
@@ -191,6 +192,7 @@ export async function sendMessage(
191
192
  text: note,
192
193
  attachments: files.map((path) => attachmentOf(path)),
193
194
  source: { kind: via, ref: ref ?? null },
195
+ ...(instruction === undefined || instruction.length === 0 ? {} : { instruction }),
194
196
  };
195
197
  // The message is a fact first; the event is what starts the answer.
196
198
  const record = async (): Promise<void> => {
@@ -544,6 +546,19 @@ async function prepareAccess(
544
546
  }
545
547
  }
546
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
+
547
562
  const accessAction: ActionTypeDefinition = {
548
563
  name: "access",
549
564
  on: CHAT_TYPE,
@@ -559,6 +574,9 @@ const accessAction: ActionTypeDefinition = {
559
574
  if (!isAccessLevel(level)) {
560
575
  throw new Error(`the access level must be one of ${ACCESS_LEVELS.join(", ")}`);
561
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);
562
580
  const from = chat.accessLevel ?? chat.accessDefault ?? "ask";
563
581
  if (from === level && chat.accessChosen === true) return `chat ${ctx.object.id} already uses access level ${level}`;
564
582
  if (from === level) {
package/src/model.ts CHANGED
@@ -422,6 +422,8 @@ export interface MessageData {
422
422
  readonly source: { readonly kind: string; readonly ref: string | null };
423
423
  /** An assistant message: the ids of the messages it answers. */
424
424
  readonly replyTo?: readonly string[] | undefined;
425
+ /** A user message: text only the agent is given after the text; no view shows it. */
426
+ readonly instruction?: string | undefined;
425
427
  /** The run whose answer this message or entry belongs to. */
426
428
  readonly runId?: string | undefined;
427
429
  /** An assistant message: the harness session after it. */
@@ -1033,6 +1035,9 @@ function messageOfFact(fact: PluginFact): Message | undefined {
1033
1035
  ref: typeof source.ref === "string" ? source.ref : null,
1034
1036
  },
1035
1037
  ...(Array.isArray(data.replyTo) ? { replyTo: stringList(data.replyTo) } : {}),
1038
+ ...(data.role === "user" && typeof data.instruction === "string" && data.instruction.length > 0
1039
+ ? { instruction: data.instruction }
1040
+ : {}),
1036
1041
  ...(typeof data.runId === "string" && data.runId.length > 0 ? { runId: data.runId } : {}),
1037
1042
  ...(typeof data.session === "string" ? { session: data.session } : {}),
1038
1043
  ...(typeof data.model === "string" && data.model.length > 0 ? { model: data.model } : {}),
@@ -1366,7 +1371,7 @@ export const PROMPT_MESSAGE_SEPARATOR = "\n\n---\n\n";
1366
1371
  */
1367
1372
  export function promptFor(pending: readonly Message[], images: ReadonlySet<string> = new Set()): string {
1368
1373
  const parts = pending.map((message) =>
1369
- [message.text, attachmentLines(message, images)].filter((part) => part.length > 0).join("\n\n"),
1374
+ [message.text, attachmentLines(message, images), typeof message.instruction === "string" ? message.instruction : ""].filter((part) => part.length > 0).join("\n\n"),
1370
1375
  );
1371
1376
  return parts.join(PROMPT_MESSAGE_SEPARATOR);
1372
1377
  }
package/src/reply.ts CHANGED
@@ -479,6 +479,12 @@ function levelAsker(
479
479
  };
480
480
  }
481
481
 
482
+ /** Whether the chat's working directory is no longer `cwd`, the one this reply started in. */
483
+ async function movedFrom(ctx: StepContext, chatId: string, cwd: string): Promise<boolean> {
484
+ const stored = await ctx.store.get(CHAT_TYPE, chatId);
485
+ return stored !== undefined && chatData(stored.data).cwd !== cwd;
486
+ }
487
+
482
488
  /**
483
489
  * The asker a read-only chat's harness gets: a question about writing a file
484
490
  * becomes the worktree question, which may let this call run once, remember it
@@ -490,6 +496,7 @@ function levelAsker(
490
496
  */
491
497
  function readOnlyAsker(
492
498
  ctx: StepContext,
499
+ chatId: string,
493
500
  cwd: string,
494
501
  chosen: { run: boolean; readonly stop: AbortController },
495
502
  inner: StepAsker,
@@ -498,6 +505,14 @@ function readOnlyAsker(
498
505
  return {
499
506
  async ask(request): Promise<AskOutcome> {
500
507
  if (chosen.run) throw new WorktreeChosen();
508
+ // The chat moved to its worktree while this reply ran, so what this
509
+ // reply asks is judged by the main clone's profile and its directory.
510
+ // The reply ends and is answered again in the worktree.
511
+ if (await movedFrom(ctx, chatId, cwd)) {
512
+ chosen.run = true;
513
+ chosen.stop.abort();
514
+ throw new WorktreeChosen();
515
+ }
501
516
  const write = isWriteQuestion(request);
502
517
  const call = write ? worktreeCall(request) : undefined;
503
518
  // An entry from an earlier Always allow lifts the question in any chat a person started.
@@ -517,7 +532,15 @@ function readOnlyAsker(
517
532
  ...(request.graceSecs === undefined ? {} : { graceSecs: request.graceSecs }),
518
533
  }
519
534
  : request;
520
- const outcome = await inner.ask(shaped);
535
+ // A question open when the chat moves to its worktree ends with the reply.
536
+ const outcome = await Promise.race([
537
+ inner.ask(shaped),
538
+ new Promise<never>((_resolve, reject) => {
539
+ const end = (): void => reject(new WorktreeChosen());
540
+ if (chosen.stop.signal.aborted) end();
541
+ else chosen.stop.signal.addEventListener("abort", end, { once: true });
542
+ }),
543
+ ]);
521
544
  if (outcome.kind === "timeout") return outcome;
522
545
  const answer = outcome.answer;
523
546
  if (shaped === request) return outcome;
@@ -614,6 +637,8 @@ interface Live {
614
637
  readonly notes?: readonly NoteFile[] | undefined;
615
638
  /** The level a chat that chose none starts at now; a bot gives its setting. */
616
639
  readonly accessDefault?: AccessLevel | undefined;
640
+ /** False when the chat works in its main clone and no worktree is to be offered. */
641
+ readonly worktreeOffer?: boolean | undefined;
617
642
  /** A plugin step to call after the round ends, when the chat's refresh step names one. */
618
643
  readonly after?: string | undefined;
619
644
  }
@@ -683,6 +708,7 @@ async function liveSettings(
683
708
  const accessDefault = isAccessLevel(data.accessDefault) ? data.accessDefault : undefined;
684
709
  return {
685
710
  ...(accessDefault === undefined ? {} : { accessDefault }),
711
+ ...(data.worktreeOffer === false ? { worktreeOffer: false } : {}),
686
712
  cwd: data.cwd,
687
713
  access: data.access as Record<string, JsonValue>,
688
714
  skills: data.skills.filter((item): item is string => typeof item === "string"),
@@ -1373,7 +1399,12 @@ async function replyOnce(
1373
1399
  pending = unanswered(messages, fresh.facts).filter((message) => !arrived.has(message.id));
1374
1400
  }
1375
1401
 
1402
+ let stopWatching: (() => void) | undefined;
1376
1403
  const closeMidRun = async (): Promise<void> => {
1404
+ if (stopWatching !== undefined) {
1405
+ stopWatching();
1406
+ stopWatching = undefined;
1407
+ }
1377
1408
  if (stopMidRun !== undefined) {
1378
1409
  stopMidRun();
1379
1410
  stopMidRun = undefined;
@@ -1390,12 +1421,27 @@ async function replyOnce(
1390
1421
  const readOnly = leveled.readOnly === true;
1391
1422
  // The worktree question belongs to a repository chat; a bot chat at `plan`
1392
1423
  // is read-only without one.
1393
- const worktreeChat = readOnly && (chat.parent === undefined || chat.parent.startsWith("repo:"));
1424
+ const worktreeChat =
1425
+ readOnly && live.worktreeOffer !== false && (chat.parent === undefined || chat.parent.startsWith("repo:"));
1394
1426
  const worktreeChosen = { run: false, stop: new AbortController() };
1395
1427
  // The live file holds the base profile; a level change rewrites only its level.
1396
1428
  let recheckBase: Readonly<Record<string, JsonValue>> = live.access;
1397
1429
  const withLevel = levelAsker(ctx, object.id, live.cwd, () => recheckBase, level, contextAsker(ctx));
1398
- const asker = worktreeChat ? readOnlyAsker(ctx, live.cwd, worktreeChosen, withLevel) : withLevel;
1430
+ const asker = worktreeChat ? readOnlyAsker(ctx, object.id, live.cwd, worktreeChosen, withLevel) : withLevel;
1431
+ if (worktreeChat) {
1432
+ // A level change opens the worktree before it is recorded. This reply runs
1433
+ // in the main clone with the profile it started with, so when the chat has
1434
+ // moved it ends and is answered again there, rather than going on in the
1435
+ // main clone or asking again as read-only.
1436
+ stopWatching = ctx.store.subscribe(chatRef(object.id), {}, (fact) => {
1437
+ if (fact.type !== ACCESS_FACT || worktreeChosen.run) return;
1438
+ void movedFrom(ctx, object.id, live.cwd).then((moved) => {
1439
+ if (!moved || worktreeChosen.run) return;
1440
+ worktreeChosen.run = true;
1441
+ worktreeChosen.stop.abort();
1442
+ });
1443
+ });
1444
+ }
1399
1445
  // A worktree yes aborts `stop`, so the harness ends even if it swallows the
1400
1446
  // stop error; the reply still ends `done` below.
1401
1447
  const signal = worktreeChat ? AbortSignal.any([ctx.signal, worktreeChosen.stop.signal]) : ctx.signal;
package/src/views.ts CHANGED
@@ -229,6 +229,8 @@ export interface ReplyMessage {
229
229
  readonly text: string;
230
230
  /** When it was recorded, in milliseconds since the epoch. */
231
231
  readonly at: number;
232
+ /** `true` when the text was shortened to fit the size cap; read the page with `full=true` for it whole. */
233
+ readonly cut?: true | undefined;
232
234
  }
233
235
 
234
236
  /** The recorded start of a tool call's output and how many lines it has. */
@@ -247,12 +249,16 @@ export interface ReplyThinkingItem {
247
249
  readonly kind: "thinking";
248
250
  readonly text: string;
249
251
  readonly at?: number | undefined;
252
+ /** `true` when the text was shortened to fit the size cap. */
253
+ readonly cut?: true | undefined;
250
254
  }
251
255
 
252
256
  export interface ReplyTextItem {
253
257
  readonly kind: "text";
254
258
  readonly text: string;
255
259
  readonly at?: number | undefined;
260
+ /** `true` when the text was shortened to fit the size cap. */
261
+ readonly cut?: true | undefined;
256
262
  }
257
263
 
258
264
  export interface ReplyToolItem {
@@ -268,6 +274,8 @@ export interface ReplyToolItem {
268
274
  /** Absent while the call is still running. */
269
275
  readonly result?: ToolResult | undefined;
270
276
  readonly output: ReplyOutput;
277
+ /** `true` when the input was shortened to fit the size cap. */
278
+ readonly cut?: true | undefined;
271
279
  }
272
280
 
273
281
  export type ReplyItem = ReplyThinkingItem | ReplyTextItem | ReplyToolItem;
@@ -592,16 +600,19 @@ function jsonBytes(value: unknown): number {
592
600
  * The transcript's data, cut to fit its budget: tool output text first, then
593
601
  * the other reply text, and at last the oldest reply blocks. A read that still
594
602
  * did not fit would be refused, so this always answers within the budget.
603
+ * Every reply is measured once and a running total is kept, so the work is
604
+ * linear in the size of the page; `measure` is a seam for tests.
595
605
  */
596
- function replyData(
606
+ export function replyData(
597
607
  replies: readonly ReplyBlock[],
598
608
  maxBytes: number,
599
609
  base: Readonly<Record<string, JsonValue>> = {},
610
+ measure: (value: unknown) => number = jsonBytes,
600
611
  ): Readonly<Record<string, JsonValue>> {
601
612
  const data = (shown: readonly ReplyBlock[], extra: Readonly<Record<string, JsonValue>> = base) =>
602
613
  ({ ...extra, replies: shown }) as unknown as Readonly<Record<string, JsonValue>>;
603
614
  const whole = data(replies);
604
- if (jsonBytes(whole) <= maxBytes) return whole;
615
+ if (measure(whole) <= maxBytes) return whole;
605
616
  // A tool's output is the largest part and the least useful to a structured
606
617
  // client, so it goes first, keeping its line count and `truncated`.
607
618
  const blanked = replies.map((reply) => ({
@@ -617,55 +628,109 @@ function replyData(
617
628
  }),
618
629
  })),
619
630
  }));
620
- if (jsonBytes(data(blanked)) <= maxBytes) return data(blanked);
621
- // Thinking, text, input and answer text are shortened next, in steps, so a
622
- // long absence still leaves every reply's structure.
623
- for (const cap of [512, 128, 32, 0]) {
624
- const cut = blanked.map((reply) => cutReply(reply, cap));
625
- if (jsonBytes(data(cut)) <= maxBytes) return data(cut);
631
+ // The page's size is the wrapper (the base and an empty list), each reply,
632
+ // and the commas between replies; each part is measured once.
633
+ const overhead = measure(data([]));
634
+ const sizes = blanked.map((reply) => measure(reply));
635
+ let sum = sizes.reduce((total, size) => total + size, 0);
636
+ const sizeOf = (count: number, inner: number): number => overhead + inner + Math.max(0, count - 1);
637
+ if (sizeOf(blanked.length, sum) <= maxBytes) return data(blanked);
638
+ // Shortening goes in three passes, each the oldest reply first and whole
639
+ // reply by whole reply, so the newest stays whole the longest. Pass 1
640
+ // shortens everything that is not an answer (thinking, text, tool input and
641
+ // the input messages, which keep a preview). Pass 2 shortens answers to a
642
+ // preview of about two lines. Pass 3 goes below the preview, and only then
643
+ // are replies dropped.
644
+ const cuts: ReplyBlock[] = [...blanked];
645
+ const step = (at: number, caps: ReplyCaps): boolean => {
646
+ const original = cuts[at];
647
+ if (original === undefined) return false;
648
+ const cut = cutReply(original, caps);
649
+ const size = measure(cut);
650
+ sum += size - (sizes[at] ?? 0);
651
+ sizes[at] = size;
652
+ cuts[at] = cut;
653
+ return sizeOf(cuts.length, sum) <= maxBytes;
654
+ };
655
+ const passes: readonly (readonly ReplyCaps[])[] = [
656
+ FREE_CAPS.map((free) => ({ free, input: Math.max(free, PREVIEW_BYTES), answer: Infinity })),
657
+ [{ free: 0, input: PREVIEW_BYTES, answer: PREVIEW_BYTES }],
658
+ [64, 0].map((all) => ({ free: all, input: all, answer: all })),
659
+ ];
660
+ for (const pass of passes) {
661
+ for (let at = 0; at < cuts.length; at += 1) {
662
+ for (const caps of pass) if (step(at, caps)) return data(cuts);
663
+ }
626
664
  }
627
665
  // Even empty text leaves too much structure: the oldest replies go.
628
- for (let drop = 1; drop <= blanked.length; drop += 1) {
629
- const kept = blanked.slice(drop);
630
- const cut = kept.map((reply) => cutReply(reply, 0));
631
- if (jsonBytes(data(cut)) <= maxBytes) return data(cut);
666
+ for (let drop = 1; drop <= cuts.length; drop += 1) {
667
+ sum -= sizes[drop - 1] ?? 0;
668
+ if (sizeOf(cuts.length - drop, sum) <= maxBytes) return data(cuts.slice(drop));
632
669
  }
633
- const empty = data([]);
634
- if (jsonBytes(empty) <= maxBytes) return empty;
635
670
  // The base is the only thing left; it is small in every caller but is cut
636
671
  // last rather than letting the read be refused.
637
- return (jsonBytes({ replies: [] }) <= maxBytes ? { replies: [] } : {}) as Readonly<Record<string, JsonValue>>;
672
+ if (overhead <= maxBytes) return data([]);
673
+ return (measure({ replies: [] }) <= maxBytes ? { replies: [] } : {}) as Readonly<Record<string, JsonValue>>;
638
674
  }
639
675
 
640
- /** Text cut to fit a byte budget, ending with an ellipsis when it was longer. */
676
+ /** The preview an older reply's answer and input keep while anything else can still be cut: about two lines. */
677
+ const PREVIEW_BYTES = 200;
678
+ const FREE_CAPS: readonly number[] = [128, 0];
679
+
680
+ /** Byte caps for the three kinds of text in a reply; `Infinity` leaves a kind whole. */
681
+ interface ReplyCaps {
682
+ readonly free: number;
683
+ readonly input: number;
684
+ readonly answer: number;
685
+ }
686
+
687
+ /**
688
+ * Text cut to fit a byte budget, ending with an ellipsis when it was longer.
689
+ * The cut is at a line or sentence end when one is in the last quarter of what
690
+ * fits, and never inside a code point.
691
+ */
641
692
  function shorten(text: string, capBytes: number): string {
642
693
  if (capBytes <= 0) return "";
643
694
  if (Buffer.byteLength(text, "utf8") <= capBytes) return text;
644
695
  if (capBytes <= 3) return "";
645
696
  let end = Math.min(text.length, capBytes);
646
697
  while (end > 0 && Buffer.byteLength(text.slice(0, end), "utf8") + 3 > capBytes) end -= 1;
647
- return end === 0 ? "" : `${text.slice(0, end)}…`;
648
- }
649
-
650
- /** One reply with its free text cut to a budget and its tool output left empty. */
651
- function cutReply(reply: ReplyBlock, capBytes: number): ReplyBlock {
652
- const message = (block: ReplyMessage): ReplyMessage => ({
653
- ...block,
654
- text: shorten(block.text, capBytes),
655
- });
698
+ const last = text.charCodeAt(end - 1);
699
+ if (end > 0 && last >= 0xd800 && last <= 0xdbff) end -= 1;
700
+ if (end === 0) return "";
701
+ const head = text.slice(0, end);
702
+ const floor = Math.floor(end * 0.75);
703
+ const newline = head.lastIndexOf("\n");
704
+ if (newline > 0 && newline >= floor) {
705
+ const line = head.slice(0, newline).trimEnd();
706
+ if (line !== "") return `${line}…`;
707
+ }
708
+ const sentence = /[.!?。!?](?=\s|$)/g;
709
+ let stop = -1;
710
+ for (let found = sentence.exec(head); found !== null; found = sentence.exec(head)) stop = found.index + 1;
711
+ if (stop > 0 && stop >= floor) return `${head.slice(0, stop)}…`;
712
+ return `${head}…`;
713
+ }
714
+
715
+ /** One reply with its free text cut to a budget; every text that got shorter says `cut`. */
716
+ function cutReply(reply: ReplyBlock, caps: ReplyCaps): ReplyBlock {
717
+ const text = (original: string, capBytes: number): { readonly text: string; readonly cut?: true } => {
718
+ const shortened = shorten(original, capBytes);
719
+ return shortened === original ? { text: shortened } : { text: shortened, cut: true };
720
+ };
721
+ const message = (block: ReplyMessage, capBytes: number): ReplyMessage => ({ ...block, ...text(block.text, capBytes) });
656
722
  const item = (entry: ReplyItem): ReplyItem => {
657
723
  if (entry.kind === "tool") {
658
- return {
659
- ...entry,
660
- input: entry.input === null ? null : shorten(entry.input, capBytes),
661
- };
724
+ if (entry.input === null) return entry;
725
+ const shortened = shorten(entry.input, caps.free);
726
+ return shortened === entry.input ? entry : { ...entry, input: shortened, cut: true };
662
727
  }
663
- return { ...entry, text: shorten(entry.text, capBytes) };
728
+ return { ...entry, ...text(entry.text, caps.free) };
664
729
  };
665
730
  return {
666
731
  ...reply,
667
- input: reply.input.map(message),
668
- ...(reply.answer === undefined ? {} : { answer: message(reply.answer) }),
732
+ input: reply.input.map((block) => message(block, caps.input)),
733
+ ...(reply.answer === undefined ? {} : { answer: message(reply.answer, caps.answer) }),
669
734
  process: reply.process.map((group) => ({
670
735
  ...group,
671
736
  items: group.items.map(item),