@av-pi-studio/server 0.0.113 → 0.0.115

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.
Files changed (30) hide show
  1. package/dist/agent/agent-service.d.ts +5 -0
  2. package/dist/agent/agent-service.js +12 -0
  3. package/dist/agent/agent-todos/agent-todos-rpc.d.ts +16 -0
  4. package/dist/agent/agent-todos/agent-todos-rpc.js +20 -0
  5. package/dist/agent/agent-todos/agent-todos-service.d.ts +68 -0
  6. package/dist/agent/agent-todos/agent-todos-service.js +155 -0
  7. package/dist/agent/agent-todos/todo-limits.d.ts +9 -0
  8. package/dist/agent/agent-todos/todo-limits.js +50 -0
  9. package/dist/agent/provider-contract.d.ts +24 -1
  10. package/dist/agent/providers/mock/mock-provider.d.ts +31 -2
  11. package/dist/agent/providers/mock/mock-provider.js +134 -1
  12. package/dist/agent/providers/mock/todo-script.d.ts +55 -0
  13. package/dist/agent/providers/mock/todo-script.js +168 -0
  14. package/dist/agent/providers/mock/tool-script.d.ts +28 -0
  15. package/dist/agent/providers/mock/tool-script.js +72 -0
  16. package/dist/agent/providers/pi/agent.d.ts +5 -1
  17. package/dist/agent/providers/pi/agent.js +51 -1
  18. package/dist/agent/providers/pi/event-mapper.d.ts +15 -12
  19. package/dist/agent/providers/pi/event-mapper.js +33 -15
  20. package/dist/agent/providers/pi/session-hydration.d.ts +9 -0
  21. package/dist/agent/providers/pi/session-hydration.js +12 -0
  22. package/dist/agent/providers/pi/todos.d.ts +65 -0
  23. package/dist/agent/providers/pi/todos.js +122 -0
  24. package/dist/agent/providers/pi/tool-output-coalescer.d.ts +58 -0
  25. package/dist/agent/providers/pi/tool-output-coalescer.js +121 -0
  26. package/dist/agent/slash-command-operations.d.ts +7 -0
  27. package/dist/agent/slash-command-operations.js +1 -0
  28. package/dist/daemon/bootstrap.js +19 -1
  29. package/dist/daemon/dev-bootstrap.js +20 -1
  30. package/package.json +8 -3
@@ -1,4 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { capAgentTodos } from "../../agent-todos/todo-limits.js";
3
+ import { advanceTodos, blockedTodos, clearTodos, doneTodos, getTodoScriptHelpText, hugeTodos, literalTodos, manyTodos, parseTodoScript, planTodos, } from "./todo-script.js";
4
+ import { getToolScriptHelpText, parseToolScript, toolScriptEvents, } from "./tool-script.js";
2
5
  import { getUiScriptHelpText, parseUiScript } from "./ui-script.js";
3
6
  /**
4
7
  * In-process `mock` provider (features/agent-providers.md § Provider entry — dev/test only). It
@@ -14,7 +17,16 @@ export const MOCK_CAPABILITIES = {
14
17
  supportsToolInvocations: true,
15
18
  supportsSteering: true,
16
19
  supportsExtensionUi: true,
20
+ supportsTodos: true,
17
21
  };
22
+ /** Keyed by `PersistenceHandle.sessionId` (the mock session's own `id`, stable for its whole
23
+ * lifetime and reused verbatim by `describePersistence`/`importSession`). Lets
24
+ * `MockAgentClient.readTodos(handle)` answer the process-less path in-process, mirroring how a
25
+ * real daemon restart would re-read a provider-native file. Entries are replaced on every
26
+ * `emitTodos` call, never removed on `close()` — a process-less read happens AFTER the session
27
+ * that produced the data has closed, so clearing on close would defeat the whole point of this
28
+ * map. Bounded by distinct mock session ids created in the process. */
29
+ const mockTodosByHandle = new Map();
18
30
  const MOCK_MODES = [
19
31
  { id: "default", label: "Default" },
20
32
  { id: "plan", label: "Plan" },
@@ -53,13 +65,22 @@ export class MockAgentSession {
53
65
  // instead of) its existing `uiResponses` recording used by direct `emitUiRequest`/`respondToUi`
54
66
  // callers.
55
67
  pendingScriptedResponses = new Map();
68
+ // Agent todos (sprint-079/task-005): no `pi` process exists to script this family either, so the
69
+ // mock provider exposes a scripted emitter (`emitTodos`) plus `#todo ...` prompt recipes
70
+ // (`todo-script.ts`), mirroring the `#ui` precedent above.
71
+ todoSubscribers = new Set();
72
+ currentTodos = { tasks: [], truncated: false };
56
73
  constructor(config, options = {}) {
57
74
  this.config = config;
58
75
  this.turnDelayMs = options.turnDelayMs ?? 5;
59
76
  this.compactDelayMs = options.compactDelayMs ?? MOCK_COMPACT_DELAY_MS;
60
77
  }
61
78
  emit(event) {
62
- this.history.push(event);
79
+ // Ephemeral partial tool snapshots reach subscribers but never the replay buffer — the mirror
80
+ // of the Pi coalescer's history rule (tool-output-streaming.md tenet 2), so a post-restart
81
+ // hydration contains no partials.
82
+ if (!(event.kind === "tool_call" && event.partial))
83
+ this.history.push(event);
63
84
  for (const cb of this.subscribers)
64
85
  cb(event);
65
86
  }
@@ -75,6 +96,12 @@ export class MockAgentSession {
75
96
  const script = parseUiScript(prompt);
76
97
  if (script !== null)
77
98
  return this.startUiScriptTurn(script);
99
+ const todoRecipe = parseTodoScript(prompt);
100
+ if (todoRecipe !== null)
101
+ return this.startTodoScriptTurn(todoRecipe);
102
+ const toolRecipe = parseToolScript(prompt);
103
+ if (toolRecipe !== null)
104
+ return this.startToolScriptTurn(toolRecipe);
78
105
  const turnId = randomUUID();
79
106
  this.activeTurn = turnId;
80
107
  this.emit({ kind: "turn_started", turnId });
@@ -120,6 +147,79 @@ export class MockAgentSession {
120
147
  void this.runUiScript(turnId, steps);
121
148
  return Promise.resolve({ turnId });
122
149
  }
150
+ /** `#todo ...` prompt (sprint-079/task-005): run a recipe through `emitTodos`, then end the turn
151
+ * with a short assistant text confirming what was emitted (or, for `help`, the recipe list)
152
+ * instead of the normal echoed turn. Mirrors `startUiScriptTurn`'s shape: resolves immediately
153
+ * with the turn id, the emission and the echo happen after `turnDelayMs`. */
154
+ startTodoScriptTurn(recipe) {
155
+ const turnId = randomUUID();
156
+ this.activeTurn = turnId;
157
+ this.emit({ kind: "turn_started", turnId });
158
+ setTimeout(() => {
159
+ if (this.activeTurn !== turnId)
160
+ return;
161
+ let text;
162
+ if (recipe === "help") {
163
+ text = getTodoScriptHelpText();
164
+ }
165
+ else {
166
+ const list = this.emitTodos(this.buildTodoRecipe(recipe));
167
+ text = `todo ${recipe}: ${list.tasks.length} task(s)${list.truncated ? " (truncated)" : ""}`;
168
+ }
169
+ this.emit({ kind: "assistant_message", messageId: randomUUID(), text, final: true });
170
+ this.emit({ kind: "turn_completed", turnId });
171
+ this.activeTurn = null;
172
+ }, this.turnDelayMs);
173
+ return Promise.resolve({ turnId });
174
+ }
175
+ /** `#tool ...` prompt (sprint-058/task-004): after `turnDelayMs`, emit the scripted tool-call
176
+ * lifecycle (start, 3 partials, end) synchronously — no timers between tool events — then the
177
+ * usual echo and `turn_completed`. `help` emits the recipe list and no tool events. */
178
+ startToolScriptTurn(recipe) {
179
+ const turnId = randomUUID();
180
+ this.activeTurn = turnId;
181
+ this.emit({ kind: "turn_started", turnId });
182
+ setTimeout(() => {
183
+ if (this.activeTurn !== turnId)
184
+ return;
185
+ let text;
186
+ if (recipe === "help") {
187
+ text = getToolScriptHelpText();
188
+ }
189
+ else {
190
+ for (const event of toolScriptEvents(recipe, randomUUID()))
191
+ this.emit(event);
192
+ text = `echo: #tool ${recipe}`;
193
+ }
194
+ this.emit({ kind: "assistant_message", messageId: randomUUID(), text, final: true });
195
+ this.emit({ kind: "turn_completed", turnId });
196
+ this.activeTurn = null;
197
+ }, this.turnDelayMs);
198
+ return Promise.resolve({ turnId });
199
+ }
200
+ /** Builds the raw (uncapped) task list for every recipe except `help`, which `startTodoScriptTurn`
201
+ * handles itself. `advance` reads `currentTodos` — the only recipe whose result depends on
202
+ * session state — everything else is a pure `todo-script.ts` builder. */
203
+ buildTodoRecipe(recipe) {
204
+ switch (recipe) {
205
+ case "plan":
206
+ return planTodos();
207
+ case "advance":
208
+ return advanceTodos(this.currentTodos.tasks);
209
+ case "done":
210
+ return doneTodos();
211
+ case "many":
212
+ return manyTodos();
213
+ case "blocked":
214
+ return blockedTodos();
215
+ case "literal":
216
+ return literalTodos();
217
+ case "huge":
218
+ return hugeTodos();
219
+ case "clear":
220
+ return clearTodos();
221
+ }
222
+ }
123
223
  async runUiScript(turnId, steps) {
124
224
  const responses = await Promise.all(steps.map((step) => this.raiseScriptedDialog(step)));
125
225
  if (this.activeTurn !== turnId)
@@ -273,6 +373,27 @@ export class MockAgentSession {
273
373
  cb(req);
274
374
  return req;
275
375
  }
376
+ // Agent todos (features/agent-todos.md § Provider contract): `supportsTodos` members. The mock
377
+ // caps through `capAgentTodos` directly — never through `providers/pi/todos.ts`, which is a
378
+ // different provider's recognition logic for a different wire shape.
379
+ onTodos(cb) {
380
+ this.todoSubscribers.add(cb);
381
+ return () => this.todoSubscribers.delete(cb);
382
+ }
383
+ readTodos() {
384
+ return this.currentTodos;
385
+ }
386
+ /** Test/dev hook (sprint-079/task-005): cap `tasks` through `capAgentTodos`, store it as the
387
+ * session's current list, publish it to `onTodos` subscribers and the process-less
388
+ * `mockTodosByHandle` map, and return what was actually emitted. */
389
+ emitTodos(tasks) {
390
+ const capped = capAgentTodos(tasks);
391
+ this.currentTodos = capped;
392
+ mockTodosByHandle.set(this.id, capped);
393
+ for (const cb of this.todoSubscribers)
394
+ cb(capped);
395
+ return capped;
396
+ }
276
397
  describePersistence() {
277
398
  return { provider: this.provider, sessionId: this.id, nativeHandle: `mock:${this.id}` };
278
399
  }
@@ -414,6 +535,18 @@ export class MockAgentClient {
414
535
  isAvailable() {
415
536
  return true;
416
537
  }
538
+ /** Process-less counterpart of `MockAgentSession.readTodos` (features/agent-todos.md § Provider
539
+ * contract): the last list `emitTodos` published for this handle's session, from the
540
+ * module-level `mockTodosByHandle` map (keyed by `sessionId`) — no session is spawned. An
541
+ * unknown handle (never emitted, or no `sessionId`) answers an empty list, matching the
542
+ * "missing file is an empty list" convention the real adapter uses. */
543
+ readTodos(handle) {
544
+ const key = handle.sessionId;
545
+ return ((key !== undefined ? mockTodosByHandle.get(key) : undefined) ?? {
546
+ tasks: [],
547
+ truncated: false,
548
+ });
549
+ }
417
550
  async importSession(args) {
418
551
  const session = new MockAgentSession({ provider: "mock", cwd: args.cwd }, this.options);
419
552
  return {
@@ -0,0 +1,55 @@
1
+ import type { AgentTodo } from "@av-pi-studio/protocol";
2
+ /**
3
+ * Scripted todo-list trigger for the mock provider (sprint-079/task-005). Lets a browser-connected
4
+ * client drive every todo-panel state the web-client must render by typing a `#todo ...` prompt, so
5
+ * the UI work in sprint-080 has reachable triggers for every state — grouped completed tasks,
6
+ * blocked tasks, truncation, literal markdown, clearing — with no Pi and no model
7
+ * (features/agent-todos.md § Provider contract, § Acceptance A11). Mirrors s068/t001's `#ui`
8
+ * recipes (`ui-script.ts`): a pure, cheap-prefix-checked parser, a `help` recipe echoed verbatim by
9
+ * `#todo help`, and recognised-but-unknown input falling back to help rather than an ordinary echo.
10
+ *
11
+ * `advance` is the one recipe whose RESULT depends on session state (the current list), so this
12
+ * module keeps it pure too: `advanceTodos(current)` takes the session's current list as input and
13
+ * returns the next one. `MockAgentSession` is the only caller that knows what "current" means.
14
+ *
15
+ * Grammar (also echoed verbatim by `#todo help`):
16
+ *
17
+ * #todo plan 4 tasks, the first in_progress with an activeForm
18
+ * #todo advance completes the current task, starts the next (relative to the session's list)
19
+ * #todo done all tasks completed
20
+ * #todo many 12 tasks, 7 completed (exercises grouping and scroll)
21
+ * #todo blocked blockedBy including a dangling id, plus description/owner
22
+ * #todo literal a subject containing literal markdown/HTML, rendered verbatim
23
+ * #todo huge 250 tasks with over-cap fields (exercises the cap path)
24
+ * #todo clear empty list
25
+ * #todo help this list
26
+ */
27
+ export declare const TODO_SCRIPT_RECIPES: readonly ["plan", "advance", "done", "many", "blocked", "literal", "huge", "clear", "help"];
28
+ export type TodoScriptRecipe = (typeof TODO_SCRIPT_RECIPES)[number];
29
+ export declare function getTodoScriptHelpText(): string;
30
+ /** Parses a `#todo ...` prompt into the recipe it names. Returns `null` when `prompt` is not a
31
+ * recognised script — the overwhelmingly common case, kept a cheap prefix check. A `#todo` prompt
32
+ * whose recipe is empty or unrecognised still names a script (so the caller must show help, not
33
+ * run an ordinary echoed turn) — it returns `"help"`, never `null`, for those. */
34
+ export declare function parseTodoScript(prompt: string): TodoScriptRecipe | null;
35
+ /** `#todo plan`: 4 tasks, the first `in_progress` with an `activeForm`. */
36
+ export declare function planTodos(): AgentTodo[];
37
+ /** `#todo advance`: completes the session's current `in_progress` task (if any) and starts the
38
+ * next `pending` one (if any), relative to `current` — never reads global state. A list with no
39
+ * `in_progress` and no `pending` task (e.g. `done`, or the empty list before `plan`) is returned
40
+ * unchanged. */
41
+ export declare function advanceTodos(current: readonly AgentTodo[]): AgentTodo[];
42
+ /** `#todo done`: all tasks completed. */
43
+ export declare function doneTodos(): AgentTodo[];
44
+ /** `#todo many`: 12 tasks, 7 completed — exercises grouping and scroll. */
45
+ export declare function manyTodos(): AgentTodo[];
46
+ /** `#todo blocked`: `blockedBy` (including a dangling id), plus `description`/`owner`. */
47
+ export declare function blockedTodos(): AgentTodo[];
48
+ /** `#todo literal`: subject containing literal markdown/HTML, rendered verbatim (never parsed). */
49
+ export declare function literalTodos(): AgentTodo[];
50
+ /** `#todo huge`: 250 tasks (over `AGENT_TODOS_MAX_TASKS`) with over-cap text fields and an
51
+ * over-cap `blockedBy`, so `capAgentTodos` truncates the list AND every field. */
52
+ export declare function hugeTodos(): AgentTodo[];
53
+ /** `#todo clear`: empty list. */
54
+ export declare function clearTodos(): AgentTodo[];
55
+ //# sourceMappingURL=todo-script.d.ts.map
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Scripted todo-list trigger for the mock provider (sprint-079/task-005). Lets a browser-connected
3
+ * client drive every todo-panel state the web-client must render by typing a `#todo ...` prompt, so
4
+ * the UI work in sprint-080 has reachable triggers for every state — grouped completed tasks,
5
+ * blocked tasks, truncation, literal markdown, clearing — with no Pi and no model
6
+ * (features/agent-todos.md § Provider contract, § Acceptance A11). Mirrors s068/t001's `#ui`
7
+ * recipes (`ui-script.ts`): a pure, cheap-prefix-checked parser, a `help` recipe echoed verbatim by
8
+ * `#todo help`, and recognised-but-unknown input falling back to help rather than an ordinary echo.
9
+ *
10
+ * `advance` is the one recipe whose RESULT depends on session state (the current list), so this
11
+ * module keeps it pure too: `advanceTodos(current)` takes the session's current list as input and
12
+ * returns the next one. `MockAgentSession` is the only caller that knows what "current" means.
13
+ *
14
+ * Grammar (also echoed verbatim by `#todo help`):
15
+ *
16
+ * #todo plan 4 tasks, the first in_progress with an activeForm
17
+ * #todo advance completes the current task, starts the next (relative to the session's list)
18
+ * #todo done all tasks completed
19
+ * #todo many 12 tasks, 7 completed (exercises grouping and scroll)
20
+ * #todo blocked blockedBy including a dangling id, plus description/owner
21
+ * #todo literal a subject containing literal markdown/HTML, rendered verbatim
22
+ * #todo huge 250 tasks with over-cap fields (exercises the cap path)
23
+ * #todo clear empty list
24
+ * #todo help this list
25
+ */
26
+ export const TODO_SCRIPT_RECIPES = [
27
+ "plan",
28
+ "advance",
29
+ "done",
30
+ "many",
31
+ "blocked",
32
+ "literal",
33
+ "huge",
34
+ "clear",
35
+ "help",
36
+ ];
37
+ const RECIPE_SET = new Set(TODO_SCRIPT_RECIPES);
38
+ const HELP_TEXT = `#todo script recipes:
39
+ #todo plan 4 tasks, the first in_progress with an activeForm
40
+ #todo advance completes the current task, starts the next
41
+ #todo done all tasks completed
42
+ #todo many 12 tasks, 7 completed
43
+ #todo blocked blockedBy including a dangling id, plus description/owner
44
+ #todo literal a subject containing literal markdown/HTML
45
+ #todo huge 250 tasks with over-cap fields
46
+ #todo clear empty list
47
+ #todo help this list`;
48
+ export function getTodoScriptHelpText() {
49
+ return HELP_TEXT;
50
+ }
51
+ /** Parses a `#todo ...` prompt into the recipe it names. Returns `null` when `prompt` is not a
52
+ * recognised script — the overwhelmingly common case, kept a cheap prefix check. A `#todo` prompt
53
+ * whose recipe is empty or unrecognised still names a script (so the caller must show help, not
54
+ * run an ordinary echoed turn) — it returns `"help"`, never `null`, for those. */
55
+ export function parseTodoScript(prompt) {
56
+ const trimmed = prompt.trim();
57
+ if (!/^#todo(\s|$)/i.test(trimmed))
58
+ return null;
59
+ const rest = trimmed.slice("#todo".length).trim();
60
+ if (rest === "")
61
+ return "help";
62
+ return RECIPE_SET.has(rest) ? rest : "help";
63
+ }
64
+ const PLAN_SUBJECTS = ["Design the schema", "Implement the service", "Wire the SDK", "Write tests"];
65
+ /** `#todo plan`: 4 tasks, the first `in_progress` with an `activeForm`. */
66
+ export function planTodos() {
67
+ return PLAN_SUBJECTS.map((subject, i) => i === 0
68
+ ? { id: i + 1, subject, status: "in_progress", activeForm: "Designing the schema" }
69
+ : { id: i + 1, subject, status: "pending" });
70
+ }
71
+ /** `#todo advance`: completes the session's current `in_progress` task (if any) and starts the
72
+ * next `pending` one (if any), relative to `current` — never reads global state. A list with no
73
+ * `in_progress` and no `pending` task (e.g. `done`, or the empty list before `plan`) is returned
74
+ * unchanged. */
75
+ export function advanceTodos(current) {
76
+ const next = current.map((task) => ({ ...task }));
77
+ const activeIndex = next.findIndex((task) => task.status === "in_progress");
78
+ if (activeIndex !== -1) {
79
+ const { activeForm: _activeForm, ...rest } = next[activeIndex];
80
+ next[activeIndex] = { ...rest, status: "completed" };
81
+ }
82
+ const pendingIndex = next.findIndex((task) => task.status === "pending");
83
+ if (pendingIndex !== -1) {
84
+ const task = next[pendingIndex];
85
+ next[pendingIndex] = {
86
+ ...task,
87
+ status: "in_progress",
88
+ activeForm: task.activeForm ?? `Working on ${task.subject.toLowerCase()}`,
89
+ };
90
+ }
91
+ return next;
92
+ }
93
+ /** `#todo done`: all tasks completed. */
94
+ export function doneTodos() {
95
+ return PLAN_SUBJECTS.map((subject, i) => ({ id: i + 1, subject, status: "completed" }));
96
+ }
97
+ /** `#todo many`: 12 tasks, 7 completed — exercises grouping and scroll. */
98
+ export function manyTodos() {
99
+ return Array.from({ length: 12 }, (_, i) => {
100
+ const id = i + 1;
101
+ if (i < 7)
102
+ return { id, subject: `Completed task ${id}`, status: "completed" };
103
+ if (i === 7) {
104
+ return {
105
+ id,
106
+ subject: `Current task ${id}`,
107
+ status: "in_progress",
108
+ activeForm: `Working on current task ${id}`,
109
+ };
110
+ }
111
+ return { id, subject: `Pending task ${id}`, status: "pending" };
112
+ });
113
+ }
114
+ /** `#todo blocked`: `blockedBy` (including a dangling id), plus `description`/`owner`. */
115
+ export function blockedTodos() {
116
+ return [
117
+ {
118
+ id: 1,
119
+ subject: "Provision the staging database",
120
+ status: "completed",
121
+ description: "One-time setup; later tasks depend on its connection string.",
122
+ owner: "infra",
123
+ },
124
+ {
125
+ id: 2,
126
+ subject: "Migrate the schema",
127
+ status: "pending",
128
+ description: "Waiting on review of the migration plan.",
129
+ owner: "backend",
130
+ blockedBy: [1, 99],
131
+ },
132
+ {
133
+ id: 3,
134
+ subject: "Backfill historical rows",
135
+ status: "pending",
136
+ description: "Depends on the migration landing first.",
137
+ blockedBy: [2],
138
+ },
139
+ ];
140
+ }
141
+ const LITERAL_SUBJECT = "**x** <b>y</b> [l](http://e)";
142
+ /** `#todo literal`: subject containing literal markdown/HTML, rendered verbatim (never parsed). */
143
+ export function literalTodos() {
144
+ return [{ id: 1, subject: LITERAL_SUBJECT, status: "in_progress", activeForm: LITERAL_SUBJECT }];
145
+ }
146
+ /** `#todo huge`: 250 tasks (over `AGENT_TODOS_MAX_TASKS`) with over-cap text fields and an
147
+ * over-cap `blockedBy`, so `capAgentTodos` truncates the list AND every field. */
148
+ export function hugeTodos() {
149
+ const longSubject = "x".repeat(600);
150
+ const longActiveForm = "y".repeat(600);
151
+ const longDescription = "z".repeat(4100);
152
+ const longOwner = "o".repeat(150);
153
+ const manyBlockers = Array.from({ length: 60 }, (_, i) => i + 1000);
154
+ return Array.from({ length: 250 }, (_, i) => ({
155
+ id: i + 1,
156
+ subject: longSubject,
157
+ status: "pending",
158
+ activeForm: longActiveForm,
159
+ description: longDescription,
160
+ owner: longOwner,
161
+ blockedBy: manyBlockers,
162
+ }));
163
+ }
164
+ /** `#todo clear`: empty list. */
165
+ export function clearTodos() {
166
+ return [];
167
+ }
168
+ //# sourceMappingURL=todo-script.js.map
@@ -0,0 +1,28 @@
1
+ import type { AgentStreamEvent } from "@av-pi-studio/protocol";
2
+ /**
3
+ * Scripted tool-call trigger for the mock provider (sprint-058/task-004). Typing a `#tool ...`
4
+ * prompt makes the mock run a shell tool call that streams ephemeral `partial: true` snapshots, so
5
+ * the whole live-tool-output path (broadcast without `seq`, no timeline append, no history replay,
6
+ * client live tail) is exercisable with no Pi and no credentials. Mirrors `#ui` / `#todo`
7
+ * (`ui-script.ts`, `todo-script.ts`): a pure, cheap-prefix-checked parser, a `help` recipe, and
8
+ * recognised-but-unknown input falling back to help rather than an ordinary echo.
9
+ *
10
+ * Grammar (also echoed verbatim by `#tool help`):
11
+ *
12
+ * #tool shell start row, 3 growing partial snapshots, completed row with the full output
13
+ * #tool empty same, but the completed row carries an EMPTY output (terminal-authority edge)
14
+ * #tool help this list
15
+ *
16
+ * A bare `#tool` runs the `shell` recipe; an unrecognised recipe shows help.
17
+ */
18
+ export declare const TOOL_SCRIPT_RECIPES: readonly ["shell", "empty", "help"];
19
+ export type ToolScriptRecipe = (typeof TOOL_SCRIPT_RECIPES)[number];
20
+ export declare function getToolScriptHelpText(): string;
21
+ /** Parses a `#tool ...` prompt into the recipe it names. Returns `null` when `prompt` is not a
22
+ * script. A bare `#tool` is the `shell` recipe; an unrecognised recipe returns `"help"`. */
23
+ export declare function parseToolScript(prompt: string): ToolScriptRecipe | null;
24
+ /** The `tool_call` events for a non-`help` recipe, in emission order: start row, 3 partial
25
+ * snapshots whose output ACCUMULATES (each contains all prior text, like bash's replace-semantics
26
+ * snapshots), then the terminal row. */
27
+ export declare function toolScriptEvents(recipe: Exclude<ToolScriptRecipe, "help">, callId: string): AgentStreamEvent[];
28
+ //# sourceMappingURL=tool-script.d.ts.map
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Scripted tool-call trigger for the mock provider (sprint-058/task-004). Typing a `#tool ...`
3
+ * prompt makes the mock run a shell tool call that streams ephemeral `partial: true` snapshots, so
4
+ * the whole live-tool-output path (broadcast without `seq`, no timeline append, no history replay,
5
+ * client live tail) is exercisable with no Pi and no credentials. Mirrors `#ui` / `#todo`
6
+ * (`ui-script.ts`, `todo-script.ts`): a pure, cheap-prefix-checked parser, a `help` recipe, and
7
+ * recognised-but-unknown input falling back to help rather than an ordinary echo.
8
+ *
9
+ * Grammar (also echoed verbatim by `#tool help`):
10
+ *
11
+ * #tool shell start row, 3 growing partial snapshots, completed row with the full output
12
+ * #tool empty same, but the completed row carries an EMPTY output (terminal-authority edge)
13
+ * #tool help this list
14
+ *
15
+ * A bare `#tool` runs the `shell` recipe; an unrecognised recipe shows help.
16
+ */
17
+ export const TOOL_SCRIPT_RECIPES = ["shell", "empty", "help"];
18
+ const RECIPE_SET = new Set(TOOL_SCRIPT_RECIPES);
19
+ const HELP_TEXT = `#tool script recipes:
20
+ #tool shell a shell tool call streaming 3 growing output snapshots, then completing
21
+ #tool empty the same, but the completed call carries an empty final output
22
+ #tool help this list`;
23
+ export function getToolScriptHelpText() {
24
+ return HELP_TEXT;
25
+ }
26
+ /** Parses a `#tool ...` prompt into the recipe it names. Returns `null` when `prompt` is not a
27
+ * script. A bare `#tool` is the `shell` recipe; an unrecognised recipe returns `"help"`. */
28
+ export function parseToolScript(prompt) {
29
+ const trimmed = prompt.trim();
30
+ if (!/^#tool(\s|$)/i.test(trimmed))
31
+ return null;
32
+ const rest = trimmed.slice("#tool".length).trim();
33
+ if (rest === "")
34
+ return "shell";
35
+ return RECIPE_SET.has(rest) ? rest : "help";
36
+ }
37
+ const SHELL_COMMAND = "npm test";
38
+ const OUTPUT_LINES = ["> running suite A", "> running suite B", "> running suite C"];
39
+ /** The `tool_call` events for a non-`help` recipe, in emission order: start row, 3 partial
40
+ * snapshots whose output ACCUMULATES (each contains all prior text, like bash's replace-semantics
41
+ * snapshots), then the terminal row. */
42
+ export function toolScriptEvents(recipe, callId) {
43
+ const events = [
44
+ {
45
+ kind: "tool_call",
46
+ callId,
47
+ status: "running",
48
+ tool: { kind: "shell", command: SHELL_COMMAND },
49
+ },
50
+ ];
51
+ for (let i = 1; i <= OUTPUT_LINES.length; i++) {
52
+ events.push({
53
+ kind: "tool_call",
54
+ callId,
55
+ status: "running",
56
+ partial: true,
57
+ tool: { kind: "shell", command: SHELL_COMMAND, output: OUTPUT_LINES.slice(0, i).join("\n") },
58
+ });
59
+ }
60
+ events.push({
61
+ kind: "tool_call",
62
+ callId,
63
+ status: "completed",
64
+ tool: {
65
+ kind: "shell",
66
+ command: SHELL_COMMAND,
67
+ output: recipe === "empty" ? "" : `${OUTPUT_LINES.join("\n")}\nall passed`,
68
+ },
69
+ });
70
+ return events;
71
+ }
72
+ //# sourceMappingURL=tool-script.js.map
@@ -1,5 +1,5 @@
1
1
  import type { AgentCapabilityFlags, AgentSessionConfig } from "@av-pi-studio/protocol";
2
- import type { AgentClient, AgentModeDefinition, AgentModelDefinition, AgentSession, CreateSessionOptions, ImportableSessionRow, ImportSessionArgs, ImportSessionResult, LaunchContext, PersistenceHandle } from "../../provider-contract.js";
2
+ import type { AgentClient, AgentModeDefinition, AgentModelDefinition, AgentSession, AgentTodoList, CreateSessionOptions, ImportableSessionRow, ImportSessionArgs, ImportSessionResult, LaunchContext, PersistenceHandle } from "../../provider-contract.js";
3
3
  import type { TimelineRow } from "../../timeline-store.js";
4
4
  import { type PiTransportFactory } from "./rpc-transport.js";
5
5
  /**
@@ -52,6 +52,7 @@ export declare class PiAgentClient implements AgentClient {
52
52
  supportsRewindBoth: import("zod").ZodOptional<import("zod").ZodBoolean>;
53
53
  supportsSteering: import("zod").ZodOptional<import("zod").ZodBoolean>;
54
54
  supportsExtensionUi: import("zod").ZodOptional<import("zod").ZodBoolean>;
55
+ supportsTodos: import("zod").ZodOptional<import("zod").ZodBoolean>;
55
56
  }, import("zod").ZodTypeAny, "passthrough">;
56
57
  private readonly command;
57
58
  private readonly factory;
@@ -113,6 +114,9 @@ export declare class PiAgentClient implements AgentClient {
113
114
  importSession(args: ImportSessionArgs): Promise<ImportSessionResult>;
114
115
  /** Rebuild a timeline by reading Pi's own on-disk JSONL session file (no live process needed). */
115
116
  hydrateTimeline(handle: PersistenceHandle): TimelineRow[];
117
+ /** Process-less counterpart of `AgentSession.readTodos`, for a record with no live session
118
+ * (e.g. after a daemon restart). Reads `handle.nativeHandle` directly; never spawns `pi`. */
119
+ readTodos(handle: PersistenceHandle): AgentTodoList;
116
120
  }
117
121
  /** Factory matching the provider-registry signature. */
118
122
  export declare function createPiClient(deps?: PiClientDeps): PiAgentClient;
@@ -2,9 +2,11 @@ import { randomUUID } from "node:crypto";
2
2
  import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import { createPiEventMapper } from "./event-mapper.js";
5
- import { hydrateTimelineFromSessionFile } from "./session-hydration.js";
6
5
  import { createProcessTransport, defaultPiCommand, resolveBinaryOnPath, } from "./rpc-transport.js";
6
+ import { hydrateTimelineFromSessionFile, readTodosFromSessionFile } from "./session-hydration.js";
7
7
  import { deriveThinkingLevels } from "./thinking-levels.js";
8
+ import { toAgentTodos, todoDetailsFromFrame } from "./todos.js";
9
+ import { createToolOutputCoalescer } from "./tool-output-coalescer.js";
8
10
  /**
9
11
  * Pi provider adapter (features/agent-providers.md § Pi lifecycle / § Models·modes·features /
10
12
  * § Import & resume). Spawns `pi --mode rpc` (or a configured `command`), maps RPC events to
@@ -20,6 +22,7 @@ export const PI_CAPABILITIES = {
20
22
  supportsToolInvocations: true,
21
23
  supportsSteering: true,
22
24
  supportsExtensionUi: true,
25
+ supportsTodos: true,
23
26
  };
24
27
  /** Build Pi argv, appending (never replacing) the system prompt and optional `--mcp-config`. */
25
28
  export function buildPiArgs(base, opts) {
@@ -113,8 +116,13 @@ class PiAgentSession {
113
116
  capabilities = PI_CAPABILITIES;
114
117
  subscribers = new Set();
115
118
  uiSubscribers = new Set();
119
+ todoSubscribers = new Set();
116
120
  history = [];
117
121
  eventMapper = createPiEventMapper();
122
+ /** Owns ephemeral `partial: true` tool output: throttled, tail-capped, kept out of `history`. */
123
+ partialOutput = createToolOutputCoalescer({
124
+ deliver: (event) => this.fanOut(event),
125
+ });
118
126
  modes = [];
119
127
  mode;
120
128
  model;
@@ -135,13 +143,34 @@ class PiAgentSession {
135
143
  cb(req);
136
144
  return;
137
145
  }
146
+ // Agent todos (features/agent-todos.md § Pi adapter: live updates) — runs IN ADDITION to
147
+ // the mapping below; the timeline row for the same frame is unchanged. Pi announces a
148
+ // `todo` change twice (`entry_appended` then `tool_execution_end`); the service, not this
149
+ // adapter, dedupes the pair. No `parentToolCallId` filter on purpose: a nested call (e.g.
150
+ // `ctx.executeTool`/`codemode`) runs in the same session and mutates the same list, so it
151
+ // is a legitimate snapshot too.
152
+ const details = todoDetailsFromFrame(raw);
153
+ if (details) {
154
+ const list = toAgentTodos(details);
155
+ for (const cb of this.todoSubscribers)
156
+ cb(list);
157
+ }
138
158
  const event = this.eventMapper.map(raw);
139
159
  if (event)
140
160
  this.emit(event);
141
161
  });
142
162
  }
143
163
  emit(event) {
164
+ // Partials are live-stream-only (features/tool-output-streaming.md): the coalescer delivers
165
+ // them to subscribers itself, so they never reach `history` and its replay. Every other event
166
+ // keeps the record-then-fan-out path; the coalescer has already cancelled any partial
167
+ // flush it supersedes (a call's terminal, a turn terminal), so no partial outruns it.
168
+ if (this.partialOutput.accept(event))
169
+ return;
144
170
  this.history.push(event);
171
+ this.fanOut(event);
172
+ }
173
+ fanOut(event) {
145
174
  for (const cb of this.subscribers)
146
175
  cb(event);
147
176
  }
@@ -313,6 +342,18 @@ class PiAgentSession {
313
342
  respondToUi(providerRequestId, response) {
314
343
  this.transport.notify("extension_ui_response", { ...response, id: providerRequestId });
315
344
  }
345
+ onTodos(cb) {
346
+ this.todoSubscribers.add(cb);
347
+ return () => this.todoSubscribers.delete(cb);
348
+ }
349
+ /** Re-read `this.sessionFile` each call so it follows a fork/new_session rebind
350
+ * (`refreshSessionFile`). Throws on an unreadable file so the caller (the agent-todos service)
351
+ * can log it with the agent id; no file at all is a legitimate empty state, not an error. */
352
+ readTodos() {
353
+ if (!this.sessionFile)
354
+ return { tasks: [], truncated: false };
355
+ return readTodosFromSessionFile(this.sessionFile);
356
+ }
316
357
  describePersistence() {
317
358
  return {
318
359
  provider: this.provider,
@@ -478,6 +519,7 @@ class PiAgentSession {
478
519
  }));
479
520
  }
480
521
  close() {
522
+ this.partialOutput.cancelAll();
481
523
  this.subscribers.clear();
482
524
  return this.transport.close();
483
525
  }
@@ -681,6 +723,14 @@ export class PiAgentClient {
681
723
  return [];
682
724
  return hydrateTimelineFromSessionFile(sessionFile);
683
725
  }
726
+ /** Process-less counterpart of `AgentSession.readTodos`, for a record with no live session
727
+ * (e.g. after a daemon restart). Reads `handle.nativeHandle` directly; never spawns `pi`. */
728
+ readTodos(handle) {
729
+ const sessionFile = typeof handle.nativeHandle === "string" ? handle.nativeHandle : undefined;
730
+ if (!sessionFile)
731
+ return { tasks: [], truncated: false };
732
+ return readTodosFromSessionFile(sessionFile);
733
+ }
684
734
  }
685
735
  /** Factory matching the provider-registry signature. */
686
736
  export function createPiClient(deps = {}) {