@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,11 +1,13 @@
1
1
  import type { AgentStreamEvent, ToolCallDetail } from "@av-pi-studio/protocol";
2
2
  /**
3
- * Map a Pi tool-call payload to a normalized `ToolCallDetail`. Accepts either a
4
- * `tool_execution_start`-shaped record (`toolName` + `args`) or a `tool_execution_end`-shaped one
5
- * (`toolName` + `result`, no `args`). For `edit`, the human-readable unified `patch` is only
6
- * present on the *end* event under `result.details.patch`, so it is pulled from there when args
7
- * carry no diff. `output` (tool stdout/result text) is only present on *end* events — `start`
8
- * events have no `result` yet, so `outputOf` yields `undefined` for them, which is correct.
3
+ * Map a Pi tool-call payload to a normalized `ToolCallDetail`. Accepts a
4
+ * `tool_execution_start`-shaped record (`toolName` + `args`), a `tool_execution_update`-shaped one
5
+ * (`toolName` + `args` + `partialResult`) or a `tool_execution_end`-shaped one (`toolName` +
6
+ * `result`, no `args`). For `edit`, the human-readable unified `patch` is only present on the
7
+ * *end* event under `result.details.patch`, so it is pulled from there when args carry no diff.
8
+ * `output` (tool stdout/result text) follows the event: absent on `start` events (no `result` or
9
+ * `partialResult` yet, so `outputOf` yields `undefined` — correct), the output *so far* on
10
+ * `update` events (`partialResult`), and the final output on `end` events (`result`).
9
11
  */
10
12
  export declare function mapToolCall(raw: unknown): ToolCallDetail;
11
13
  export interface PiEventMapper {
@@ -16,7 +18,8 @@ export interface PiEventMapper {
16
18
  * Stateful Pi event mapper (features/agent-sessions.md § Stream events).
17
19
  *
18
20
  * Real Pi RPC events (docs/rpc.md): `agent_start`/`agent_end`, `turn_start`/`turn_end`,
19
- * `message_update` (carrying an `assistantMessageEvent` delta), `tool_execution_start|end`, etc.
21
+ * `message_update` (carrying an `assistantMessageEvent` delta), `tool_execution_start|update|end`,
22
+ * etc.
20
23
  *
21
24
  * Pi's session run loop emits ONE `agent_end` **per low-level run** — a retryable error,
22
25
  * overflow-compaction, or a queued steering/follow-up message all loop into another run before
@@ -30,11 +33,11 @@ export declare function createPiEventMapper(): PiEventMapper;
30
33
  /**
31
34
  * Stateless convenience wrapper — maps a single event through a **fresh** mapper instance. Fine
32
35
  * for one-off/unit assertions of turn-agnostic events (`agent_start`, `message_update`,
33
- * `tool_execution_start|end`, `queue_update`, unknown types). It cannot report a turn's terminal
34
- * event on its own: since disposition is latched from a *prior* `agent_end` in the same session,
35
- * a lone `agent_end`/`agent_settled` call here always sees fresh (`"completed"`) state. Callers
36
- * observing a full turn lifecycle (e.g. `PiAgentSession`) MUST use `createPiEventMapper()` and
37
- * reuse one instance for the session's lifetime.
36
+ * `tool_execution_start|update|end`, `queue_update`, unknown types). It cannot report a turn's
37
+ * terminal event on its own: since disposition is latched from a *prior* `agent_end` in the same
38
+ * session, a lone `agent_end`/`agent_settled` call here always sees fresh (`"completed"`) state.
39
+ * Callers observing a full turn lifecycle (e.g. `PiAgentSession`) MUST use `createPiEventMapper()`
40
+ * and reuse one instance for the session's lifetime.
38
41
  */
39
42
  export declare function mapPiEvent(raw: unknown): AgentStreamEvent | null;
40
43
  //# sourceMappingURL=event-mapper.d.ts.map
@@ -11,9 +11,14 @@ function str(value) {
11
11
  return typeof value === "string" ? value : undefined;
12
12
  }
13
13
  const COMPACTION_REASONS = ["manual", "threshold", "overflow"];
14
- /** Join `result.content` text blocks (Pi RPC `tool_execution_end` shape) into one string. */
14
+ /**
15
+ * Join a tool payload's content text blocks into one string. Pi reports a tool's text under two
16
+ * keys depending on the event: `result.content` on `tool_execution_end`, and
17
+ * `partialResult.content` on `tool_execution_update` (update events carry no `result`; Pi
18
+ * `docs/json.md` § tool events). One reader for both — `result` wins when present.
19
+ */
15
20
  function outputOf(tool) {
16
- const content = asRecord(tool.result).content;
21
+ const content = asRecord(tool.result).content ?? asRecord(tool.partialResult).content;
17
22
  if (!Array.isArray(content))
18
23
  return undefined;
19
24
  const text = content
@@ -23,12 +28,14 @@ function outputOf(tool) {
23
28
  return text || undefined;
24
29
  }
25
30
  /**
26
- * Map a Pi tool-call payload to a normalized `ToolCallDetail`. Accepts either a
27
- * `tool_execution_start`-shaped record (`toolName` + `args`) or a `tool_execution_end`-shaped one
28
- * (`toolName` + `result`, no `args`). For `edit`, the human-readable unified `patch` is only
29
- * present on the *end* event under `result.details.patch`, so it is pulled from there when args
30
- * carry no diff. `output` (tool stdout/result text) is only present on *end* events — `start`
31
- * events have no `result` yet, so `outputOf` yields `undefined` for them, which is correct.
31
+ * Map a Pi tool-call payload to a normalized `ToolCallDetail`. Accepts a
32
+ * `tool_execution_start`-shaped record (`toolName` + `args`), a `tool_execution_update`-shaped one
33
+ * (`toolName` + `args` + `partialResult`) or a `tool_execution_end`-shaped one (`toolName` +
34
+ * `result`, no `args`). For `edit`, the human-readable unified `patch` is only present on the
35
+ * *end* event under `result.details.patch`, so it is pulled from there when args carry no diff.
36
+ * `output` (tool stdout/result text) follows the event: absent on `start` events (no `result` or
37
+ * `partialResult` yet, so `outputOf` yields `undefined` — correct), the output *so far* on
38
+ * `update` events (`partialResult`), and the final output on `end` events (`result`).
32
39
  */
33
40
  export function mapToolCall(raw) {
34
41
  const tool = asRecord(raw);
@@ -83,7 +90,8 @@ export function mapToolCall(raw) {
83
90
  * Stateful Pi event mapper (features/agent-sessions.md § Stream events).
84
91
  *
85
92
  * Real Pi RPC events (docs/rpc.md): `agent_start`/`agent_end`, `turn_start`/`turn_end`,
86
- * `message_update` (carrying an `assistantMessageEvent` delta), `tool_execution_start|end`, etc.
93
+ * `message_update` (carrying an `assistantMessageEvent` delta), `tool_execution_start|update|end`,
94
+ * etc.
87
95
  *
88
96
  * Pi's session run loop emits ONE `agent_end` **per low-level run** — a retryable error,
89
97
  * overflow-compaction, or a queued steering/follow-up message all loop into another run before
@@ -198,6 +206,17 @@ export function createPiEventMapper() {
198
206
  tool: mapToolCall(event),
199
207
  status: "running",
200
208
  };
209
+ // In-flight output snapshot. Ephemeral (`partial: true`): the mapper stays stateless and
210
+ // forwards exactly the text Pi sent — never concatenating successive updates; rate control
211
+ // and ordering against the terminal event live in `PiAgentSession` (tool-output-coalescer).
212
+ case "tool_execution_update":
213
+ return {
214
+ kind: "tool_call",
215
+ callId: str(event.toolCallId),
216
+ tool: mapToolCall(event),
217
+ status: "running",
218
+ partial: true,
219
+ };
201
220
  case "tool_execution_end":
202
221
  return {
203
222
  kind: "tool_call",
@@ -277,7 +296,6 @@ export function createPiEventMapper() {
277
296
  case "turn_end":
278
297
  case "message_start":
279
298
  case "message_end":
280
- case "tool_execution_update":
281
299
  case "auto_retry_start":
282
300
  case "auto_retry_end":
283
301
  return null;
@@ -290,11 +308,11 @@ export function createPiEventMapper() {
290
308
  /**
291
309
  * Stateless convenience wrapper — maps a single event through a **fresh** mapper instance. Fine
292
310
  * for one-off/unit assertions of turn-agnostic events (`agent_start`, `message_update`,
293
- * `tool_execution_start|end`, `queue_update`, unknown types). It cannot report a turn's terminal
294
- * event on its own: since disposition is latched from a *prior* `agent_end` in the same session,
295
- * a lone `agent_end`/`agent_settled` call here always sees fresh (`"completed"`) state. Callers
296
- * observing a full turn lifecycle (e.g. `PiAgentSession`) MUST use `createPiEventMapper()` and
297
- * reuse one instance for the session's lifetime.
311
+ * `tool_execution_start|update|end`, `queue_update`, unknown types). It cannot report a turn's
312
+ * terminal event on its own: since disposition is latched from a *prior* `agent_end` in the same
313
+ * session, a lone `agent_end`/`agent_settled` call here always sees fresh (`"completed"`) state.
314
+ * Callers observing a full turn lifecycle (e.g. `PiAgentSession`) MUST use `createPiEventMapper()`
315
+ * and reuse one instance for the session's lifetime.
298
316
  */
299
317
  export function mapPiEvent(raw) {
300
318
  return createPiEventMapper().map(raw);
@@ -1,3 +1,4 @@
1
+ import type { AgentTodoList } from "../../provider-contract.js";
1
2
  import type { TimelineRow } from "../../timeline-store.js";
2
3
  /**
3
4
  * Load a Pi session file and replay its active branch into daemon `TimelineRow`s, wrapped with
@@ -8,4 +9,12 @@ import type { TimelineRow } from "../../timeline-store.js";
8
9
  * timeline, not a crash).
9
10
  */
10
11
  export declare function hydrateTimelineFromSessionFile(sessionFile: string): TimelineRow[];
12
+ /**
13
+ * Re-derive the agent's todo list from Pi's own on-disk JSONL session file, without spawning a
14
+ * process (task-004 — the process-less counterpart of the live `onTodos` fan-out). Unlike
15
+ * `hydrateTimelineFromSessionFile`, an unreadable/corrupt file THROWS rather than returning an
16
+ * empty result: the caller (the agent-todos service) logs the failure with the agent id
17
+ * (spec: warn + empty), which a silently empty list here would prevent.
18
+ */
19
+ export declare function readTodosFromSessionFile(sessionFile: string): AgentTodoList;
11
20
  //# sourceMappingURL=session-hydration.d.ts.map
@@ -1,5 +1,6 @@
1
1
  import { SessionManager } from "@earendil-works/pi-coding-agent";
2
2
  import { mapToolCall } from "./event-mapper.js";
3
+ import { replayTodosFromBranch } from "./todos.js";
3
4
  /**
4
5
  * Rehydrate a daemon `TimelineRow[]` from Pi's own on-disk JSONL session file (docs:
5
6
  * session-format.md § SessionMessageEntry). Pi persists the full conversation (messages, tool
@@ -193,4 +194,15 @@ export function hydrateTimelineFromSessionFile(sessionFile) {
193
194
  closeTurn();
194
195
  return rows;
195
196
  }
197
+ /**
198
+ * Re-derive the agent's todo list from Pi's own on-disk JSONL session file, without spawning a
199
+ * process (task-004 — the process-less counterpart of the live `onTodos` fan-out). Unlike
200
+ * `hydrateTimelineFromSessionFile`, an unreadable/corrupt file THROWS rather than returning an
201
+ * empty result: the caller (the agent-todos service) logs the failure with the agent id
202
+ * (spec: warn + empty), which a silently empty list here would prevent.
203
+ */
204
+ export function readTodosFromSessionFile(sessionFile) {
205
+ const entries = SessionManager.open(sessionFile).getBranch();
206
+ return replayTodosFromBranch(entries);
207
+ }
196
208
  //# sourceMappingURL=session-hydration.js.map
@@ -0,0 +1,65 @@
1
+ import type { AgentTodoList } from "../../provider-contract.js";
2
+ /**
3
+ * Recognition of the `rpiv-todo` extension's state for the Pi provider (features/agent-todos.md
4
+ * § Pi adapter: recognition). The agent's todo list is not exposed by Pi itself: the extension
5
+ * (`@juicesharp/rpiv-todo`) keeps it in module state and renders it through a factory `setWidget`
6
+ * that Pi never forwards over RPC. So the adapter re-derives it from the two places the
7
+ * extension also leaves it — live, from the RPC stream; at rest, from Pi's session file.
8
+ *
9
+ * DELIBERATELY MIRRORS INTERNALS — NOT IMPORTABLE. None of this is public API of Pi or of the
10
+ * extension, and the extension's package cannot be imported by the daemon. Mirrored from
11
+ * `@juicesharp/rpiv-todo@2.15.0` (verified live against Pi 1.4.0, sprint-079/task-001):
12
+ * - `tool/types.ts`: `TOOL_NAME = "todo"`, `STATE_ENTRY_TYPE = "rpiv-todo-state"`, the `Task` /
13
+ * `TaskDetails` shapes and the four statuses (`deleted` is a tombstone kept IN the list)
14
+ * - `state/replay.ts`: `isTask`, `isTaskDetails` ("skip whole" validation) and `replayFromBranch`
15
+ * (state entries beat `toolResult` details once any exists)
16
+ * Re-check all of it when the curated pack's rpiv-todo version changes (the source is unpinned:
17
+ * `extensions/curated-packs.ts`) and when Pi is bumped (`entry_appended` and `tool_execution_end`
18
+ * frame shapes, `SessionManager.getBranch()` entries). Drift fails closed: a snapshot that no
19
+ * longer validates is ignored and the last valid list stays, never a wrong one.
20
+ */
21
+ export declare const TODO_TOOL_NAME = "todo";
22
+ export declare const TODO_STATE_ENTRY_TYPE = "rpiv-todo-state";
23
+ /** One task as rpiv-todo persists it (`metadata` is opaque extension data and never forwarded). */
24
+ interface TodoTask {
25
+ id: number;
26
+ subject: string;
27
+ status: "pending" | "in_progress" | "completed" | "deleted";
28
+ description?: string;
29
+ activeForm?: string;
30
+ owner?: string;
31
+ blockedBy?: number[];
32
+ metadata?: Record<string, unknown>;
33
+ }
34
+ /** rpiv-todo's `TaskDetails` envelope (`action`/`params`/`error` are ignored here). */
35
+ export interface TodoDetails {
36
+ tasks: TodoTask[];
37
+ nextId: number;
38
+ }
39
+ /**
40
+ * Strict discriminator for a `{tasks, nextId}` envelope. If ANY task is malformed the whole
41
+ * snapshot is rejected, exactly as the extension does: a foreign tool that happens to be named
42
+ * `todo`, or a future schema, then shows no panel instead of a wrong one.
43
+ */
44
+ export declare function isTodoDetails(value: unknown): value is TodoDetails;
45
+ /** Wire projection: drop tombstones, `metadata` and `nextId`, then sort and cap. */
46
+ export declare function toAgentTodos(details: TodoDetails): AgentTodoList;
47
+ /**
48
+ * The list on a session branch, in rpiv-todo's own precedence: walk chronologically and keep the
49
+ * last valid snapshot from each source. `rpiv-todo-state` custom entries are written for EVERY
50
+ * state-changing call (including nested `ctx.executeTool` calls that never land as a `toolResult`),
51
+ * so once any exists they are authoritative; `toolResult` details serve sessions written before
52
+ * state entries existed. An empty branch is an empty list.
53
+ */
54
+ export declare function replayTodosFromBranch(entries: Iterable<unknown>): AgentTodoList;
55
+ /**
56
+ * Live recogniser over a raw Pi RPC frame. Pi 1.4.0 announces a `todo` change twice:
57
+ * `entry_appended` (the extension's `rpiv-todo-state` entry; fires for every state change, however
58
+ * the tool was reached) and then `tool_execution_end` (direct calls; also `list`/error calls with
59
+ * unchanged state). Both carry the full list, so either is a complete snapshot; the service dedupes
60
+ * the pair. `parentToolCallId` is deliberately NOT inspected: a nested call (`ctx.executeTool`, e.g.
61
+ * Pi's `codemode`) runs in the SAME session and mutates the same list.
62
+ */
63
+ export declare function todoDetailsFromFrame(frame: unknown): TodoDetails | undefined;
64
+ export {};
65
+ //# sourceMappingURL=todos.d.ts.map
@@ -0,0 +1,122 @@
1
+ import { capAgentTodos } from "../../agent-todos/todo-limits.js";
2
+ /**
3
+ * Recognition of the `rpiv-todo` extension's state for the Pi provider (features/agent-todos.md
4
+ * § Pi adapter: recognition). The agent's todo list is not exposed by Pi itself: the extension
5
+ * (`@juicesharp/rpiv-todo`) keeps it in module state and renders it through a factory `setWidget`
6
+ * that Pi never forwards over RPC. So the adapter re-derives it from the two places the
7
+ * extension also leaves it — live, from the RPC stream; at rest, from Pi's session file.
8
+ *
9
+ * DELIBERATELY MIRRORS INTERNALS — NOT IMPORTABLE. None of this is public API of Pi or of the
10
+ * extension, and the extension's package cannot be imported by the daemon. Mirrored from
11
+ * `@juicesharp/rpiv-todo@2.15.0` (verified live against Pi 1.4.0, sprint-079/task-001):
12
+ * - `tool/types.ts`: `TOOL_NAME = "todo"`, `STATE_ENTRY_TYPE = "rpiv-todo-state"`, the `Task` /
13
+ * `TaskDetails` shapes and the four statuses (`deleted` is a tombstone kept IN the list)
14
+ * - `state/replay.ts`: `isTask`, `isTaskDetails` ("skip whole" validation) and `replayFromBranch`
15
+ * (state entries beat `toolResult` details once any exists)
16
+ * Re-check all of it when the curated pack's rpiv-todo version changes (the source is unpinned:
17
+ * `extensions/curated-packs.ts`) and when Pi is bumped (`entry_appended` and `tool_execution_end`
18
+ * frame shapes, `SessionManager.getBranch()` entries). Drift fails closed: a snapshot that no
19
+ * longer validates is ignored and the last valid list stays, never a wrong one.
20
+ */
21
+ export const TODO_TOOL_NAME = "todo";
22
+ export const TODO_STATE_ENTRY_TYPE = "rpiv-todo-state";
23
+ const optional = (value, valid) => value === undefined || valid(value);
24
+ const isString = (v) => typeof v === "string";
25
+ function isTodoTask(value) {
26
+ if (!value || typeof value !== "object")
27
+ return false;
28
+ const t = value;
29
+ return (Number.isSafeInteger(t.id) &&
30
+ typeof t.subject === "string" &&
31
+ (t.status === "pending" ||
32
+ t.status === "in_progress" ||
33
+ t.status === "completed" ||
34
+ t.status === "deleted") &&
35
+ optional(t.description, isString) &&
36
+ optional(t.activeForm, isString) &&
37
+ optional(t.owner, isString) &&
38
+ optional(t.blockedBy, (v) => Array.isArray(v) && v.every((id) => Number.isSafeInteger(id))) &&
39
+ optional(t.metadata, (v) => typeof v === "object" && v !== null));
40
+ }
41
+ /**
42
+ * Strict discriminator for a `{tasks, nextId}` envelope. If ANY task is malformed the whole
43
+ * snapshot is rejected, exactly as the extension does: a foreign tool that happens to be named
44
+ * `todo`, or a future schema, then shows no panel instead of a wrong one.
45
+ */
46
+ export function isTodoDetails(value) {
47
+ if (!value || typeof value !== "object")
48
+ return false;
49
+ const v = value;
50
+ return Array.isArray(v.tasks) && v.tasks.every(isTodoTask) && Number.isSafeInteger(v.nextId);
51
+ }
52
+ /** Wire projection: drop tombstones, `metadata` and `nextId`, then sort and cap. */
53
+ export function toAgentTodos(details) {
54
+ const tasks = [];
55
+ for (const task of details.tasks) {
56
+ if (task.status === "deleted")
57
+ continue;
58
+ const todo = { id: task.id, subject: task.subject, status: task.status };
59
+ if (task.activeForm !== undefined)
60
+ todo.activeForm = task.activeForm;
61
+ if (task.description !== undefined)
62
+ todo.description = task.description;
63
+ if (task.owner !== undefined)
64
+ todo.owner = task.owner;
65
+ if (task.blockedBy !== undefined)
66
+ todo.blockedBy = task.blockedBy;
67
+ tasks.push(todo);
68
+ }
69
+ return capAgentTodos(tasks);
70
+ }
71
+ /**
72
+ * The list on a session branch, in rpiv-todo's own precedence: walk chronologically and keep the
73
+ * last valid snapshot from each source. `rpiv-todo-state` custom entries are written for EVERY
74
+ * state-changing call (including nested `ctx.executeTool` calls that never land as a `toolResult`),
75
+ * so once any exists they are authoritative; `toolResult` details serve sessions written before
76
+ * state entries existed. An empty branch is an empty list.
77
+ */
78
+ export function replayTodosFromBranch(entries) {
79
+ let fromEntries;
80
+ let fromResults;
81
+ for (const entry of entries) {
82
+ const e = entry;
83
+ if (e.type === "custom") {
84
+ if (e.customType === TODO_STATE_ENTRY_TYPE && isTodoDetails(e.data))
85
+ fromEntries = e.data;
86
+ continue;
87
+ }
88
+ if (e.type !== "message")
89
+ continue;
90
+ const msg = e.message;
91
+ if (msg?.role !== "toolResult" || msg.toolName !== TODO_TOOL_NAME)
92
+ continue;
93
+ if (isTodoDetails(msg.details))
94
+ fromResults = msg.details;
95
+ }
96
+ return toAgentTodos(fromEntries ?? fromResults ?? { tasks: [], nextId: 1 });
97
+ }
98
+ /**
99
+ * Live recogniser over a raw Pi RPC frame. Pi 1.4.0 announces a `todo` change twice:
100
+ * `entry_appended` (the extension's `rpiv-todo-state` entry; fires for every state change, however
101
+ * the tool was reached) and then `tool_execution_end` (direct calls; also `list`/error calls with
102
+ * unchanged state). Both carry the full list, so either is a complete snapshot; the service dedupes
103
+ * the pair. `parentToolCallId` is deliberately NOT inspected: a nested call (`ctx.executeTool`, e.g.
104
+ * Pi's `codemode`) runs in the SAME session and mutates the same list.
105
+ */
106
+ export function todoDetailsFromFrame(frame) {
107
+ if (!frame || typeof frame !== "object")
108
+ return undefined;
109
+ const f = frame;
110
+ if (f.type === "entry_appended") {
111
+ const entry = f.entry;
112
+ if (entry?.type === "custom" && entry.customType === TODO_STATE_ENTRY_TYPE) {
113
+ return isTodoDetails(entry.data) ? entry.data : undefined;
114
+ }
115
+ return undefined;
116
+ }
117
+ if (f.type === "tool_execution_end" && f.toolName === TODO_TOOL_NAME) {
118
+ return isTodoDetails(f.result?.details) ? f.result.details : undefined;
119
+ }
120
+ return undefined;
121
+ }
122
+ //# sourceMappingURL=todos.js.map
@@ -0,0 +1,58 @@
1
+ import type { AgentStreamEvent } from "@av-pi-studio/protocol";
2
+ /**
3
+ * Per-`callId` rate and size control for ephemeral partial tool output
4
+ * (features/tool-output-streaming.md § Server — per-callId coalescer).
5
+ *
6
+ * `PiAgentSession` routes every mapped event through `accept`. A `partial: true` `tool_call` is
7
+ * owned by the coalescer from then on: it is delivered to subscribers (never recorded in the
8
+ * session's replay history) on a leading + trailing edge at most every `PARTIAL_MIN_INTERVAL_MS`
9
+ * per call, latest snapshot winning, with its output tail-capped. Any other event is handed back
10
+ * unchanged for the caller's normal record-and-fan-out path, after the coalescer has dropped the
11
+ * state it supersedes:
12
+ *
13
+ * - a non-partial `tool_call` (start, `"started"`, `completed`/`error`) cancels that call's
14
+ * pending flush and snapshot — a trailing flush firing after the terminal would regress the
15
+ * card from `completed` back to `running`;
16
+ * - a turn terminal (`turn_completed`/`turn_failed`/`turn_canceled`) cancels every pending flush,
17
+ * so nothing escapes after a turn ends or is aborted (`cancelAll` covers session close).
18
+ *
19
+ * Dropping intermediate snapshots is lossless for snapshot-style tools (bash sends accumulated
20
+ * output); a delta-style tool would show its latest chunk — a documented degradation, not
21
+ * reconciled here.
22
+ *
23
+ * The cap is measured in UTF-8 bytes (`Buffer.byteLength`) — the unit that bounds the wire frame —
24
+ * and cut on a code-point boundary. Only partial snapshots are capped; a terminal event's output
25
+ * is authoritative and passes through untouched.
26
+ *
27
+ * Clock and timers are injectable so tests assert timing without real waiting; the defaults read
28
+ * the globals at call time so fake timers installed later are honoured.
29
+ */
30
+ /** Minimum spacing between emitted partials of one call (≤5 broadcasts/s per tool call). */
31
+ export declare const PARTIAL_MIN_INTERVAL_MS = 200;
32
+ /** Largest tail (UTF-8 bytes) of a snapshot put on the wire; bounds relay frame size. */
33
+ export declare const PARTIAL_OUTPUT_CAP_BYTES = 65536;
34
+ /** Cancels a callback scheduled through {@link ToolOutputCoalescerOptions.schedule}. */
35
+ export type CancelTimer = () => void;
36
+ export interface ToolOutputCoalescerOptions {
37
+ /** Receives each partial that survives throttling, tail-capped: synchronously on the leading
38
+ * edge, from a timer on the trailing edge. */
39
+ deliver: (event: AgentStreamEvent) => void;
40
+ /** Epoch milliseconds; defaults to `Date.now`. */
41
+ now?: () => number;
42
+ /** Runs `callback` after `delayMs` and returns its canceller; defaults to an unref'd
43
+ * `setTimeout`. */
44
+ schedule?: (callback: () => void, delayMs: number) => CancelTimer;
45
+ }
46
+ export interface ToolOutputCoalescer {
47
+ /**
48
+ * Route one mapped event. Returns `true` when `event` is a partial the coalescer took over
49
+ * (delivered now or later through `deliver`; the caller must neither record nor emit it) and
50
+ * `false` for every other event, which the caller records and emits as usual — superseded
51
+ * pending partials have already been cancelled.
52
+ */
53
+ accept(event: AgentStreamEvent): boolean;
54
+ /** Cancel every pending flush and forget all per-call state (turn terminal, session close). */
55
+ cancelAll(): void;
56
+ }
57
+ export declare function createToolOutputCoalescer(options: ToolOutputCoalescerOptions): ToolOutputCoalescer;
58
+ //# sourceMappingURL=tool-output-coalescer.d.ts.map
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Per-`callId` rate and size control for ephemeral partial tool output
3
+ * (features/tool-output-streaming.md § Server — per-callId coalescer).
4
+ *
5
+ * `PiAgentSession` routes every mapped event through `accept`. A `partial: true` `tool_call` is
6
+ * owned by the coalescer from then on: it is delivered to subscribers (never recorded in the
7
+ * session's replay history) on a leading + trailing edge at most every `PARTIAL_MIN_INTERVAL_MS`
8
+ * per call, latest snapshot winning, with its output tail-capped. Any other event is handed back
9
+ * unchanged for the caller's normal record-and-fan-out path, after the coalescer has dropped the
10
+ * state it supersedes:
11
+ *
12
+ * - a non-partial `tool_call` (start, `"started"`, `completed`/`error`) cancels that call's
13
+ * pending flush and snapshot — a trailing flush firing after the terminal would regress the
14
+ * card from `completed` back to `running`;
15
+ * - a turn terminal (`turn_completed`/`turn_failed`/`turn_canceled`) cancels every pending flush,
16
+ * so nothing escapes after a turn ends or is aborted (`cancelAll` covers session close).
17
+ *
18
+ * Dropping intermediate snapshots is lossless for snapshot-style tools (bash sends accumulated
19
+ * output); a delta-style tool would show its latest chunk — a documented degradation, not
20
+ * reconciled here.
21
+ *
22
+ * The cap is measured in UTF-8 bytes (`Buffer.byteLength`) — the unit that bounds the wire frame —
23
+ * and cut on a code-point boundary. Only partial snapshots are capped; a terminal event's output
24
+ * is authoritative and passes through untouched.
25
+ *
26
+ * Clock and timers are injectable so tests assert timing without real waiting; the defaults read
27
+ * the globals at call time so fake timers installed later are honoured.
28
+ */
29
+ /** Minimum spacing between emitted partials of one call (≤5 broadcasts/s per tool call). */
30
+ export const PARTIAL_MIN_INTERVAL_MS = 200;
31
+ /** Largest tail (UTF-8 bytes) of a snapshot put on the wire; bounds relay frame size. */
32
+ export const PARTIAL_OUTPUT_CAP_BYTES = 65536;
33
+ /** One shared bucket for events without a `callId`; partial and terminal must agree on the key. */
34
+ function callKey(event) {
35
+ return event.callId ?? "";
36
+ }
37
+ /** The last `maxBytes` UTF-8 bytes of `text`, starting on a code-point boundary. */
38
+ function tailWithinBytes(text, maxBytes) {
39
+ // UTF-8 spends at most 3 bytes per UTF-16 code unit, so a short string cannot exceed the cap.
40
+ if (text.length * 3 <= maxBytes || Buffer.byteLength(text, "utf8") <= maxBytes)
41
+ return text;
42
+ const bytes = Buffer.from(text, "utf8");
43
+ let start = bytes.length - maxBytes;
44
+ // Skip UTF-8 continuation bytes (0b10xxxxxx) so the cut never splits a character.
45
+ while (start < bytes.length && (bytes.readUInt8(start) & 0xc0) === 0x80)
46
+ start++;
47
+ return bytes.toString("utf8", start);
48
+ }
49
+ function withTailCap(event) {
50
+ const output = event.tool.output;
51
+ if (output === undefined)
52
+ return event;
53
+ const tail = tailWithinBytes(output, PARTIAL_OUTPUT_CAP_BYTES);
54
+ return tail === output ? event : { ...event, tool: { ...event.tool, output: tail } };
55
+ }
56
+ function scheduleTimeout(callback, delayMs) {
57
+ const handle = setTimeout(callback, delayMs);
58
+ // A pending flush must never keep the daemon alive.
59
+ handle.unref();
60
+ return () => clearTimeout(handle);
61
+ }
62
+ export function createToolOutputCoalescer(options) {
63
+ const { deliver } = options;
64
+ const now = options.now ?? (() => Date.now());
65
+ const schedule = options.schedule ?? scheduleTimeout;
66
+ const calls = new Map();
67
+ const flush = (state) => {
68
+ const event = state.pending;
69
+ state.pending = undefined;
70
+ state.cancelFlush = undefined;
71
+ if (!event)
72
+ return;
73
+ state.lastEmit = now();
74
+ deliver(withTailCap(event));
75
+ };
76
+ const offerPartial = (event) => {
77
+ const key = callKey(event);
78
+ const at = now();
79
+ const state = calls.get(key);
80
+ if (state && at - state.lastEmit < PARTIAL_MIN_INTERVAL_MS) {
81
+ // Too soon: the latest snapshot supersedes any pending one; one flush per call is enough.
82
+ state.pending = event;
83
+ state.cancelFlush ??= schedule(() => flush(state), state.lastEmit + PARTIAL_MIN_INTERVAL_MS - at);
84
+ return;
85
+ }
86
+ // Leading edge. A flush may still be pending if its timer is running late — this snapshot is
87
+ // newer than the pending one, so retire the flush instead of letting it deliver a stale one.
88
+ state?.cancelFlush?.();
89
+ calls.set(key, { lastEmit: at });
90
+ deliver(withTailCap(event));
91
+ };
92
+ const cancelAll = () => {
93
+ for (const state of calls.values())
94
+ state.cancelFlush?.();
95
+ calls.clear();
96
+ };
97
+ return {
98
+ accept(event) {
99
+ if (event.kind === "tool_call") {
100
+ if (event.partial) {
101
+ offerPartial(event);
102
+ return true;
103
+ }
104
+ // Start, `"started"` or terminal: this call's partials are over — nothing pending may
105
+ // outlive the event about to be emitted.
106
+ const key = callKey(event);
107
+ calls.get(key)?.cancelFlush?.();
108
+ calls.delete(key);
109
+ return false;
110
+ }
111
+ if (event.kind === "turn_completed" ||
112
+ event.kind === "turn_failed" ||
113
+ event.kind === "turn_canceled") {
114
+ cancelAll();
115
+ }
116
+ return false;
117
+ },
118
+ cancelAll,
119
+ };
120
+ }
121
+ //# sourceMappingURL=tool-output-coalescer.js.map
@@ -24,6 +24,13 @@ export interface SlashCommandOpsDeps {
24
24
  resolveClient: (provider: string) => AgentClient;
25
25
  broadcast: (sessions: Iterable<Session>, message: unknown) => void;
26
26
  logger?: Logger;
27
+ /**
28
+ * Called after a fork rebinds the agent's native session and the timeline is reset (the same
29
+ * branch that broadcasts `agent_timeline_reset`). The agent-todos service re-reads the new
30
+ * branch here: the todo list is derived from the session file, which just changed. Not a stream
31
+ * event, so nothing else would tell it.
32
+ */
33
+ onTimelineReset?: (agentId: string) => void;
27
34
  }
28
35
  export interface ListProviderModelsResult {
29
36
  type: "list_provider_models_response";
@@ -209,6 +209,7 @@ export class SlashCommandOperationsService {
209
209
  agentId,
210
210
  reason: "fork",
211
211
  });
212
+ this.deps.onTimelineReset?.(agentId);
212
213
  }
213
214
  }
214
215
  return { type: "agent_fork_response", payload };
@@ -27,6 +27,8 @@ import { loadConfig } from "../config/daemon-config.js";
27
27
  import { createDaemonLogger } from "../logging/logger.js";
28
28
  import { registerAgentUiHandlers } from "../agent/agent-ui/agent-ui-rpc.js";
29
29
  import { AgentUiService } from "../agent/agent-ui/agent-ui-service.js";
30
+ import { registerAgentTodosHandlers } from "../agent/agent-todos/agent-todos-rpc.js";
31
+ import { AgentTodosService } from "../agent/agent-todos/agent-todos-service.js";
30
32
  import { AgentManager } from "../agent/agent-manager.js";
31
33
  import { AgentService, getTimeline } from "../agent/agent-service.js";
32
34
  import { SessionOperationsService } from "../agent/session-operations.js";
@@ -214,12 +216,25 @@ export function startDaemon(opts) {
214
216
  // ── Extension UI bridge (features/extension-ui-rpc.md) — constructed before the manager so
215
217
  // `onSessionAttached` below can close over it.
216
218
  const agentUiService = new AgentUiService({ broadcast, getActiveSessions, logger });
219
+ // ── Agent todos (features/agent-todos.md) — also before the manager (`onSessionAttached`), but it
220
+ // reads the agent record + live session back through `manager`, so those are lazy closures.
221
+ const agentTodosService = new AgentTodosService({
222
+ broadcast,
223
+ getActiveSessions,
224
+ getAgent: (agentId) => manager.get(agentId),
225
+ resolveClient,
226
+ logger,
227
+ });
217
228
  // ── Disk-persisted agent manager (recovers agents on boot) ───────────────────
218
229
  const manager = new AgentManager({
219
230
  home,
220
231
  saveAgent: (record) => saveAgent(home, record),
221
232
  loadAllAgents: () => loadAllAgents(home),
222
- onSessionAttached: (agentId, session) => agentUiService.attach(agentId, session),
233
+ // `onSessionAttached` is a single slot: compose every bridge that watches a new session.
234
+ onSessionAttached: (agentId, session) => {
235
+ agentUiService.attach(agentId, session);
236
+ agentTodosService.attach(agentId, session);
237
+ },
223
238
  logger,
224
239
  });
225
240
  // Forward archive/delete lifecycle events to every connected client (multi-tab/multi-client
@@ -231,6 +246,7 @@ export function startDaemon(opts) {
231
246
  logger.info({ agentId: event.agentId }, event.type.replace("_", " "));
232
247
  broadcast(getActiveSessions(), { type: "session", message: event });
233
248
  agentUiService.sweep(event.agentId, "aborted");
249
+ agentTodosService.sweep(event.agentId);
234
250
  }
235
251
  });
236
252
  const registry = new HandlerRegistry(logger);
@@ -255,12 +271,14 @@ export function startDaemon(opts) {
255
271
  resolveClient,
256
272
  broadcast,
257
273
  logger,
274
+ onTimelineReset: (agentId) => agentTodosService.reconcile(agentId),
258
275
  });
259
276
  slashCommandOps.registerHandlers(registry, getActiveSessions);
260
277
  registerTimelineHandler(registry, { manager, resolveClient });
261
278
  const permissionService = new PermissionService({ manager, broadcast });
262
279
  permissionService.registerHandlers(registry, getActiveSessions);
263
280
  registerAgentUiHandlers(registry, { service: agentUiService, logger });
281
+ registerAgentTodosHandlers(registry, { service: agentTodosService });
264
282
  // ── Directory listing (agents) ────────────────────────────────────────────────
265
283
  registry.register("list_agents_request", (ctx) => ({
266
284
  type: "list_agents_response",