proper-base 0.6.0 → 0.8.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,166 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import {
3
+ AgentSession,
4
+ InteractiveMode,
5
+ type MarkdownTransformer,
6
+ type SessionManager,
7
+ } from "@earendil-works/pi-coding-agent";
8
+ import { installWrapper, originalInput } from "./host-interop.ts";
9
+ import type { PromptDisplayController } from "./prompt-display.ts";
10
+ import { splitSkillText } from "./skill-context.ts";
11
+
12
+ type Message = Parameters<SessionManager["appendMessage"]>[0];
13
+ type Manager = Pick<SessionManager, "getBranch">;
14
+ type Controller = { activate(manager: Manager): void; dispose(): void };
15
+ const INSTALLED = Symbol.for("pi-proper-base.prompt-display");
16
+ const host = globalThis as typeof globalThis & { [INSTALLED]?: Controller };
17
+
18
+ /** Pi 0.86 has neither input correlation nor message identity in Markdown hooks.
19
+ * Keep this adapter removable when those APIs exist. Never emulate expansion.
20
+ * @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Prompt display]]
21
+ */
22
+ export function installPromptDisplayHost(
23
+ display: PromptDisplayController,
24
+ commands: () => ReadonlyArray<{ name: string; source: string }>,
25
+ marker: MarkdownTransformer,
26
+ ): Controller {
27
+ host[INSTALLED]?.dispose();
28
+ let active = true;
29
+ let manager: Manager | undefined;
30
+ const dispatch = new AsyncLocalStorage<{
31
+ raw: string | undefined;
32
+ bound: boolean;
33
+ }>();
34
+ const restorers: Array<() => void> = [];
35
+ const agents = new WeakSet<AgentSession["agent"]>();
36
+ const managers = new WeakSet<SessionManager>();
37
+
38
+ function bindSession(session: AgentSession): void {
39
+ const agent = session.agent;
40
+ if (!agents.has(agent)) {
41
+ agents.add(agent);
42
+ for (const name of ["prompt", "steer", "followUp"] as const) {
43
+ const original = agent[name];
44
+ const wrapped = function (this: typeof agent, ...args: unknown[]) {
45
+ const scope = dispatch.getStore();
46
+ if (active && scope?.raw !== undefined && !scope.bound) {
47
+ const values = (
48
+ Array.isArray(args[0]) ? args[0] : [args[0]]
49
+ ) as Message[];
50
+ const message = values.find((value) => value?.role === "user");
51
+ if (message) {
52
+ display.bind(message, scope.raw);
53
+ scope.bound = true;
54
+ }
55
+ }
56
+ return Reflect.apply(original, this, args);
57
+ };
58
+ restorers.push(installWrapper(agent, name, wrapped));
59
+ }
60
+ }
61
+ const store = session.sessionManager;
62
+ if (!managers.has(store)) {
63
+ managers.add(store);
64
+ const append = store.appendMessage;
65
+ const wrapped: typeof append = function (this: SessionManager, message) {
66
+ const id = append.call(this, message);
67
+ if (active) display.persist(message, id);
68
+ return id;
69
+ };
70
+ restorers.push(installWrapper(store, "appendMessage", wrapped));
71
+ }
72
+ }
73
+
74
+ for (const name of ["prompt", "steer", "followUp"] as const) {
75
+ const original = AgentSession.prototype[name];
76
+ const wrapped = function (this: AgentSession, ...args: unknown[]) {
77
+ if (!active || this.sessionManager !== manager)
78
+ return Reflect.apply(original, this, args);
79
+ bindSession(this);
80
+ const options = args[name === "prompt" ? 1 : 2] as
81
+ | { source?: string; expandPromptTemplates?: boolean }
82
+ | undefined;
83
+ const text = originalInput(args[0] as string, options);
84
+ const command = /^\/([^\s]+)/.exec(text)?.[1];
85
+ const raw =
86
+ (options?.source ?? "interactive") === "interactive" &&
87
+ options?.expandPromptTemplates !== false &&
88
+ command &&
89
+ commands().some(
90
+ (item) => item.name === command && item.source === "prompt",
91
+ )
92
+ ? text
93
+ : undefined;
94
+ return dispatch.run({ raw, bound: false }, () =>
95
+ Reflect.apply(original, this, args),
96
+ );
97
+ };
98
+ restorers.push(installWrapper(AgentSession.prototype, name, wrapped));
99
+ }
100
+
101
+ // Swap only the text Pi gives its native user component, preserving images,
102
+ // layout and other transformers. Persisted and model-facing text is untouched.
103
+ type InteractiveHost = {
104
+ session: AgentSession;
105
+ getUserMessageText(message: Message): string;
106
+ getMarkdownTransformers(): MarkdownTransformer[];
107
+ addMessageToChat(
108
+ message: Message,
109
+ options?: { populateHistory?: boolean },
110
+ ): void;
111
+ editor: { addToHistory?(text: string): void };
112
+ };
113
+ const prototype = InteractiveMode.prototype as unknown as InteractiveHost;
114
+ const original = prototype.getUserMessageText;
115
+ const wrapped: typeof original = function (this: InteractiveHost, message) {
116
+ if (!active || !this.getMarkdownTransformers().includes(marker))
117
+ return original.call(this, message);
118
+ if (manager !== this.session.sessionManager) {
119
+ // Reload rebuilds chat before session_start. Resolve entry identities now.
120
+ manager = this.session.sessionManager;
121
+ display.restore(manager.getBranch());
122
+ }
123
+ return display.rawFor(message) ?? original.call(this, message);
124
+ };
125
+ restorers.push(installWrapper(prototype, "getUserMessageText", wrapped));
126
+
127
+ // Pi collapses only the first skill block, rendering the rest as user text.
128
+ // Feed each block through its native renderer without changing the message.
129
+ const addMessage = prototype.addMessageToChat;
130
+ const addSkills: typeof addMessage = function (
131
+ this: InteractiveHost,
132
+ message,
133
+ options,
134
+ ) {
135
+ if (
136
+ !active ||
137
+ message.role !== "user" ||
138
+ !this.getMarkdownTransformers().includes(marker)
139
+ )
140
+ return addMessage.call(this, message, options);
141
+ const text = this.getUserMessageText(message);
142
+ const { skills, request } = splitSkillText(text);
143
+ if (skills.length < 2) return addMessage.call(this, message, options);
144
+ for (const skill of skills)
145
+ addMessage.call(this, { ...message, content: skill.block });
146
+ if (request) addMessage.call(this, { ...message, content: request });
147
+ if (options?.populateHistory) this.editor.addToHistory?.(text);
148
+ };
149
+ restorers.push(installWrapper(prototype, "addMessageToChat", addSkills));
150
+
151
+ const controller: Controller = {
152
+ activate(next) {
153
+ manager = next;
154
+ display.restore(next.getBranch());
155
+ },
156
+ dispose() {
157
+ active = false;
158
+ for (const restore of restorers.reverse()) restore();
159
+ dispatch.disable();
160
+ display.clear();
161
+ if (host[INSTALLED] === controller) delete host[INSTALLED];
162
+ },
163
+ };
164
+ host[INSTALLED] = controller;
165
+ return controller;
166
+ }
@@ -1,101 +1,63 @@
1
- import { createHash } from "node:crypto";
1
+ import type { SessionManager } from "@earendil-works/pi-coding-agent";
2
2
 
3
3
  export const PROMPT_DISPLAY_ENTRY = "proper-prompt-display";
4
-
5
- type Command = { name: string; source: string };
6
- type Message = { content: string | Array<{ type: string; text?: string }> };
7
- type Entry = {
8
- type: string;
9
- customType?: string;
10
- data?: unknown;
11
- };
12
- export type PromptDisplayRecord = { hash: string; raw: string };
13
-
14
- export type PromptDisplayController = {
15
- captureInput(text: string, commands: Command[]): void;
16
- captureUser(message: Message): void;
17
- transform(markdown: string): string;
18
- drain(): PromptDisplayRecord[];
19
- restore(entries: Entry[]): void;
20
- clear(): void;
21
- };
22
-
23
- export function createPromptDisplay(): PromptDisplayController {
24
- const display = new Map<string, string>();
25
- const pending = new Map<string, string>();
26
- const inputs: Array<string | undefined> = [];
27
-
4
+ type Message = Parameters<SessionManager["appendMessage"]>[0];
5
+ type Entry = ReturnType<SessionManager["getBranch"]>[number];
6
+ export type PromptDisplayRecord = { messageEntryId: string; raw: string };
7
+
8
+ /** Display metadata belongs to a message, never to its text or submission order. */
9
+ export function createPromptDisplay() {
10
+ let display = new WeakMap<Message, string>();
11
+ const pending: PromptDisplayRecord[] = [];
28
12
  return {
29
- captureInput(text, commands) {
30
- const name = /^\/([^\s]+)/.exec(text)?.[1];
31
- const prompt = name
32
- ? commands.some(
33
- (command) => command.name === name && command.source === "prompt",
34
- )
35
- : false;
36
- inputs.push(prompt ? text : undefined);
13
+ bind(message: Message, raw: string) {
14
+ display.set(message, raw);
37
15
  },
38
- captureUser(message) {
39
- const raw = inputs.shift();
40
- if (!raw) return;
41
- const expanded = messageText(message);
42
- if (!expanded) return;
43
- const key = hash(expanded);
44
- display.set(key, raw);
45
- pending.set(key, raw);
16
+ rawFor(message: Message): string | undefined {
17
+ return display.get(message);
46
18
  },
47
- transform(markdown) {
48
- return display.get(hash(markdown)) ?? markdown;
19
+ persist(message: Message, messageEntryId: string) {
20
+ const raw = display.get(message);
21
+ if (raw !== undefined) pending.push({ messageEntryId, raw });
49
22
  },
50
- drain() {
51
- const records = [...pending].map(([hash, raw]) => ({ hash, raw }));
52
- pending.clear();
53
- return records;
23
+ drain(): PromptDisplayRecord[] {
24
+ return pending.splice(0);
54
25
  },
55
- restore(entries) {
56
- display.clear();
57
- pending.clear();
58
- inputs.length = 0;
26
+ restore(entries: Entry[]) {
27
+ display = new WeakMap();
28
+ pending.length = 0;
29
+ const messages = new Map(
30
+ entries.flatMap((entry) =>
31
+ entry.type === "message" && entry.message.role === "user"
32
+ ? [[entry.id, entry.message] as const]
33
+ : [],
34
+ ),
35
+ );
59
36
  for (const entry of entries) {
60
37
  if (
61
38
  entry.type !== "custom" ||
62
39
  entry.customType !== PROMPT_DISPLAY_ENTRY
63
- ) {
40
+ )
64
41
  continue;
42
+ const data = entry.data as { prompts?: unknown } | undefined;
43
+ if (!data || !Array.isArray(data.prompts)) continue;
44
+ for (const record of data.prompts) {
45
+ if (
46
+ !record ||
47
+ typeof record !== "object" ||
48
+ typeof record.messageEntryId !== "string" ||
49
+ typeof record.raw !== "string"
50
+ )
51
+ continue;
52
+ const message = messages.get(record.messageEntryId);
53
+ if (message) display.set(message, record.raw);
65
54
  }
66
- const records = asRecords(entry.data);
67
- for (const record of records) display.set(record.hash, record.raw);
68
55
  }
69
56
  },
70
57
  clear() {
71
- display.clear();
72
- pending.clear();
73
- inputs.length = 0;
58
+ display = new WeakMap();
59
+ pending.length = 0;
74
60
  },
75
61
  };
76
62
  }
77
-
78
- function messageText(message: Message): string {
79
- if (typeof message.content === "string") return message.content;
80
- return message.content
81
- .filter((part) => part.type === "text" && typeof part.text === "string")
82
- .map((part) => part.text ?? "")
83
- .join("");
84
- }
85
-
86
- function hash(text: string): string {
87
- return createHash("sha256").update(text.trim()).digest("hex");
88
- }
89
-
90
- function asRecords(data: unknown): PromptDisplayRecord[] {
91
- if (typeof data !== "object" || data === null) return [];
92
- const prompts = (data as { prompts?: unknown }).prompts;
93
- if (!Array.isArray(prompts)) return [];
94
- return prompts.flatMap((record) => {
95
- if (typeof record !== "object" || record === null) return [];
96
- const { hash, raw } = record as { hash?: unknown; raw?: unknown };
97
- return typeof hash === "string" && typeof raw === "string"
98
- ? [{ hash, raw }]
99
- : [];
100
- });
101
- }
63
+ export type PromptDisplayController = ReturnType<typeof createPromptDisplay>;
@@ -0,0 +1,16 @@
1
+ import type { NormalizedBuildSystemPromptOptions } from "@earendil-works/pi-coding-agent";
2
+
3
+ /** Compose normally; never turn structured input into an opaque replacement. */
4
+ export function appendPromptSection(
5
+ options: NormalizedBuildSystemPromptOptions,
6
+ name: string,
7
+ text: string,
8
+ ): void {
9
+ if (options.forceSystemPrompt !== undefined) {
10
+ // A prior extension explicitly replaced the prompt. Preserve that choice;
11
+ // Pi ignores structured sections in this mode, so append to its text.
12
+ options.forceSystemPrompt += `\n\n<${name}>\n${text}\n</${name}>`;
13
+ } else {
14
+ options.sections[name] = text;
15
+ }
16
+ }
@@ -20,6 +20,8 @@ import { open, readdir, stat } from "node:fs/promises";
20
20
  import { join, resolve } from "node:path";
21
21
  import { createInterface } from "node:readline";
22
22
 
23
+ import { SessionSelectorComponent } from "@earendil-works/pi-coding-agent";
24
+
23
25
  import { projectKey } from "./store.ts";
24
26
 
25
27
  /** Structurally compatible with pi's `SessionInfo`. */
@@ -448,12 +450,18 @@ export function createSessionListers(agentDir: string) {
448
450
  * was handed restores full-text search without the loader ever waiting for it.
449
451
  * Sessions arrive newest-first, which is the order the picker shows them in.
450
452
  */
451
- export function backfillSearchText(sessions: SessionInfo[]): () => void {
453
+ export function backfillSearchText(
454
+ sessions: SessionInfo[],
455
+ onUpdate?: (session: SessionInfo) => void,
456
+ ): () => void {
452
457
  let cancelled = false;
453
458
  void (async () => {
454
459
  for (const session of sessions) {
455
460
  if (cancelled) return;
456
- session.allMessagesText = await readSearchText(session.path);
461
+ const text = await readSearchText(session.path);
462
+ if (cancelled) return;
463
+ session.allMessagesText = text;
464
+ onUpdate?.(session);
457
465
  }
458
466
  })();
459
467
  return () => {
@@ -461,37 +469,140 @@ export function backfillSearchText(sessions: SessionInfo[]): () => void {
461
469
  };
462
470
  }
463
471
 
464
- type Listers = { list: unknown; listAll: unknown };
472
+ type Lister = (...args: never[]) => unknown;
473
+ type Listers = { list: Lister; listAll: Lister };
474
+ type SessionListSurface = {
475
+ allSessions: SessionInfo[];
476
+ showCwd: boolean;
477
+ filteredSessions: Array<{ session: SessionInfo }>;
478
+ selectedIndex: number;
479
+ getSelectedSessionPath(): string | undefined;
480
+ setSessions(sessions: SessionInfo[], showCwd: boolean): void;
481
+ };
482
+ type SelectorSurface = {
483
+ sessionList: SessionListSurface;
484
+ requestRender(): void;
485
+ };
486
+ type SessionListController = { restore(): void };
465
487
 
466
488
  const FAST_SESSION_LIST = Symbol.for("pi-proper-base.fast-session-list");
489
+ const SELECTOR_REFRESH = Symbol.for("pi-proper-base.session-selector-refresh");
490
+ type TaggedListers = Listers & {
491
+ [FAST_SESSION_LIST]?: SessionListController | true;
492
+ };
493
+ type TaggedSelectorPrototype = {
494
+ handleInput(data: string): void;
495
+ [SELECTOR_REFRESH]?: SessionListController;
496
+ };
467
497
 
468
- /**
469
- * Point pi's session listing at the fast readers.
470
- *
471
- * Pi's `SessionManager` is a module singleton reached through static property
472
- * lookups, so replacing the two listing methods covers `/resume` without
473
- * touching the picker. Installation is idempotent: the class outlives every
474
- * session, so a reload must not stack wrappers.
475
- */
476
- export function installFastSessionList(target: object, agentDir: string): void {
477
- const tagged = target as Listers & { [FAST_SESSION_LIST]?: true };
478
- if (tagged[FAST_SESSION_LIST]) return;
498
+ /** Install fast listers plus live query refresh, with reload-safe ownership. */
499
+ export function installFastSessionList(
500
+ target: object,
501
+ agentDir: string,
502
+ ): () => void {
503
+ const tagged = target as TaggedListers;
504
+ const previous = tagged[FAST_SESSION_LIST];
505
+ if (previous && previous !== true) previous.restore();
506
+ const selectorPrototype =
507
+ SessionSelectorComponent.prototype as unknown as TaggedSelectorPrototype;
508
+ selectorPrototype[SELECTOR_REFRESH]?.restore();
509
+ const originalList = tagged.list;
510
+ const originalListAll = tagged.listAll;
511
+ const originalHandleInput = selectorPrototype.handleInput;
479
512
  const fast = createSessionListers(agentDir);
513
+ const selectors = new Set<WeakRef<SelectorSurface>>();
514
+ const seen = new WeakSet<SelectorSurface>();
515
+ const pending = new Set<SessionInfo>();
516
+ let installed = true;
517
+ let refreshTimer: ReturnType<typeof setTimeout> | undefined;
480
518
  let cancelBackfill: (() => void) | undefined;
519
+
520
+ const refreshMatchingQueries = () => {
521
+ refreshTimer = undefined;
522
+ for (const reference of selectors) {
523
+ const selector = reference.deref();
524
+ if (!selector) {
525
+ selectors.delete(reference);
526
+ continue;
527
+ }
528
+ const list = selector.sessionList;
529
+ if (
530
+ !list ||
531
+ !Array.isArray(list.allSessions) ||
532
+ !list.allSessions.some((session) => pending.has(session)) ||
533
+ typeof list.setSessions !== "function"
534
+ )
535
+ continue;
536
+ const selectedPath = list.getSelectedSessionPath?.();
537
+ list.setSessions(list.allSessions, list.showCwd);
538
+ if (selectedPath && Array.isArray(list.filteredSessions)) {
539
+ const selectedIndex = list.filteredSessions.findIndex(
540
+ (item) => item.session.path === selectedPath,
541
+ );
542
+ if (selectedIndex >= 0) list.selectedIndex = selectedIndex;
543
+ }
544
+ selector.requestRender?.();
545
+ }
546
+ pending.clear();
547
+ };
548
+ const scheduleRefresh = (updated: SessionInfo) => {
549
+ pending.add(updated);
550
+ refreshTimer ??= setTimeout(refreshMatchingQueries, 16);
551
+ refreshTimer.unref();
552
+ };
481
553
  const served = (sessions: SessionInfo[]): SessionInfo[] => {
482
- // Only the newest listing is worth completing; a rescan replaces it.
554
+ if (!installed) return sessions;
483
555
  cancelBackfill?.();
484
- cancelBackfill = backfillSearchText(sessions);
556
+ cancelBackfill = backfillSearchText(sessions, scheduleRefresh);
485
557
  return sessions;
486
558
  };
487
- tagged.list = (
559
+ const list = (
488
560
  cwd: string,
489
561
  sessionDir?: string,
490
562
  onProgress?: ProgressCallback,
491
- ) => fast.list(cwd, sessionDir, onProgress).then(served);
492
- tagged.listAll = (
563
+ ) =>
564
+ installed
565
+ ? fast.list(cwd, sessionDir, onProgress).then(served)
566
+ : Reflect.apply(originalList, target, [cwd, sessionDir, onProgress]);
567
+ const listAll = (
493
568
  sessionDirOrProgress?: string | ProgressCallback,
494
569
  onProgress?: ProgressCallback,
495
- ) => fast.listAll(sessionDirOrProgress, onProgress).then(served);
496
- tagged[FAST_SESSION_LIST] = true;
570
+ ) =>
571
+ installed
572
+ ? fast.listAll(sessionDirOrProgress, onProgress).then(served)
573
+ : Reflect.apply(originalListAll, target, [
574
+ sessionDirOrProgress,
575
+ onProgress,
576
+ ]);
577
+ function handleInput(this: SelectorSurface, data: string): void {
578
+ if (installed && !seen.has(this)) {
579
+ seen.add(this);
580
+ selectors.add(new WeakRef(this));
581
+ }
582
+ originalHandleInput.call(this, data);
583
+ }
584
+ const controller: SessionListController = {
585
+ restore() {
586
+ installed = false;
587
+ cancelBackfill?.();
588
+ clearTimeout(refreshTimer);
589
+ pending.clear();
590
+ selectors.clear();
591
+ if (tagged[FAST_SESSION_LIST] !== controller) return;
592
+ if (tagged.list === (list as Lister)) tagged.list = originalList;
593
+ if (tagged.listAll === (listAll as Lister))
594
+ tagged.listAll = originalListAll;
595
+ if (selectorPrototype.handleInput === handleInput)
596
+ selectorPrototype.handleInput = originalHandleInput;
597
+ delete tagged[FAST_SESSION_LIST];
598
+ if (selectorPrototype[SELECTOR_REFRESH] === controller)
599
+ delete selectorPrototype[SELECTOR_REFRESH];
600
+ },
601
+ };
602
+ tagged.list = list as Lister;
603
+ tagged.listAll = listAll as Lister;
604
+ selectorPrototype.handleInput = handleInput;
605
+ tagged[FAST_SESSION_LIST] = controller;
606
+ selectorPrototype[SELECTOR_REFRESH] = controller;
607
+ return () => controller.restore();
497
608
  }