pi-suite 0.0.0-stage → 0.3.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.
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 +108 -0
  161. package/src/runtime/responses/payload.ts +78 -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,200 @@
1
+ import { open, type FileHandle } from 'node:fs/promises';
2
+ import { ToolError } from './errors.ts';
3
+
4
+ /**
5
+ * Shared output reading for job logs and agent transcripts. Offsets are always raw source
6
+ * bytes so pages and searches can be resumed exactly; rendering (ANSI removal, CR overwrite)
7
+ * only changes the returned text.
8
+ */
9
+ export type ReadSource = { size: number; read(offset: number, length: number): Promise<Buffer>; close(): Promise<void> };
10
+ export type ReadRequest = { offset?: number; limitBytes?: number; search?: string; context?: number };
11
+ export type ReadPage = {
12
+ text: string; offset: number; nextOffset: number; totalBytes: number; endOfStream: boolean;
13
+ truncated?: { head: [number, number]; keys: [number, number][]; tail: [number, number]; omittedBytes: number; keyLines: number };
14
+ matches?: number;
15
+ };
16
+ export const READ_LIMITS = { defaultBytes: 4096, maxBytes: 65536, maxMatches: 50, defaultContext: 2, maxContext: 20, chunk: 65536 };
17
+ // Lines worth surfacing from an omitted middle section; matched case-insensitively.
18
+ const KEY_LINE = /\b(error|errors|fail(?:ed|ure|s)?|fatal|exception|traceback|panic|denied|not found|warn(?:ing)?|exit code|segmentation fault|assert(?:ion)?)\b/i;
19
+
20
+ export async function fileSource(path: string): Promise<ReadSource> {
21
+ const file: FileHandle = await open(path, 'r');
22
+ const size = (await file.stat()).size;
23
+ return { size, async read(offset, length) {
24
+ const buffer = Buffer.alloc(Math.max(0, Math.min(length, size - offset)));
25
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, offset);
26
+ return buffer.subarray(0, bytesRead);
27
+ }, close: () => file.close() };
28
+ }
29
+ export function textSource(text: string): ReadSource {
30
+ const buffer = Buffer.from(text, 'utf8');
31
+ return { size: buffer.length, read: async (offset, length) => buffer.subarray(offset, offset + length), close: async () => {} };
32
+ }
33
+
34
+ /** Byte length to cut at so a multi-byte UTF-8 character is never split at the end. */
35
+ function utf8End(buffer: Buffer, end: number): number {
36
+ let lead = end - 1;
37
+ while (lead > 0 && (buffer[lead] & 0xc0) === 0x80) lead--;
38
+ const byte = buffer[lead];
39
+ const length = byte >= 0xc2 && byte <= 0xdf ? 2 : byte >= 0xe0 && byte <= 0xef ? 3 : byte >= 0xf0 && byte <= 0xf4 ? 4 : 1;
40
+ return lead + length > end ? lead : end;
41
+ }
42
+ function utf8Start(buffer: Buffer): number {
43
+ let start = 0;
44
+ while (start < Math.min(3, buffer.length) && (buffer[start] & 0xc0) === 0x80) start++;
45
+ return start;
46
+ }
47
+ /** A rendered line can exceed its allocation; clip on UTF-8 boundaries and make that visible. */
48
+ export function boundedText(text: string, budget: number): string {
49
+ if (Buffer.byteLength(text) <= budget) return text;
50
+ // UTF-8 needs at least one byte per UTF-16 code unit. Encoding only this prefix
51
+ // avoids allocating a second full transcript just to return a small preview.
52
+ const bytes = Buffer.from(text.slice(0, budget));
53
+ const marker = '... [truncated]'.slice(0, budget);
54
+ return bytes.subarray(0, utf8End(bytes, budget - marker.length)).toString('utf8') + marker;
55
+ }
56
+ /** Keep the same read mode and caller's limits when the model follows a continuation hint. */
57
+ export function readContinuation(request: ReadRequest, offset: number): ReadRequest {
58
+ return { offset, search: request.search, context: request.context, limitBytes: request.limitBytes };
59
+ }
60
+ function formatBytes(bytes: number): string {
61
+ return bytes < 1024 ? `${bytes} B` : bytes < 1048576 ? `${(bytes / 1024).toFixed(1)} KiB` : `${(bytes / 1048576).toFixed(1)} MiB`;
62
+ }
63
+ /**
64
+ * Search and monitor trigger patterns: `/re/flags`, or a bare pattern matched case-insensitively.
65
+ * Invalid caller input is a tool INVALID_ARGS error.
66
+ */
67
+ export function compileSearch(search: string): RegExp {
68
+ const literal = /^\/(.*)\/([a-z]*)$/s.exec(search);
69
+ try { return literal ? new RegExp(literal[1], literal[2].replace('g', '')) : new RegExp(search, 'i'); }
70
+ catch (error) { throw new ToolError('INVALID_ARGS', `Invalid search pattern: ${error instanceof Error ? error.message : String(error)}. Check the regex and flags.`); }
71
+ }
72
+
73
+ /** Streams complete lines with their starting byte offsets from [from, to). */
74
+ async function* lines(source: ReadSource, from: number, to: number): AsyncGenerator<{ offset: number; bytes: Buffer }> {
75
+ let pending: Buffer[] = [], pendingBytes = 0, pendingAt = from;
76
+ for (let position = from; position < to;) {
77
+ const chunk = await source.read(position, Math.min(READ_LIMITS.chunk, to - position));
78
+ if (!chunk.length) break;
79
+ position += chunk.length;
80
+ let start = 0;
81
+ for (let index = chunk.indexOf(10); index >= 0; index = chunk.indexOf(10, start)) {
82
+ const fragment = chunk.subarray(start, index);
83
+ // Complete JS regexes need the whole logical line. Join once at its end;
84
+ // copying and scanning the accumulated prefix on every chunk is quadratic.
85
+ const bytes = pendingBytes ? Buffer.concat([...pending, fragment], pendingBytes + fragment.length) : fragment;
86
+ pending = []; pendingBytes = 0;
87
+ yield { offset: pendingAt, bytes };
88
+ start = index + 1;
89
+ pendingAt = position - chunk.length + start;
90
+ }
91
+ if (start < chunk.length) { pending.push(chunk.subarray(start)); pendingBytes += chunk.length - start; }
92
+ }
93
+ if (pendingBytes) yield { offset: pendingAt, bytes: pending.length === 1 ? pending[0] : Buffer.concat(pending, pendingBytes) };
94
+ }
95
+
96
+ export async function readBounded(source: ReadSource, request: ReadRequest, render: (raw: string) => string): Promise<ReadPage> {
97
+ const limit = request.limitBytes ?? READ_LIMITS.defaultBytes;
98
+ const size = source.size;
99
+ if (request.search !== undefined) return search(source, request, render, limit);
100
+ if (request.offset !== undefined) {
101
+ const offset = Math.min(request.offset, size);
102
+ const buffer = await source.read(offset, limit + 3);
103
+ // The snapshot may end while a live writer is part-way through a UTF-8 character.
104
+ // Leave those bytes for the next page rather than emitting a replacement character.
105
+ const start = utf8Start(buffer), end = utf8End(buffer, Math.min(limit, buffer.length));
106
+ const nextOffset = offset + Math.max(start, end);
107
+ return { text: render(buffer.subarray(start, Math.max(start, end)).toString('utf8')), offset: offset + start, nextOffset, totalBytes: size, endOfStream: nextOffset >= size };
108
+ }
109
+ if (size <= limit) {
110
+ const buffer = await source.read(0, size);
111
+ return { text: render(buffer.toString('utf8')), offset: 0, nextOffset: size, totalBytes: size, endOfStream: true };
112
+ }
113
+ // Smart default: head 20%, key lines from the omitted middle 30%, tail 50%, aligned to lines.
114
+ const headBuffer = await source.read(0, Math.floor(limit * 0.2));
115
+ const headEnd = headBuffer.lastIndexOf(10) + 1 || utf8End(headBuffer, headBuffer.length);
116
+ const tailBudget = Math.floor(limit * 0.5);
117
+ const tailRaw = await source.read(size - tailBudget, tailBudget);
118
+ const tailCut = tailRaw.indexOf(10) + 1 || utf8Start(tailRaw);
119
+ const tailStart = size - tailBudget + tailCut;
120
+ const keyBudget = limit - headEnd - (size - tailStart);
121
+ // Each key line carries its adjacent lines for context. Keep the earliest blocks within half
122
+ // of the budget and a rolling window of the latest blocks in the rest.
123
+ type Line = { text: string; start: number; end: number };
124
+ type Block = { text: string; bytes: number; range: [number, number] };
125
+ const first: Block[] = [], recent: Block[] = [];
126
+ let keyLines = 0, firstBytes = 0, recentBytes = 0, previous: Line | undefined;
127
+ let pending: { before?: Line; match: Line } | undefined;
128
+ const collect = (before: Line | undefined, match: Line, after?: Line) => {
129
+ const allocation = Math.floor(keyBudget / 2) - 1, contextBudget = Math.floor(allocation / 4);
130
+ const preceding = before ? boundedText(` ${before.text}`, contextBudget) : undefined;
131
+ const following = after ? boundedText(` ${after.text}`, contextBudget) : undefined;
132
+ // The match retains half the block even when both context lines exceed the budget.
133
+ const used = [preceding, following].reduce((bytes, text) => bytes + (text === undefined ? 0 : Buffer.byteLength(text) + 1), 0);
134
+ const text = [preceding, boundedText(`> ${match.text}`, allocation - used), following].filter(text => text !== undefined).join('\n');
135
+ const block: Block = { text, bytes: Buffer.byteLength(text) + 1, range: [before?.start ?? match.start, after?.end ?? match.end] };
136
+ if (!recent.length && firstBytes + block.bytes <= keyBudget / 2) { first.push(block); firstBytes += block.bytes; }
137
+ else {
138
+ recent.push(block); recentBytes += block.bytes;
139
+ while (recent.length > 1 && recentBytes > keyBudget - firstBytes) recentBytes -= recent.shift()!.bytes;
140
+ }
141
+ };
142
+ for await (const line of lines(source, headEnd, tailStart)) {
143
+ const text = render(line.bytes.toString('utf8')), matched = KEY_LINE.test(text);
144
+ // Match against the complete line, then retain only what can reach the page.
145
+ const current = { text: boundedText(text, keyBudget), start: line.offset, end: Math.min(tailStart, line.offset + line.bytes.length + 1) };
146
+ if (pending) collect(pending.before, pending.match, current);
147
+ pending = matched ? { before: previous, match: current } : undefined;
148
+ if (pending) keyLines++;
149
+ previous = current;
150
+ }
151
+ if (pending) collect(pending.before, pending.match);
152
+ const picked = [...first.map(item => item.text), ...(keyLines > first.length + recent.length ? [' …'] : []), ...recent.map(item => item.text)];
153
+ const omitted = tailStart - headEnd;
154
+ const marker = `[… ${formatBytes(omitted)} omitted (bytes ${headEnd}–${tailStart}), ${keyLines} matching lines; use offset or search …]`;
155
+ const text = [render(headBuffer.subarray(0, headEnd).toString('utf8')).replace(/\n$/, ''), marker, ...picked,
156
+ ...(picked.length ? ['[… end of matching lines …]'] : []), render(tailRaw.subarray(tailCut).toString('utf8'))].join('\n');
157
+ return { text, offset: 0, nextOffset: size, totalBytes: size, endOfStream: true,
158
+ truncated: { head: [0, headEnd], keys: [...first, ...recent].map(item => item.range), tail: [tailStart, size], omittedBytes: omitted, keyLines } };
159
+ }
160
+
161
+ /** Line numbers count from the search start offset; matched lines also show their byte offset for resuming. */
162
+ async function search(source: ReadSource, request: ReadRequest, render: (raw: string) => string, limit: number): Promise<ReadPage> {
163
+ const pattern = compileSearch(request.search!);
164
+ const context = Math.min(request.context ?? READ_LIMITS.defaultContext, READ_LIMITS.maxContext);
165
+ const from = Math.min(request.offset ?? 0, source.size);
166
+ const out: string[] = [], before: string[] = [];
167
+ let matches = 0, lineNumber = 0, after = 0, bytes = 0, nextOffset = source.size, lastPrinted = -1;
168
+ const append = (text: string, allocation = limit - bytes) => {
169
+ const separator = Number(out.length > 0);
170
+ const line = boundedText(text, Math.max(0, Math.min(allocation, limit - bytes - separator)));
171
+ out.push(line); bytes += Buffer.byteLength(line) + separator;
172
+ };
173
+ for await (const line of lines(source, from, source.size)) {
174
+ // Count serialized context and prefixes too; resume at the first unprocessed raw line.
175
+ if (out.length && limit - bytes < 32) { nextOffset = line.offset; break; }
176
+ lineNumber++;
177
+ const text = render(line.bytes.toString('utf8'));
178
+ pattern.lastIndex = 0;
179
+ let matched: boolean;
180
+ try { matched = pattern.test(text); }
181
+ catch (error) {
182
+ if (!(error instanceof RangeError)) throw error;
183
+ // V8 can exhaust its regex stack on large Unicode lines. A partial match
184
+ // would be misleading; fail the search and leave raw pagination available.
185
+ throw new ToolError('REGEX_RESOURCE_LIMIT', `JavaScript regex could not evaluate the ${line.bytes.length}-byte line at offset ${line.offset}: ${error.message}; read with offset or use a simpler search pattern`);
186
+ }
187
+ if (matched) {
188
+ if (matches >= READ_LIMITS.maxMatches || bytes >= limit) { nextOffset = line.offset; break; }
189
+ matches++;
190
+ if (lastPrinted >= 0 && lineNumber - before.length > lastPrinted + 1) append('--');
191
+ for (const [index, item] of before.entries()) append(`${lineNumber - before.length + index} ${item}`,
192
+ Math.floor((limit - bytes) / (before.length - index + 1)));
193
+ append(`${lineNumber}@${line.offset}> ${text}`);
194
+ before.length = 0; after = context; lastPrinted = lineNumber;
195
+ } else if (after > 0) { append(`${lineNumber} ${text}`); after--; lastPrinted = lineNumber; }
196
+ else { before.push(boundedText(text, limit)); if (before.length > context) before.shift(); }
197
+ }
198
+ return { text: out.join('\n') || boundedText(`No lines match ${request.search}`, limit), offset: from, nextOffset, totalBytes: source.size,
199
+ endOfStream: nextOffset >= source.size, matches };
200
+ }
@@ -0,0 +1,50 @@
1
+ import { createBashToolDefinition, createPowerShellToolDefinition, type ExtensionAPI, type ToolRenderers } from '@earendil-works/pi-coding-agent';
2
+ import { registerToolRenderers } from './tools.ts';
3
+ import * as tasks from '../tasks/render.ts';
4
+ import * as jobs from '../jobs/render.ts';
5
+ import * as agents from '../agents/render.ts';
6
+ import { STRUCTURED_OUTPUT_TOOL_NAME, structuredOutputRenderers } from '../agents/output/tool.ts';
7
+ import * as goal from '../goal/render.ts';
8
+ import { askRenderers } from '../ask/tool-render.ts';
9
+ import { WORKFLOW_ENTRY_TYPE } from '../agents/workflow/entry.ts';
10
+ import { workflowEntryRenderer, workflowRenderers } from '../agents/workflow/render.ts';
11
+ import { waitRenderers } from './wait-render.ts';
12
+ import { loadConfig } from './config.ts';
13
+ import { notificationRenderer } from './notification-render.ts';
14
+ import { builtinCommandRenderers } from '../ui/rendering/builtin-command.ts';
15
+
16
+ /** Display definitions load with the extension; they neither admit nor execute tools.
17
+ * Children pass their admitted config snapshot (or an owner-supplied provider), not execution cwd.
18
+ */
19
+ export function registerSuiteRenderers(pi: ExtensionAPI, commandHighlight?: boolean | (() => boolean)): void {
20
+ goal.registerGoalMessageRenderers(pi);
21
+ pi.registerMessageRenderer('pi-suite:notification', notificationRenderer);
22
+ pi.registerEntryRenderer(WORKFLOW_ENTRY_TYPE, workflowEntryRenderer);
23
+ // Factory scope has no session cwd. Freeze each context's saved option on first display;
24
+ // /reload creates a fresh registry, including when history is rebuilt before session_start.
25
+ const options = new Map<string, boolean>();
26
+ const enabled = commandHighlight === undefined ? (cwd: string) => {
27
+ if (!options.has(cwd)) options.set(cwd, loadConfig(cwd).ui.highlightBuiltinCommands);
28
+ return options.get(cwd)!;
29
+ } : typeof commandHighlight === 'boolean' ? () => commandHighlight : commandHighlight;
30
+ if (commandHighlight === undefined) pi.on('session_start', (_event, ctx) => {
31
+ // Capture before Settings can save a new value, even if no command tool has been drawn yet.
32
+ enabled(ctx.cwd);
33
+ });
34
+ // The public factories expose native display slots. Only those slots enter the history lookup;
35
+ // their execute functions are neither registered nor called, just as in Transcript's native lookup.
36
+ const slots = ({ renderCall, renderResult, renderShell }: ToolRenderers): ToolRenderers => ({ renderCall, renderResult, renderShell });
37
+ registerToolRenderers(pi, {
38
+ bash: slots(createBashToolDefinition(process.cwd()) as unknown as ToolRenderers),
39
+ powershell: slots(createPowerShellToolDefinition(process.cwd()) as unknown as ToolRenderers),
40
+ task_list: tasks.listRenderers, task_get: tasks.getRenderers, task_edit: tasks.editRenderers,
41
+ job_start: jobs.startRenderers, job_list: jobs.listRenderers, job_get: jobs.getRenderers,
42
+ job_read: jobs.readRenderers, job_write: jobs.writeRenderers, job_stop: jobs.stopRenderers,
43
+ agent_start: agents.startRenderers, agent_list: agents.listRenderers, agent_get: agents.getRenderers,
44
+ agent_read: agents.readRenderers, agent_send: agents.sendRenderers, agent_stop: agents.stopRenderers,
45
+ [STRUCTURED_OUTPUT_TOOL_NAME]: structuredOutputRenderers,
46
+ agent_workflow: workflowRenderers(), ask_user: askRenderers(), wait: waitRenderers,
47
+ goal_complete: goal.completeRenderers, goal_blocked: goal.blockedRenderers, goal_wait: goal.waitRenderers,
48
+ }, { bash: base => builtinCommandRenderers(base, 'bash', enabled),
49
+ powershell: base => builtinCommandRenderers(base, 'powershell', enabled) });
50
+ }
@@ -0,0 +1,108 @@
1
+ import { createHash } from 'node:crypto';
2
+ import type { AgentBeforeSettleEvent, BoundaryResult, ExtensionAPI, ExtensionContext, TurnEndEvent } from '@earendil-works/pi-coding-agent';
3
+ import type { SessionBinding, Binding } from '../binding.ts';
4
+ import { isolateIds, replayIds, replayPayload, resourceMismatch } from './payload.ts';
5
+
6
+ export const RECOVERY_ENTRY = 'pi-suite:responses-isolation';
7
+ type Isolation = { version: 1; scope: string; ids: string[] };
8
+ type Request = { generation: number; binding: Binding; scope: string; leaf: string | null; ids: string[]; signal?: AbortSignal };
9
+ type Failure = { request: Request; entryId: string; error: string };
10
+
11
+ /** Per-session request projection only; retries/backoff and their budgets belong to Pi.
12
+ * The append-only branch record stores IDs and a hashed endpoint scope, never payload/auth.
13
+ */
14
+ export class ResponsesRecovery {
15
+ private isolated = new Map<string, Set<string>>();
16
+ private request?: Request;
17
+ private failure?: Failure;
18
+ private recovering?: { generation: number; scope: string };
19
+ private generation = 0;
20
+ constructor(private binding: SessionBinding, private enabled: boolean) {}
21
+
22
+ reset(ctx?: ExtensionContext): void {
23
+ this.request = undefined; this.failure = undefined; this.recovering = undefined;
24
+ this.isolated.clear(); this.generation++;
25
+ if (!this.enabled || !ctx) return;
26
+ for (const entry of ctx.sessionManager.getBranch()) {
27
+ if (entry.type !== 'custom' || entry.customType !== RECOVERY_ENTRY) continue;
28
+ const data = entry.data as Partial<Isolation> | undefined;
29
+ if (!data || data.version !== 1 || typeof data.scope !== 'string' || !Array.isArray(data.ids) ||
30
+ data.ids.some(id => typeof id !== 'string')) throw new Error('Invalid Responses isolation record');
31
+ const ids = this.isolated.get(data.scope) ?? new Set<string>();
32
+ for (const id of data.ids) ids.add(id);
33
+ this.isolated.set(data.scope, ids);
34
+ }
35
+ }
36
+
37
+ beforeRequest(payload: unknown, ctx: ExtensionContext): unknown {
38
+ // A new final payload invalidates the last attempt, but not the recovery phase:
39
+ // a native 429/5xx retry is still part of the same repair.
40
+ this.request = undefined; this.failure = undefined;
41
+ const active = this.binding.current, model = ctx.model;
42
+ if (!this.enabled || !active || active.ctx.sessionManager !== ctx.sessionManager || model?.api !== 'openai-responses') return;
43
+ const wire = replayPayload(payload, model.id);
44
+ if (!wire) return;
45
+ const scope = createHash('sha256').update(JSON.stringify([model.provider, model.api, model.id, model.baseUrl])).digest('hex');
46
+ if (this.recovering && this.recovering.scope !== scope) this.recovering = undefined;
47
+ const projected = isolateIds(wire, this.isolated.get(scope) ?? new Set());
48
+ this.request = { generation: ++this.generation, binding: active, scope,
49
+ leaf: ctx.sessionManager.getLeafId(), ids: replayIds(projected ?? wire), signal: ctx.signal };
50
+ return projected;
51
+ }
52
+
53
+ turnEnd(event: TurnEndEvent, ctx: ExtensionContext): void {
54
+ const request = this.request;
55
+ this.failure = undefined;
56
+ if (!request || !this.binding.isCurrent(request.binding)) return;
57
+ const message = event.message, model = ctx.model;
58
+ if (message.role !== 'assistant' || message.provider !== model?.provider || message.api !== model.api || message.model !== model.id) return;
59
+ // Correlate the persisted source, not just the most recently observed error string.
60
+ const source = ctx.sessionManager.getEntry(event.messageEntryId);
61
+ if (source?.type !== 'message' || source.message !== message &&
62
+ (source.message.role !== 'assistant' || source.message.timestamp !== message.timestamp)) return;
63
+ const branch = ctx.sessionManager.getBranch(), sourceIndex = branch.findIndex(entry => entry.id === source.id);
64
+ const leafIndex = request.leaf === null ? -1 : branch.findIndex(entry => entry.id === request.leaf);
65
+ if (sourceIndex < 0 || request.leaf !== null && leafIndex < 0 || sourceIndex <= leafIndex ||
66
+ branch.slice(leafIndex + 1, sourceIndex).some(entry => entry.type === 'message' && entry.message.role === 'assistant')) return;
67
+ if (message.stopReason === 'error') {
68
+ if (!message.content.length && message.errorMessage) this.failure = { request, entryId: source.id, error: message.errorMessage };
69
+ } else if (message.stopReason !== 'aborted') this.recovering = undefined;
70
+ }
71
+
72
+ beforeSettle(event: AgentBeforeSettleEvent): BoundaryResult | undefined {
73
+ const failure = this.failure;
74
+ if (!failure || event.outcome !== 'error' || failure.request.signal?.aborted || !this.binding.isCurrent(failure.request.binding) ||
75
+ failure.request.generation !== this.request?.generation || !failure.request.ids.length ||
76
+ !resourceMismatch(failure.error, failure.request.ids)) return;
77
+ // One repair phase may span many native attempts, but never opens a second budget
78
+ // when those attempts finally exhaust. A successful turn permits a later new phase.
79
+ if (this.recovering) return;
80
+ const source = event.context.contextEntries.find(entry => entry.sourceEntry.id === failure.entryId);
81
+ if (!source) return; // Compaction/another projection removed the source from this boundary.
82
+ const visible = source.messages.length;
83
+ if (!visible && event.continue) return; // A preceding extension already owns this failure.
84
+ const { scope, ids, generation } = failure.request;
85
+ const known = this.isolated.get(scope) ?? new Set<string>();
86
+ const fresh = ids.filter(id => !known.has(id));
87
+ if (!fresh.length) return;
88
+ this.recovering = { generation, scope };
89
+ for (const id of fresh) known.add(id);
90
+ this.isolated.set(scope, known);
91
+ return { continue: true, entries: [...event.entries,
92
+ { type: 'custom', customType: RECOVERY_ENTRY, data: { version: 1, scope, ids: fresh } satisfies Isolation },
93
+ ...(visible ? [{ type: 'context_edit' as const, targetId: failure.entryId, replacement: null }] : []),
94
+ ] };
95
+ }
96
+
97
+ settled(): void { this.request = undefined; this.failure = undefined; this.recovering = undefined; }
98
+ }
99
+
100
+ /** The caller owns ordering with Goal and notifications at the actionable/final boundaries. */
101
+ export function registerResponsesRecovery(pi: ExtensionAPI, binding: SessionBinding, enabled: boolean): ResponsesRecovery {
102
+ const recovery = new ResponsesRecovery(binding, enabled);
103
+ if (enabled) {
104
+ pi.on('before_provider_request', (event, ctx) => recovery.beforeRequest(event.payload, ctx));
105
+ pi.on('turn_end', (event, ctx) => recovery.turnEnd(event, ctx));
106
+ }
107
+ return recovery;
108
+ }
@@ -0,0 +1,78 @@
1
+ type Item = Record<string, unknown>;
2
+ export type ReplayPayload = Item & { input: Item[] };
3
+ const object = (value: unknown): value is Item => value !== null && typeof value === 'object' && !Array.isArray(value);
4
+ const upstreamId = (item: Item): string | undefined => typeof item.id === 'string' &&
5
+ /^(?:rs|msg|fc|ctc)_/.test(item.id) && !item.id.startsWith('msg_pi_') ? item.id : undefined;
6
+
7
+ /** Validate only at the wire boundary: deleting an ID is safe only for self-contained items.
8
+ * Pi 1.5.0 serializes grammar calls as custom_tool_call/input with a separate call_id.
9
+ */
10
+ export function replayPayload(value: unknown, model: string): ReplayPayload | undefined {
11
+ if (!object(value) || value.model !== model || value.store === true ||
12
+ value.previous_response_id !== undefined || !Array.isArray(value.input)) return;
13
+ for (const item of value.input) {
14
+ if (!object(item)) return;
15
+ switch (item.type) {
16
+ case undefined: // SDK's input messages omit type.
17
+ case 'message':
18
+ if (!['user', 'assistant', 'system', 'developer'].includes(String(item.role)) ||
19
+ !(typeof item.content === 'string' || Array.isArray(item.content))) return;
20
+ break;
21
+ case 'reasoning':
22
+ if (typeof item.encrypted_content !== 'string' || !item.encrypted_content) return;
23
+ break;
24
+ case 'function_call':
25
+ case 'custom_tool_call':
26
+ if (typeof item.call_id !== 'string' || typeof item.name !== 'string' ||
27
+ typeof item[item.type === 'function_call' ? 'arguments' : 'input'] !== 'string') return;
28
+ break;
29
+ case 'function_call_output':
30
+ case 'custom_tool_call_output':
31
+ if (typeof item.call_id !== 'string' || !('output' in item)) return;
32
+ break;
33
+ // These are SDK-generated inline declarations/configuration, not resource references.
34
+ case 'additional_tools': case 'configuration_update': case 'tool_search_call': case 'tool_search_output':
35
+ if (item.id !== undefined) return;
36
+ break;
37
+ default: return; // Includes item_reference, compaction and server-side tool state.
38
+ }
39
+ if (item.id !== undefined && !upstreamId(item) && !(typeof item.id === 'string' && item.id.startsWith('msg_pi_'))) return;
40
+ }
41
+ return value as ReplayPayload;
42
+ }
43
+
44
+ export function replayIds(payload: ReplayPayload): string[] {
45
+ return payload.input.flatMap(item => {
46
+ if (!['reasoning', 'message', 'function_call', 'custom_tool_call'].includes(String(item.type))) return [];
47
+ const id = upstreamId(item); return id ? [id] : [];
48
+ });
49
+ }
50
+
51
+ /** Copy only the changed path. Body, cipher, phase, arguments and call_id retain identity. */
52
+ export function isolateIds(payload: ReplayPayload, ids: ReadonlySet<string>): ReplayPayload | undefined {
53
+ let changed = false;
54
+ const input = payload.input.map(item => {
55
+ const id = upstreamId(item);
56
+ if (!id || !ids.has(id)) return item;
57
+ changed = true;
58
+ const { id: _id, ...replay } = item;
59
+ return replay;
60
+ });
61
+ return changed ? { ...payload, input } : undefined;
62
+ }
63
+
64
+ /** SDK errors are normalized even when an HTTP status callback is unavailable.
65
+ * Require a specific ownership/dependency failure, not a generic HTTP 400 or crypto error.
66
+ */
67
+ export function resourceMismatch(error: string, ids: readonly string[]): boolean {
68
+ const text = error.toLowerCase();
69
+ if (/\b(?:401|403|429|5\d\d)\b|rate.?limit|quota|billing|context.{0,20}(?:length|window)|maximum context/.test(text)) return false;
70
+ const namedItem = ids.some(id => error.includes(id));
71
+ const resource = /(?:different|another|across|cross)[ -](?:openai[ -])?(?:resource|organization|project)|(?:resource|organization|project).{0,50}(?:mismatch|does not match|not belong)/.test(text);
72
+ // Gateways may omit the item ID and qualify/redact the resource name. Recognize
73
+ // the explicit creation-origin sentence, not arbitrary words between "different" and "resource".
74
+ const createdElsewhere = /\bitem was created (?:under|in) (?:a different|another) [^.!?\r\n]{0,80}\b(?:resource|organization|project)\b/.test(text);
75
+ const ownership = namedItem && /not found|does not exist|belongs to|was created in|provided without.{0,80}required|not owned by/.test(text);
76
+ const cipher = namedItem && /encrypted.{0,40}(?:cannot|could not|failed|invalid|verif|decrypt)|(?:decrypt|verif).{0,40}(?:encrypted|reasoning)/.test(text);
77
+ return resource || createdElsewhere || ownership || cipher;
78
+ }
@@ -0,0 +1,24 @@
1
+ import type { ExtensionAPI, ExtensionCommandContext } from '@earendil-works/pi-coding-agent';
2
+ import type { SuiteConfig } from '../config.ts';
3
+ import type { Dock } from '../../ui/dock.ts';
4
+ import type { Notifications } from '../notifications.ts';
5
+
6
+ /** Compaction can finish without agent_settled; request native shutdown after cancellation. */
7
+ export async function quit(ctx: ExtensionCommandContext): Promise<void> {
8
+ if (!ctx.isIdle()) { ctx.abort(); await ctx.waitForIdle(); }
9
+ ctx.shutdown();
10
+ }
11
+
12
+ export function registerSuiteCommand(pi: ExtensionAPI, dock: Dock, notices: Notifications, config: () => SuiteConfig,
13
+ types?: (ctx: ExtensionCommandContext) => Promise<void>): void {
14
+ // Types can refresh saved config without re-registering modules or commands.
15
+ const active = config();
16
+ if (active.commands.exit) pi.registerCommand('exit', { description: 'Quit Pi', handler: async (_args, ctx) => quit(ctx) });
17
+ pi.registerCommand('suite', { description: 'Configure Pi Suite settings', handler: async (_args, ctx) => {
18
+ const release = notices.hold();
19
+ try {
20
+ const { showSuiteSettings } = await import('./view.ts');
21
+ await showSuiteSettings(ctx, dock, () => active, types ? () => types(ctx) : undefined);
22
+ } finally { release(); }
23
+ } });
24
+ }
@@ -0,0 +1,84 @@
1
+ import { getSettingsListTheme, type ExtensionCommandContext } from '@earendil-works/pi-coding-agent';
2
+ import { SettingsList, truncateToWidth } from '@earendil-works/pi-tui';
3
+ import type { TSchema } from 'typebox';
4
+ import { configSchema, defaults, loadConfig, readConfig, type SuiteConfig } from '../config.ts';
5
+ import { configField, configPaths, writeConfigFields, type ConfigLayer } from '../config-fields.ts';
6
+ import { selectValue } from '../../ui/select.ts';
7
+ import type { Dock } from '../../ui/dock.ts';
8
+ import { commandFrame } from '../../ui/frame.ts';
9
+
10
+ const describe = (value: unknown): string => value === undefined ? 'inherit' : JSON.stringify(value);
11
+ type FieldSchema = TSchema & { type?: string; enum?: string[]; description?: string };
12
+ type Field = { path: string[]; schema: FieldSchema };
13
+ const fields: Field[] = Object.entries(configSchema.properties).flatMap(([section, schema]) =>
14
+ Object.entries(schema.properties as Record<string, FieldSchema>).map(([field, schema]) => ({ path: [section, field], schema })));
15
+
16
+ async function editValue(ctx: ExtensionCommandContext, field: Field, current: unknown): Promise<{ value: unknown } | undefined> {
17
+ const title = field.path.join('.');
18
+ if (field.schema.type === 'boolean' || Array.isArray(field.schema.enum)) {
19
+ const values = field.schema.type === 'boolean' ? ['true', 'false'] : field.schema.enum as string[];
20
+ const choice = await selectValue(ctx, title, values.map(value => ({ value, label: value })), String(current));
21
+ return choice === undefined ? undefined : { value: field.schema.type === 'boolean' ? choice === 'true' : choice };
22
+ }
23
+ if (field.schema.type === 'string' || field.schema.type === 'integer') {
24
+ const choice = await ctx.ui.input(title, current === undefined ? '' : String(current));
25
+ if (field.schema.type === 'integer' && choice !== undefined && !choice.trim()) throw new Error(`Enter an integer for ${title}.`);
26
+ return choice === undefined ? undefined : { value: field.schema.type === 'integer' ? Number(choice) : choice };
27
+ }
28
+ const text = await ctx.ui.editor(`${title} · JSON`, JSON.stringify(current ?? (field.schema.type === 'object' ? {} : []), null, 2));
29
+ return text === undefined ? undefined : { value: JSON.parse(text) as unknown };
30
+ }
31
+
32
+ export async function showSuiteSettings(ctx: ExtensionCommandContext, dock: Dock, config: () => SuiteConfig,
33
+ types?: () => Promise<void>): Promise<void> {
34
+ if (ctx.mode !== 'tui') {
35
+ const saved = loadConfig(ctx.cwd);
36
+ ctx.ui.notify(JSON.stringify(saved, null, 2));
37
+ return;
38
+ }
39
+ let initial: string | undefined;
40
+ for (;;) {
41
+ const saved = loadConfig(ctx.cwd), paths = configPaths(ctx.cwd);
42
+ const layers = { user: readConfig(paths.user), project: readConfig(paths.project) };
43
+ const effective = (field: Field) => configField(saved, field.path);
44
+ const items = fields.map(field => {
45
+ const source = configField(layers.project, field.path) !== undefined ? 'project'
46
+ : configField(layers.user, field.path) !== undefined ? 'user' : 'default';
47
+ const active = configField(config(), field.path);
48
+ return { id: field.path.join('.'), label: field.path.join(' · '), currentValue: describe(effective(field)), values: ['Edit…'],
49
+ description: `${field.schema.description ? `${field.schema.description}\n` : ''}Source: ${source}\nDefault: ${describe(configField(defaults, field.path))}\nUser: ${describe(configField(layers.user, field.path))}\nProject: ${describe(configField(layers.project, field.path))}\nEffective: ${describe(effective(field))}${field.path[0] === 'modules' || field.path[0] === 'commands' ? `\nActive: ${describe(active)}` : ''}` };
50
+ });
51
+ dock.setDetail(true);
52
+ let selected: string | undefined;
53
+ try {
54
+ selected = await ctx.ui.custom<string | undefined>((tui, theme, _keys, done) => {
55
+ const list = new SettingsList(items, Math.max(1, Math.floor(tui.terminal.rows * 0.7) - 7), getSettingsListTheme(), id => done(id), () => done(undefined), { enableSearch: true });
56
+ if (initial) list.selectItem(initial);
57
+ let listRows = 0;
58
+ return { render: width => {
59
+ const content = list.render(width); listRows = content.length;
60
+ return commandFrame(width, [truncateToWidth('Pi Suite · Settings', width), ...content], theme);
61
+ }, invalidate: () => list.invalidate(), handleInput: data => { list.handleInput(data); tui.requestRender(); },
62
+ handleMouse: event => event.y >= 2 && event.y < listRows + 2 ? list.handleMouse({ ...event, y: event.y - 2 }) : undefined };
63
+ });
64
+ } finally { dock.setDetail(false); }
65
+ if (selected === undefined) return;
66
+ initial = selected;
67
+ const field = fields.find(field => field.path.join('.') === selected)!;
68
+ const actions = [{ value: 'edit:user', label: 'Edit user' }, { value: 'edit:project', label: 'Edit project' },
69
+ { value: 'clear:user', label: 'Clear user override' }, { value: 'clear:project', label: 'Clear project override' },
70
+ ...selected === 'agents.types' && types ? [{ value: 'types', label: 'Agent types' }] : []];
71
+ const source = configField(layers.project, field.path) === undefined ? 'user' : 'project';
72
+ const action = await selectValue(ctx, `${selected} · saved ${describe(effective(field))}`, actions, `edit:${source}`);
73
+ if (action === undefined) continue;
74
+ if (action === 'types') { await types!(); continue; }
75
+ const [operation, layer] = action.split(':') as ['edit' | 'clear', ConfigLayer];
76
+ try {
77
+ const change = operation === 'clear' ? { value: undefined } : await editValue(ctx, field, configField(layers[layer], field.path) ?? effective(field));
78
+ if (!change) continue;
79
+ await writeConfigFields(ctx.cwd, [{ ...change, path: field.path, layer }]);
80
+ const value = configField(loadConfig(ctx.cwd), field.path);
81
+ ctx.ui.notify(`${selected} saved to ${paths[layer]} · effective ${describe(value)} · /reload to apply`);
82
+ } catch (error) { ctx.ui.notify(error instanceof Error ? error.message : String(error), 'error'); }
83
+ }
84
+ }