@indexyz/pi-todo 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/LICENSE +21 -0
- package/README.md +81 -2
- package/config.ts +141 -0
- package/docs/configuration.md +108 -0
- package/docs/overlay.md +128 -0
- package/docs/tool-schema.md +191 -0
- package/index.ts +302 -0
- package/locales/de.json +19 -0
- package/locales/en.json +17 -0
- package/locales/es.json +19 -0
- package/locales/fr.json +19 -0
- package/locales/pt-BR.json +19 -0
- package/locales/pt.json +19 -0
- package/locales/ru.json +19 -0
- package/locales/uk.json +19 -0
- package/locales/zh.json +19 -0
- package/package.json +87 -4
- package/state/i18n-bridge.ts +64 -0
- package/state/invariants.ts +20 -0
- package/state/replay.ts +142 -0
- package/state/selectors.ts +108 -0
- package/state/state-reducer.ts +324 -0
- package/state/state.ts +18 -0
- package/state/store.ts +125 -0
- package/state/task-graph.ts +61 -0
- package/todo-overlay.ts +255 -0
- package/todo.ts +168 -0
- package/tool/normalize-params.ts +44 -0
- package/tool/response-envelope.ts +114 -0
- package/tool/sanitize.ts +34 -0
- package/tool/types.ts +188 -0
- package/view/format.ts +202 -0
package/todo-overlay.ts
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* todo-overlay.ts — Persistent widget showing todo list above the editor.
|
|
3
|
+
*
|
|
4
|
+
* Lifecycle controller for Pi's `setWidget` contract: factory-form
|
|
5
|
+
* registration in widgetContainerAbove, register-once + requestRender()
|
|
6
|
+
* refresh, configurable collapse-not-scroll (default 12 content rows via
|
|
7
|
+
* getMaxWidgetLines(); plus a trailing spacer row so the widget renders up
|
|
8
|
+
* to 13 lines), Pi tool-output expansion awareness, auto-hide when empty.
|
|
9
|
+
*
|
|
10
|
+
* Reads live state via `getRenderState()` (the ctx-less foreground slot) at render
|
|
11
|
+
* time — NEVER `replayFromBranch` from `tool_execution_end` (branch is stale;
|
|
12
|
+
* `message_end` runs after).
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import type { ExtensionUIContext, Theme } from "@earendil-works/pi-coding-agent";
|
|
16
|
+
import { type TUI, truncateToWidth } from "@earendil-works/pi-tui";
|
|
17
|
+
import { COLLAPSE_KEY_OFF, getMaxWidgetLines, resolveCollapseKey } from "./config.ts";
|
|
18
|
+
import { formatStatusLabel, t } from "./state/i18n-bridge.ts";
|
|
19
|
+
import {
|
|
20
|
+
selectHasActive,
|
|
21
|
+
selectOverlayLayout,
|
|
22
|
+
selectShowTaskIds,
|
|
23
|
+
selectTodoCounts,
|
|
24
|
+
} from "./state/selectors.ts";
|
|
25
|
+
import { getRenderState } from "./state/store.ts";
|
|
26
|
+
import { formatOverlayTaskLine } from "./view/format.ts";
|
|
27
|
+
|
|
28
|
+
const WIDGET_KEY = "rpiv-todos";
|
|
29
|
+
|
|
30
|
+
// English fallbacks for localized overlay chrome strings.
|
|
31
|
+
const OVERLAY_HEADING = "Todos";
|
|
32
|
+
const OVERLAY_MORE = "more";
|
|
33
|
+
const OVERLAY_EXPAND_HINT = "{key} to expand";
|
|
34
|
+
const OVERLAY_COLLAPSED = "collapsed";
|
|
35
|
+
|
|
36
|
+
export class TodoOverlay {
|
|
37
|
+
private uiCtx: ExtensionUIContext | undefined;
|
|
38
|
+
private widgetRegistered = false;
|
|
39
|
+
private tui: TUI | undefined;
|
|
40
|
+
private completedTaskIdsPendingHide = new Set<number>();
|
|
41
|
+
private hiddenCompletedTaskIds = new Set<number>();
|
|
42
|
+
private lastNextId: number | undefined;
|
|
43
|
+
private collapsed = false;
|
|
44
|
+
|
|
45
|
+
setUICtx(ctx: ExtensionUIContext): void {
|
|
46
|
+
// Identity-compare so repeat session_start handlers are idempotent;
|
|
47
|
+
// on identity change (/reload) invalidate so update() re-registers.
|
|
48
|
+
if (ctx !== this.uiCtx) {
|
|
49
|
+
this.uiCtx = ctx;
|
|
50
|
+
this.widgetRegistered = false;
|
|
51
|
+
this.tui = undefined;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
update(): void {
|
|
56
|
+
if (!this.uiCtx) return;
|
|
57
|
+
const snapshot = this.getSnapshot();
|
|
58
|
+
const visible = this.selectOverlayTasks(snapshot);
|
|
59
|
+
|
|
60
|
+
if (visible.length === 0) {
|
|
61
|
+
if (this.widgetRegistered) {
|
|
62
|
+
this.uiCtx.setWidget(WIDGET_KEY, undefined);
|
|
63
|
+
this.widgetRegistered = false;
|
|
64
|
+
this.tui = undefined;
|
|
65
|
+
}
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (!this.widgetRegistered) {
|
|
70
|
+
this.uiCtx.setWidget(
|
|
71
|
+
WIDGET_KEY,
|
|
72
|
+
(tui, factoryTheme) => {
|
|
73
|
+
this.tui = tui;
|
|
74
|
+
return {
|
|
75
|
+
render: (width: number) => this.renderWidget(this.uiCtx?.theme ?? factoryTheme, width),
|
|
76
|
+
invalidate: () => {
|
|
77
|
+
// No rendered strings are cached. Pi invalidates on theme changes;
|
|
78
|
+
// the next render reads uiCtx.theme.
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
},
|
|
82
|
+
{ placement: "aboveEditor" },
|
|
83
|
+
);
|
|
84
|
+
this.widgetRegistered = true;
|
|
85
|
+
} else {
|
|
86
|
+
this.tui?.requestRender();
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
resetCompletedDisplayState(): void {
|
|
91
|
+
this.completedTaskIdsPendingHide.clear();
|
|
92
|
+
this.hiddenCompletedTaskIds.clear();
|
|
93
|
+
this.lastNextId = undefined;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
hideCompletedTasksFromPreviousTurn(): void {
|
|
97
|
+
if (this.completedTaskIdsPendingHide.size === 0) return;
|
|
98
|
+
for (const taskId of this.completedTaskIdsPendingHide) {
|
|
99
|
+
this.hiddenCompletedTaskIds.add(taskId);
|
|
100
|
+
}
|
|
101
|
+
this.completedTaskIdsPendingHide.clear();
|
|
102
|
+
this.tui?.requestRender();
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
toggleCollapse(): void {
|
|
106
|
+
this.collapsed = !this.collapsed;
|
|
107
|
+
// Forced full redraw on the collapsed↔expanded height step, mirroring the
|
|
108
|
+
// lane-dock's requestRender(shapeChanged); distinct from the non-forced
|
|
109
|
+
// requestRender() refresh paths in update()/hideCompletedTasksFromPreviousTurn().
|
|
110
|
+
this.tui?.requestRender(true);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
isRegistered(): boolean {
|
|
114
|
+
return this.widgetRegistered;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
private getSnapshot() {
|
|
118
|
+
const state = getRenderState();
|
|
119
|
+
if (this.lastNextId !== undefined && state.nextId < this.lastNextId) {
|
|
120
|
+
this.resetCompletedDisplayState();
|
|
121
|
+
}
|
|
122
|
+
this.lastNextId = state.nextId;
|
|
123
|
+
const completedTaskIds = new Set(
|
|
124
|
+
state.tasks.filter((task) => task.status === "completed").map((task) => task.id),
|
|
125
|
+
);
|
|
126
|
+
for (const taskId of this.completedTaskIdsPendingHide) {
|
|
127
|
+
if (!completedTaskIds.has(taskId)) this.completedTaskIdsPendingHide.delete(taskId);
|
|
128
|
+
}
|
|
129
|
+
for (const taskId of this.hiddenCompletedTaskIds) {
|
|
130
|
+
if (!completedTaskIds.has(taskId)) this.hiddenCompletedTaskIds.delete(taskId);
|
|
131
|
+
}
|
|
132
|
+
return { tasks: [...state.tasks], nextId: state.nextId };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
private selectOverlayTasks(snapshot: ReturnType<TodoOverlay["getSnapshot"]>) {
|
|
136
|
+
return snapshot.tasks.filter(
|
|
137
|
+
(task) => task.status !== "deleted" && !this.shouldHideCompletedTask(task),
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
private shouldHideCompletedTask(
|
|
142
|
+
task: ReturnType<TodoOverlay["getSnapshot"]>["tasks"][number],
|
|
143
|
+
): boolean {
|
|
144
|
+
return task.status === "completed" && this.hiddenCompletedTaskIds.has(task.id);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
private renderWidget(theme: Theme, width: number): string[] {
|
|
148
|
+
const snapshot = this.getSnapshot();
|
|
149
|
+
const overlayTasks = this.selectOverlayTasks(snapshot);
|
|
150
|
+
if (overlayTasks.length === 0) return [];
|
|
151
|
+
|
|
152
|
+
const overlayState = { tasks: overlayTasks, nextId: snapshot.nextId };
|
|
153
|
+
const truncate = (line: string): string => truncateToWidth(line, width, "…");
|
|
154
|
+
const counts = selectTodoCounts(overlayState);
|
|
155
|
+
const hasActive = selectHasActive(overlayState);
|
|
156
|
+
const showIds = selectShowTaskIds(overlayState);
|
|
157
|
+
|
|
158
|
+
const headingColor = hasActive ? "accent" : "dim";
|
|
159
|
+
const headingIcon = hasActive ? "●" : "○";
|
|
160
|
+
const headingText = `${t("overlay.heading", OVERLAY_HEADING)} (${counts.completed}/${counts.total})`;
|
|
161
|
+
const heading = truncate(
|
|
162
|
+
`${theme.fg(headingColor, headingIcon)} ${theme.fg(headingColor, headingText)}`,
|
|
163
|
+
);
|
|
164
|
+
|
|
165
|
+
// Collapsed view: just the heading + a dim "└─" expand hint, then the
|
|
166
|
+
// trailing spacer. Short-circuit before the budget math and the completed-
|
|
167
|
+
// display tracking — nothing is shown to track, and skipping the tracking
|
|
168
|
+
// when nothing is rendered is correctness, not optimization. The hint splices
|
|
169
|
+
// the resolved key into the {key} placeholder (per-render, like the row
|
|
170
|
+
// budget); a config edit needs /reload to re-bind the actual shortcut. The
|
|
171
|
+
// "off" sentinel is reachable here mid-session (config edited after the
|
|
172
|
+
// shortcut was bound and the overlay collapsed) — render a static collapsed
|
|
173
|
+
// label instead of splicing the sentinel into the placeholder.
|
|
174
|
+
if (this.collapsed) {
|
|
175
|
+
const key = resolveCollapseKey();
|
|
176
|
+
const hint =
|
|
177
|
+
key === COLLAPSE_KEY_OFF
|
|
178
|
+
? t("overlay.collapsed", OVERLAY_COLLAPSED)
|
|
179
|
+
: t("overlay.expandHint", OVERLAY_EXPAND_HINT).replace("{key}", key);
|
|
180
|
+
return this.withTrailingSpacer([
|
|
181
|
+
heading,
|
|
182
|
+
truncate(`${theme.fg("dim", "└─")} ${theme.fg("dim", hint)}`),
|
|
183
|
+
]);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const lines: string[] = [heading];
|
|
187
|
+
// Budget for content rows (heading + tasks/summary). The rendered widget is
|
|
188
|
+
// one line taller — withTrailingSpacer() appends a blank row below the panel.
|
|
189
|
+
// Pi's global tool-output expansion mode is read on every render so its
|
|
190
|
+
// expand/collapse shortcut also expands this live widget. Optional chaining
|
|
191
|
+
// preserves compatibility with hosts predating getToolsExpanded().
|
|
192
|
+
const bodyBudget =
|
|
193
|
+
this.uiCtx?.getToolsExpanded?.() === true ? overlayTasks.length : getMaxWidgetLines() - 1;
|
|
194
|
+
const layout = selectOverlayLayout(overlayState, bodyBudget);
|
|
195
|
+
for (const task of layout.visible) {
|
|
196
|
+
lines.push(
|
|
197
|
+
truncate(`${theme.fg("dim", "├─")} ${formatOverlayTaskLine(task, theme, showIds)}`),
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const newlyDisplayedCompletedTaskIds = overlayTasks
|
|
202
|
+
.filter(
|
|
203
|
+
(task) =>
|
|
204
|
+
task.status === "completed" &&
|
|
205
|
+
!this.completedTaskIdsPendingHide.has(task.id) &&
|
|
206
|
+
!this.hiddenCompletedTaskIds.has(task.id),
|
|
207
|
+
)
|
|
208
|
+
.map((task) => task.id);
|
|
209
|
+
for (const taskId of newlyDisplayedCompletedTaskIds) {
|
|
210
|
+
this.completedTaskIdsPendingHide.add(taskId);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
if (layout.hiddenCompleted === 0 && layout.truncatedTail === 0) {
|
|
214
|
+
const last = lines.length - 1;
|
|
215
|
+
lines[last] = lines[last].replace("├─", "└─");
|
|
216
|
+
return this.withTrailingSpacer(lines);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const totalHidden = layout.hiddenCompleted + layout.truncatedTail;
|
|
220
|
+
const overflowParts: string[] = [];
|
|
221
|
+
if (layout.hiddenCompleted > 0)
|
|
222
|
+
overflowParts.push(`${layout.hiddenCompleted} ${formatStatusLabel("completed")}`);
|
|
223
|
+
if (layout.truncatedTail > 0)
|
|
224
|
+
overflowParts.push(`${layout.truncatedTail} ${formatStatusLabel("pending")}`);
|
|
225
|
+
const more = t("overlay.more", OVERLAY_MORE);
|
|
226
|
+
const summary =
|
|
227
|
+
overflowParts.length > 0
|
|
228
|
+
? `+${totalHidden} ${more} (${overflowParts.join(", ")})`
|
|
229
|
+
: `+${totalHidden} ${more}`;
|
|
230
|
+
lines.push(truncate(`${theme.fg("dim", "└─")} ${theme.fg("dim", summary)}`));
|
|
231
|
+
return this.withTrailingSpacer(lines);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Append a trailing blank line so the overlay isn't flush against the
|
|
236
|
+
* editor box. Pi's host adds a leading spacer above the widget but none
|
|
237
|
+
* below, which leaves the last "└─" row (or the "+N more" summary) glued
|
|
238
|
+
* to the input box. The empty string gives the "Todos" panel a little
|
|
239
|
+
* breathing room.
|
|
240
|
+
*/
|
|
241
|
+
private withTrailingSpacer(lines: string[]): string[] {
|
|
242
|
+
if (lines.length === 0) return lines;
|
|
243
|
+
lines.push("");
|
|
244
|
+
return lines;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
dispose(): void {
|
|
248
|
+
if (this.uiCtx) this.uiCtx.setWidget(WIDGET_KEY, undefined);
|
|
249
|
+
this.widgetRegistered = false;
|
|
250
|
+
this.tui = undefined;
|
|
251
|
+
this.uiCtx = undefined;
|
|
252
|
+
this.collapsed = false;
|
|
253
|
+
this.resetCompletedDisplayState();
|
|
254
|
+
}
|
|
255
|
+
}
|
package/todo.ts
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* todo tool + /todos command — thin registration shell.
|
|
3
|
+
*
|
|
4
|
+
* Tool/command identity, schema, types, reducer, store, replay, response
|
|
5
|
+
* envelope, selectors, and view formatters live in the layered modules under
|
|
6
|
+
* `tool/`, `state/`, and `view/`. This file is the package-root registration
|
|
7
|
+
* surface — it mirrors `packages/rpiv-ask-user-question/ask-user-question.ts`
|
|
8
|
+
* which keeps the tool registration at the package root.
|
|
9
|
+
*
|
|
10
|
+
* Public re-exports below preserve the package-root import surface so that
|
|
11
|
+
* `index.ts`, `todo-overlay.ts`, and the global `test/setup.ts` `beforeEach`
|
|
12
|
+
* continue to import from `./todo.js`.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
16
|
+
import { loadConfig, validateGuidanceFields } from "./config.ts";
|
|
17
|
+
import { formatStatusLabel, t } from "./state/i18n-bridge.ts";
|
|
18
|
+
import { selectTasksByStatus, selectTodoCounts, selectVisibleTasks } from "./state/selectors.ts";
|
|
19
|
+
import { applyTaskMutation, changesState } from "./state/state-reducer.ts";
|
|
20
|
+
import { commitState, getRenderState, getState, sid } from "./state/store.ts";
|
|
21
|
+
import { prepareTodoArguments } from "./tool/normalize-params.ts";
|
|
22
|
+
import { buildToolResult } from "./tool/response-envelope.ts";
|
|
23
|
+
import {
|
|
24
|
+
COMMAND_NAME,
|
|
25
|
+
ERR_REQUIRES_INTERACTIVE,
|
|
26
|
+
MSG_NO_TODOS,
|
|
27
|
+
STATE_ENTRY_TYPE,
|
|
28
|
+
type TaskAction,
|
|
29
|
+
type TaskMutationParams,
|
|
30
|
+
TOOL_LABEL,
|
|
31
|
+
TOOL_NAME,
|
|
32
|
+
TodoParamsSchema,
|
|
33
|
+
} from "./tool/types.ts";
|
|
34
|
+
import { formatCommandTaskLine, renderTodoCall, renderTodoResult } from "./view/format.ts";
|
|
35
|
+
|
|
36
|
+
// English fallbacks for localized /todos section headers — the box-drawing
|
|
37
|
+
// decoration is part of the localized string so translators can adjust spacing.
|
|
38
|
+
const SECTION_PENDING = "── Pending ──";
|
|
39
|
+
const SECTION_IN_PROGRESS = "── In Progress ──";
|
|
40
|
+
const SECTION_COMPLETED = "── Completed ──";
|
|
41
|
+
|
|
42
|
+
// ---------------------------------------------------------------------------
|
|
43
|
+
// Public re-exports — existing consumers (overlay, tests, index.ts) keep
|
|
44
|
+
// importing from `./todo.js`. New code may opt into deeper imports.
|
|
45
|
+
// ---------------------------------------------------------------------------
|
|
46
|
+
|
|
47
|
+
export { isTransitionValid } from "./state/invariants.ts";
|
|
48
|
+
export { applyTaskMutation } from "./state/state-reducer.ts";
|
|
49
|
+
export { __resetState, getNextId, getTodos, setActiveRenderSession, sid } from "./state/store.ts";
|
|
50
|
+
export { deriveBlocks, detectCycle } from "./state/task-graph.ts";
|
|
51
|
+
export type { Task, TaskAction, TaskDetails, TaskStatus } from "./tool/types.ts";
|
|
52
|
+
export { TOOL_NAME } from "./tool/types.ts";
|
|
53
|
+
|
|
54
|
+
// ---------------------------------------------------------------------------
|
|
55
|
+
// Tool registration
|
|
56
|
+
// ---------------------------------------------------------------------------
|
|
57
|
+
|
|
58
|
+
export const DEFAULT_PROMPT_SNIPPET = "Manage a task list to track multi-step progress";
|
|
59
|
+
export const DEFAULT_PROMPT_GUIDELINES: string[] = [
|
|
60
|
+
"Use `todo` for complex work with 3+ steps, when the user gives you a list of tasks, or immediately after receiving new instructions to capture requirements. Skip it for single trivial tasks and purely conversational requests.",
|
|
61
|
+
"When starting a task from the todo list, mark it in_progress BEFORE beginning work. Mark it completed IMMEDIATELY when done — never batch completions. Exactly one task in_progress at a time.",
|
|
62
|
+
"Never mark a task completed if tests are failing, the implementation is partial, or you hit unresolved errors — keep it in_progress and create a new task for the blocker instead.",
|
|
63
|
+
"Task status is a 4-state machine: pending → in_progress → completed, plus deleted as a tombstone. Pass activeForm (present-continuous label, e.g. 'researching existing tool') when marking in_progress.",
|
|
64
|
+
'To change a task\'s status, call update with the task id and the target status, e.g. {"action":"update","id":3,"status":"completed"} or {"action":"update","id":3,"status":"in_progress","activeForm":"writing tests"}. status is the field that changes the task; an update without a mutable field (status or another) is rejected.',
|
|
65
|
+
"Use blockedBy to express dependencies (A is blocked by B). On create, pass blockedBy as the initial set. On update, use addBlockedBy / removeBlockedBy (additive merge — do not resend the full array). Cycles are rejected.",
|
|
66
|
+
"To create several independent tasks at once, pass create with tasks: [{subject}, ...]. Do not also pass subject. tasks[] cannot blockedBy each other (ids do not exist until the call commits); create the prerequisite first, then the dependent with blockedBy. Dependency chains stay single-create.",
|
|
67
|
+
"list hides tombstoned (deleted) tasks by default; pass includeDeleted:true to see them. Pass status to filter by a single status.",
|
|
68
|
+
"Subject must be short and imperative (e.g. 'Research existing tool'); description is for long-form detail. activeForm is a present-continuous label shown while in_progress.",
|
|
69
|
+
];
|
|
70
|
+
|
|
71
|
+
export function registerTodoTool(pi: ExtensionAPI): void {
|
|
72
|
+
const guidance = validateGuidanceFields(loadConfig().guidance);
|
|
73
|
+
pi.registerTool({
|
|
74
|
+
name: TOOL_NAME,
|
|
75
|
+
label: TOOL_LABEL,
|
|
76
|
+
description:
|
|
77
|
+
"Manage a task list for tracking multi-step progress. Actions: create (new task, or several independent tasks at once via tasks[]), update (change status/fields/dependencies), list (all tasks, optionally filtered by status), get (single task details), delete (tombstone), clear (reset all). Status: pending → in_progress → completed, plus deleted tombstone. Use this to plan and track multi-step work like research, design, and implementation.",
|
|
78
|
+
promptSnippet: guidance.promptSnippet ?? DEFAULT_PROMPT_SNIPPET,
|
|
79
|
+
promptGuidelines: guidance.promptGuidelines ?? DEFAULT_PROMPT_GUIDELINES,
|
|
80
|
+
parameters: TodoParamsSchema,
|
|
81
|
+
// Undo a double-encoded tasks[] before Pi validates it (#244 shape).
|
|
82
|
+
prepareArguments: prepareTodoArguments,
|
|
83
|
+
|
|
84
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
85
|
+
const result = applyTaskMutation(
|
|
86
|
+
getState(sid(ctx)),
|
|
87
|
+
params.action as TaskAction,
|
|
88
|
+
params as TaskMutationParams,
|
|
89
|
+
);
|
|
90
|
+
commitState(sid(ctx), result.state);
|
|
91
|
+
const toolResult = buildToolResult(
|
|
92
|
+
params.action as TaskAction,
|
|
93
|
+
params as TaskMutationParams,
|
|
94
|
+
result.state,
|
|
95
|
+
result.op,
|
|
96
|
+
);
|
|
97
|
+
// Persist a compact operation record as a custom entry on the calling session's branch, however the
|
|
98
|
+
// tool was reached: a call made through another tool (`ctx.executeTool`, e.g. codemode)
|
|
99
|
+
// never lands as a standalone `toolResult`, so its `details` alone would not survive
|
|
100
|
+
// replay. Pi's own codemode persists its `store()` the same way.
|
|
101
|
+
if (changesState(result.op)) pi.appendEntry(STATE_ENTRY_TYPE, toolResult.details);
|
|
102
|
+
return toolResult;
|
|
103
|
+
},
|
|
104
|
+
|
|
105
|
+
// renderCall reflects the FOREGROUND slot, not the calling session's. Pi's
|
|
106
|
+
// `ToolRenderContext` carries no session identity (no sessionManager/sessionId),
|
|
107
|
+
// so this ctx-less hook cannot re-key by caller. For the foreground session's
|
|
108
|
+
// own transcript that is exactly right. A detached/child call rendered in the
|
|
109
|
+
// lane-transcript viewer whose task lives only in the child's slot misses the
|
|
110
|
+
// foreground lookup and falls back to `#<id>` (see renderTodoCall). That is the
|
|
111
|
+
// safe outcome: per-session ids restart at 1, so searching sibling slots could
|
|
112
|
+
// surface the WRONG subject — the `#<id>` fallback is intentional, not a gap.
|
|
113
|
+
renderCall(args, theme, _context) {
|
|
114
|
+
return renderTodoCall(args as never, theme, getRenderState());
|
|
115
|
+
},
|
|
116
|
+
|
|
117
|
+
renderResult(result, _opts, theme, context) {
|
|
118
|
+
return renderTodoResult(result, theme, context?.isError);
|
|
119
|
+
},
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// ---------------------------------------------------------------------------
|
|
124
|
+
// /todos slash command
|
|
125
|
+
// ---------------------------------------------------------------------------
|
|
126
|
+
|
|
127
|
+
export function registerTodosCommand(pi: ExtensionAPI): void {
|
|
128
|
+
pi.registerCommand(COMMAND_NAME, {
|
|
129
|
+
description: "Show all todos on the current branch, grouped by status",
|
|
130
|
+
handler: async (_args, ctx) => {
|
|
131
|
+
if (!ctx.hasUI) {
|
|
132
|
+
ctx.ui.notify(t("command.requires_interactive", ERR_REQUIRES_INTERACTIVE), "error");
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
const state = getState(sid(ctx));
|
|
136
|
+
const visible = selectVisibleTasks(state);
|
|
137
|
+
if (visible.length === 0) {
|
|
138
|
+
ctx.ui.notify(t("command.no_todos", MSG_NO_TODOS), "info");
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
const groups = selectTasksByStatus(state);
|
|
142
|
+
const counts = selectTodoCounts(state);
|
|
143
|
+
|
|
144
|
+
const header: string[] = [];
|
|
145
|
+
if (counts.completed > 0)
|
|
146
|
+
header.push(`${counts.completed}/${counts.total} ${formatStatusLabel("completed")}`);
|
|
147
|
+
if (counts.inProgress > 0)
|
|
148
|
+
header.push(`${counts.inProgress} ${formatStatusLabel("in_progress")}`);
|
|
149
|
+
if (counts.pending > 0) header.push(`${counts.pending} ${formatStatusLabel("pending")}`);
|
|
150
|
+
|
|
151
|
+
const lines: string[] = [header.join(" · ")];
|
|
152
|
+
if (groups.pending.length > 0) {
|
|
153
|
+
lines.push(t("command.section.pending", SECTION_PENDING));
|
|
154
|
+
for (const task of groups.pending) lines.push(formatCommandTaskLine(task, "○"));
|
|
155
|
+
}
|
|
156
|
+
if (groups.inProgress.length > 0) {
|
|
157
|
+
lines.push(t("command.section.in_progress", SECTION_IN_PROGRESS));
|
|
158
|
+
for (const task of groups.inProgress) lines.push(formatCommandTaskLine(task, "◐"));
|
|
159
|
+
}
|
|
160
|
+
if (groups.completed.length > 0) {
|
|
161
|
+
lines.push(t("command.section.completed", SECTION_COMPLETED));
|
|
162
|
+
for (const task of groups.completed) lines.push(formatCommandTaskLine(task, "✓"));
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
ctx.ui.notify(lines.join("\n"), "info");
|
|
166
|
+
},
|
|
167
|
+
});
|
|
168
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { TodoParams } from "./types.ts";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Pi's `prepareArguments` hook: undo a double-encoded `tasks[]` before schema
|
|
5
|
+
* validation. Some tool-call parsers (vLLM/LiteLLM-served GLM/Qwen-class models)
|
|
6
|
+
* emit nested structures as JSON strings — `tasks` itself, or its items — the same
|
|
7
|
+
* shape rpiv-ask-user-question decodes for `questions` (#244). Only a string at an
|
|
8
|
+
* array/object position is decoded, and only when it parses to the expected shape;
|
|
9
|
+
* anything else is passed through untouched so validation still reports the real
|
|
10
|
+
* problem. Well-formed arguments are returned as-is.
|
|
11
|
+
*/
|
|
12
|
+
export function prepareTodoArguments(args: unknown): TodoParams {
|
|
13
|
+
if (!isRecord(args) || args.tasks === undefined) return args as TodoParams;
|
|
14
|
+
const tasks = decodeArray(args.tasks);
|
|
15
|
+
if (!Array.isArray(tasks)) return args as TodoParams;
|
|
16
|
+
const decoded = tasks.map(decodeObject);
|
|
17
|
+
if (tasks === args.tasks && decoded.every((item, i) => item === tasks[i]))
|
|
18
|
+
return args as TodoParams;
|
|
19
|
+
return { ...args, tasks: decoded } as unknown as TodoParams;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
23
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** A JSON string holding an array → that array; anything else unchanged. */
|
|
27
|
+
function decodeArray(value: unknown): unknown {
|
|
28
|
+
const parsed = typeof value === "string" ? parseJson(value) : value;
|
|
29
|
+
return Array.isArray(parsed) ? parsed : value;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** A JSON string holding an object → that object; anything else unchanged. */
|
|
33
|
+
function decodeObject(value: unknown): unknown {
|
|
34
|
+
const parsed = typeof value === "string" ? parseJson(value) : value;
|
|
35
|
+
return isRecord(parsed) ? parsed : value;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function parseJson(text: string): unknown {
|
|
39
|
+
try {
|
|
40
|
+
return JSON.parse(text);
|
|
41
|
+
} catch {
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import type { TaskState } from "../state/state.ts";
|
|
2
|
+
import type { Op } from "../state/state-reducer.ts";
|
|
3
|
+
import { deriveBlocks } from "../state/task-graph.ts";
|
|
4
|
+
import { sanitizeTerminalText } from "./sanitize.ts";
|
|
5
|
+
import type { Task, TaskAction, TaskDetails, TaskMutationParams } from "./types.ts";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Format a single task as a `[status] #id subject [(activeForm)] [⛓ #dep,…]`
|
|
9
|
+
* line. Used by the `list` content branch only — the overlay and `/todos`
|
|
10
|
+
* formatting paths use `view/format.ts` for richer presentations.
|
|
11
|
+
*/
|
|
12
|
+
function formatListLine(t: Task): string {
|
|
13
|
+
const block = t.blockedBy?.length ? ` ⛓ ${t.blockedBy.map((id) => `#${id}`).join(",")}` : "";
|
|
14
|
+
const form =
|
|
15
|
+
t.status === "in_progress" && t.activeForm ? ` (${sanitizeTerminalText(t.activeForm)})` : "";
|
|
16
|
+
return `[${t.status}] #${t.id} ${sanitizeTerminalText(t.subject)}${form}${block}`;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Multi-line presentation for the `get` action. Order of rows is pinned by
|
|
21
|
+
* pre-refactor `todo.ts:354-376` — description, activeForm, blockedBy, blocks,
|
|
22
|
+
* owner — so envelope-level snapshot tests stay byte-equivalent.
|
|
23
|
+
*/
|
|
24
|
+
function formatGetLines(task: Task, state: TaskState): string {
|
|
25
|
+
const blocks = deriveBlocks(state.tasks).get(task.id) ?? [];
|
|
26
|
+
const lines = [`#${task.id} [${task.status}] ${sanitizeTerminalText(task.subject)}`];
|
|
27
|
+
if (task.description) lines.push(` description: ${sanitizeTerminalText(task.description)}`);
|
|
28
|
+
if (task.activeForm) lines.push(` activeForm: ${sanitizeTerminalText(task.activeForm)}`);
|
|
29
|
+
if (task.blockedBy?.length) {
|
|
30
|
+
lines.push(` blockedBy: ${task.blockedBy.map((id) => `#${id}`).join(", ")}`);
|
|
31
|
+
}
|
|
32
|
+
if (blocks.length) {
|
|
33
|
+
lines.push(` blocks: ${blocks.map((id) => `#${id}`).join(", ")}`);
|
|
34
|
+
}
|
|
35
|
+
if (task.owner) lines.push(` owner: ${sanitizeTerminalText(task.owner)}`);
|
|
36
|
+
return lines.join("\n");
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Pure formatter: `(op, state) → string`. Closed switch on `op.kind` —
|
|
41
|
+
* adding a new `Op` variant fails to compile here until a branch is added.
|
|
42
|
+
* The strings on each branch are byte-equivalent to pre-refactor `todo.ts`
|
|
43
|
+
* reducer output.
|
|
44
|
+
*/
|
|
45
|
+
export function formatContent(op: Op, state: TaskState): string {
|
|
46
|
+
switch (op.kind) {
|
|
47
|
+
case "create": {
|
|
48
|
+
// Defensive — each `op.taskIds` entry resolves on the success path.
|
|
49
|
+
return op.taskIds
|
|
50
|
+
.map((id) => {
|
|
51
|
+
const created = state.tasks.find((x) => x.id === id);
|
|
52
|
+
if (!created) return `Created #${id}`;
|
|
53
|
+
return `Created #${created.id}: ${sanitizeTerminalText(created.subject)} (pending)`;
|
|
54
|
+
})
|
|
55
|
+
.join("\n");
|
|
56
|
+
}
|
|
57
|
+
case "update": {
|
|
58
|
+
if (!op.changed) {
|
|
59
|
+
return `No change: #${op.id} already matches the requested values (status: ${op.toStatus})`;
|
|
60
|
+
}
|
|
61
|
+
const transition =
|
|
62
|
+
op.fromStatus !== op.toStatus ? ` (${op.fromStatus} → ${op.toStatus})` : "";
|
|
63
|
+
return `Updated #${op.id}${transition}`;
|
|
64
|
+
}
|
|
65
|
+
case "delete":
|
|
66
|
+
return `Deleted #${op.id}: ${sanitizeTerminalText(op.subject)}`;
|
|
67
|
+
case "clear":
|
|
68
|
+
return `Cleared ${op.count} tasks`;
|
|
69
|
+
case "list": {
|
|
70
|
+
let view = state.tasks;
|
|
71
|
+
if (!op.includeDeleted) view = view.filter((t) => t.status !== "deleted");
|
|
72
|
+
if (op.statusFilter) view = view.filter((t) => t.status === op.statusFilter);
|
|
73
|
+
return view.length === 0 ? "No tasks" : view.map(formatListLine).join("\n");
|
|
74
|
+
}
|
|
75
|
+
case "get":
|
|
76
|
+
return formatGetLines(op.task, state);
|
|
77
|
+
case "error":
|
|
78
|
+
return `Error: ${op.message}`;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Build the LLM-facing tool envelope after the store has committed the
|
|
84
|
+
* reducer's new state. `details` is the persistence + replay snapshot —
|
|
85
|
+
* `state/replay.ts` consumes this exact shape on session lifecycle events.
|
|
86
|
+
*
|
|
87
|
+
* Mirrors `packages/rpiv-ask-user-question/tool/response-envelope.ts:13-47`.
|
|
88
|
+
*/
|
|
89
|
+
export function buildToolResult(
|
|
90
|
+
action: TaskAction,
|
|
91
|
+
params: TaskMutationParams,
|
|
92
|
+
state: TaskState,
|
|
93
|
+
op: Op,
|
|
94
|
+
): { content: Array<{ type: "text"; text: string }>; details: TaskDetails } {
|
|
95
|
+
const text = formatContent(op, state);
|
|
96
|
+
const details: TaskDetails = {
|
|
97
|
+
action,
|
|
98
|
+
params: params as Record<string, unknown>,
|
|
99
|
+
tasks: state.tasks,
|
|
100
|
+
nextId: state.nextId,
|
|
101
|
+
// Field-only updates need a status hint when rendered from session JSON.
|
|
102
|
+
...(op.kind === "update" && params.status === undefined ? { taskStatus: op.toStatus } : {}),
|
|
103
|
+
...(op.kind === "error" ? { error: op.message } : {}),
|
|
104
|
+
};
|
|
105
|
+
// Keep the complete state available to the live tool result while making the
|
|
106
|
+
// session representation an action record. Pi persists details through JSON,
|
|
107
|
+
// so non-enumerable state fields are omitted from both tool results and the
|
|
108
|
+
// matching custom entry without changing the in-memory shape.
|
|
109
|
+
Object.defineProperties(details, {
|
|
110
|
+
tasks: { value: state.tasks, enumerable: false },
|
|
111
|
+
nextId: { value: state.nextId, enumerable: false },
|
|
112
|
+
});
|
|
113
|
+
return { content: [{ type: "text", text }], details };
|
|
114
|
+
}
|
package/tool/sanitize.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Remove terminal control characters from model-controlled task text before
|
|
3
|
+
* it reaches Pi's terminal renderer. Complete CSI/OSC escape sequences are
|
|
4
|
+
* dropped whole (no printable remnants like `[31m`), newlines and tabs
|
|
5
|
+
* become spaces so task fields cannot change the layout, and bidi controls
|
|
6
|
+
* are removed so a field cannot reorder how neighbouring output reads.
|
|
7
|
+
*/
|
|
8
|
+
const CSI_SEQUENCE = new RegExp(String.raw`(?:\u001b\[|\u009b)[0-?]*[ -/]*[@-~]`, "g");
|
|
9
|
+
const OSC_SEQUENCE = new RegExp(
|
|
10
|
+
String.raw`(?:\u001b\]|\u009d)[^\u0007\u009c\u001b]*(?:\u0007|\u009c|\u001b\\)?`,
|
|
11
|
+
"g",
|
|
12
|
+
);
|
|
13
|
+
const ESCAPE_SEQUENCE = new RegExp(String.raw`\u001b.`, "g");
|
|
14
|
+
const CONTROL_CHARACTER = new RegExp(String.raw`[\u0000-\u001f\u007f-\u009f]`, "g");
|
|
15
|
+
|
|
16
|
+
export function sanitizeTerminalText(value: string): string {
|
|
17
|
+
return (
|
|
18
|
+
value
|
|
19
|
+
// CSI sequences, via both ESC-[ and the C1 single-byte introducer.
|
|
20
|
+
.replace(CSI_SEQUENCE, "")
|
|
21
|
+
// OSC sequences with their payload; an unterminated OSC swallows the
|
|
22
|
+
// rest of the string, matching how a real terminal would treat it.
|
|
23
|
+
.replace(OSC_SEQUENCE, "")
|
|
24
|
+
// Any remaining two-character ESC sequence.
|
|
25
|
+
.replace(ESCAPE_SEQUENCE, "")
|
|
26
|
+
// Unicode line/paragraph separators join lines like \n does below.
|
|
27
|
+
.replace(/[\u2028\u2029]/g, " ")
|
|
28
|
+
.replace(CONTROL_CHARACTER, (character) =>
|
|
29
|
+
character === "\n" || character === "\r" || character === "\t" ? " " : "",
|
|
30
|
+
)
|
|
31
|
+
// Bidi embedding/override/isolate controls and LRM/RLM marks.
|
|
32
|
+
.replace(/[\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, "")
|
|
33
|
+
);
|
|
34
|
+
}
|