pi-suite 0.0.0-stage → 0.3.1

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 (220) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +100 -2
  3. package/README.zh-CN.md +101 -0
  4. package/package.json +63 -4
  5. package/skills/pi-suite-jobs/SKILL.md +76 -0
  6. package/skills/pi-suite-workflow/SKILL.md +114 -0
  7. package/src/agents/catalog.ts +80 -0
  8. package/src/agents/child.ts +79 -0
  9. package/src/agents/commands.ts +17 -0
  10. package/src/agents/defaults.ts +78 -0
  11. package/src/agents/history.ts +112 -0
  12. package/src/agents/index.ts +211 -0
  13. package/src/agents/manager.ts +438 -0
  14. package/src/agents/mentions/clone.ts +51 -0
  15. package/src/agents/mentions/grammar.ts +64 -0
  16. package/src/agents/mentions/index.ts +76 -0
  17. package/src/agents/mentions/provider.ts +79 -0
  18. package/src/agents/model-editor.ts +95 -0
  19. package/src/agents/models.ts +43 -0
  20. package/src/agents/output/schema.ts +101 -0
  21. package/src/agents/output/tool.ts +98 -0
  22. package/src/agents/parent.ts +13 -0
  23. package/src/agents/questions.ts +63 -0
  24. package/src/agents/records.ts +90 -0
  25. package/src/agents/registry.ts +20 -0
  26. package/src/agents/render.ts +85 -0
  27. package/src/agents/resources/context.ts +48 -0
  28. package/src/agents/resources/loader.ts +86 -0
  29. package/src/agents/resources/memory.ts +67 -0
  30. package/src/agents/resources/packages.ts +96 -0
  31. package/src/agents/resources/paths.ts +8 -0
  32. package/src/agents/resources/prompts.ts +11 -0
  33. package/src/agents/resources/scope.ts +147 -0
  34. package/src/agents/resources/selectors.ts +186 -0
  35. package/src/agents/retry.ts +20 -0
  36. package/src/agents/rpc/handlers.ts +62 -0
  37. package/src/agents/rpc/index.ts +73 -0
  38. package/src/agents/rpc/options.ts +44 -0
  39. package/src/agents/run-groups.ts +16 -0
  40. package/src/agents/runner.ts +131 -0
  41. package/src/agents/runtime.ts +40 -0
  42. package/src/agents/schedules/index.ts +136 -0
  43. package/src/agents/schedules/menu.ts +38 -0
  44. package/src/agents/schedules/parse.ts +42 -0
  45. package/src/agents/schedules/store.ts +78 -0
  46. package/src/agents/schema.ts +5 -0
  47. package/src/agents/session.ts +29 -0
  48. package/src/agents/tools.ts +177 -0
  49. package/src/agents/types.ts +87 -0
  50. package/src/agents/ui/index.ts +42 -0
  51. package/src/agents/ui/runs.ts +122 -0
  52. package/src/agents/ui/types.ts +91 -0
  53. package/src/agents/viewer-info.ts +36 -0
  54. package/src/agents/viewer.ts +160 -0
  55. package/src/agents/workflow/collisions.ts +124 -0
  56. package/src/agents/workflow/entry.ts +93 -0
  57. package/src/agents/workflow/host.ts +119 -0
  58. package/src/agents/workflow/index.ts +100 -0
  59. package/src/agents/workflow/journal.ts +147 -0
  60. package/src/agents/workflow/literal.ts +57 -0
  61. package/src/agents/workflow/manager.ts +169 -0
  62. package/src/agents/workflow/meta.ts +323 -0
  63. package/src/agents/workflow/progress/format.ts +184 -0
  64. package/src/agents/workflow/progress/index.ts +3 -0
  65. package/src/agents/workflow/progress/model.ts +224 -0
  66. package/src/agents/workflow/progress/types.ts +144 -0
  67. package/src/agents/workflow/render.ts +46 -0
  68. package/src/agents/workflow/runtime/helpers.ts +236 -0
  69. package/src/agents/workflow/runtime/index.ts +3 -0
  70. package/src/agents/workflow/runtime/run.ts +646 -0
  71. package/src/agents/workflow/runtime/types.ts +273 -0
  72. package/src/agents/workflow/saved.ts +74 -0
  73. package/src/agents/workflow/store.ts +23 -0
  74. package/src/agents/workflow/task.ts +277 -0
  75. package/src/agents/workflow/tool-description.ts +32 -0
  76. package/src/agents/workflow/tools.ts +66 -0
  77. package/src/agents/workflow/ui/menu.ts +144 -0
  78. package/src/agents/workflow/ui/progress.ts +91 -0
  79. package/src/agents/workflow/worker/bootstrap.ts +316 -0
  80. package/src/agents/workflow/worker/flow.ts +218 -0
  81. package/src/agents/workflow/worker/index.ts +7 -0
  82. package/src/agents/workflow/worker/scope.ts +215 -0
  83. package/src/ask/.gitkeep +0 -0
  84. package/src/ask/form.ts +67 -0
  85. package/src/ask/index.ts +73 -0
  86. package/src/ask/keys.ts +32 -0
  87. package/src/ask/layout.ts +78 -0
  88. package/src/ask/queue.ts +40 -0
  89. package/src/ask/render.ts +62 -0
  90. package/src/ask/result.ts +56 -0
  91. package/src/ask/schema.ts +67 -0
  92. package/src/ask/tool-render.ts +49 -0
  93. package/src/ask/view.ts +406 -0
  94. package/src/goal/.gitkeep +0 -0
  95. package/src/goal/activity.ts +50 -0
  96. package/src/goal/commands.ts +75 -0
  97. package/src/goal/context.ts +36 -0
  98. package/src/goal/index.ts +38 -0
  99. package/src/goal/manager.ts +386 -0
  100. package/src/goal/presentation.ts +15 -0
  101. package/src/goal/render.ts +36 -0
  102. package/src/goal/snapshot.ts +78 -0
  103. package/src/goal/state.ts +39 -0
  104. package/src/goal/store.ts +59 -0
  105. package/src/goal/tools.ts +59 -0
  106. package/src/goal/wait.ts +39 -0
  107. package/src/index.ts +20 -0
  108. package/src/jobs/backends/linux-tree.ts +87 -0
  109. package/src/jobs/backends/pipe.ts +74 -0
  110. package/src/jobs/backends/process.ts +79 -0
  111. package/src/jobs/backends/pty-job.ts +45 -0
  112. package/src/jobs/backends/pty.ts +502 -0
  113. package/src/jobs/backends/windows-tree.ts +289 -0
  114. package/src/jobs/commands.ts +7 -0
  115. package/src/jobs/control.ts +13 -0
  116. package/src/jobs/index.ts +331 -0
  117. package/src/jobs/launch/config.ts +26 -0
  118. package/src/jobs/launch/name.ts +16 -0
  119. package/src/jobs/launch/presets.ts +61 -0
  120. package/src/jobs/log-viewer.ts +147 -0
  121. package/src/jobs/manager.ts +507 -0
  122. package/src/jobs/monitors/compile.ts +101 -0
  123. package/src/jobs/monitors/hands-free.ts +108 -0
  124. package/src/jobs/monitors/runtime.ts +165 -0
  125. package/src/jobs/output.ts +54 -0
  126. package/src/jobs/query.ts +62 -0
  127. package/src/jobs/render.ts +103 -0
  128. package/src/jobs/runtime.ts +89 -0
  129. package/src/jobs/state.ts +25 -0
  130. package/src/jobs/store.ts +168 -0
  131. package/src/jobs/terminal/keys.ts +292 -0
  132. package/src/jobs/terminal/protocol.ts +37 -0
  133. package/src/jobs/terminal/read.ts +131 -0
  134. package/src/jobs/terminal/render.ts +70 -0
  135. package/src/jobs/terminal/screen.ts +92 -0
  136. package/src/jobs/terminal/session.ts +100 -0
  137. package/src/jobs/terminal/shell.ts +22 -0
  138. package/src/jobs/terminal/snapshot.ts +8 -0
  139. package/src/jobs/terminal/visible-text.ts +53 -0
  140. package/src/jobs/tools.ts +203 -0
  141. package/src/jobs/types.ts +60 -0
  142. package/src/jobs/viewer/component.ts +209 -0
  143. package/src/jobs/viewer/metadata.ts +9 -0
  144. package/src/jobs/viewer.ts +149 -0
  145. package/src/jobs/workspace.ts +31 -0
  146. package/src/runtime/.gitkeep +0 -0
  147. package/src/runtime/binding.ts +26 -0
  148. package/src/runtime/cli-prompt.ts +24 -0
  149. package/src/runtime/clipboard.ts +16 -0
  150. package/src/runtime/config-edit.ts +31 -0
  151. package/src/runtime/config-fields.ts +65 -0
  152. package/src/runtime/config.ts +111 -0
  153. package/src/runtime/errors.ts +11 -0
  154. package/src/runtime/json-store.ts +156 -0
  155. package/src/runtime/notification-render.ts +35 -0
  156. package/src/runtime/notifications.ts +98 -0
  157. package/src/runtime/owner.ts +54 -0
  158. package/src/runtime/read.ts +200 -0
  159. package/src/runtime/renderers.ts +50 -0
  160. package/src/runtime/responses/index.ts +126 -0
  161. package/src/runtime/responses/payload.ts +101 -0
  162. package/src/runtime/settings/index.ts +24 -0
  163. package/src/runtime/settings/view.ts +84 -0
  164. package/src/runtime/suite.ts +192 -0
  165. package/src/runtime/text.ts +6 -0
  166. package/src/runtime/tools.ts +131 -0
  167. package/src/runtime/wait-render.ts +33 -0
  168. package/src/runtime/wait.ts +134 -0
  169. package/src/tasks/commands.ts +41 -0
  170. package/src/tasks/index.ts +305 -0
  171. package/src/tasks/model.ts +152 -0
  172. package/src/tasks/presentation.ts +40 -0
  173. package/src/tasks/query.ts +38 -0
  174. package/src/tasks/render.ts +54 -0
  175. package/src/tasks/schema.ts +25 -0
  176. package/src/tasks/store.ts +164 -0
  177. package/src/tasks/tools.ts +69 -0
  178. package/src/tasks/types.ts +61 -0
  179. package/src/tasks/viewer.ts +68 -0
  180. package/src/ui/.gitkeep +0 -0
  181. package/src/ui/actions.ts +50 -0
  182. package/src/ui/browser-chrome.ts +175 -0
  183. package/src/ui/browser.ts +292 -0
  184. package/src/ui/details.ts +111 -0
  185. package/src/ui/dock/line.ts +14 -0
  186. package/src/ui/dock/rows.ts +78 -0
  187. package/src/ui/dock.ts +224 -0
  188. package/src/ui/format.ts +25 -0
  189. package/src/ui/frame.ts +8 -0
  190. package/src/ui/inline-input.ts +98 -0
  191. package/src/ui/reading.ts +105 -0
  192. package/src/ui/rendering/builtin-command.ts +34 -0
  193. package/src/ui/rendering/command.ts +60 -0
  194. package/src/ui/rendering/read-page.ts +15 -0
  195. package/src/ui/rendering/shell/bash.ts +281 -0
  196. package/src/ui/rendering/shell/index.ts +24 -0
  197. package/src/ui/rendering/shell/powershell.ts +155 -0
  198. package/src/ui/rendering/shell/spans.ts +28 -0
  199. package/src/ui/scroll.ts +111 -0
  200. package/src/ui/select.ts +67 -0
  201. package/src/ui/status.ts +67 -0
  202. package/src/ui/structured-details.ts +41 -0
  203. package/src/ui/terminal.ts +137 -0
  204. package/src/ui/ticker.ts +18 -0
  205. package/src/ui/tool-render.ts +152 -0
  206. package/src/ui/transcript.ts +140 -0
  207. package/src/ui/viewer/agent-information.ts +34 -0
  208. package/src/ui/viewer/editor.ts +18 -0
  209. package/src/ui/viewer/navigation.ts +25 -0
  210. package/themes/oh-my-pi.json +95 -0
  211. package/third-party/UPSTREAM.md +88 -0
  212. package/third-party/licenses/.gitkeep +0 -0
  213. package/third-party/licenses/oh-my-pi.txt +23 -0
  214. package/third-party/licenses/pi-ask-user.txt +21 -0
  215. package/third-party/licenses/pi-background-jobs.txt +21 -0
  216. package/third-party/licenses/pi-goal.txt +21 -0
  217. package/third-party/licenses/pi-interactive-shell.txt +25 -0
  218. package/third-party/licenses/pi-subagents.txt +21 -0
  219. package/third-party/licenses/pi-tasks.txt +21 -0
  220. package/third-party/sources.json +111 -0
@@ -0,0 +1,164 @@
1
+ // Task-specific mutations use the shared asynchronous JSON store/lock protocol.
2
+ // Adapted from @tintinweb/pi-tasks 0.9.1 src/task-store.ts (MIT).
3
+ import { createHash } from 'node:crypto';
4
+ import { Value } from 'typebox/value';
5
+ import { Type } from 'typebox';
6
+ import { JsonStore } from '../runtime/json-store.ts';
7
+ import { ToolError } from '../runtime/errors.ts';
8
+ import { applyChanges, taskViews, validateHierarchy } from './model.ts';
9
+ import { checkGeneration, emptyTasks, requireGeneration, storeSchema, groupId, type TaskChange, type TaskData, type TaskDisplay, type TaskEditResult } from './types.ts';
10
+
11
+ const { generation: _generation, resetReason: _resetReason, ...v3Fields } = storeSchema.properties;
12
+ const v3Schema = Type.Object({ ...v3Fields, version: Type.Literal(3) }, { additionalProperties: false });
13
+
14
+ const { nextChild: _nextChild, ...legacyFields } = storeSchema.properties.tasks.items.properties;
15
+ const legacySchema = Type.Object({ ...v3Fields, version: Type.Literal(2),
16
+ tasks: Type.Array(Type.Object({ ...legacyFields, id: groupId,
17
+ blockedBy: Type.Array(groupId, { maxItems: 100, uniqueItems: true }) }, { additionalProperties: false })),
18
+ }, { additionalProperties: false });
19
+
20
+ function migrate(value: unknown): unknown {
21
+ if (!value || typeof value !== 'object' || !('version' in value) || value.version !== 2) return value;
22
+ // Validate the historical shape before transforming it; malformed files remain errors.
23
+ if (!Value.Check(legacySchema, value)) throw new Error('Invalid version 2 task data');
24
+ const data = structuredClone(value) as unknown as TaskData;
25
+ if (new Set(data.tasks.map(task => task.id)).size !== data.tasks.length
26
+ || data.tasks.some(task => !Number.isSafeInteger(Number(task.id)) || Number(task.id) >= data.nextId)) throw new Error('Invalid version 2 task IDs');
27
+ const ids = new Map<string, string>();
28
+ const children = new Map<string, TaskData['tasks']>();
29
+ for (const task of data.tasks) if (task.parentId) {
30
+ const list = children.get(task.parentId) ?? [];
31
+ list.push(task); children.set(task.parentId, list);
32
+ }
33
+ for (const group of data.tasks.filter(task => !task.parentId)) {
34
+ group.nextChild = 1;
35
+ const sorted = (children.get(group.id) ?? []).sort((a, b) => a.createdAt - b.createdAt || Number(a.id) - Number(b.id));
36
+ for (const child of sorted) ids.set(child.id, `${group.id}.${group.nextChild++}`);
37
+ }
38
+ // Keep group slots, while child slots follow their newly assigned ordinals.
39
+ const positions = new Map<string, number>();
40
+ data.tasks = data.tasks.map(task => {
41
+ if (!task.parentId) return task;
42
+ const index = positions.get(task.parentId) ?? 0;
43
+ positions.set(task.parentId, index + 1);
44
+ return children.get(task.parentId)![index];
45
+ });
46
+ for (const task of data.tasks) {
47
+ task.id = ids.get(task.id) ?? task.id;
48
+ task.blockedBy = task.blockedBy.map(id => ids.get(id) ?? id);
49
+ }
50
+ (data as unknown as { version: number }).version = 3;
51
+ return data;
52
+ }
53
+
54
+ function decode(value: unknown, generation: string): TaskData {
55
+ value = migrate(value);
56
+ if (Value.Check(v3Schema, value)) value = { ...value, version: 4, generation };
57
+ if (!Value.Check(storeSchema, value)) throw new Error('Invalid version or task data');
58
+ validateHierarchy(value); return value;
59
+ }
60
+ const display = (data: TaskData): TaskDisplay[] => taskViews(data).map(({ id, title, parentId, status, updatedAt, progress }) =>
61
+ ({ id, title, parentId, status, updatedAt, progress }));
62
+ const complete = (data: TaskData) => data.tasks.length > 0 && taskViews(data).every(task => task.status === 'done');
63
+
64
+ export class TaskStore extends JsonStore<TaskData> {
65
+ private ready: Promise<void>;
66
+ private completionListeners = new Set<(rows: TaskDisplay[], generation: string, sourceGeneration: string) => void>();
67
+ readonly initialGeneration: string;
68
+ constructor(path?: string, legacy?: Promise<unknown>) {
69
+ // Readers/processes of an uninitialized or v3 file must agree before the first locked
70
+ // commit. Clear then replaces this capability with a fresh, unpredictable generation.
71
+ const initial = emptyTasks(path ? `initial:${createHash('sha256').update(path).digest('hex')}` : undefined);
72
+ super(path, initial, value => decode(value, initial.generation), 'TASK');
73
+ this.initialGeneration = initial.generation;
74
+ this.ready = legacy ? legacy.then(value => { this.data = decode(value, initial.generation); }) : Promise.resolve();
75
+ }
76
+ override async snapshot(generation?: string): Promise<TaskData> {
77
+ await this.ready;
78
+ const data = await super.snapshot();
79
+ if (generation !== undefined) checkGeneration(data, generation);
80
+ return data;
81
+ }
82
+ async edit(changes: TaskChange[], generation: string, signal?: AbortSignal): Promise<TaskEditResult> {
83
+ requireGeneration(generation); await this.ready;
84
+ let completed: TaskDisplay[] | undefined;
85
+ const result = await this.mutate(data => {
86
+ // Check after reload and lock wait, not against the caller's stale cache.
87
+ checkGeneration(data, generation);
88
+ const result = applyChanges(data, changes);
89
+ if (complete(data)) { completed = display(data); Object.assign(data, emptyTasks(undefined, 'completed')); }
90
+ return { ...result, generation: data.generation, ...completed ? { cleared: 'completed' as const } : {} };
91
+ }, signal);
92
+ if (completed) for (const listener of this.completionListeners) listener(completed, result.generation, generation);
93
+ return result;
94
+ }
95
+ async clear(generation: string, signal?: AbortSignal): Promise<TaskEditResult> {
96
+ requireGeneration(generation); await this.ready;
97
+ return this.mutate(data => {
98
+ checkGeneration(data, generation); Object.assign(data, emptyTasks(undefined, 'clear'));
99
+ return { changes: [], derived: [], progress: [], warnings: [], generation: data.generation, cleared: 'clear' };
100
+ }, signal);
101
+ }
102
+ /** Only the currently bound target opts into cleaning completed restored data. */
103
+ async recover(): Promise<TaskData> {
104
+ const data = await this.snapshot();
105
+ if (complete(data)) await this.mutate(current => {
106
+ checkGeneration(current, data.generation);
107
+ if (complete(current)) Object.assign(current, emptyTasks(undefined, 'completed'));
108
+ });
109
+ return this.snapshot();
110
+ }
111
+ async seed(seed: TaskData, generation: string): Promise<void> {
112
+ requireGeneration(generation); await this.ready;
113
+ return this.mutate(data => {
114
+ checkGeneration(data, generation);
115
+ // Independent target identity also prevents re-seeding a cleared target.
116
+ if (!data.tasks.length && data.nextId === 1 && data.generation === this.initialGeneration) {
117
+ const clone = structuredClone(seed);
118
+ Object.assign(data, clone, { generation: data.generation });
119
+ }
120
+ });
121
+ }
122
+ onCompletion(listener: (rows: TaskDisplay[], generation: string, sourceGeneration: string) => void): () => void {
123
+ this.completionListeners.add(listener); return () => this.completionListeners.delete(listener);
124
+ }
125
+ async link(id: string, reference: { agentId?: string; jobId?: string }, generation: string): Promise<void> {
126
+ requireGeneration(generation); await this.ready;
127
+ return this.mutate(data => {
128
+ checkGeneration(data, generation);
129
+ const task = data.tasks.find(task => task.id === id);
130
+ if (!task?.parentId) throw new ToolError('NOT_FOUND', `No child task ${id} in this list. Use task_list({state:"all"}) to find a child ID.`);
131
+ if (reference.agentId) task.owner = reference.agentId;
132
+ if (reference.jobId && !task.jobIds.includes(reference.jobId)) task.jobIds.push(reference.jobId);
133
+ task.updatedAt = Date.now();
134
+ });
135
+ }
136
+ }
137
+
138
+ // Keep v3 reachable only for retirement, never as an alternative write path. A public
139
+ // snapshot queues behind its admitted mutations. Revoke new entries synchronously, then
140
+ // publish v4 only after that barrier; in-flight v3 writes cannot follow new task reuse.
141
+ const key = Symbol.for('pi-suite.tasks.stores.v4');
142
+ const oldKey = Symbol.for('pi-suite.tasks.stores.v3');
143
+ type LegacyStore = Pick<TaskStore, 'current' | 'snapshot' | 'edit' | 'seed' | 'link'>;
144
+ const globals = globalThis as typeof globalThis & { [key]?: Map<string, TaskStore>; [oldKey]?: Map<string, LegacyStore> };
145
+ function retire(store: LegacyStore): Promise<unknown> {
146
+ const barrier = store.snapshot();
147
+ const reject = () => Promise.reject(new ToolError('TASK_STALE', 'This task store comes from an earlier pi-suite load and is retired. Call task_list({}) and retry with the current tools; running executions are not stopped.'));
148
+ for (const method of ['snapshot', 'edit', 'seed', 'link']) Object.defineProperty(store, method, { value: reject, configurable: true });
149
+ return barrier.finally(() => {
150
+ Object.defineProperty(store, 'current', { get() { throw new ToolError('TASK_STALE', 'This task store comes from an earlier pi-suite load and is retired. Call task_list({}) and retry with the current tools.'); }, configurable: true });
151
+ });
152
+ }
153
+ export function taskStore(target: string, path?: string): TaskStore {
154
+ const stores = globals[key] ??= new Map();
155
+ let store = stores.get(target);
156
+ if (!store) {
157
+ const old = globals[oldKey]?.get(target);
158
+ const legacy = old ? retire(old) : undefined;
159
+ // Keep the retired entry: pre-reload taskStore closures also retain this map and
160
+ // would otherwise construct a fresh v3 writer for the same in-memory target.
161
+ store = new TaskStore(path, legacy); stores.set(target, store);
162
+ }
163
+ return store;
164
+ }
@@ -0,0 +1,69 @@
1
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
2
+ import { Type } from 'typebox';
3
+ import { registerBoundTool, checkedArguments, LIST_LIMITS, paginate, textResult } from '../runtime/tools.ts';
4
+ import { boundedText } from '../runtime/read.ts';
5
+ import type { TasksModule } from './index.ts';
6
+ import { taskId, taskScope, groupId, generationSchema, type TaskScope, type TaskView } from './types.ts';
7
+ import { taskDetails, taskLabel, type TaskFilter } from './query.ts';
8
+ import { taskViews } from './model.ts';
9
+ import { editSchema, editArguments, editChanges } from './schema.ts';
10
+ import { requireGeneration } from './types.ts';
11
+ import { editLines } from './presentation.ts';
12
+
13
+ import { listRenderers, getRenderers, editRenderers } from './render.ts';
14
+
15
+ const listSchema = Type.Object({ generation: Type.Optional(generationSchema), groupId: Type.Optional(groupId),
16
+ state: Type.Optional(Type.Union([Type.Literal('unfinished'), Type.Literal('doing'), Type.Literal('blocked'), Type.Literal('done'), Type.Literal('all')])),
17
+ cursor: Type.Optional(Type.String({ maxLength: 200 })), limit: Type.Optional(Type.Integer({ minimum: 1, maximum: LIST_LIMITS.maxLimit })) }, { additionalProperties: false });
18
+ const getSchema = Type.Object({ generation: generationSchema, id: taskId, scope: Type.Optional(taskScope) }, { additionalProperties: false });
19
+ const queryHint = 'Get the local generation with task_list({}). Pass the source generation with groupId, cursor, or id.';
20
+
21
+ export function registerTaskTools(pi: ExtensionAPI, tasks: TasksModule): void {
22
+ const scopeHint = tasks.scopeHint;
23
+ // Assignment is fixed at admission. Omit drops object options; retain strict validation.
24
+ const getParameters = scopeHint ? getSchema : Type.Omit(getSchema, ['scope'], { additionalProperties: false });
25
+ const editParameters = scopeHint ? editSchema : Type.Omit(editSchema, ['scope'], { additionalProperties: false });
26
+ registerBoundTool(pi, { name: 'task_list', label: 'Tasks', description: 'List tasks by group and state (default: unfinished); page with cursor and limit. Call task_list({}) for the local generation. Pass the source generation with groupId or cursor. Group counts include all children. For one task, use task_get.' + scopeHint,
27
+ parameters: listSchema, prepareArguments: checkedArguments(listSchema, queryHint),
28
+ async execute(_id, params, _signal, _update, ctx) {
29
+ if (params.groupId || params.cursor) requireGeneration(params.generation);
30
+ const { rows, data } = await tasks.list(ctx, { parentId: params.groupId, state: params.state as TaskFilter | undefined }, params.generation);
31
+ const views = new Map(taskViews(data).map(task => [task.id, task]));
32
+ const label = (task: TaskView) => taskLabel({ ...task, title: boundedText(task.title, 200) });
33
+ const { page, nextCursor } = paginate(rows, task => {
34
+ const group = views.get(task.parentId ?? task.id)!;
35
+ return { createdAt: new Date(group.createdAt).toISOString(), id: `${group.id.padStart(16, '0')}:${(task.parentId ? task.id.split('.')[1]! : '0').padStart(16, '0')}` };
36
+ }, params.cursor, params.limit ?? LIST_LIMITS.defaultLimit, { oldest: true, budgetBytes: LIST_LIMITS.defaultBytes - 512,
37
+ size: task => Buffer.byteLength(label(task)) + Buffer.byteLength(boundedText(task.blockedReason ?? '', 200))
38
+ + (task.parentId ? Buffer.byteLength(label(views.get(task.parentId)!)) : 0) + 80 });
39
+ // A page may start mid-group. Reinsert organization context without advancing its cursor.
40
+ const shown = new Map<string, TaskView>();
41
+ for (const task of page) { if (task.parentId) shown.set(task.parentId, views.get(task.parentId)!); shown.set(task.id, task); }
42
+ const more = nextCursor ? `more: task_list(${JSON.stringify({ ...params, generation: data.generation, cursor: nextCursor })})` : undefined;
43
+ return textResult([`generation: ${data.generation}`, `tasks ${page.length}/${rows.length} ${params.state ?? 'unfinished'}${params.groupId ? ` group ${params.groupId}` : ''}`,
44
+ ...[...shown.values()].map(task => `${label(task)}${task.blockedReason ? ` · ${boundedText(task.blockedReason, 200)}` : ''}`), more],
45
+ { tasks: [...shown.values()], generation: data.generation, nextCursor });
46
+ },
47
+ ...listRenderers,
48
+ }, 'initial');
49
+ registerBoundTool(pi, { name: 'task_get', label: 'Task', description: 'Read one group or child, including description, blockers and execution links. A group read does not list its children; call task_list with groupId and generation.' + scopeHint,
50
+ parameters: getParameters, prepareArguments: checkedArguments(getParameters, queryHint),
51
+ async execute(_id, params, _signal, _update, ctx) {
52
+ const scope = (params as { scope?: TaskScope }).scope;
53
+ const { task, views } = await tasks.get(ctx, params.id, params.generation, scope);
54
+ return textResult([`generation: ${params.generation}`, scope === 'assigned' ? `assigned task ${params.id} (parent list)` : undefined, ...taskDetails(task, views)], { task, generation: params.generation });
55
+ },
56
+ ...getRenderers,
57
+ }, 'initial');
58
+ registerBoundTool(pi, { name: 'task_edit', label: 'Tasks',
59
+ description: 'Use the source generation from task_list({}) for local edits. Add a group with optional children titles (no status), or a child with parentId (no children). Use start/done/block/unblock with a child ID such as 1.2; block accepts reason. Multiple children may be doing. Unblock does not remove dependencies. Update fields; to move, delete then add. Deleting a group with children requires cascade:true. Batch changes commit all or none. Use top-level clear, not in a batch or assigned scope, to delete the whole local list with its dependencies and execution links and restart numbering at 1; a nonempty list also clears when all tasks are done. IDs may be reused after a clear, under a new generation. Edits do not stop executions or complete the goal.' + scopeHint,
60
+ parameters: editParameters, prepareArguments: editArguments,
61
+ async execute(_id, params, signal, _update, ctx) {
62
+ const scope = (params as { scope?: TaskScope }).scope;
63
+ const result = await tasks.edit(ctx, editChanges(params), params.generation, signal, scope);
64
+ return textResult([`generation: ${result.generation}`, scope === 'assigned' ? 'assigned task progress (parent list)' : undefined,
65
+ result.cleared ? `tasks cleared (${result.cleared}); numbering restarts at 1, old references expired` : undefined, ...editLines(result)], result);
66
+ },
67
+ ...editRenderers,
68
+ }, 'initial');
69
+ }
@@ -0,0 +1,61 @@
1
+ // Adapted from @tintinweb/pi-tasks 0.9.1 src/types.ts (MIT, third-party/licenses/pi-tasks.txt).
2
+ // Groups organize direct children; execution status is stored only on children.
3
+ import { randomUUID } from 'node:crypto';
4
+ import { Type, type Static } from 'typebox';
5
+ import { ToolError } from '../runtime/errors.ts';
6
+
7
+ export const groupId = Type.String({ pattern: '^[1-9][0-9]*$' });
8
+ export const childId = Type.String({ pattern: '^[1-9][0-9]*\\.[1-9][0-9]*$' });
9
+ export const taskId = Type.String({ pattern: '^[1-9][0-9]*(?:\\.[1-9][0-9]*)?$' });
10
+ export const taskScope = Type.Union([Type.Literal('local'), Type.Literal('assigned')]);
11
+ export type TaskScope = Static<typeof taskScope>;
12
+ export const title = Type.String({ minLength: 1, maxLength: 200 });
13
+ export const description = Type.String({ maxLength: 8000 });
14
+ export const status = Type.Union([Type.Literal('todo'), Type.Literal('doing'), Type.Literal('blocked'), Type.Literal('done')]);
15
+ export const reason = Type.String({ maxLength: 500 });
16
+ const dependencies = Type.Array(taskId, { maxItems: 100, uniqueItems: true });
17
+ const editable = { title: Type.Optional(title), description: Type.Optional(description), blockedBy: Type.Optional(dependencies) };
18
+ export const mutationSchema = Type.Union([
19
+ Type.Object({ op: Type.Literal('add'), title, description: editable.description, blockedBy: editable.blockedBy,
20
+ parentId: Type.Optional(groupId), status: Type.Optional(status), children: Type.Optional(Type.Array(title, { maxItems: 100 })) }, { additionalProperties: false }),
21
+ Type.Object({ op: Type.Literal('update'), id: taskId, ...editable, status: Type.Optional(status), blockedReason: Type.Optional(reason) }, { additionalProperties: false }),
22
+ Type.Object({ op: Type.Literal('delete'), id: taskId, cascade: Type.Optional(Type.Boolean()) }, { additionalProperties: false }),
23
+ ]);
24
+ export const changeSchema = Type.Union([mutationSchema,
25
+ Type.Object({ op: Type.Union([Type.Literal('start'), Type.Literal('done'), Type.Literal('unblock')]), id: childId }, { additionalProperties: false }),
26
+ Type.Object({ op: Type.Literal('block'), id: childId, reason: Type.Optional(reason) }, { additionalProperties: false }),
27
+ ]);
28
+ export type TaskChange = Static<typeof changeSchema>;
29
+ export const generationSchema = Type.String({ minLength: 1, maxLength: 100 });
30
+ export const storeSchema = Type.Object({
31
+ version: Type.Literal(4), generation: generationSchema,
32
+ resetReason: Type.Optional(Type.Union([Type.Literal('completed'), Type.Literal('clear')])),
33
+ nextId: Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }),
34
+ tasks: Type.Array(Type.Object({
35
+ id: taskId, nextChild: Type.Optional(Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER })), title, description: Type.Optional(description), parentId: Type.Optional(groupId), status: Type.Optional(status),
36
+ blockedBy: dependencies, owner: Type.Optional(Type.String()), jobIds: Type.Array(Type.String()),
37
+ blockedReason: Type.Optional(reason),
38
+ createdAt: Type.Integer({ minimum: 0 }), updatedAt: Type.Integer({ minimum: 0 }),
39
+ }, { additionalProperties: false })),
40
+ }, { additionalProperties: false });
41
+ export type TaskData = Static<typeof storeSchema>;
42
+ export type Task = TaskData['tasks'][number];
43
+ export type TaskStatus = Static<typeof status>;
44
+ export type TaskView = Omit<Task, 'status'> & { status: TaskStatus; blocks: string[]; progress?: { done: number; total: number } };
45
+ export type EditReceipt = { op: TaskChange['op']; id: string; title: string; parentId?: string; fields?: Record<string, unknown>; before?: TaskStatus; after?: TaskStatus };
46
+ export type DerivedChange = { id: string; title: string; parentId: string; before: TaskStatus; status: TaskStatus };
47
+ export type EditResult = { changes: EditReceipt[]; derived: DerivedChange[]; progress: { id: string; status: TaskStatus; done: number; total: number }[]; warnings: string[] };
48
+ export type TaskDisplay = Pick<TaskView, 'id' | 'title' | 'parentId' | 'status' | 'updatedAt' | 'progress'>;
49
+ export type TaskEditResult = EditResult & { generation: string; cleared?: 'completed' | 'clear' };
50
+ export const emptyTasks = (generation: string = randomUUID(), resetReason?: TaskData['resetReason']): TaskData =>
51
+ ({ version: 4, generation, ...resetReason ? { resetReason } : {}, nextId: 1, tasks: [] });
52
+
53
+ // Generation guards live with the data contract so agents/jobs can validate references
54
+ // without importing the persistence layer.
55
+ export function requireGeneration(generation: unknown): asserts generation is string {
56
+ if (typeof generation !== 'string' || !generation) throw new ToolError('TASK_GENERATION_REQUIRED', 'Task references require their source generation; discover your local generation with task_list({}).');
57
+ }
58
+ export function checkGeneration(data: TaskData, generation: unknown): void {
59
+ requireGeneration(generation);
60
+ if (data.generation !== generation) throw new ToolError('TASK_STALE', 'Task generation expired; no changes committed. Read task_list({}) for the current list; never reuse an old ID automatically.');
61
+ }
@@ -0,0 +1,68 @@
1
+ import type { ExtensionContext, Theme } from '@earendil-works/pi-coding-agent';
2
+ import { truncateToWidth, type TUI } from '@earendil-works/pi-tui';
3
+ import { BrowserView, browseState } from '../ui/browser.ts';
4
+ import type { Dock } from '../ui/dock.ts';
5
+ import type { SessionBinding } from '../runtime/binding.ts';
6
+ import { parseTaskReference, taskReferenceKey, type TasksModule } from './index.ts';
7
+ import { checkGeneration } from './types.ts';
8
+ import { queryTasks, taskDetailsView, taskTitle, type TaskFilter } from './query.ts';
9
+ import { taskViews } from './model.ts';
10
+ import { taskRow } from './presentation.ts';
11
+ import type { TaskData, TaskView } from './types.ts';
12
+
13
+ /** Selection keys include the source generation; numeric IDs are reusable. */
14
+ export class TaskBrowserView extends BrowserView {
15
+ constructor(tui: TUI, data: () => TaskData, done: (value?: string) => void, groupId?: string, state: TaskFilter = 'all',
16
+ subscribe?: (refresh: () => void) => () => void, theme?: Theme) {
17
+ let generation = data().generation;
18
+ const current = () => { const value = data(); if (value.generation !== generation) { generation = value.generation; groupId = undefined; } return value; };
19
+ const groups = () => taskViews(current()).filter(task => !task.parentId);
20
+ let views = new Map<string, TaskView>();
21
+ super(tui, { title: 'Tasks', state: browseState(), subscribe,
22
+ total: () => queryTasks(current(), {parentId: groupId, state: 'all'}).length,
23
+ selection: item => ({name: views.get(item.value)!.title, id: views.get(item.value)!.id}),
24
+ layout: { truncatePrimary: ({text, maxWidth}) => truncateToWidth(text, maxWidth, '') },
25
+ controls: [
26
+ { key: 'g', label: 'Group', selected: () => groupId ?? 'all', items: () => [{ value: 'all', label: 'All' },
27
+ ...groups().map(group => ({ value: group.id, label: `${group.id}` }))], select: value => { groupId = value === 'all' ? undefined : value; } },
28
+ { key: 's', label: 'State', selected: () => state, items: () => [
29
+ { value: 'unfinished', label: 'Unfinished' }, { value: 'doing', label: 'Running' }, { value: 'blocked', label: 'Blocked' },
30
+ { value: 'done', label: 'Completed' }, { value: 'all', label: 'All' }], select: value => { state = value as TaskFilter; } },
31
+ ], items: () => {
32
+ if (groupId && !groups().some(group => group.id === groupId)) groupId = undefined;
33
+ const snapshot = current(); views = new Map(taskViews(snapshot).map(task => [taskReferenceKey(snapshot.generation, task.id), task]));
34
+ const byId = new Map([...views.values()].map(task => [task.id, task]));
35
+ return queryTasks(snapshot, { parentId: groupId, state }).map(task => ({ value: taskReferenceKey(snapshot.generation, task.id), status: task.status,
36
+ label: taskRow(task),
37
+ description: task.progress ? `${task.progress.done}/${task.progress.total}` : '',
38
+ search: `${task.id} ${task.title} ${task.description ?? ''} ${task.blockedReason ?? ''} ${task.status}`,
39
+ details: () => taskDetailsView(task, byId) }));
40
+ } }, done, theme);
41
+ }
42
+ }
43
+
44
+ /** Dock opens a read-only task receipt; selection never edits or changes task status. */
45
+ export async function showTask(ctx: ExtensionContext, tasks: TasksModule, dock: Dock, reference: string, binding: SessionBinding): Promise<void> {
46
+ const current = binding.current;
47
+ if (!current) return;
48
+ const { id, generation } = parseTaskReference(reference);
49
+ const {task, views} = await tasks.get(ctx, id, generation);
50
+ if (!binding.isCurrent(current) || ctx.signal?.aborted) return;
51
+ const { showDetails } = await import('../ui/details.ts');
52
+ if (!binding.isCurrent(current) || ctx.signal?.aborted) return;
53
+ await showDetails(ctx, dock, `Tasks ▸ ${taskTitle(task)}`, taskDetailsView(task, views), 'text');
54
+ }
55
+
56
+ export async function showTasks(ctx: ExtensionContext, tasks: TasksModule, groupId: string | undefined, state: TaskFilter,
57
+ binding: SessionBinding): Promise<void> {
58
+ const current = binding.current;
59
+ if (!current) return;
60
+ const selected = await ctx.ui.custom<string | undefined>((tui, theme, _keys, done) =>
61
+ new TaskBrowserView(tui, () => tasks.current(ctx), done, groupId, state, refresh => tasks.subscribe(ctx, refresh), theme));
62
+ if (!binding.isCurrent(current) || ctx.signal?.aborted) return;
63
+ if (selected) {
64
+ const { id, generation } = parseTaskReference(selected), data = tasks.current(ctx);
65
+ checkGeneration(data, generation);
66
+ const task = taskViews(data).find(task => task.id === id); tasks.selectGroup(task?.parentId ?? task?.id);
67
+ }
68
+ }
File without changes
@@ -0,0 +1,50 @@
1
+ import type { Theme } from '@earendil-works/pi-coding-agent';
2
+ import type { InlineRequest } from './inline-input.ts';
3
+ import { confirmation, keyHint } from './browser-chrome.ts';
4
+ import { matchesKey, truncateToWidth, wrapTextWithAnsi, type KeyId } from '@earendil-works/pi-tui';
5
+
6
+ /**
7
+ * Every action is reached by its own key, so the bar never holds a cursor that can
8
+ * disagree with what Enter does. Several actions may share a key when their
9
+ * availability is mutually exclusive (Pause/Resume, Stop subtree/Cleanup jobs).
10
+ */
11
+ export type DetailAction = { key: KeyId; label: string; available?: () => boolean; confirm?: boolean } &
12
+ ({run: () => void; input?: never} | {input: () => InlineRequest; run?: never});
13
+
14
+ export const keyLabel = (key: KeyId): string => key === 'enter' ? 'Enter' : key;
15
+ /** Other readers keep their compact phone layout; fixed footers can opt into bounded wrapping. */
16
+ export const keyHelp = (text: string, width: number, maxRows?: number): string[] => {
17
+ const lines = width >= 80 || maxRows !== undefined ? wrapTextWithAnsi(text, width) : [truncateToWidth(text, width)];
18
+ return maxRows === undefined ? lines : lines.slice(0, maxRows);
19
+ };
20
+
21
+ /** Detail and browser frames share availability and two-step confirmation. */
22
+ export class ActionBar {
23
+ private armed?: DetailAction;
24
+ constructor(private source: () => DetailAction[], private compose: (request: InlineRequest) => void) {}
25
+ disarm(): void { this.armed = undefined; }
26
+ available(): DetailAction[] {
27
+ const actions = this.source().filter(action => action.available?.() !== false);
28
+ if (this.armed && !actions.some(action => action.label === this.armed!.label && action.key === this.armed!.key)) this.armed = undefined;
29
+ return actions;
30
+ }
31
+ /** One confirmation wording for every destructive key keeps the prompt in the UI's language. */
32
+ hint(theme?: Theme): string | undefined {
33
+ this.available();
34
+ return this.armed && confirmation(keyLabel(this.armed.key), this.armed.label.toLowerCase(), theme);
35
+ }
36
+ render(theme?: Theme, exclude: readonly KeyId[] = []): string {
37
+ return this.available().filter(action => !exclude.includes(action.key)).map(action => keyHint(keyLabel(action.key), action.label.toLowerCase(), theme)).join(' · ');
38
+ }
39
+ /** Any other key cancels a pending confirmation, so a stray second press cannot act on new state. */
40
+ handleInput(data: string): boolean {
41
+ const action = this.available().find(action => matchesKey(data, action.key));
42
+ const previous = this.armed; this.armed = undefined;
43
+ if (!action) return false;
44
+ // Sources rebuild action objects per call; identity is the key and label pair.
45
+ if (action.confirm && (previous?.key !== action.key || previous.label !== action.label)) this.armed = action;
46
+ else if (action.input) this.compose(action.input());
47
+ else action.run();
48
+ return true;
49
+ }
50
+ }
@@ -0,0 +1,175 @@
1
+ import type { Theme, ThemeColor } from '@earendil-works/pi-coding-agent';
2
+ import { sanitizeText } from '../runtime/text.ts';
3
+ import { truncateToWidth, visibleWidth, type KeyId, type SelectItem } from '@earendil-works/pi-tui';
4
+
5
+ /** A choice applies as soon as it is picked; there is no cursor that differs from the applied value. */
6
+ export interface BrowseChoice { items: () => SelectItem[]; selected: () => string; select: (value: string, done: (value?: string) => void) => void }
7
+ /** Item descriptions (e.g. counts) appear in the control row; the status line names only the label. */
8
+ export interface BrowseControl extends BrowseChoice { key: KeyId; label: string }
9
+ export interface BrowseSelection { name: string; id?: string }
10
+ /** Explicit fields prevent a state word in an object's name from acquiring status color. */
11
+ export interface DisplayField { text: string; state?: string; tone?: ThemeColor }
12
+ export type DisplayText = string | readonly DisplayField[];
13
+
14
+ const current = (choice: BrowseChoice) => choice.items().find(item => item.value === choice.selected());
15
+ const cell = (item: SelectItem) => item.description ? `${item.label} ${item.description}` : item.label;
16
+ const paint = (token: ThemeColor, text: string, theme?: Theme) => theme?.fg(token, text) ?? text;
17
+ const strong = (text: string, theme?: Theme) => theme?.bold(text) ?? text;
18
+ /** Browser and detail roles live here so pages provide data, never ANSI or palette choices. */
19
+ export const heading = (text: string, theme?: Theme) => paint('accent', strong(text, theme), theme);
20
+ /** Focus decorates chrome only; record states and highlighted reader content keep their own palette. */
21
+ export const focusLabel = (text: string, active: boolean, theme?: Theme) => active ? heading(`▸ ${text}`, theme) : paint('muted', ` ${text}`, theme);
22
+ const focusRule = (text: string, active: boolean, theme?: Theme) => paint(active ? 'accent' : 'borderMuted', text, theme);
23
+ const ruled = (text: string, width: number, active: boolean, theme?: Theme) => {
24
+ const caption = truncateToWidth(text, width), room = width - visibleWidth(caption);
25
+ return caption + (room > 1 ? focusRule(` ${'─'.repeat(room - 1)}`, active, theme) : ' '.repeat(room));
26
+ };
27
+ export const paneHeading = (text: string, width: number, active: boolean, theme?: Theme) => ruled(focusLabel(text, active, theme), width, active, theme);
28
+ export const feedback = (text: string, error: boolean, theme?: Theme) => paint(error ? 'error' : 'muted', text, theme);
29
+ export const newOutputHint = (theme?: Theme, compact = false) => compact ? `${paint('dim', '↓ ', theme)}${keyToken('End', theme)}`
30
+ : `${paint('dim', '↓ new output · ', theme)}${keyHint('End', 'to follow', theme)}`;
31
+ /** The title names what is being read; on narrow screens the new-output hint shrinks before the title disappears. */
32
+ export function readerHeading(title: string, position: string, hasNewOutput: boolean, width: number, theme?: Theme, active?: boolean): string {
33
+ const suffix = (compact: boolean) => `${paint('muted', ` · ${position}`, theme)}${hasNewOutput ? ` · ${newOutputHint(theme, compact)}` : ''}`;
34
+ const tail = width - visibleWidth(suffix(false)) >= 16 ? suffix(false) : suffix(true);
35
+ const shownTitle = truncateToWidth(sanitizeText(title).replace(/[\n\t]/g, ' '), Math.max(0, width - visibleWidth(tail) - (active === undefined ? 0 : 2)));
36
+ const caption = (active === undefined ? heading(shownTitle, theme) : focusLabel(shownTitle, active, theme)) + tail;
37
+ return active === undefined ? truncateToWidth(caption, width) : ruled(caption, width, active, theme);
38
+ }
39
+ export const selectedTab = (text: string, theme?: Theme) => theme?.bg('selectedBg', strong(text, theme)) ?? text;
40
+ export const keyToken = (key: string, theme?: Theme) => paint(key === 'x' ? 'error' : 'warning', strong(key, theme), theme);
41
+ export const keyHint = (key: string, action: string, theme?: Theme) => `${keyToken(key, theme)} ${paint('dim', action, theme)}`;
42
+ export const confirmation = (key: string, action: string, theme?: Theme) =>
43
+ `${paint(key === 'x' ? 'error' : 'warning', `Press ${keyToken(key, theme)} again to ${action}`, theme)} · ${paint('dim', 'any other key cancels', theme)}`;
44
+ export const divider = (text: string, theme?: Theme) => paint('borderMuted', text, theme);
45
+ export const separator = (width: number, theme?: Theme) => divider('─'.repeat(width), theme);
46
+ /** Native SelectList supplies a literal `→ `; tree callers opt out with an empty marker. */
47
+ export const selectedRow = (text: string, width: number, theme?: Theme, active = true, marker = '→ ') => {
48
+ // Only split a known literal prefix, never arbitrary characters from ANSI-styled content.
49
+ const marked = marker && text.startsWith(marker) ? paint(active ? 'accent' : 'muted', marker, theme) + text.slice(marker.length) : text;
50
+ const row = `${marked}${' '.repeat(Math.max(0, width - visibleWidth(text)))}`;
51
+ // An inactive selection still identifies the record, but cannot compete with the focused pane.
52
+ if (!active || !theme) return row;
53
+ // TUI truncation emits SGR 0; restore only the selection background, never a row-wide foreground.
54
+ return theme.bg('selectedBg', strong(row, theme).replace(/\x1b\[0m/g, '\x1b[0m' + theme.getBgAnsi('selectedBg')));
55
+ };
56
+ const stateTones: Record<string, ThemeColor> = { running: 'success', starting: 'success', waiting: 'warning', 'waiting(parent)': 'warning',
57
+ 'cleanup pending': 'warning', 'cleanup unconfirmed': 'warning', stopping: 'warning', queued: 'warning',
58
+ failed: 'error', limited: 'error', timed_out: 'error', completed: 'dim', stopped: 'dim', doing: 'success', blocked: 'warning', done: 'dim',
59
+ enabled: 'success', disabled: 'dim', paused: 'warning', todo: 'accent', success: 'success', error: 'error' };
60
+ export const stateTone = (state: string): ThemeColor | undefined => stateTones[state];
61
+
62
+ const detailTones = { label: 'muted', id: 'accent', meta: 'dim', number: 'toolOutput', error: 'error' } as const;
63
+ export interface DetailPart extends Pick<DisplayField, 'text' | 'state'> {
64
+ role?: 'heading' | keyof typeof detailTones;
65
+ }
66
+ export function detailPartText(part: DetailPart, theme?: Theme): string {
67
+ const text = sanitizeText(part.text);
68
+ const tone = part.state ? stateTone(part.state) : part.role && part.role !== 'heading' ? detailTones[part.role] : undefined;
69
+ if (!theme || (!tone && part.role !== 'heading')) return text;
70
+ // Reset before whitespace: Pi's native wrapper can emit an extra blank row
71
+ // between long words if an active style is the only content on that row.
72
+ return text.replace(/\S+/g, word => tone ? paint(tone, word, theme) : heading(word, theme));
73
+ }
74
+ /** Structured fields are literal domain data; sanitize before adding trusted theme escapes. */
75
+ export function displayText(value: DisplayText, theme?: Theme, fallbackTone?: ThemeColor): string {
76
+ if (typeof value === 'string') return fallbackTone && value ? paint(fallbackTone, value, theme) : value;
77
+ return value.map(field => {
78
+ const text = sanitizeText(field.text).replace(/[\r\n\t]/g, ' '), tone = field.state ? stateTone(field.state) : field.tone;
79
+ const shown = field.state === 'done' ? theme?.strikethrough(text) ?? text : text;
80
+ return tone || fallbackTone ? paint(tone ?? fallbackTone!, shown, theme) : shown;
81
+ }).join('');
82
+ }
83
+ export function recordStyle(text: DisplayText, state: string | undefined, theme?: Theme): string {
84
+ if (typeof text !== 'string') return displayText(text, theme);
85
+ if (!state) return text;
86
+ const tone = stateTone(state);
87
+ if (!tone) return text;
88
+ if (['todo', 'doing', 'blocked', 'done'].includes(state)) return paint(tone, state === 'done' ? theme?.strikethrough(text) ?? text : text, theme);
89
+ if (state === 'enabled' || state === 'disabled') text = text.replace(state === 'enabled' ? '●' : '○', icon => paint(tone, icon, theme));
90
+ // Only color a declared state at a field boundary, not a matching word in a record's name.
91
+ const literal = state.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
92
+ return text.replace(new RegExp(`(^| · |(?:job_[a-f0-9]{8}|wf_[a-f0-9]{12}) )(${literal})(?= · |$)`), (_match, prefix: string, word: string) => prefix + paint(tone, word, theme));
93
+ }
94
+ const mark = (text: string, on: boolean, theme?: Theme) => on ? heading(text, theme) : paint('muted', text, theme);
95
+
96
+ /** Pressing a control key moves to the next choice and applies it immediately. */
97
+ export function cycle(choice: BrowseChoice, done: (value?: string) => void, step = 1): void {
98
+ const items = choice.items(), index = items.findIndex(item => item.value === choice.selected());
99
+ if (items.length) choice.select(items[(index + step + items.length) % items.length].value, done);
100
+ }
101
+
102
+ /** `<command> ▸ <page>` always leads; the tab bar degrades to bare digits, then disappears, before the page name is cut. */
103
+ export function titleRow(title: string, pages: BrowseChoice | undefined, width: number, theme?: Theme, page?: string): string {
104
+ const head = heading(`${title} ▸ ${pages ? current(pages)?.label ?? pages.selected() : page ?? 'List'}`, theme);
105
+ if (!pages) return truncateToWidth(head, width);
106
+ const items = pages.items();
107
+ for (const full of [true, false]) {
108
+ const tabs = items.map((item, i) => {
109
+ const selected = item.value === pages.selected();
110
+ const tab = `${keyToken(String(i + 1), theme)}${full ? ` ${paint(selected ? 'text' : 'muted', item.label, theme)}` : ''}`;
111
+ return selected ? selectedTab(tab, theme) : tab;
112
+ }).join(full ? ' ' : ' ');
113
+ const line = `${head} ${tabs}`;
114
+ if (visibleWidth(line) <= width) return line;
115
+ }
116
+ return truncateToWidth(head, width);
117
+ }
118
+
119
+ export function controlRows(controls: BrowseControl[], width: number, theme?: Theme): string[] {
120
+ const label = (control: BrowseControl) => `${paint('muted', control.label, theme)} (${keyToken(control.key, theme)}): `;
121
+ const rows = controls.map(control => `${label(control)}${control.items()
122
+ .map(item => mark(cell(item), item.value === control.selected(), theme)).join(' · ')}`);
123
+ if (rows.length && visibleWidth(rows.join(' ')) <= width) return [rows.join(' ')];
124
+ return controls.map((control, i) => {
125
+ if (visibleWidth(rows[i]) <= width) return rows[i];
126
+ // Narrow rows keep only the applied value; its key still reaches the hidden choices.
127
+ const item = current(control);
128
+ return truncateToWidth(`${label(control)}${mark(item ? cell(item) : control.selected(), true, theme)} ›`, width);
129
+ });
130
+ }
131
+
132
+ export function statusLabels(controls: BrowseControl[]): string[] { return controls.map(control => current(control)?.label ?? control.selected()); }
133
+
134
+ /** Existing controls already describe an empty list's escape route; no page-specific key prose. */
135
+ export function emptyRow(page: string, controls: BrowseControl[], query: string, pages?: BrowseChoice, theme?: Theme): string {
136
+ const next = (message: string, key: string, action: string) => `${paint('dim', message, theme)} · ${paint('dim', 'press ', theme)}${keyHint(key, action, theme)}`;
137
+ if (query) return next('No matches', 'Esc', 'to clear filter');
138
+ const filter = controls.find(control => control.items().some(item => item.value === 'all') && control.selected() !== 'all');
139
+ if (filter) {
140
+ const all = filter.items().find(item => item.value === 'all')!;
141
+ return next(`No ${current(filter)?.label.toLowerCase()} ${page.toLowerCase()}`, filter.key, `for ${all.label}${all.description ? ` (${all.description})` : ''}`);
142
+ }
143
+ const control = controls.find(control => control.items().length > 1);
144
+ if (control) {
145
+ const items = control.items(), index = items.findIndex(item => item.value === control.selected());
146
+ return next(`No ${page.toLowerCase()}`, control.key, `for ${items[(index + 1) % items.length].label}`);
147
+ }
148
+ const pageIndex = pages?.items().findIndex(item => item.value !== pages.selected()) ?? -1;
149
+ return pageIndex >= 0 ? next(`No ${page.toLowerCase()}`, String(pageIndex + 1), `for ${pages!.items()[pageIndex].label}`)
150
+ : next(`No ${page.toLowerCase()}`, 'Esc', 'to close');
151
+ }
152
+
153
+ /**
154
+ * Status line: page, filters, matches and the selected record. Below 80 columns the page and
155
+ * selection move to the front. Both name and ID receive space, even for a long workflow ID.
156
+ */
157
+ export function statusRow(width: number, page: string | undefined, filters: string[], selection?: BrowseSelection, theme?: Theme): string {
158
+ const literal = (text: string) => sanitizeText(text).replace(/[\r\n\t]/g, ' ');
159
+ const fit = (max: number) => {
160
+ if (!selection) return '';
161
+ const name = literal(selection.name), id = selection.id && literal(selection.id);
162
+ if (!id) return paint('text', truncateToWidth(name, max), theme);
163
+ // Names explain what is selected; IDs disambiguate it. Neither may consume the entire row.
164
+ const nameRoom = Math.min(visibleWidth(name), Math.max(1, Math.floor((max - 3) / 2)));
165
+ const shownId = truncateToWidth(id, Math.max(0, max - nameRoom - 3));
166
+ return `${paint('text', truncateToWidth(name, max - visibleWidth(shownId) - 3), theme)} ${paint('muted', `(${shownId})`, theme)}`;
167
+ };
168
+ const join = ' · ', filterText = paint('muted', filters.join(join), theme);
169
+ const head = [...page ? [paint('text', page, theme)] : [], ...filters.length ? [filterText] : []].join(paint('muted', join, theme));
170
+ const room = width - visibleWidth(head) - 3;
171
+ if (!selection) return truncateToWidth(head, width);
172
+ if (width >= 80 && room >= 12) return `${head}${paint('muted', join, theme)}${fit(room)}`;
173
+ const prefix = page ? `${paint('text', page, theme)}${paint('muted', join, theme)}` : '';
174
+ return truncateToWidth([prefix + fit(width - visibleWidth(prefix)), ...filters.length ? [filterText] : []].join(paint('muted', join, theme)), width);
175
+ }