proper-base 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,561 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ type Component,
4
+ stripTerminalSequences,
5
+ Text,
6
+ type TUI,
7
+ type TuiInputListener,
8
+ truncateToWidth,
9
+ visibleWidth,
10
+ } from "@earendil-works/pi-tui";
11
+
12
+ const INSTALLED = Symbol.for("pi-proper-base.transcript-cleanup");
13
+ const PROCESS_LINK_PREFIX = "pi-proper-base://process/";
14
+ const SGR_MOUSE_TAIL = /^\[<(\d+);(\d+);(\d+)([Mm])$/;
15
+ const LEFT_BUTTON = "0";
16
+
17
+ type Keybindings = {
18
+ getKeys(action: "app.tools.expand"): readonly string[];
19
+ };
20
+ type ComponentContainer = Component & { children: Component[] };
21
+ type AssistantMessage = {
22
+ content: Array<{ type: string; text?: string; thinking?: string }>;
23
+ stopReason?: string;
24
+ errorMessage?: string;
25
+ timestamp?: number;
26
+ };
27
+ type AssistantComponent = Component & {
28
+ lastMessage?: AssistantMessage;
29
+ updateContent?(message: AssistantMessage, isStreaming?: boolean): void;
30
+ };
31
+ type InstalledContainer = ComponentContainer & {
32
+ [INSTALLED]?: TranscriptCleanupController;
33
+ };
34
+ type State = {
35
+ ctx: ExtensionContext;
36
+ tui: TUI;
37
+ keybindings: Keybindings;
38
+ activeStart: number | undefined;
39
+ completed: Set<Component>;
40
+ owned: Set<Component>;
41
+ expanded: Map<object, boolean>;
42
+ groups: Map<string, object>;
43
+ ids: WeakMap<object, string>;
44
+ nextId: number;
45
+ globalExpanded: boolean;
46
+ };
47
+ type DetailKind = "tool" | "error";
48
+ type Detail = {
49
+ owner: object;
50
+ kind: DetailKind;
51
+ label: string;
52
+ component: Component;
53
+ };
54
+ type ToolComponent = Component & {
55
+ toolName?: string;
56
+ args?: unknown;
57
+ result?: { isError?: boolean };
58
+ setExpanded?(expanded: boolean): void;
59
+ };
60
+ type MouseTui = TUI & {
61
+ inputListeners?: Set<TuiInputListener>;
62
+ previousLines?: string[];
63
+ previousScreen?: string[];
64
+ };
65
+
66
+ export type TranscriptCleanupController = {
67
+ start(): void;
68
+ completeAssistant(message: object): void;
69
+ completeTool(toolCallId: string): void;
70
+ settle(): void;
71
+ update(ctx: ExtensionContext, tui: TUI, keybindings: Keybindings): void;
72
+ uninstall(): void;
73
+ };
74
+
75
+ export function installTranscriptCleanup(
76
+ tui: TUI,
77
+ ctx: ExtensionContext,
78
+ keybindings: Keybindings,
79
+ ): TranscriptCleanupController | undefined {
80
+ const chat = findChatContainer(tui) as InstalledContainer | undefined;
81
+ if (!chat) return undefined;
82
+ if (chat[INSTALLED]) {
83
+ chat[INSTALLED].update(ctx, tui, keybindings);
84
+ return chat[INSTALLED];
85
+ }
86
+
87
+ let state: State = {
88
+ ctx,
89
+ tui,
90
+ keybindings,
91
+ activeStart: ctx.isIdle() ? undefined : chat.children.length,
92
+ completed: new Set(),
93
+ owned: new Set(chat.children),
94
+ expanded: new Map(),
95
+ groups: new Map(),
96
+ ids: new WeakMap(),
97
+ nextId: 0,
98
+ globalExpanded: ctx.ui.getToolsExpanded(),
99
+ };
100
+ const render = chat.render;
101
+ const listener: TuiInputListener = (data) => handleClick(data, state);
102
+ const unsubscribe = tui.addInputListener(listener);
103
+ prioritize(tui, listener);
104
+ const controller: TranscriptCleanupController = {
105
+ start() {
106
+ if (state.activeStart === undefined) {
107
+ state = {
108
+ ...state,
109
+ activeStart: chat.children.length,
110
+ completed: new Set(),
111
+ };
112
+ }
113
+ },
114
+ completeAssistant(message) {
115
+ const completed = message as AssistantMessage;
116
+ const assistant = chat.children.find((child) => {
117
+ if (componentName(child) !== "AssistantMessageComponent") return false;
118
+ const current = (child as AssistantComponent).lastMessage;
119
+ return (
120
+ current === message ||
121
+ (completed.timestamp !== undefined &&
122
+ current?.timestamp === completed.timestamp)
123
+ );
124
+ });
125
+ if (assistant) {
126
+ state.completed.add(assistant);
127
+ state.owned.add(assistant);
128
+ }
129
+ },
130
+ completeTool(toolCallId) {
131
+ const tool = chat.children.find(
132
+ (child) =>
133
+ componentName(child) === "ToolExecutionComponent" &&
134
+ (child as ToolComponent & { toolCallId?: string }).toolCallId ===
135
+ toolCallId,
136
+ );
137
+ if (tool) {
138
+ state.completed.add(tool);
139
+ state.owned.add(tool);
140
+ }
141
+ },
142
+ settle() {
143
+ const owned = new Set(state.owned);
144
+ for (const child of chat.children.slice(
145
+ state.activeStart ?? chat.children.length,
146
+ )) {
147
+ owned.add(child);
148
+ }
149
+ state = {
150
+ ...state,
151
+ activeStart: undefined,
152
+ completed: new Set(),
153
+ owned,
154
+ };
155
+ state.tui.requestRender();
156
+ },
157
+ update(nextCtx, nextTui, nextKeybindings) {
158
+ state = {
159
+ ...state,
160
+ ctx: nextCtx,
161
+ tui: nextTui,
162
+ keybindings: nextKeybindings,
163
+ };
164
+ },
165
+ uninstall() {
166
+ if (chat[INSTALLED] !== controller) return;
167
+ unsubscribe();
168
+ chat.render = render;
169
+ delete chat[INSTALLED];
170
+ },
171
+ };
172
+ chat.render = (width: number) => {
173
+ const globalExpanded = state.ctx.ui.getToolsExpanded();
174
+ if (globalExpanded !== state.globalExpanded) {
175
+ state = { ...state, globalExpanded, expanded: new Map() };
176
+ }
177
+ state.groups.clear();
178
+ if (state.activeStart === undefined && state.ctx.isIdle()) {
179
+ return renderCollapsed(chat.children, width, state);
180
+ }
181
+ const start = state.activeStart ?? chat.children.length;
182
+ return [
183
+ ...renderCollapsed(chat.children.slice(0, start), width, state),
184
+ ...renderActive(chat.children.slice(start), width, state),
185
+ ];
186
+ };
187
+ chat[INSTALLED] = controller;
188
+ return controller;
189
+ }
190
+
191
+ function renderActive(
192
+ children: Component[],
193
+ width: number,
194
+ state: State,
195
+ ): string[] {
196
+ const output: string[][] = Array.from({ length: children.length });
197
+ let hasTextBelow = false;
198
+ for (let index = children.length - 1; index >= 0; index--) {
199
+ const child = children[index];
200
+ if (!child) continue;
201
+ const native = child.render(width);
202
+ output[index] =
203
+ state.completed.has(child) && hasTextBelow
204
+ ? renderGroup([child], width, state)
205
+ : native;
206
+ if (hasSectionText(native)) hasTextBelow = true;
207
+ }
208
+ return output.flat();
209
+ }
210
+
211
+ function renderCollapsed(
212
+ children: Component[],
213
+ width: number,
214
+ state: State,
215
+ ): string[] {
216
+ const lines: string[] = [];
217
+ let group: Component[] = [];
218
+ const flush = () => {
219
+ if (!group.length) return;
220
+ lines.push(...renderGroup(group, width, state));
221
+ group = [];
222
+ };
223
+
224
+ for (let index = 0; index < children.length; index++) {
225
+ const child = children[index];
226
+ if (!child) continue;
227
+ if (
228
+ componentName(child) === "Spacer" &&
229
+ isUserBoundary(children[index + 1])
230
+ ) {
231
+ flush();
232
+ lines.push(...child.render(width));
233
+ continue;
234
+ }
235
+ if (isUserBoundary(child)) {
236
+ flush();
237
+ group = [child];
238
+ } else if (
239
+ group.length ||
240
+ componentName(child) === "AssistantMessageComponent"
241
+ ) {
242
+ group.push(child);
243
+ } else {
244
+ lines.push(...child.render(width));
245
+ }
246
+ }
247
+ flush();
248
+ return lines;
249
+ }
250
+
251
+ function renderGroup(
252
+ group: Component[],
253
+ width: number,
254
+ state: State,
255
+ ): string[] {
256
+ const lines: string[] = [];
257
+
258
+ for (const child of group) {
259
+ const name = componentName(child);
260
+ if (isUserBoundary(child)) {
261
+ lines.push(...child.render(width));
262
+ continue;
263
+ }
264
+ if (name === "Spacer") {
265
+ if (!state.owned.has(child)) lines.push(...child.render(width));
266
+ continue;
267
+ }
268
+ if (name === "AssistantMessageComponent") {
269
+ const assistant = child as AssistantComponent;
270
+ const message = assistant.lastMessage;
271
+ if (!message || !assistant.updateContent) {
272
+ lines.push(...child.render(width));
273
+ continue;
274
+ }
275
+ const hasToolCall = message.content.some(
276
+ (part) => part.type === "toolCall",
277
+ );
278
+ message.content.forEach((part) => {
279
+ if (part.type === "thinking" && part.thinking?.trim()) {
280
+ lines.push(
281
+ ...renderAssistantContent(assistant, message, [part], width),
282
+ );
283
+ }
284
+ if (hasToolCall && part.type === "text" && part.text?.trim()) {
285
+ lines.push(
286
+ ...withVerticalSpacing(
287
+ renderAssistantContent(assistant, message, [part], width),
288
+ ),
289
+ );
290
+ }
291
+ });
292
+ if (["aborted", "error", "length"].includes(message.stopReason ?? "")) {
293
+ const error =
294
+ message.errorMessage ??
295
+ (message.stopReason === "length"
296
+ ? "Response was truncated before completion."
297
+ : "Operation aborted");
298
+ lines.push(
299
+ ...renderDetail(
300
+ {
301
+ owner: child,
302
+ kind: "error",
303
+ label: `error · ${oneLine(error)}`,
304
+ component: new Text(state.ctx.ui.theme.fg("error", error), 1, 0),
305
+ },
306
+ width,
307
+ state,
308
+ ),
309
+ );
310
+ }
311
+ if (!hasToolCall) {
312
+ const direct = message.content.filter(
313
+ (part) => part.type === "text" && part.text?.trim(),
314
+ );
315
+ if (direct.length) {
316
+ lines.push(
317
+ ...renderAssistantContent(assistant, message, direct, width),
318
+ );
319
+ }
320
+ }
321
+ continue;
322
+ }
323
+ if (name === "ToolExecutionComponent") {
324
+ const tool = child as ToolComponent;
325
+ const error = tool.result?.isError === true;
326
+ lines.push(
327
+ ...renderDetail(
328
+ {
329
+ owner: child,
330
+ kind: error ? "error" : "tool",
331
+ label: describeTool(tool, error),
332
+ component: child,
333
+ },
334
+ width,
335
+ state,
336
+ ),
337
+ );
338
+ continue;
339
+ }
340
+ if (!state.owned.has(child)) {
341
+ lines.push(...child.render(width));
342
+ continue;
343
+ }
344
+ lines.push(...withVerticalSpacing(child.render(width)));
345
+ }
346
+ return lines;
347
+ }
348
+
349
+ function renderAssistantContent(
350
+ assistant: AssistantComponent,
351
+ message: AssistantMessage,
352
+ content: AssistantMessage["content"],
353
+ width: number,
354
+ ): string[] {
355
+ if (!assistant.updateContent) return assistant.render(width);
356
+ const { errorMessage: _errorMessage, ...rest } = message;
357
+ assistant.updateContent({ ...rest, content, stopReason: "stop" }, false);
358
+ try {
359
+ return assistant.render(width);
360
+ } finally {
361
+ assistant.updateContent(message, false);
362
+ }
363
+ }
364
+
365
+ function withVerticalSpacing(lines: string[]): string[] {
366
+ return lines.length ? ["", ...lines, ""] : [];
367
+ }
368
+
369
+ function hasSectionText(lines: string[]): boolean {
370
+ return lines.some((line) => {
371
+ const text = stripTerminalSequences(line).trim();
372
+ return (
373
+ text.length > 0 &&
374
+ !/(?:^|\s)Working(?:\.\.\.|…)(?:\s+\([^)]*\))?$/.test(text)
375
+ );
376
+ });
377
+ }
378
+
379
+ function renderDetail(detail: Detail, width: number, state: State): string[] {
380
+ let id = state.ids.get(detail.owner);
381
+ if (!id) {
382
+ id = String(++state.nextId);
383
+ state.ids.set(detail.owner, id);
384
+ }
385
+ state.groups.set(id, detail.owner);
386
+ const expanded = state.expanded.get(detail.owner) ?? state.globalExpanded;
387
+ const keys = state.keybindings.getKeys("app.tools.expand").join("/");
388
+ const action = expanded ? "collapse" : "expand";
389
+ const hint = keys
390
+ ? ` (click or ${keys} to ${action})`
391
+ : ` (click to ${action})`;
392
+ const label = `${expanded ? "▾" : "▸"} ${detail.label}${hint}`;
393
+ const styled = state.ctx.ui.theme.fg(detailColor(detail.kind), label);
394
+ const header = truncateToWidth(
395
+ `\x1b]8;;${PROCESS_LINK_PREFIX}${id}\x07${styled}\x1b]8;;\x07`,
396
+ width,
397
+ "",
398
+ );
399
+ const lines = [
400
+ `${header}${" ".repeat(Math.max(0, width - visibleWidth(header)))}`,
401
+ ];
402
+ const expandable = detail.component as ToolComponent;
403
+ expandable.setExpanded?.(expanded);
404
+ if (expanded) {
405
+ lines.push(...detail.component.render(width));
406
+ const button = `\x1b[7m ${state.ctx.ui.theme.fg(detailColor(detail.kind), "collapse")} \x1b[27m`;
407
+ const linked = `\x1b]8;;${PROCESS_LINK_PREFIX}${id}\x07${button}\x1b]8;;\x07`;
408
+ const rendered = truncateToWidth(linked, width, "");
409
+ lines.push(
410
+ `${rendered}${" ".repeat(Math.max(0, width - visibleWidth(rendered)))}`,
411
+ );
412
+ }
413
+ return lines;
414
+ }
415
+
416
+ function detailColor(
417
+ kind: DetailKind,
418
+ ): Parameters<ExtensionContext["ui"]["theme"]["fg"]>[0] {
419
+ switch (kind) {
420
+ case "tool":
421
+ return "mdLink";
422
+ case "error":
423
+ return "error";
424
+ }
425
+ }
426
+
427
+ function describeTool(tool: ToolComponent, error: boolean): string {
428
+ const name = tool.toolName ?? "tool";
429
+ const args = asRecord(tool.args);
430
+ const value = ["path", "command", "pattern", "query", "task", "url", "action"]
431
+ .map((key) => args?.[key])
432
+ .find((candidate): candidate is string => typeof candidate === "string");
433
+ const target = value ? ` · ${oneLine(value)}` : "";
434
+ return `${error ? "error" : "tool"} · ${name}${target}`;
435
+ }
436
+
437
+ function oneLine(text: string): string {
438
+ return stripTerminalSequences(text).replace(/\s+/g, " ").trim().slice(0, 120);
439
+ }
440
+
441
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
442
+ return typeof value === "object" && value !== null
443
+ ? (value as Record<string, unknown>)
444
+ : undefined;
445
+ }
446
+
447
+ function handleClick(
448
+ data: string,
449
+ state: State,
450
+ ): { consume: true } | undefined {
451
+ if (!data.startsWith("\x1b")) return undefined;
452
+ const match = SGR_MOUSE_TAIL.exec(data.slice(1));
453
+ if (!match || match[1] !== LEFT_BUTTON) return undefined;
454
+ const column = Number.parseInt(match[2] ?? "", 10) - 1;
455
+ const row = Number.parseInt(match[3] ?? "", 10) - 1;
456
+ const line = screenLines(state.tui)[row];
457
+ if (!line) return undefined;
458
+ const link = linkAtColumn(line, column);
459
+ if (!link?.startsWith(PROCESS_LINK_PREFIX)) return undefined;
460
+ const owner = state.groups.get(link.slice(PROCESS_LINK_PREFIX.length));
461
+ if (!owner) return undefined;
462
+ if (match[4] === "M") {
463
+ state.expanded.set(
464
+ owner,
465
+ !(state.expanded.get(owner) ?? state.globalExpanded),
466
+ );
467
+ state.tui.requestRender();
468
+ }
469
+ return { consume: true };
470
+ }
471
+
472
+ function screenLines(tui: TUI): string[] {
473
+ const host = tui as MouseTui;
474
+ return host.previousScreen ?? host.previousLines ?? [];
475
+ }
476
+
477
+ function linkAtColumn(line: string, column: number): string | undefined {
478
+ let active: string | undefined;
479
+ let visible = 0;
480
+ for (let index = 0; index < line.length; ) {
481
+ if (line.startsWith("\x1b]8;;", index)) {
482
+ const end = line.indexOf("\x07", index + 5);
483
+ if (end < 0) break;
484
+ active = line.slice(index + 5, end) || undefined;
485
+ index = end + 1;
486
+ continue;
487
+ }
488
+ if (line[index] === "\x1b") {
489
+ const end = line.indexOf("m", index + 1);
490
+ if (end < 0) break;
491
+ index = end + 1;
492
+ continue;
493
+ }
494
+ const character = line[index] ?? "";
495
+ const width = visibleWidth(character);
496
+ if (column >= visible && column < visible + width) return active;
497
+ visible += width;
498
+ index += character.length;
499
+ }
500
+ return undefined;
501
+ }
502
+
503
+ function prioritize(tui: TUI, listener: TuiInputListener): void {
504
+ const listeners = (tui as MouseTui).inputListeners;
505
+ if (!listeners?.has(listener)) return;
506
+ const rest = [...listeners].filter((entry) => entry !== listener);
507
+ listeners.clear();
508
+ listeners.add(listener);
509
+ for (const entry of rest) listeners.add(entry);
510
+ }
511
+
512
+ function findChatContainer(tui: TUI): ComponentContainer | undefined {
513
+ for (const root of roots(tui)) {
514
+ const document = find(root, (component) => {
515
+ const children = childrenOf(component);
516
+ return (
517
+ children.length >= 3 &&
518
+ children
519
+ .slice(0, 3)
520
+ .every((child) => componentName(child) === "Container")
521
+ );
522
+ });
523
+ const chat = document ? childrenOf(document)[2] : undefined;
524
+ if (chat) return chat as ComponentContainer;
525
+ }
526
+ return undefined;
527
+ }
528
+
529
+ function find(
530
+ root: Component,
531
+ matches: (component: Component) => boolean,
532
+ ): Component | undefined {
533
+ if (matches(root)) return root;
534
+ for (const child of childrenOf(root)) {
535
+ const found = find(child, matches);
536
+ if (found) return found;
537
+ }
538
+ return undefined;
539
+ }
540
+
541
+ function roots(tui: TUI): Component[] {
542
+ const layoutRoot = (tui as TUI & { layoutRoot?: Component }).layoutRoot;
543
+ return layoutRoot ? [layoutRoot] : tui.children;
544
+ }
545
+
546
+ function childrenOf(component: Component): Component[] {
547
+ return (component as Partial<ComponentContainer>).children ?? [];
548
+ }
549
+
550
+ function componentName(component: Component): string | undefined {
551
+ return (component as { constructor?: { name?: string } }).constructor?.name;
552
+ }
553
+
554
+ function isUserBoundary(component: Component | undefined): boolean {
555
+ if (!component) return false;
556
+ const name = componentName(component);
557
+ return (
558
+ name === "UserMessageComponent" ||
559
+ name === "SkillInvocationMessageComponent"
560
+ );
561
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * CLIProxyAPI can end a stream before the first payload; pi-ai surfaces it
3
+ * as "Codex error: empty_stream: upstream stream closed before first
4
+ * payload", which matches none of pi's retryable-error patterns and kills
5
+ * the turn. Rewriting the message with a "network error:" prefix makes
6
+ * pi's normal retry budget/backoff apply. Same mechanism the provider
7
+ * package uses for its own transient patterns; message_end transforms
8
+ * chain, so both normalizers compose.
9
+ */
10
+
11
+ /** Structural subset of pi-ai's AssistantMessage used by the normalizer. */
12
+ export interface ErroredMessage {
13
+ role: string;
14
+ stopReason?: string;
15
+ errorMessage?: string;
16
+ }
17
+
18
+ const CPA_TRANSIENT_ERROR_PATTERN =
19
+ /\bempty_stream\b|\bupstream stream closed before first payload\b/i;
20
+ const NETWORK_ERROR_PREFIX = "network error:";
21
+
22
+ /** Return a retryable copy of a CPA transient stream error, or the
23
+ * message unchanged when it is not one (reference equality = no-op). */
24
+ export function normalizeCpaTransientError<T extends ErroredMessage>(
25
+ message: T,
26
+ ): T {
27
+ if (
28
+ message.role !== "assistant" ||
29
+ message.stopReason !== "error" ||
30
+ !message.errorMessage ||
31
+ message.errorMessage.startsWith(NETWORK_ERROR_PREFIX) ||
32
+ !CPA_TRANSIENT_ERROR_PATTERN.test(message.errorMessage)
33
+ ) {
34
+ return message;
35
+ }
36
+ return {
37
+ ...message,
38
+ errorMessage: `${NETWORK_ERROR_PREFIX} ${message.errorMessage}`,
39
+ };
40
+ }