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.
package/index.ts ADDED
@@ -0,0 +1,596 @@
1
+ /**
2
+ * proper-base — baseline editor, fullscreen, history, and footer behavior.
3
+ *
4
+ * pi's Up/Down history covers the current session only, so a new session in a
5
+ * project you have worked in for weeks starts empty. This extension seeds the
6
+ * editor from the other sessions recorded for the same working directory, and
7
+ * records every prompt as you submit it.
8
+ *
9
+ * The editor submit path is the only trusted source: Pi session messages store
10
+ * expanded skills and prompt templates rather than the exact outgoing input.
11
+ */
12
+
13
+ import {
14
+ CustomEditor,
15
+ type ExtensionAPI,
16
+ type ExtensionContext,
17
+ getAgentDir,
18
+ } from "@earendil-works/pi-coding-agent";
19
+
20
+ import {
21
+ installAutocompleteDetails,
22
+ installInlineSlashAutocomplete,
23
+ installModelAutocompleteSubmit,
24
+ sortModelAutocompleteDescending,
25
+ } from "./src/autocomplete-details.ts";
26
+ import {
27
+ installEditorNavigation,
28
+ installPromptClear,
29
+ installReverseHistorySearch,
30
+ type ReverseHistorySearchController,
31
+ } from "./src/editor-navigation.ts";
32
+ import { installFooterColors } from "./src/footer-colors.ts";
33
+ import {
34
+ isRecallable,
35
+ mergePrompts,
36
+ resolveBase,
37
+ WRAPPED,
38
+ } from "./src/history.ts";
39
+ import { type HistoryGuard, installHistoryGuard } from "./src/history-guard.ts";
40
+ import { omitPriorTurnImages } from "./src/image-context.ts";
41
+ import {
42
+ type ImagePreviewController,
43
+ installImagePreview,
44
+ } from "./src/image-preview.ts";
45
+ import { installJumpToBottom } from "./src/jump-to-bottom.ts";
46
+ import {
47
+ createPromptDisplay,
48
+ PROMPT_DISPLAY_ENTRY,
49
+ } from "./src/prompt-display.ts";
50
+ import { installRecorder } from "./src/recorder.ts";
51
+ import { installSmartSelection } from "./src/smart-selection.ts";
52
+ import {
53
+ appendPrompt,
54
+ compactIfNeeded,
55
+ readPrompts,
56
+ storePath,
57
+ } from "./src/store.ts";
58
+ import {
59
+ installTranscriptCleanup,
60
+ type TranscriptCleanupController,
61
+ } from "./src/transcript-cleanup.ts";
62
+ import { normalizeCpaTransientError } from "./src/transient-retry.ts";
63
+
64
+ /** Prompts seeded into the editor. Older prompts past this point are dropped. */
65
+ const MAX_ENTRIES = 200;
66
+ const CANCEL_PROMPT_COMMAND = "__proper-cancel-prompt";
67
+ const CANCEL_ANCHOR = "proper-cancel-anchor";
68
+ const RESTORE_MODEL_COMMAND = "__proper-restore-model";
69
+ const SESSION_TITLE_INSTRUCTION = `At the end of your first assistant response, add exactly one line in this format: <session_title>concise 3-7 word task title</session_title>. Use plain text without quotes or terminal control characters. This is hidden session metadata; do not mention it.`;
70
+ const SESSION_TITLE_PATTERN = /\s*<session_title>([^<]*)<\/session_title>\s*$/i;
71
+ const SESSION_TITLE_DISPLAY_PATTERN = /\s*<session_title>[\s\S]*$/i;
72
+ const SESSION_TITLE_MAX_LENGTH = 64;
73
+
74
+ type EditorFactory = NonNullable<
75
+ ReturnType<ExtensionContext["ui"]["getEditorComponent"]>
76
+ >;
77
+
78
+ type TaggedFactory = EditorFactory & { [WRAPPED]?: EditorFactory | null };
79
+ type EditorKeybindings = Parameters<EditorFactory>[2];
80
+
81
+ const FULLSCREEN_KEYBINDINGS = Symbol.for(
82
+ "pi-proper-base.fullscreen-keybindings",
83
+ );
84
+ const LEGACY_FULLSCREEN_KEYBINDINGS = Symbol.for(
85
+ "pi-proper-customs.fullscreen-keybindings",
86
+ );
87
+ const FULLSCREEN_KEYS = {
88
+ "tui.altScreen.pageUp": "ctrl+shift+pageUp",
89
+ "tui.altScreen.pageDown": "ctrl+shift+pageDown",
90
+ "tui.altScreen.top": "ctrl+shift+home",
91
+ "tui.altScreen.bottom": "ctrl+shift+end",
92
+ } as const;
93
+
94
+ type KeybindingController = { apply(): void };
95
+ type PatchedKeybindings = EditorKeybindings & {
96
+ [FULLSCREEN_KEYBINDINGS]?: true | KeybindingController;
97
+ [LEGACY_FULLSCREEN_KEYBINDINGS]?: true | KeybindingController;
98
+ };
99
+
100
+ function installKeybindings(keybindings: EditorKeybindings): void {
101
+ const patched = keybindings as PatchedKeybindings;
102
+ const apply = () => {
103
+ const imagePasteKeys = [
104
+ ...new Set([
105
+ ...keybindings.getKeys("app.clipboard.pasteImage"),
106
+ "ctrl+v" as const,
107
+ "ctrl+shift+v" as const,
108
+ ]),
109
+ ];
110
+ const newLineKeys = [
111
+ ...new Set([
112
+ ...keybindings.getKeys("tui.input.newLine"),
113
+ "shift+enter" as const,
114
+ "alt+enter" as const,
115
+ ]),
116
+ ];
117
+ const followUpKeys = keybindings
118
+ .getKeys("app.message.followUp")
119
+ .filter((key) => key !== "alt+enter");
120
+ keybindings.setUserBindings({
121
+ ...keybindings.getUserBindings(),
122
+ ...FULLSCREEN_KEYS,
123
+ "app.clipboard.pasteImage": imagePasteKeys,
124
+ "tui.input.newLine": newLineKeys,
125
+ "app.message.followUp": followUpKeys,
126
+ });
127
+ };
128
+ const existing =
129
+ patched[FULLSCREEN_KEYBINDINGS] ?? patched[LEGACY_FULLSCREEN_KEYBINDINGS];
130
+ if (existing && existing !== true) {
131
+ existing.apply = apply;
132
+ patched[FULLSCREEN_KEYBINDINGS] = existing;
133
+ delete patched[LEGACY_FULLSCREEN_KEYBINDINGS];
134
+ existing.apply();
135
+ return;
136
+ }
137
+
138
+ const reload = keybindings.reload.bind(keybindings);
139
+ const controller: KeybindingController = { apply };
140
+ keybindings.reload = () => {
141
+ reload();
142
+ controller.apply();
143
+ };
144
+ patched[FULLSCREEN_KEYBINDINGS] = controller;
145
+ delete patched[LEGACY_FULLSCREEN_KEYBINDINGS];
146
+ controller.apply();
147
+ }
148
+
149
+ type EditorTui = Parameters<EditorFactory>[0];
150
+ type PromptEditor = ReturnType<EditorFactory> & {
151
+ isShowingAutocomplete?(): boolean;
152
+ };
153
+ type PendingPrompt = {
154
+ text: string;
155
+ messageTimestamp?: number;
156
+ processed: boolean;
157
+ cancelled: boolean;
158
+ entryId?: string;
159
+ };
160
+ type RestoreRequest = { entryId: string };
161
+
162
+ /**
163
+ * `details` shape of the `ask_user_question` tool result, from
164
+ * `@juicesharp/rpiv-ask-user-question`.
165
+ */
166
+ type QuestionnaireDetails = { cancelled?: boolean; error?: string };
167
+
168
+ function extractSessionTitle(text: string): string | undefined {
169
+ const match = SESSION_TITLE_PATTERN.exec(text);
170
+ if (!match) return undefined;
171
+
172
+ return (
173
+ (match[1] ?? "")
174
+ .replace(/\p{Cc}/gu, " ")
175
+ .replace(/\s+/g, " ")
176
+ .trim()
177
+ .slice(0, SESSION_TITLE_MAX_LENGTH)
178
+ .trim() || undefined
179
+ );
180
+ }
181
+
182
+ type ModelReference = { provider: string; id: string };
183
+
184
+ function encodeModelReference(model: ModelReference): string {
185
+ return encodeURIComponent(
186
+ JSON.stringify({ provider: model.provider, id: model.id }),
187
+ );
188
+ }
189
+
190
+ function decodeModelReference(value: string): ModelReference | undefined {
191
+ try {
192
+ const parsed = JSON.parse(
193
+ decodeURIComponent(value.trim()),
194
+ ) as Partial<ModelReference> | null;
195
+ if (
196
+ !parsed ||
197
+ typeof parsed.provider !== "string" ||
198
+ !parsed.provider ||
199
+ typeof parsed.id !== "string" ||
200
+ !parsed.id
201
+ )
202
+ return undefined;
203
+ return { provider: parsed.provider, id: parsed.id };
204
+ } catch {
205
+ return undefined;
206
+ }
207
+ }
208
+
209
+ export default function (pi: ExtensionAPI) {
210
+ let removeFooterColors: (() => void) | undefined;
211
+ let removeJumpToBottom: (() => void) | undefined;
212
+ let removePromptClear: (() => void) | undefined;
213
+ let removeSmartSelection: (() => void) | undefined;
214
+ let imagePreview: ImagePreviewController | undefined;
215
+ let removeTerminalInput: (() => void) | undefined;
216
+ let transcriptCleanup: TranscriptCleanupController | undefined;
217
+ let activeEditor: PromptEditor | undefined;
218
+ let activeTui: EditorTui | undefined;
219
+ let submittedPrompt: string | undefined;
220
+ let pendingPrompt: PendingPrompt | undefined;
221
+ let restoreRequest: RestoreRequest | undefined;
222
+ let sessionTitlePending = false;
223
+ const promptDisplay = createPromptDisplay();
224
+
225
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Prompt display]]
226
+ pi.registerMarkdownTransformer?.((markdown, context) => {
227
+ if (context.messageType === "user")
228
+ return promptDisplay.transform(markdown);
229
+ if (context.messageType !== "assistant") return markdown;
230
+ return markdown.replace(SESSION_TITLE_DISPLAY_PATTERN, "");
231
+ });
232
+
233
+ const findPendingEntry = (ctx: ExtensionContext) => {
234
+ if (!pendingPrompt?.messageTimestamp) return undefined;
235
+ return [...ctx.sessionManager.getBranch()]
236
+ .reverse()
237
+ .find(
238
+ (entry) =>
239
+ entry.type === "message" &&
240
+ entry.message.role === "user" &&
241
+ entry.message.timestamp === pendingPrompt?.messageTimestamp,
242
+ );
243
+ };
244
+
245
+ pi.registerCommand?.(RESTORE_MODEL_COMMAND, {
246
+ description: "Internal: restore the model after /clear",
247
+ handler: async (args, ctx) => {
248
+ const reference = decodeModelReference(args);
249
+ if (!reference) {
250
+ ctx.ui.notify("Could not restore model after /clear", "error");
251
+ return;
252
+ }
253
+ const model = ctx.modelRegistry.find(reference.provider, reference.id);
254
+ if (!model || !(await pi.setModel(model))) {
255
+ ctx.ui.notify(
256
+ `Could not restore model ${reference.provider}/${reference.id}`,
257
+ "error",
258
+ );
259
+ }
260
+ },
261
+ });
262
+
263
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Model-preserving clear]]
264
+ pi.registerCommand?.("clear", {
265
+ description: "Start a new session with the current model",
266
+ handler: async (_args, ctx) => {
267
+ const restoreCommand = ctx.model
268
+ ? `/${RESTORE_MODEL_COMMAND} ${encodeModelReference(ctx.model)}`
269
+ : undefined;
270
+ await ctx.newSession(
271
+ restoreCommand
272
+ ? {
273
+ withSession: async (replacementCtx) => {
274
+ await replacementCtx.sendUserMessage(restoreCommand, {
275
+ expandPromptTemplates: true,
276
+ });
277
+ },
278
+ }
279
+ : undefined,
280
+ );
281
+ },
282
+ });
283
+
284
+ pi.registerCommand?.(CANCEL_PROMPT_COMMAND, {
285
+ description: "Internal: remove an unprocessed cancelled prompt",
286
+ handler: async (_args, ctx) => {
287
+ const request = restoreRequest;
288
+ restoreRequest = undefined;
289
+ if (!request) return;
290
+
291
+ const target = ctx.sessionManager.getEntry(request.entryId);
292
+ if (target?.type !== "message" || target.message.role !== "user") return;
293
+ try {
294
+ if (ctx.sessionManager.getLeafId() === request.entryId) {
295
+ pi.appendEntry(CANCEL_ANCHOR, { targetId: request.entryId });
296
+ }
297
+ await ctx.navigateTree(request.entryId, { summarize: false });
298
+ } catch (error) {
299
+ ctx.ui.notify(
300
+ `Could not remove cancelled prompt: ${error instanceof Error ? error.message : String(error)}`,
301
+ "error",
302
+ );
303
+ }
304
+ },
305
+ });
306
+
307
+ pi.on("input", (event) => {
308
+ if (event.source === "interactive") {
309
+ promptDisplay.captureInput(event.text, pi.getCommands());
310
+ }
311
+ if (
312
+ event.source === "interactive" &&
313
+ event.streamingBehavior !== undefined
314
+ ) {
315
+ submittedPrompt = undefined;
316
+ return;
317
+ }
318
+ if (event.source !== "interactive" || !event.text.trim()) return;
319
+ pendingPrompt = {
320
+ text: submittedPrompt ?? event.text,
321
+ processed: false,
322
+ cancelled: false,
323
+ };
324
+ submittedPrompt = undefined;
325
+ });
326
+
327
+ pi.on("message_start", (event) => {
328
+ if (event.message.role === "user") {
329
+ promptDisplay.captureUser(event.message);
330
+ if (pendingPrompt) {
331
+ pendingPrompt.messageTimestamp = event.message.timestamp;
332
+ }
333
+ return;
334
+ }
335
+ if (!pendingPrompt) return;
336
+ if (
337
+ event.message.role === "assistant" &&
338
+ event.message.stopReason !== "aborted"
339
+ ) {
340
+ pendingPrompt.processed = true;
341
+ imagePreview?.clear();
342
+ }
343
+ });
344
+
345
+ pi.on("message_update", () => {
346
+ if (pendingPrompt) pendingPrompt.processed = true;
347
+ });
348
+
349
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Model image context]]
350
+ pi.on("context", (event) => {
351
+ const messages = omitPriorTurnImages(event.messages);
352
+ if (messages !== event.messages) return { messages };
353
+ });
354
+
355
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Automatic session title]]
356
+ pi.on("before_agent_start", (event) => {
357
+ if (!sessionTitlePending || pi.getSessionName?.()) {
358
+ sessionTitlePending = false;
359
+ return;
360
+ }
361
+ return {
362
+ systemPrompt: `${event.systemPrompt}\n\n${SESSION_TITLE_INSTRUCTION}`,
363
+ };
364
+ });
365
+
366
+ pi.on("message_end", (event) => {
367
+ if (event.message.role === "assistant") {
368
+ transcriptCleanup?.completeAssistant(event.message);
369
+ }
370
+ const normalized = normalizeCpaTransientError(event.message);
371
+ if (normalized !== event.message) return { message: normalized };
372
+ });
373
+
374
+ pi.on("message_end", (event) => {
375
+ if (
376
+ !sessionTitlePending ||
377
+ event.message.role !== "assistant" ||
378
+ event.message.stopReason === "aborted" ||
379
+ event.message.stopReason === "error" ||
380
+ pi.getSessionName?.()
381
+ ) {
382
+ return;
383
+ }
384
+
385
+ const title = event.message.content.find(
386
+ (part) => part.type === "text" && extractSessionTitle(part.text),
387
+ );
388
+ if (title?.type !== "text") {
389
+ if (
390
+ event.message.stopReason === "stop" ||
391
+ event.message.stopReason === "length"
392
+ ) {
393
+ sessionTitlePending = false;
394
+ }
395
+ return;
396
+ }
397
+ const extracted = extractSessionTitle(title.text);
398
+ if (!extracted) return;
399
+
400
+ sessionTitlePending = false;
401
+ pi.setSessionName?.(extracted);
402
+ });
403
+
404
+ pi.on("agent_start", () => {
405
+ transcriptCleanup?.start();
406
+ });
407
+
408
+ pi.on("tool_execution_start", () => {
409
+ if (pendingPrompt) pendingPrompt.processed = true;
410
+ });
411
+
412
+ pi.on("tool_execution_end", (event) => {
413
+ transcriptCleanup?.completeTool(event.toolCallId);
414
+ });
415
+
416
+ pi.on("agent_settled", (_event, ctx) => {
417
+ const prompts = promptDisplay.drain();
418
+ if (prompts.length) pi.appendEntry(PROMPT_DISPLAY_ENTRY, { prompts });
419
+ const ui = ctx.ui as ExtensionContext["ui"] & {
420
+ getToolsExpanded?(): boolean;
421
+ setToolsExpanded?(expanded: boolean): void;
422
+ };
423
+ if (ui.getToolsExpanded?.()) ui.setToolsExpanded?.(false);
424
+ transcriptCleanup?.settle();
425
+ submittedPrompt = undefined;
426
+ const candidate = pendingPrompt;
427
+ if (!candidate) return;
428
+ if (candidate.cancelled && !candidate.processed) {
429
+ const entry = candidate.entryId
430
+ ? ctx.sessionManager.getEntry(candidate.entryId)
431
+ : findPendingEntry(ctx);
432
+ if (entry?.type === "message" && entry.message.role === "user") {
433
+ restoreRequest = { entryId: entry.id };
434
+ pendingPrompt = undefined;
435
+ pi.sendUserMessage(`/${CANCEL_PROMPT_COMMAND}`, {
436
+ expandPromptTemplates: true,
437
+ });
438
+ return;
439
+ }
440
+ }
441
+ pendingPrompt = undefined;
442
+ imagePreview?.clear();
443
+ });
444
+
445
+ // Esc on the questionnaire resolves a normal tool result, so the turn
446
+ // continues and the model answers a decline it did not need. Aborting
447
+ // returns to the prompt instead, matching Esc during streaming.
448
+ pi.on("tool_result", (event, ctx) => {
449
+ if (event.toolName !== "ask_user_question") return;
450
+ const details = event.details as QuestionnaireDetails | undefined;
451
+ // The tool also reports `cancelled` for host and validation failures,
452
+ // which carry `error`. Those must reach the model so it can fall back to
453
+ // asking in plain text.
454
+ if (details?.cancelled && !details.error) ctx.abort();
455
+ });
456
+
457
+ pi.on("session_shutdown", () => {
458
+ removeFooterColors?.();
459
+ removeFooterColors = undefined;
460
+ removeJumpToBottom?.();
461
+ removeJumpToBottom = undefined;
462
+ removePromptClear?.();
463
+ removePromptClear = undefined;
464
+ removeSmartSelection?.();
465
+ removeSmartSelection = undefined;
466
+ imagePreview?.dispose();
467
+ imagePreview = undefined;
468
+ removeTerminalInput?.();
469
+ removeTerminalInput = undefined;
470
+ transcriptCleanup?.uninstall();
471
+ transcriptCleanup = undefined;
472
+ activeEditor = undefined;
473
+ activeTui = undefined;
474
+ submittedPrompt = undefined;
475
+ pendingPrompt = undefined;
476
+ restoreRequest = undefined;
477
+ sessionTitlePending = false;
478
+ promptDisplay.clear();
479
+ });
480
+
481
+ pi.on("session_start", async (_event, ctx) => {
482
+ promptDisplay.restore(ctx.sessionManager.getBranch());
483
+ sessionTitlePending =
484
+ !pi.getSessionName?.() &&
485
+ !ctx.sessionManager
486
+ .getBranch()
487
+ .some(
488
+ (entry) =>
489
+ entry.type === "message" && entry.message.role === "assistant",
490
+ );
491
+ submittedPrompt = undefined;
492
+ pendingPrompt = undefined;
493
+ restoreRequest = undefined;
494
+ removeTerminalInput?.();
495
+ removeTerminalInput = ctx.ui.onTerminalInput?.((data) => {
496
+ const candidate = pendingPrompt;
497
+ const promptText = candidate?.text ?? submittedPrompt;
498
+ if (data !== "\x1b" || !promptText || candidate?.processed === true) {
499
+ return undefined;
500
+ }
501
+ if (activeEditor?.isShowingAutocomplete?.()) return undefined;
502
+ const focused = (
503
+ activeTui as EditorTui & {
504
+ getFocusedComponent?(): unknown;
505
+ }
506
+ )?.getFocusedComponent?.();
507
+ if (focused && focused !== activeEditor) return undefined;
508
+
509
+ const entry = findPendingEntry(ctx);
510
+ if (!candidate || (!entry && ctx.isIdle())) {
511
+ ctx.ui.setEditorText(promptText);
512
+ submittedPrompt = undefined;
513
+ pendingPrompt = undefined;
514
+ return undefined;
515
+ }
516
+
517
+ candidate.cancelled = true;
518
+ if (entry) candidate.entryId = entry.id;
519
+ else delete candidate.entryId;
520
+ ctx.ui.setEditorText(promptText);
521
+ return undefined;
522
+ });
523
+ ctx.ui.addAutocompleteProvider?.(sortModelAutocompleteDescending);
524
+
525
+ const store = storePath(getAgentDir(), ctx.cwd);
526
+ compactIfNeeded(store);
527
+
528
+ // Stores written before command filtering still hold UI commands.
529
+ const commands = pi.getCommands();
530
+ const seeded = mergePrompts(readPrompts(store), MAX_ENTRIES).filter(
531
+ (text) => isRecallable(text, commands),
532
+ );
533
+ let historyGuard: HistoryGuard | undefined;
534
+ let historySearch: ReverseHistorySearchController | undefined;
535
+ const record = (text: string, sourceText: string) => {
536
+ if (isRecallable(text, pi.getCommands())) {
537
+ appendPrompt(store, text);
538
+ historyGuard?.add(text);
539
+ historySearch?.add(text);
540
+ }
541
+ if (
542
+ !sourceText.trimStart().startsWith("/") &&
543
+ !sourceText.trimStart().startsWith("!")
544
+ ) {
545
+ submittedPrompt = sourceText;
546
+ }
547
+ };
548
+
549
+ // Wrap the installed editor rather than replacing it, so this composes
550
+ // with extensions that provide their own editor.
551
+ const base = resolveBase(ctx.ui.getEditorComponent());
552
+ const factory: TaggedFactory = (tui, theme, keybindings) => {
553
+ installKeybindings(keybindings);
554
+ const editor =
555
+ base?.(tui, theme, keybindings) ??
556
+ new CustomEditor(tui, theme, keybindings);
557
+ activeEditor = editor as PromptEditor;
558
+ activeTui = tui;
559
+ // @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Settled transcript]]
560
+ transcriptCleanup?.uninstall();
561
+ transcriptCleanup = installTranscriptCleanup(tui, ctx, keybindings);
562
+ removeSmartSelection?.();
563
+ removeSmartSelection = installSmartSelection(tui);
564
+ historyGuard = installHistoryGuard(editor);
565
+ removeJumpToBottom?.();
566
+ removeJumpToBottom = installJumpToBottom(editor, tui);
567
+ imagePreview?.dispose();
568
+ imagePreview = installImagePreview(editor, tui);
569
+ installEditorNavigation(editor, keybindings);
570
+ installInlineSlashAutocomplete(editor);
571
+ installRecorder(
572
+ editor,
573
+ record,
574
+ (text) => imagePreview?.prepare(text) ?? text,
575
+ );
576
+ installModelAutocompleteSubmit(editor, keybindings);
577
+ removePromptClear?.();
578
+ removePromptClear = installPromptClear(editor, tui, keybindings, ctx);
579
+ historySearch = installReverseHistorySearch(
580
+ editor,
581
+ tui,
582
+ keybindings,
583
+ seeded,
584
+ MAX_ENTRIES,
585
+ );
586
+ installAutocompleteDetails(editor, tui, theme);
587
+ removeFooterColors?.();
588
+ removeFooterColors = installFooterColors(tui, ctx);
589
+ for (const prompt of seeded) historyGuard?.add(prompt);
590
+ return editor;
591
+ };
592
+ factory[WRAPPED] = base ?? null;
593
+
594
+ ctx.ui.setEditorComponent(factory);
595
+ });
596
+ }
package/install.mjs ADDED
@@ -0,0 +1,84 @@
1
+ /**
2
+ * npm `postinstall` hook.
3
+ *
4
+ * Pi has no package install hook of its own, so a default that another
5
+ * extension reads only from `settings.json` is written here: once, when the
6
+ * package is installed, never from a running session. Plain JavaScript because
7
+ * npm runs this with bare `node`.
8
+ *
9
+ * Runs for `pi install npm:proper-base`, for git sources, and for `npm
10
+ * install` in a local checkout. A local path registered with `pi install
11
+ * /path/to/proper-base` is only recorded in settings, so it seeds when that
12
+ * checkout's own `npm install` runs.
13
+ */
14
+
15
+ import { readFileSync, renameSync, writeFileSync } from "node:fs";
16
+ import { homedir } from "node:os";
17
+ import { join } from "node:path";
18
+ import { fileURLToPath } from "node:url";
19
+
20
+ /** Pi's user agent directory: `PI_CODING_AGENT_DIR`, else `~/.pi/agent`. */
21
+ export function agentDir() {
22
+ const configured = process.env.PI_CODING_AGENT_DIR;
23
+ if (!configured) return join(homedir(), ".pi", "agent");
24
+ return configured.startsWith("~/")
25
+ ? join(homedir(), configured.slice(2))
26
+ : configured;
27
+ }
28
+
29
+ function asObject(value) {
30
+ return typeof value === "object" && value !== null && !Array.isArray(value)
31
+ ? value
32
+ : undefined;
33
+ }
34
+
35
+ /**
36
+ * Give pi-subagents' packaged `worker` agent a fresh context by default.
37
+ *
38
+ * `worker` ships `defaultContext: fork`, which replays the parent transcript
39
+ * into every child. When parent and child resolve to the same model, Pi keeps
40
+ * the inherited signed thinking blocks and Anthropic rejects the request with
41
+ * "`thinking` blocks in the latest assistant message cannot be modified".
42
+ *
43
+ * Returns true only when the file was rewritten.
44
+ */
45
+ export function seedWorkerContext(dir) {
46
+ const file = join(dir, "settings.json");
47
+ let settings;
48
+ try {
49
+ settings = asObject(JSON.parse(readFileSync(file, "utf-8")));
50
+ } catch {
51
+ // No settings file yet, or one Pi itself cannot read. Writing here would
52
+ // destroy content we failed to parse, so leave it untouched.
53
+ return false;
54
+ }
55
+ if (!settings) return false;
56
+
57
+ const subagents = asObject(settings.subagents) ?? {};
58
+ const overrides = asObject(subagents.agentOverrides) ?? {};
59
+ if ("worker" in overrides) return false;
60
+
61
+ settings.subagents = {
62
+ ...subagents,
63
+ agentOverrides: { ...overrides, worker: { defaultContext: "fresh" } },
64
+ };
65
+
66
+ // Rename onto the target so a crash mid-write cannot truncate settings.
67
+ const staged = `${file}.proper-base`;
68
+ writeFileSync(staged, `${JSON.stringify(settings, null, 2)}\n`, "utf-8");
69
+ renameSync(staged, file);
70
+ return true;
71
+ }
72
+
73
+ if (process.argv[1] === fileURLToPath(import.meta.url)) {
74
+ try {
75
+ if (seedWorkerContext(agentDir())) {
76
+ console.log(
77
+ "proper-base: set subagents.agentOverrides.worker.defaultContext to fresh",
78
+ );
79
+ }
80
+ } catch (error) {
81
+ // A failed convenience default must never fail the install.
82
+ console.warn(`proper-base: could not seed settings.json: ${error}`);
83
+ }
84
+ }