@av-pi-studio/server 0.0.112 → 0.0.114

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.
@@ -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
@@ -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,10 @@ 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";
8
9
  /**
9
10
  * Pi provider adapter (features/agent-providers.md § Pi lifecycle / § Models·modes·features /
10
11
  * § Import & resume). Spawns `pi --mode rpc` (or a configured `command`), maps RPC events to
@@ -20,6 +21,7 @@ export const PI_CAPABILITIES = {
20
21
  supportsToolInvocations: true,
21
22
  supportsSteering: true,
22
23
  supportsExtensionUi: true,
24
+ supportsTodos: true,
23
25
  };
24
26
  /** Build Pi argv, appending (never replacing) the system prompt and optional `--mcp-config`. */
25
27
  export function buildPiArgs(base, opts) {
@@ -113,6 +115,7 @@ class PiAgentSession {
113
115
  capabilities = PI_CAPABILITIES;
114
116
  subscribers = new Set();
115
117
  uiSubscribers = new Set();
118
+ todoSubscribers = new Set();
116
119
  history = [];
117
120
  eventMapper = createPiEventMapper();
118
121
  modes = [];
@@ -135,6 +138,18 @@ class PiAgentSession {
135
138
  cb(req);
136
139
  return;
137
140
  }
141
+ // Agent todos (features/agent-todos.md § Pi adapter: live updates) — runs IN ADDITION to
142
+ // the mapping below; the timeline row for the same frame is unchanged. Pi announces a
143
+ // `todo` change twice (`entry_appended` then `tool_execution_end`); the service, not this
144
+ // adapter, dedupes the pair. No `parentToolCallId` filter on purpose: a nested call (e.g.
145
+ // `ctx.executeTool`/`codemode`) runs in the same session and mutates the same list, so it
146
+ // is a legitimate snapshot too.
147
+ const details = todoDetailsFromFrame(raw);
148
+ if (details) {
149
+ const list = toAgentTodos(details);
150
+ for (const cb of this.todoSubscribers)
151
+ cb(list);
152
+ }
138
153
  const event = this.eventMapper.map(raw);
139
154
  if (event)
140
155
  this.emit(event);
@@ -313,6 +328,18 @@ class PiAgentSession {
313
328
  respondToUi(providerRequestId, response) {
314
329
  this.transport.notify("extension_ui_response", { ...response, id: providerRequestId });
315
330
  }
331
+ onTodos(cb) {
332
+ this.todoSubscribers.add(cb);
333
+ return () => this.todoSubscribers.delete(cb);
334
+ }
335
+ /** Re-read `this.sessionFile` each call so it follows a fork/new_session rebind
336
+ * (`refreshSessionFile`). Throws on an unreadable file so the caller (the agent-todos service)
337
+ * can log it with the agent id; no file at all is a legitimate empty state, not an error. */
338
+ readTodos() {
339
+ if (!this.sessionFile)
340
+ return { tasks: [], truncated: false };
341
+ return readTodosFromSessionFile(this.sessionFile);
342
+ }
316
343
  describePersistence() {
317
344
  return {
318
345
  provider: this.provider,
@@ -681,6 +708,14 @@ export class PiAgentClient {
681
708
  return [];
682
709
  return hydrateTimelineFromSessionFile(sessionFile);
683
710
  }
711
+ /** Process-less counterpart of `AgentSession.readTodos`, for a record with no live session
712
+ * (e.g. after a daemon restart). Reads `handle.nativeHandle` directly; never spawns `pi`. */
713
+ readTodos(handle) {
714
+ const sessionFile = typeof handle.nativeHandle === "string" ? handle.nativeHandle : undefined;
715
+ if (!sessionFile)
716
+ return { tasks: [], truncated: false };
717
+ return readTodosFromSessionFile(sessionFile);
718
+ }
684
719
  }
685
720
  /** Factory matching the provider-registry signature. */
686
721
  export function createPiClient(deps = {}) {
@@ -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
@@ -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",
@@ -15,6 +15,8 @@ import { createWebSocketServer } from "../ws/ws-server.js";
15
15
  import { HandlerRegistry, routeTextFrame } from "../ws/router.js";
16
16
  import { registerAgentUiHandlers } from "../agent/agent-ui/agent-ui-rpc.js";
17
17
  import { AgentUiService } from "../agent/agent-ui/agent-ui-service.js";
18
+ import { registerAgentTodosHandlers } from "../agent/agent-todos/agent-todos-rpc.js";
19
+ import { AgentTodosService } from "../agent/agent-todos/agent-todos-service.js";
18
20
  import { AgentManager } from "../agent/agent-manager.js";
19
21
  import { AgentService } from "../agent/agent-service.js";
20
22
  import { deterministicFallback } from "../agent/structured-generation.js";
@@ -54,6 +56,16 @@ export function startDevDaemon(opts) {
54
56
  // dev daemon is mock-only, so a UI family unexercisable here would be untestable exactly where a
55
57
  // sibling UI scope needs to develop against it.
56
58
  const agentUiService = new AgentUiService({ broadcast, getActiveSessions, logger });
59
+ // ── Agent todos (features/agent-todos.md) — registered in dev for the same reason as the UI
60
+ // bridge: the mock provider is the scripted producer (`#todo …` prompts). `manager` and
61
+ // `resolveClient` are declared below, so both are read lazily.
62
+ const agentTodosService = new AgentTodosService({
63
+ broadcast,
64
+ getActiveSessions,
65
+ getAgent: (agentId) => manager.get(agentId),
66
+ resolveClient: (provider) => resolveClient(provider),
67
+ logger,
68
+ });
57
69
  // ── In-memory agent manager (no disk persistence in dev mode) ──────────────
58
70
  const agentsById = new Map();
59
71
  const manager = new AgentManager({
@@ -63,7 +75,11 @@ export function startDevDaemon(opts) {
63
75
  },
64
76
  loadAllAgents: async () => [...agentsById.values()],
65
77
  deleteAgent: async (_cwd, id) => agentsById.delete(id),
66
- onSessionAttached: (agentId, session) => agentUiService.attach(agentId, session),
78
+ // `onSessionAttached` is a single slot: compose every bridge that watches a new session.
79
+ onSessionAttached: (agentId, session) => {
80
+ agentUiService.attach(agentId, session);
81
+ agentTodosService.attach(agentId, session);
82
+ },
67
83
  logger,
68
84
  });
69
85
  // ── Provider resolution: mock only in dev ───────────────────────────────────
@@ -76,6 +92,7 @@ export function startDevDaemon(opts) {
76
92
  if (event.type === "agent_archived" || event.type === "agent_deleted") {
77
93
  broadcast(getActiveSessions(), { type: "session", message: event });
78
94
  agentUiService.sweep(event.agentId, "aborted");
95
+ agentTodosService.sweep(event.agentId);
79
96
  }
80
97
  });
81
98
  // ── Handler registry ────────────────────────────────────────────────────────
@@ -103,12 +120,14 @@ export function startDevDaemon(opts) {
103
120
  resolveClient,
104
121
  broadcast,
105
122
  logger,
123
+ onTimelineReset: (agentId) => agentTodosService.reconcile(agentId),
106
124
  });
107
125
  slashCommandOps.registerHandlers(registry, getActiveSessions);
108
126
  registerTimelineHandler(registry, { manager, resolveClient });
109
127
  const permissionService = new PermissionService({ manager, broadcast });
110
128
  permissionService.registerHandlers(registry, getActiveSessions);
111
129
  registerAgentUiHandlers(registry, { service: agentUiService, logger });
130
+ registerAgentTodosHandlers(registry, { service: agentTodosService });
112
131
  // Unlike extensions (production-only), this subsystem must exist in dev: the web client is
113
132
  // developed against the dev daemon, and without it every dev session runs the
114
133
  // capability-absent degrade path and can never exercise the toggle.