@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.
@@ -0,0 +1,19 @@
1
+ {
2
+ "_meta.notes": "中文翻译。欢迎中文母语者通过 PR 审校。",
3
+
4
+ "status.pending": "待处理",
5
+ "status.in_progress": "进行中",
6
+ "status.completed": "已完成",
7
+ "status.deleted": "已删除",
8
+
9
+ "overlay.heading": "任务清单",
10
+ "overlay.more": "更多",
11
+ "overlay.expandHint": "按 {key} 展开",
12
+ "overlay.collapsed": "已折叠",
13
+
14
+ "command.no_todos": "暂无任务。可以让 agent 添加一些!",
15
+ "command.requires_interactive": "/todos 需要交互模式",
16
+ "command.section.pending": "── 待处理 ──",
17
+ "command.section.in_progress": "── 进行中 ──",
18
+ "command.section.completed": "── 已完成 ──"
19
+ }
package/package.json CHANGED
@@ -1,6 +1,89 @@
1
1
  {
2
2
  "name": "@indexyz/pi-todo",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "A Pi todo tool and live task overlay with compact session persistence",
5
+ "keywords": [
6
+ "pi",
7
+ "pi-package",
8
+ "task-list",
9
+ "todo"
10
+ ],
11
+ "homepage": "https://github.com/5aaee9/pi-agent-extensions/tree/main/pi-todo#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/5aaee9/pi-agent-extensions/issues"
14
+ },
15
+ "license": "MIT",
16
+ "author": "5aaee9",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/5aaee9/pi-agent-extensions.git",
20
+ "directory": "pi-todo"
21
+ },
22
+ "files": [
23
+ "config.ts",
24
+ "index.ts",
25
+ "locales/",
26
+ "todo.ts",
27
+ "todo-overlay.ts",
28
+ "LICENSE",
29
+ "docs/configuration.md",
30
+ "docs/overlay.md",
31
+ "docs/tool-schema.md",
32
+ "README.md",
33
+ "CHANGELOG.md",
34
+ "state/invariants.ts",
35
+ "state/i18n-bridge.ts",
36
+ "state/replay.ts",
37
+ "state/selectors.ts",
38
+ "state/state-reducer.ts",
39
+ "state/state.ts",
40
+ "state/store.ts",
41
+ "state/task-graph.ts",
42
+ "tool/normalize-params.ts",
43
+ "tool/response-envelope.ts",
44
+ "tool/sanitize.ts",
45
+ "tool/types.ts",
46
+ "view/format.ts"
47
+ ],
48
+ "type": "module",
49
+ "publishConfig": {
50
+ "access": "public"
51
+ },
52
+ "scripts": {
53
+ "test": "vitest run",
54
+ "test:watch": "vitest",
55
+ "typecheck": "tsc --noEmit",
56
+ "check": "npm run typecheck && npm test",
57
+ "prepack": "npm run check"
58
+ },
59
+ "devDependencies": {
60
+ "@earendil-works/pi-ai": "1.5.0",
61
+ "@earendil-works/pi-coding-agent": "1.5.0",
62
+ "@earendil-works/pi-tui": "1.5.0",
63
+ "@juicesharp/rpiv-i18n": "2.15.0",
64
+ "@types/node": "^24.0.0",
65
+ "typebox": "1.3.7",
66
+ "typescript": "^7.0.2",
67
+ "vitest": "^4.1.10"
68
+ },
69
+ "peerDependencies": {
70
+ "@earendil-works/pi-ai": "*",
71
+ "@earendil-works/pi-coding-agent": "*",
72
+ "@earendil-works/pi-tui": "*",
73
+ "@juicesharp/rpiv-i18n": "*",
74
+ "typebox": "*"
75
+ },
76
+ "peerDependenciesMeta": {
77
+ "@juicesharp/rpiv-i18n": {
78
+ "optional": true
79
+ }
80
+ },
81
+ "engines": {
82
+ "node": ">=22.19.0"
83
+ },
84
+ "pi": {
85
+ "extensions": [
86
+ "./index.ts"
87
+ ]
88
+ }
89
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * i18n bridge for rpiv-todo — single thin import surface so every call site
3
+ * routes through one module. Backed by `@juicesharp/rpiv-i18n`'s SDK when
4
+ * available; degrades to canonical-English fallbacks when not.
5
+ *
6
+ * - `t(key, fallback)` is `scope("@juicesharp/rpiv-todo")` if the SDK is
7
+ * installed (live `/languages` updates propagate). If the SDK is missing
8
+ * (standalone install without rpiv-i18n), `t` is an identity passthrough
9
+ * that returns the inline English fallback at every call site, so the
10
+ * extension stays online with English UI.
11
+ * - `formatStatusLabel(status)` resolves a TaskStatus to its locale-aware
12
+ * label via the canonical `status.*` namespace, with the English literal
13
+ * as fallback so nothing renders blank if the namespace isn't registered.
14
+ * This is the SINGLE point of localization for status words — overlay,
15
+ * /todos header, /todos render-call all route through here.
16
+ *
17
+ * Strings are registered ONCE at extension load (see ../index.ts). Call sites
18
+ * MUST use this module at render time — never bake the result into a top-level
19
+ * `const X = formatStatusLabel(...)`.
20
+ */
21
+
22
+ import type { TaskStatus } from "../tool/types.ts";
23
+
24
+ export const I18N_NAMESPACE = "@juicesharp/rpiv-todo";
25
+
26
+ type ScopeFn = (key: string, fallback: string) => string;
27
+ type I18nSDK = { scope: (namespace: string) => ScopeFn };
28
+
29
+ // Prefer the live SDK if installed: closures it returns track the active
30
+ // locale, so /languages picker propagates to our render call sites. If the
31
+ // SDK isn't installed (standalone install of this extension without
32
+ // rpiv-i18n), the dynamic import fails, every t(key, fallback) returns the
33
+ // canonical English literal, and the extension stays online.
34
+ //
35
+ // Top-level await is required so a synchronous `t(...)` call from any
36
+ // downstream module sees the resolved scope; ESM module loading awaits this
37
+ // before evaluating any importer.
38
+ let scopeImpl: ScopeFn;
39
+ try {
40
+ const sdk = (await import("@juicesharp/rpiv-i18n")) as I18nSDK;
41
+ scopeImpl = sdk.scope(I18N_NAMESPACE);
42
+ } catch {
43
+ scopeImpl = (_key, fallback) => fallback;
44
+ }
45
+
46
+ export const t: ScopeFn = scopeImpl;
47
+
48
+ const STATUS_LABEL_PENDING = "pending";
49
+ const STATUS_LABEL_IN_PROGRESS = "in progress";
50
+ const STATUS_LABEL_COMPLETED = "completed";
51
+ const STATUS_LABEL_DELETED = "deleted";
52
+
53
+ export function formatStatusLabel(status: TaskStatus): string {
54
+ switch (status) {
55
+ case "pending":
56
+ return t("status.pending", STATUS_LABEL_PENDING);
57
+ case "in_progress":
58
+ return t("status.in_progress", STATUS_LABEL_IN_PROGRESS);
59
+ case "completed":
60
+ return t("status.completed", STATUS_LABEL_COMPLETED);
61
+ case "deleted":
62
+ return t("status.deleted", STATUS_LABEL_DELETED);
63
+ }
64
+ }
@@ -0,0 +1,20 @@
1
+ import type { TaskStatus } from "../tool/types.ts";
2
+
3
+ /**
4
+ * Allowed forward transitions per source status. `completed` is one-way to
5
+ * `deleted` (never back to `in_progress`); `deleted` is terminal.
6
+ *
7
+ * Idempotent same→same is checked separately in `isTransitionValid` so this
8
+ * table only enumerates actual transitions.
9
+ */
10
+ export const VALID_TRANSITIONS: Record<TaskStatus, ReadonlySet<TaskStatus>> = {
11
+ pending: new Set(["in_progress", "completed", "deleted"]),
12
+ in_progress: new Set(["pending", "completed", "deleted"]),
13
+ completed: new Set(["deleted"]),
14
+ deleted: new Set(),
15
+ };
16
+
17
+ export function isTransitionValid(from: TaskStatus, to: TaskStatus): boolean {
18
+ if (from === to) return true;
19
+ return VALID_TRANSITIONS[from].has(to);
20
+ }
@@ -0,0 +1,142 @@
1
+ import { Value } from "typebox/value";
2
+ import { STATE_ENTRY_TYPE, TOOL_NAME, TodoParamsSchema } from "../tool/types.ts";
3
+ import { applyTaskMutation } from "./state-reducer.ts";
4
+ import { EMPTY_STATE, type TaskState } from "./state.ts";
5
+ import type {
6
+ Task,
7
+ TaskAction,
8
+ TaskMutationParams,
9
+ TaskStatus,
10
+ CompactTaskDetails,
11
+ } from "../tool/types.ts";
12
+
13
+ const TASK_ACTIONS: ReadonlySet<string> = new Set<TaskAction>([
14
+ "create",
15
+ "update",
16
+ "list",
17
+ "get",
18
+ "delete",
19
+ "clear",
20
+ ]);
21
+ const TASK_STATUSES: ReadonlySet<unknown> = new Set<TaskStatus>([
22
+ "pending",
23
+ "in_progress",
24
+ "completed",
25
+ "deleted",
26
+ ]);
27
+
28
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
29
+ typeof value === "object" && value !== null && !Array.isArray(value);
30
+
31
+ const isTaskAction = (value: unknown): value is TaskAction =>
32
+ typeof value === "string" && TASK_ACTIONS.has(value);
33
+
34
+ function isTask(value: unknown): value is Task {
35
+ if (!isRecord(value)) return false;
36
+ return (
37
+ Number.isSafeInteger(value.id) &&
38
+ typeof value.subject === "string" &&
39
+ TASK_STATUSES.has(value.status) &&
40
+ (value.description === undefined || typeof value.description === "string") &&
41
+ (value.activeForm === undefined || typeof value.activeForm === "string") &&
42
+ (value.owner === undefined || typeof value.owner === "string") &&
43
+ (value.blockedBy === undefined ||
44
+ (Array.isArray(value.blockedBy) && value.blockedBy.every(Number.isSafeInteger))) &&
45
+ (value.metadata === undefined || isRecord(value.metadata))
46
+ );
47
+ }
48
+
49
+ /**
50
+ * Discriminator for legacy details envelopes with a complete task snapshot.
51
+ * A malformed or partial snapshot is skipped so replay keeps the last valid
52
+ * state instead of replacing it with corrupt data.
53
+ */
54
+ function isLegacySnapshot(value: unknown): value is TaskState {
55
+ if (!isRecord(value)) return false;
56
+ return (
57
+ Array.isArray(value.tasks) && value.tasks.every(isTask) && Number.isSafeInteger(value.nextId)
58
+ );
59
+ }
60
+
61
+ /** Discriminator for the compact action-and-parameters persistence record. */
62
+ function isCompactTaskDetails(value: unknown): value is CompactTaskDetails {
63
+ if (!isRecord(value)) return false;
64
+ return (
65
+ isTaskAction(value.action) &&
66
+ isRecord(value.params) &&
67
+ !Object.hasOwn(value, "tasks") &&
68
+ !Object.hasOwn(value, "nextId") &&
69
+ value.error === undefined &&
70
+ Value.Check(TodoParamsSchema, { ...value.params, action: value.action })
71
+ );
72
+ }
73
+
74
+ /** Fresh `TaskState` from a legacy persisted snapshot. */
75
+ function stateOf(details: TaskState): TaskState {
76
+ return { tasks: details.tasks.map((task) => ({ ...task })), nextId: details.nextId };
77
+ }
78
+
79
+ function applyRecords(records: unknown[], base: TaskState): TaskState {
80
+ // A full snapshot supersedes every earlier operation in this stream.
81
+ for (let i = records.length - 1; i >= 0; i--) {
82
+ const record = records[i];
83
+ if (!isLegacySnapshot(record)) continue;
84
+ base = stateOf(record);
85
+ records = records.slice(i + 1);
86
+ break;
87
+ }
88
+ for (const record of records) {
89
+ if (isCompactTaskDetails(record)) {
90
+ base = applyTaskMutation(base, record.action, record.params as TaskMutationParams).state;
91
+ }
92
+ }
93
+ return base;
94
+ }
95
+
96
+ /**
97
+ * Walk the current branch in chronological order and reconstruct task state.
98
+ *
99
+ * New records contain only the action and parameters needed to replay the
100
+ * operation. Legacy records contain the full `tasks`/`nextId` snapshot. Custom
101
+ * entries remain authoritative when present because a nested tool call may not
102
+ * have a standalone toolResult message. Tool results preceding the first valid
103
+ * custom entry can seed old branches, but later results duplicate the custom stream.
104
+ */
105
+ export function replayFromBranch(ctx: {
106
+ sessionManager: { getBranch(): Iterable<unknown> };
107
+ }): TaskState {
108
+ const customRecords: unknown[] = [];
109
+ const toolResultRecords: unknown[] = [];
110
+
111
+ for (const entry of ctx.sessionManager.getBranch()) {
112
+ const value = entry as {
113
+ type?: string;
114
+ customType?: string;
115
+ data?: unknown;
116
+ message?: { role?: string; toolName?: string; details?: unknown };
117
+ };
118
+
119
+ if (value.type === "custom") {
120
+ if (
121
+ value.customType === STATE_ENTRY_TYPE &&
122
+ (customRecords.length > 0 ||
123
+ isCompactTaskDetails(value.data) ||
124
+ isLegacySnapshot(value.data))
125
+ ) {
126
+ customRecords.push(value.data);
127
+ }
128
+ continue;
129
+ }
130
+
131
+ if (customRecords.length > 0 || value.type !== "message") continue;
132
+ const message = value.message;
133
+ if (message?.role === "toolResult" && message.toolName === TOOL_NAME) {
134
+ toolResultRecords.push(message.details);
135
+ }
136
+ }
137
+
138
+ const empty = { tasks: [...EMPTY_STATE.tasks], nextId: EMPTY_STATE.nextId };
139
+ const first = customRecords[0];
140
+ const base = isLegacySnapshot(first) ? empty : applyRecords(toolResultRecords, empty);
141
+ return applyRecords(customRecords, base);
142
+ }
@@ -0,0 +1,108 @@
1
+ import type { Task, TaskStatus } from "../tool/types.ts";
2
+ import type { TaskState } from "./state.ts";
3
+
4
+ /** Tasks excluding deleted tombstones — the canonical "what's visible". */
5
+ export function selectVisibleTasks(state: TaskState): readonly Task[] {
6
+ return state.tasks.filter((t) => t.status !== "deleted");
7
+ }
8
+
9
+ /**
10
+ * Group visible tasks by status. Iteration order at the call site uses
11
+ * (`completed`, `inProgress`, `pending`) to match the `/todos` header part
12
+ * order pinned by `todo.command.test.ts`.
13
+ */
14
+ export interface TasksByStatus {
15
+ pending: readonly Task[];
16
+ inProgress: readonly Task[];
17
+ completed: readonly Task[];
18
+ }
19
+ export function selectTasksByStatus(state: TaskState): TasksByStatus {
20
+ const visible = selectVisibleTasks(state);
21
+ return {
22
+ pending: visible.filter((t) => t.status === "pending"),
23
+ inProgress: visible.filter((t) => t.status === "in_progress"),
24
+ completed: visible.filter((t) => t.status === "completed"),
25
+ };
26
+ }
27
+
28
+ /** Total counts for the overlay heading (`Todos (n/m)`) and `/todos` header. */
29
+ export interface TodoCounts {
30
+ total: number;
31
+ pending: number;
32
+ inProgress: number;
33
+ completed: number;
34
+ }
35
+ export function selectTodoCounts(state: TaskState): TodoCounts {
36
+ const groups = selectTasksByStatus(state);
37
+ return {
38
+ total: groups.pending.length + groups.inProgress.length + groups.completed.length,
39
+ pending: groups.pending.length,
40
+ inProgress: groups.inProgress.length,
41
+ completed: groups.completed.length,
42
+ };
43
+ }
44
+
45
+ /**
46
+ * Whether any visible task carries a `blockedBy` reference. The overlay uses
47
+ * this to gate the `#id` prefix on per-task rows — without at least one
48
+ * `⛓ #N` suffix, the per-row id has no anchor.
49
+ */
50
+ export function selectShowTaskIds(state: TaskState): boolean {
51
+ return selectVisibleTasks(state).some((t) => t.blockedBy && t.blockedBy.length > 0);
52
+ }
53
+
54
+ /**
55
+ * Resolve a task's subject by id from the live state for renderCall's
56
+ * accent label. `undefined` when the id is unknown — caller falls back to
57
+ * `#id` plain rendering.
58
+ */
59
+ export function selectTaskSubjectById(state: TaskState, id: number): string | undefined {
60
+ return state.tasks.find((t) => t.id === id)?.subject;
61
+ }
62
+
63
+ /**
64
+ * Overlay layout decision. Encapsulates the "drop completed first, then
65
+ * truncate non-completed tail" rule. `budget` is the body-slot count (caller passes
66
+ * `getMaxWidgetLines() - 1` to reserve the heading row); on overflow the
67
+ * selector reserves one more slot internally for the summary row. Returns
68
+ * the visible task slice plus the overflow summary parts.
69
+ */
70
+ export interface OverlayLayout {
71
+ visible: readonly Task[];
72
+ hiddenCompleted: number;
73
+ truncatedTail: number;
74
+ }
75
+ export function selectOverlayLayout(state: TaskState, budget: number): OverlayLayout {
76
+ const all = selectVisibleTasks(state);
77
+ if (all.length <= budget) {
78
+ return { visible: all, hiddenCompleted: 0, truncatedTail: 0 };
79
+ }
80
+ const innerBudget = budget - 1;
81
+ const nonCompleted = all.filter((t) => t.status !== "completed");
82
+ const totalCompleted = all.length - nonCompleted.length;
83
+ if (nonCompleted.length <= innerBudget) {
84
+ const kept = new Set<Task>(nonCompleted);
85
+ for (const t of all) {
86
+ if (kept.size >= innerBudget) break;
87
+ if (t.status === "completed") kept.add(t);
88
+ }
89
+ const visible = all.filter((t) => kept.has(t));
90
+ const shownCompleted = visible.filter((t) => t.status === "completed").length;
91
+ return { visible, hiddenCompleted: totalCompleted - shownCompleted, truncatedTail: 0 };
92
+ }
93
+ const visible = nonCompleted.slice(0, innerBudget);
94
+ const truncatedTail = nonCompleted.length - innerBudget;
95
+ return { visible, hiddenCompleted: totalCompleted, truncatedTail };
96
+ }
97
+
98
+ /**
99
+ * Helper: whether any visible task is `pending` or `in_progress`. The overlay
100
+ * uses this to pick the heading icon (`accent`+`●` vs `dim`+`○`).
101
+ */
102
+ export function selectHasActive(state: TaskState): boolean {
103
+ return selectVisibleTasks(state).some(
104
+ (t) => t.status === "in_progress" || t.status === "pending",
105
+ );
106
+ }
107
+
108
+ export const ACTIVE_STATUSES: ReadonlySet<TaskStatus> = new Set(["pending", "in_progress"]);