@notation/factory 0.5.1 → 0.5.3

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.
@@ -65,6 +65,12 @@ export type RuntimeRunner = {
65
65
  * them. Without it, the runner posts only the final reply.
66
66
  */
67
67
  message?(line: string): string | undefined;
68
+ /**
69
+ * Reads one line of the CLI's output while it runs, and returns the
70
+ * model's name or id, if the line has it. The runner shows the model
71
+ * under the agent's messages.
72
+ */
73
+ model?(line: string): string | undefined;
68
74
  /** Extra environment for the CLI. */
69
75
  env?: Record<string, string>;
70
76
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@notation/factory",
3
- "version": "0.5.1",
3
+ "version": "0.5.3",
4
4
  "author": "Daniel Grant",
5
5
  "license": "MIT",
6
6
  "repository": {
package/runner/index.ts CHANGED
@@ -36,6 +36,9 @@ const BIN = join(DATA, "bin");
36
36
  /** The shortest time between two posts of an agent's messages during a run. Each post edits the run's message on the conversation. */
37
37
  const PROGRESS_INTERVAL_MS = Number(process.env.FACTORY_PROGRESS_INTERVAL_MS ?? 10 * 1000);
38
38
 
39
+ /** How often the runner edits the run's message to update its clock, while the agent writes no new message. */
40
+ const CLOCK_INTERVAL_MS = Number(process.env.FACTORY_CLOCK_INTERVAL_MS ?? 60 * 1000);
41
+
39
42
  /** The longest the runner waits, once it's told to stop, for the replies that say its runs were lost. */
40
43
  const STOP_REPLY_TIMEOUT_MS = 5000;
41
44
 
@@ -573,7 +576,7 @@ const runAgent = async (
573
576
  adapter: RuntimeRunner,
574
577
  run: Run,
575
578
  { cwd, configDir, prompt, sessionId }: { cwd: string; configDir: string; prompt: string; sessionId?: string },
576
- onMessage: (text: string) => void,
579
+ progress: Progress,
577
580
  ): Promise<{ text: string; sessionId?: string; error?: string }> => {
578
581
  await mkdir(configDir, { recursive: true });
579
582
  const context = { cwd, prompt, systemPrompt: await systemPrompt(run, cwd), dataDir: DATA, configDir };
@@ -591,12 +594,12 @@ const runAgent = async (
591
594
  },
592
595
  timeout: RUN_TIMEOUT_MS,
593
596
  input: adapter.input?.(context) ?? prompt,
594
- onLine:
595
- adapter.message &&
596
- ((line) => {
597
- const text = adapter.message?.(line);
598
- if (text?.trim()) onMessage(text);
599
- }),
597
+ onLine: (line) => {
598
+ const model = adapter.model?.(line);
599
+ if (model) progress.model(model);
600
+ const text = adapter.message?.(line);
601
+ if (text?.trim()) progress.message(text);
602
+ },
600
603
  });
601
604
  const output = adapter.parse(result.stdout);
602
605
  if (result.code !== 0 || !output || output.isError) {
@@ -626,15 +629,48 @@ const relay = async (run: Run, text: string, message?: ReplyMessage) => {
626
629
  return ((await response.json().catch(() => ({}))) as Partial<RelayResult>).message;
627
630
  };
628
631
 
629
- /** What the conversation shows under an agent's latest message while the run goes on. */
630
- const PROGRESS_NOTE = "> The agent is still running. Its final reply will replace this message.";
632
+ /** What the runner reads from the agent's output while it runs. */
633
+ type Progress = { message(text: string): void; model(name: string): void };
634
+
635
+ /**
636
+ * A model's name for people. Claude's ids, such as `claude-opus-5-5`, become
637
+ * "Claude Opus 5.5". Other names, such as Cursor's "Composer 2.5", stay as
638
+ * they are.
639
+ */
640
+ const modelName = (model: string) => {
641
+ const claude = /^claude-([a-z]+)-(\d+(?:-\d)?)(?:-\d{8})?$/.exec(model);
642
+ if (!claude) return model;
643
+ return `Claude ${claude[1]![0]!.toUpperCase()}${claude[1]!.slice(1)} ${claude[2]!.replace("-", ".")}`;
644
+ };
645
+
646
+ /** A duration as `m:ss`, or `h:mm:ss` from an hour. */
647
+ const clock = (ms: number) => {
648
+ const seconds = Math.floor(ms / 1000);
649
+ const [h, m, s] = [Math.floor(seconds / 3600), Math.floor(seconds / 60) % 60, seconds % 60];
650
+ const pad = (n: number) => String(n).padStart(2, "0");
651
+ return h ? `${h}:${pad(m)}:${pad(s)}` : `${m}:${pad(s)}`;
652
+ };
653
+
654
+ /**
655
+ * An agent's message during a run, as the conversation shows it: quoted,
656
+ * with the model and the time since the run started in small text below.
657
+ */
658
+ const progressText = (text: string, ms: number, model?: string) => {
659
+ const quoted = text
660
+ .split("\n")
661
+ .map((line) => (line ? `> ${line}` : ">"))
662
+ .join("\n");
663
+ return `${quoted}\n\n<sub>${model ? `${modelName(model)} working` : "Working"} • ${clock(ms)}</sub>`;
664
+ };
631
665
 
632
666
  /**
633
667
  * A run's replies, which share one message on the conversation. `progress`
634
668
  * posts the agent's latest message, at most once every
635
669
  * `PROGRESS_INTERVAL_MS`, and each post replaces the last. A message that
636
670
  * repeats the one already shown isn't posted again, such as a runtime's
637
- * "Thinking..." for each part of a thought. `finish` posts the final reply
671
+ * "Thinking..." for each part of a thought. While the agent writes no new
672
+ * message, the shown one is posted again every `CLOCK_INTERVAL_MS`, so its
673
+ * clock stays current. `finish` posts the final reply
638
674
  * in their place. The first post replaces the message that the router
639
675
  * posted while the run waited for the container, if there is one.
640
676
  */
@@ -643,7 +679,10 @@ const replies = (run: Run) => {
643
679
  let pending: string | undefined;
644
680
  let shown: string | undefined;
645
681
  let timer: ReturnType<typeof setTimeout> | undefined;
682
+ let ticker: ReturnType<typeof setTimeout> | undefined;
646
683
  let sentAt = 0;
684
+ let startedAt = Date.now();
685
+ let model: string | undefined;
647
686
  // Posts go one at a time, so each one knows the message that the last one posted.
648
687
  let posting: Promise<void> = Promise.resolve();
649
688
  const post = (text: string) => {
@@ -661,19 +700,36 @@ const replies = (run: Run) => {
661
700
  pending = undefined;
662
701
  if (text === shown) return;
663
702
  shown = text;
664
- post(`${text}\n\n${PROGRESS_NOTE}`).catch((error: unknown) =>
703
+ show();
704
+ };
705
+ const show = () => {
706
+ clearTimeout(ticker);
707
+ if (shown === undefined) return;
708
+ post(progressText(shown, Date.now() - startedAt, model)).catch((error: unknown) =>
665
709
  log({ run: run.id, state: "progress failed", error: message(error) }),
666
710
  );
711
+ ticker = setTimeout(show, CLOCK_INTERVAL_MS);
667
712
  };
668
713
  return {
669
- progress(text: string) {
670
- if (text === (pending ?? shown)) return;
671
- pending = text;
672
- timer ??= setTimeout(flush, Math.max(0, sentAt + PROGRESS_INTERVAL_MS - Date.now()));
714
+ /** Starts the clock, when the run leaves the queue. */
715
+ start() {
716
+ startedAt = Date.now();
673
717
  },
718
+ progress: {
719
+ message(text: string) {
720
+ if (text === (pending ?? shown)) return;
721
+ pending = text;
722
+ timer ??= setTimeout(flush, Math.max(0, sentAt + PROGRESS_INTERVAL_MS - Date.now()));
723
+ },
724
+ model(name: string) {
725
+ model = name;
726
+ },
727
+ } satisfies Progress,
674
728
  finish(text: string) {
675
729
  clearTimeout(timer);
730
+ clearTimeout(ticker);
676
731
  timer = undefined;
732
+ ticker = undefined;
677
733
  pending = undefined;
678
734
  return post(text);
679
735
  },
@@ -708,7 +764,7 @@ const held = new Map<string, ReturnType<typeof replies>>();
708
764
  * 7. Saves the worktree and the session to the state store, whether or not
709
765
  * the agent succeeded.
710
766
  */
711
- const perform = async (run: Run, notes: string[], onMessage: (text: string) => void) => {
767
+ const perform = async (run: Run, notes: string[], progress: Progress) => {
712
768
  const worktree = worktreeOf(run);
713
769
  const adapter = await loadRuntime(run.agent.runtime);
714
770
  await assertCommand(adapter.command, adapter.name);
@@ -748,7 +804,7 @@ const perform = async (run: Run, notes: string[], onMessage: (text: string) => v
748
804
  adapter,
749
805
  run,
750
806
  { cwd: worktree.path, configDir, prompt, sessionId: session?.id },
751
- onMessage,
807
+ progress,
752
808
  );
753
809
  if (result.sessionId) await writeSession(run, { id: result.sessionId, cwd: worktree.path, seen });
754
810
  if (result.error) throw new Error(result.error);
@@ -780,6 +836,7 @@ const SKIPPED_NOTE = "> An earlier run already read these messages, so this run
780
836
  const execute = async (run: Run) => {
781
837
  const started = Date.now();
782
838
  const reply = held.get(run.id) ?? replies(run);
839
+ reply.start();
783
840
  log({ run: run.id, repo: run.repo, trigger: run.trigger, worktree: run.worktree?.branch ?? "scratch", state: "started" });
784
841
  const notes: string[] = [];
785
842
  let text: string;
@@ -44,7 +44,7 @@ case "$prompt" in
44
44
  rm README.md ;;
45
45
  *"wait for it"*) printf 'protocol=https\\nhost=github.com\\n\\n' | git credential fill | grep password= >> "${calls}" ;;
46
46
  *"talk to me"*)
47
- echo '{"type":"system","subtype":"init"}'
47
+ echo '{"type":"system","subtype":"init","model":"claude-opus-5-5"}'
48
48
  echo '{"type":"assistant","parent_tool_use_id":null,"message":{"content":[{"type":"text","text":"Looking."}]}}'
49
49
  sleep 0.3
50
50
  echo '{"type":"assistant","parent_tool_use_id":null,"message":{"content":[{"type":"thinking","thinking":"hidden"}]}}'
@@ -76,7 +76,7 @@ case "$prompt" in
76
76
  echo "it broke" >&2
77
77
  exit 1 ;;
78
78
  *talk*)
79
- echo '{"type":"system","subtype":"init","session_id":"'"$session"'"}'
79
+ echo '{"type":"system","subtype":"init","session_id":"'"$session"'","model":"Composer 2.5"}'
80
80
  echo '{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"Looking."}]},"model_call_id":"m1","timestamp_ms":1}'
81
81
  sleep 0.3
82
82
  echo '{"type":"tool_call","subtype":"completed","tool_call":{"taskToolCall":{"result":{"success":{"conversationSteps":[{"assistantMessage":{"text":"A subagent."}}]}}}}}'
@@ -102,7 +102,7 @@ session="s-$(basename "$(pwd)")"
102
102
  sessions="\${FACTORY_HOME_OVERRIDE:-$HOME}/.factory/sessions"
103
103
  mkdir -p "$sessions/-p-$(basename "$(pwd)")"
104
104
  echo "$prompt" >> "$sessions/-p-$(basename "$(pwd)")/$session.jsonl"
105
- echo "{\\"type\\":\\"system\\",\\"subtype\\":\\"init\\",\\"session_id\\":\\"$session\\"}"
105
+ echo "{\\"type\\":\\"system\\",\\"subtype\\":\\"init\\",\\"session_id\\":\\"$session\\",\\"model\\":\\"claude-sonnet-5-5\\"}"
106
106
  echo "{\\"type\\":\\"message\\",\\"role\\":\\"user\\",\\"text\\":\\"the prompt\\",\\"session_id\\":\\"$session\\"}"
107
107
  case "$prompt" in
108
108
  *"fail now"*)
@@ -385,13 +385,13 @@ test("a cursor agent's messages during a run share one comment, which its final
385
385
  const conversation = "github:acme/api#32";
386
386
  await post(run({ id: conversation, message: say(conversation, "talk to me") }, { runtimes: ["cursor"], agent }));
387
387
  const first = await nextReply();
388
- assert.equal(first.text, "Looking.\n\n> The agent is still running. Its final reply will replace this message.");
388
+ assert.match(first.text, /^> Looking\.\n\n<sub>Composer 2\.5 working • 0:0\d<\/sub>$/);
389
389
  assert.equal(first.message, undefined);
390
390
  const thinking = await nextReply();
391
- assert.equal(thinking.text, "Thinking...\n\n> The agent is still running. Its final reply will replace this message.");
391
+ assert.match(thinking.text, /^> Thinking\.\.\.\n\n<sub>Composer 2\.5 working • 0:0\d<\/sub>$/);
392
392
  assert.deepEqual(thinking.message, { id, signature: "msig" });
393
393
  const second = await nextReply();
394
- assert.equal(second.text, "Found it.\n\n> The agent is still running. Its final reply will replace this message.");
394
+ assert.match(second.text, /^> Found it\.\n\n<sub>Composer 2\.5 working • 0:0\d<\/sub>$/);
395
395
  assert.deepEqual(second.message, { id, signature: "msig" });
396
396
  const final = await nextReply();
397
397
  assert.equal(final.text, "done");
@@ -460,12 +460,12 @@ test("a droid agent's messages during a run share one comment, which its final r
460
460
  const conversation = "github:acme/api#23";
461
461
  await post(run({ id: conversation, message: say(conversation, "talk to me") }, { runtimes: ["droid"], agent }));
462
462
  const first = await nextReply();
463
- assert.equal(first.text, "Looking.\n\n> The agent is still running. Its final reply will replace this message.");
463
+ assert.match(first.text, /^> Looking\.\n\n<sub>Claude Sonnet 5\.5 working • 0:0\d<\/sub>$/);
464
464
  const thinking = await nextReply();
465
- assert.equal(thinking.text, "Thinking...\n\n> The agent is still running. Its final reply will replace this message.");
465
+ assert.match(thinking.text, /^> Thinking\.\.\.\n\n<sub>Claude Sonnet 5\.5 working • 0:0\d<\/sub>$/);
466
466
  assert.deepEqual(thinking.message, { id, signature: "msig" });
467
467
  const second = await nextReply();
468
- assert.equal(second.text, "Found it.\n\n> The agent is still running. Its final reply will replace this message.");
468
+ assert.match(second.text, /^> Found it\.\n\n<sub>Claude Sonnet 5\.5 working • 0:0\d<\/sub>$/);
469
469
  assert.deepEqual(second.message, { id, signature: "msig" });
470
470
  const final = await nextReply();
471
471
  assert.equal(final.text, "done");
@@ -729,14 +729,14 @@ test("the agent's messages during a run share one comment, which its final reply
729
729
  const conversation = "github:acme/api#5";
730
730
  await post(run({ id: conversation, message: say(conversation, "talk to me") }, { worktree: { branch: "issue-5" } }));
731
731
  const first = await nextReply();
732
- assert.equal(first.text, "Looking.\n\n> The agent is still running. Its final reply will replace this message.");
732
+ assert.match(first.text, /^> Looking\.\n\n<sub>Claude Opus 5\.5 working • 0:0\d<\/sub>$/);
733
733
  assert.equal(first.message, undefined);
734
734
  // Each thought shows as "Thinking...", posted once.
735
735
  const thinking = await nextReply();
736
- assert.equal(thinking.text, "Thinking...\n\n> The agent is still running. Its final reply will replace this message.");
736
+ assert.match(thinking.text, /^> Thinking\.\.\.\n\n<sub>Claude Opus 5\.5 working • 0:0\d<\/sub>$/);
737
737
  assert.deepEqual(thinking.message, { id, signature: "msig" });
738
738
  const second = await nextReply();
739
- assert.equal(second.text, "Found it.\n\n> The agent is still running. Its final reply will replace this message.");
739
+ assert.match(second.text, /^> Found it\.\n\n<sub>Claude Opus 5\.5 working • 0:0\d<\/sub>$/);
740
740
  assert.deepEqual(second.message, { id, signature: "msig" });
741
741
  const final = await nextReply();
742
742
  assert.equal(final.text, "done");