proper-base 0.5.1 → 0.7.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/README.md +44 -13
- package/UPDATES.md +129 -0
- package/index.ts +107 -108
- package/package.json +5 -5
- package/src/auto-update/availability.ts +132 -0
- package/src/auto-update/index.ts +403 -0
- package/src/auto-update/inventory.mjs +96 -0
- package/src/auto-update/readiness.ts +94 -0
- package/src/auto-update/runtime.ts +268 -0
- package/src/auto-update/settings.ts +146 -0
- package/src/base-keybindings.ts +114 -0
- package/src/clipboard-selection.ts +310 -0
- package/src/fast-mode.ts +83 -14
- package/src/footer-colors.ts +114 -13
- package/src/host-interop.ts +49 -0
- package/src/image-preview.ts +75 -66
- package/src/overlay-scroll.ts +130 -0
- package/src/proactive-delegation.ts +110 -0
- package/src/prompt-display-host.ts +136 -0
- package/src/prompt-display.ts +44 -82
- package/src/prompt-sections.ts +16 -0
- package/src/session-list.ts +132 -21
- package/src/skill-context.ts +52 -14
- package/src/startup-defaults.ts +4 -122
- package/src/sticky-defaults.ts +196 -0
- package/src/transient-retry.ts +5 -1
- package/src/wheel-scroll.ts +24 -27
- package/src/widget-transcript.ts +120 -0
package/src/image-preview.ts
CHANGED
|
@@ -1,10 +1,8 @@
|
|
|
1
|
-
import { readFileSync } from "node:fs";
|
|
2
1
|
import { basename, extname, isAbsolute } from "node:path";
|
|
3
2
|
import {
|
|
4
3
|
type Component,
|
|
5
4
|
getCapabilities,
|
|
6
5
|
getCellDimensions,
|
|
7
|
-
getImageDimensions,
|
|
8
6
|
Image,
|
|
9
7
|
type ImageTheme,
|
|
10
8
|
Loader,
|
|
@@ -75,11 +73,6 @@ type Preview = {
|
|
|
75
73
|
cancelThumbnail: (() => void) | undefined;
|
|
76
74
|
};
|
|
77
75
|
|
|
78
|
-
type PreviewImagePlan = {
|
|
79
|
-
image: PreviewImage | undefined;
|
|
80
|
-
thumbnail: { widthPx: number; heightPx: number } | undefined;
|
|
81
|
-
};
|
|
82
|
-
|
|
83
76
|
export type ImagePreviewController = {
|
|
84
77
|
prepare(text: string): string;
|
|
85
78
|
clear(): void;
|
|
@@ -142,49 +135,63 @@ function sharpThumbnail(
|
|
|
142
135
|
done: (image: PreviewImage | undefined) => void,
|
|
143
136
|
): () => void {
|
|
144
137
|
let cancelled = false;
|
|
145
|
-
const
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
138
|
+
const metadataPipeline = sharp(path, { pages: 1 }).timeout({
|
|
139
|
+
seconds: THUMBNAIL_TIMEOUT_SECONDS,
|
|
140
|
+
});
|
|
141
|
+
let outputPipeline: ReturnType<typeof sharp> | undefined;
|
|
142
|
+
void metadataPipeline
|
|
143
|
+
.metadata()
|
|
144
|
+
.then((metadata) => {
|
|
145
|
+
if (cancelled) return undefined;
|
|
146
|
+
const orientation = metadata.orientation ?? 1;
|
|
147
|
+
const width = orientation >= 5 ? metadata.height : metadata.width;
|
|
148
|
+
const height = orientation >= 5 ? metadata.width : metadata.height;
|
|
149
|
+
outputPipeline = sharp(path, { pages: 1 }).timeout({
|
|
150
|
+
seconds: THUMBNAIL_TIMEOUT_SECONDS,
|
|
151
|
+
});
|
|
152
|
+
if (width && height && width <= widthPx && height <= heightPx) {
|
|
153
|
+
return outputPipeline
|
|
154
|
+
.rotate()
|
|
155
|
+
.toBuffer()
|
|
156
|
+
.then((output) => ({
|
|
157
|
+
base64: output.toString("base64"),
|
|
158
|
+
mimeType: MIME_TYPES[extname(path).toLowerCase()] ?? "image/png",
|
|
159
|
+
}));
|
|
160
160
|
}
|
|
161
|
+
return outputPipeline
|
|
162
|
+
.rotate()
|
|
163
|
+
.resize({
|
|
164
|
+
width: widthPx,
|
|
165
|
+
height: heightPx,
|
|
166
|
+
fit: "inside",
|
|
167
|
+
withoutEnlargement: true,
|
|
168
|
+
})
|
|
169
|
+
.png()
|
|
170
|
+
.toBuffer()
|
|
171
|
+
.then((output) => ({
|
|
172
|
+
base64: output.toString("base64"),
|
|
173
|
+
mimeType: "image/png",
|
|
174
|
+
}));
|
|
175
|
+
})
|
|
176
|
+
.then((image) => {
|
|
177
|
+
if (!cancelled && image) done(image);
|
|
161
178
|
})
|
|
162
179
|
.catch(() => {
|
|
163
180
|
if (!cancelled) done(undefined);
|
|
164
181
|
});
|
|
165
182
|
return () => {
|
|
166
183
|
cancelled = true;
|
|
167
|
-
|
|
184
|
+
metadataPipeline.destroy();
|
|
185
|
+
outputPipeline?.destroy();
|
|
168
186
|
};
|
|
169
187
|
}
|
|
170
188
|
|
|
171
|
-
export function
|
|
172
|
-
mimeType: string,
|
|
173
|
-
source: Buffer,
|
|
174
|
-
): PreviewImagePlan {
|
|
175
|
-
const base64 = source.toString("base64");
|
|
176
|
-
const dimensions = getImageDimensions(base64, mimeType);
|
|
189
|
+
export function previewPixelBounds(): { widthPx: number; heightPx: number } {
|
|
177
190
|
const cells = getCellDimensions();
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
dimensions.widthPx <= widthPx &&
|
|
183
|
-
dimensions.heightPx <= heightPx
|
|
184
|
-
) {
|
|
185
|
-
return { image: { base64, mimeType }, thumbnail: undefined };
|
|
186
|
-
}
|
|
187
|
-
return { image: undefined, thumbnail: { widthPx, heightPx } };
|
|
191
|
+
return {
|
|
192
|
+
widthPx: Math.max(1, PREVIEW_WIDTH * cells.widthPx),
|
|
193
|
+
heightPx: Math.max(1, PREVIEW_HEIGHT * cells.heightPx),
|
|
194
|
+
};
|
|
188
195
|
}
|
|
189
196
|
|
|
190
197
|
function singleDeletionIndex(
|
|
@@ -360,38 +367,40 @@ export function installImagePreview(
|
|
|
360
367
|
const known = markersByPath.get(path);
|
|
361
368
|
if (known) return known;
|
|
362
369
|
if (!isAbsolute(path) || !CLIPBOARD_IMAGE.test(basename(path))) return;
|
|
363
|
-
|
|
364
|
-
|
|
370
|
+
if (!MIME_TYPES[extname(path).toLowerCase()]) return;
|
|
371
|
+
const marker = `[image ${++counter}]`;
|
|
372
|
+
const preview: Preview = {
|
|
373
|
+
marker,
|
|
374
|
+
path,
|
|
375
|
+
image: undefined,
|
|
376
|
+
cancelThumbnail: undefined,
|
|
377
|
+
};
|
|
378
|
+
previews.set(marker, preview);
|
|
379
|
+
markersByPath.set(path, marker);
|
|
380
|
+
const bounds = previewPixelBounds();
|
|
365
381
|
try {
|
|
366
|
-
|
|
367
|
-
const
|
|
368
|
-
const preview: Preview = {
|
|
369
|
-
marker,
|
|
382
|
+
let completed = false;
|
|
383
|
+
const cancel = thumbnailer(
|
|
370
384
|
path,
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
preview.image = image;
|
|
385
|
-
visibleMarkers = "";
|
|
386
|
-
sync(target.getText?.() ?? "");
|
|
387
|
-
tui.requestRender();
|
|
388
|
-
},
|
|
389
|
-
);
|
|
390
|
-
}
|
|
391
|
-
return marker;
|
|
385
|
+
bounds.widthPx,
|
|
386
|
+
bounds.heightPx,
|
|
387
|
+
(image) => {
|
|
388
|
+
completed = true;
|
|
389
|
+
preview.cancelThumbnail = undefined;
|
|
390
|
+
if (!image || previews.get(marker) !== preview) return;
|
|
391
|
+
preview.image = image;
|
|
392
|
+
visibleMarkers = "";
|
|
393
|
+
sync(target.getText?.() ?? "");
|
|
394
|
+
tui.requestRender();
|
|
395
|
+
},
|
|
396
|
+
);
|
|
397
|
+
if (!completed) preview.cancelThumbnail = cancel;
|
|
392
398
|
} catch {
|
|
399
|
+
previews.delete(marker);
|
|
400
|
+
markersByPath.delete(path);
|
|
393
401
|
return;
|
|
394
402
|
}
|
|
403
|
+
return marker;
|
|
395
404
|
};
|
|
396
405
|
const ingest = (text: string, cursor: number | undefined) => {
|
|
397
406
|
let mappedCursor = cursor;
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import {
|
|
2
|
+
getKeybindings,
|
|
3
|
+
isKeyRelease,
|
|
4
|
+
type TUI,
|
|
5
|
+
type TuiInputListener,
|
|
6
|
+
} from "@earendil-works/pi-tui";
|
|
7
|
+
|
|
8
|
+
const INSTALLED = Symbol.for("pi-proper-base.overlay-scroll");
|
|
9
|
+
// ESC prefix is matched separately: biome bans control characters in
|
|
10
|
+
// regexes, and string literals carry it fine.
|
|
11
|
+
const SGR_MOUSE_TAIL = /^\[<(\d+);(\d+);(\d+)[Mm]$/;
|
|
12
|
+
/** Mirrors pi-tui's private PAGE_SCROLL_OVERLAP. */
|
|
13
|
+
const PAGE_OVERLAP = 4;
|
|
14
|
+
|
|
15
|
+
/** Alternate-screen renderer surface, duck-typed since most of it is private. */
|
|
16
|
+
type ScrollHost = TUI & {
|
|
17
|
+
scrollBy(lines: number): void;
|
|
18
|
+
scrollToTop(): void;
|
|
19
|
+
scrollToBottom(): void;
|
|
20
|
+
isOverlayFocused?(): boolean;
|
|
21
|
+
getPrimaryScrollView?(): { viewportHeight: number };
|
|
22
|
+
routeWheel?(event: {
|
|
23
|
+
direction: number;
|
|
24
|
+
x: number;
|
|
25
|
+
y: number;
|
|
26
|
+
button: number;
|
|
27
|
+
}): void;
|
|
28
|
+
wheelScrollLines?: number;
|
|
29
|
+
[INSTALLED]?: () => void;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/** Same shape pi-tui's parseWheelEvent produces. */
|
|
33
|
+
export function parseWheel(data: string) {
|
|
34
|
+
if (!data.startsWith("\x1b")) return undefined;
|
|
35
|
+
const match = SGR_MOUSE_TAIL.exec(data.slice(1));
|
|
36
|
+
if (!match) return undefined;
|
|
37
|
+
const button = Number.parseInt(match[1] ?? "", 10);
|
|
38
|
+
if ((button & 64) === 0) return undefined;
|
|
39
|
+
const direction = button & 3;
|
|
40
|
+
if (direction !== 0 && direction !== 1) return undefined;
|
|
41
|
+
return {
|
|
42
|
+
direction: direction === 0 ? -1 : 1,
|
|
43
|
+
x: Number.parseInt(match[2] ?? "", 10) - 1,
|
|
44
|
+
y: Number.parseInt(match[3] ?? "", 10) - 1,
|
|
45
|
+
button,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Keep the fullscreen transcript scrollable while an overlay owns focus.
|
|
51
|
+
*
|
|
52
|
+
* Pi's viewport listener declines wheel events and every `tui.altScreen`
|
|
53
|
+
* scroll key as soon as a capturing overlay is focused, so an
|
|
54
|
+
* `ask_user_question` questionnaire freezes the transcript behind it. This
|
|
55
|
+
* listener registers after the renderer's own, so it only ever sees input the
|
|
56
|
+
* viewport (or an overlay's own mouse handler) already passed on, and routes
|
|
57
|
+
* that to the same scroll methods the renderer would have used. Keys are
|
|
58
|
+
* consumed so the overlay never receives a scroll chord; wheel events fall
|
|
59
|
+
* through untouched when no overlay is focused because the renderer already
|
|
60
|
+
* consumed them.
|
|
61
|
+
*
|
|
62
|
+
* Regular mode and renderer shapes without the scroll surface install
|
|
63
|
+
* nothing; a renamed private field only loses the wheel step or page size,
|
|
64
|
+
* not scrolling itself.
|
|
65
|
+
*
|
|
66
|
+
* @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Overlay transcript scrolling]]
|
|
67
|
+
*/
|
|
68
|
+
export function installOverlayScroll(tui: TUI): (() => void) | undefined {
|
|
69
|
+
const host = tui as ScrollHost;
|
|
70
|
+
if (
|
|
71
|
+
typeof host.scrollBy !== "function" ||
|
|
72
|
+
typeof host.scrollToTop !== "function" ||
|
|
73
|
+
typeof host.scrollToBottom !== "function"
|
|
74
|
+
) {
|
|
75
|
+
return undefined;
|
|
76
|
+
}
|
|
77
|
+
host[INSTALLED]?.();
|
|
78
|
+
|
|
79
|
+
const page = () =>
|
|
80
|
+
Math.max(
|
|
81
|
+
1,
|
|
82
|
+
(host.getPrimaryScrollView?.().viewportHeight ?? 1) - PAGE_OVERLAP,
|
|
83
|
+
);
|
|
84
|
+
const half = () =>
|
|
85
|
+
Math.max(
|
|
86
|
+
1,
|
|
87
|
+
Math.floor((host.getPrimaryScrollView?.().viewportHeight ?? 1) / 2),
|
|
88
|
+
);
|
|
89
|
+
|
|
90
|
+
const listener: TuiInputListener = (data) => {
|
|
91
|
+
if (host.isOverlayFocused?.() !== true) return undefined;
|
|
92
|
+
const wheel = parseWheel(data);
|
|
93
|
+
if (wheel) {
|
|
94
|
+
if (typeof host.routeWheel === "function") host.routeWheel(wheel);
|
|
95
|
+
else host.scrollBy(wheel.direction * (host.wheelScrollLines ?? 1));
|
|
96
|
+
return { consume: true };
|
|
97
|
+
}
|
|
98
|
+
if (!data.startsWith("\x1b")) return undefined;
|
|
99
|
+
const kb = getKeybindings();
|
|
100
|
+
const action = kb.matches(data, "tui.altScreen.pageUp")
|
|
101
|
+
? () => host.scrollBy(-page())
|
|
102
|
+
: kb.matches(data, "tui.altScreen.pageDown")
|
|
103
|
+
? () => host.scrollBy(page())
|
|
104
|
+
: kb.matches(data, "tui.altScreen.halfPageUp")
|
|
105
|
+
? () => host.scrollBy(-half())
|
|
106
|
+
: kb.matches(data, "tui.altScreen.halfPageDown")
|
|
107
|
+
? () => host.scrollBy(half())
|
|
108
|
+
: kb.matches(data, "tui.altScreen.lineUp")
|
|
109
|
+
? () => host.scrollBy(-1)
|
|
110
|
+
: kb.matches(data, "tui.altScreen.lineDown")
|
|
111
|
+
? () => host.scrollBy(1)
|
|
112
|
+
: kb.matches(data, "tui.altScreen.top")
|
|
113
|
+
? () => host.scrollToTop()
|
|
114
|
+
: kb.matches(data, "tui.altScreen.bottom")
|
|
115
|
+
? () => host.scrollToBottom()
|
|
116
|
+
: undefined;
|
|
117
|
+
if (!action) return undefined;
|
|
118
|
+
if (!isKeyRelease(data)) action();
|
|
119
|
+
return { consume: true };
|
|
120
|
+
};
|
|
121
|
+
const unsubscribe = tui.addInputListener(listener);
|
|
122
|
+
|
|
123
|
+
const dispose = () => {
|
|
124
|
+
if (host[INSTALLED] !== dispose) return;
|
|
125
|
+
unsubscribe();
|
|
126
|
+
delete host[INSTALLED];
|
|
127
|
+
};
|
|
128
|
+
host[INSTALLED] = dispose;
|
|
129
|
+
return dispose;
|
|
130
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import type { NormalizedBuildSystemPromptOptions } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { appendPromptSection } from "./prompt-sections.ts";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Codex switches GPT-6 Astra into `MultiAgentMode::Proactive` at the Ultra
|
|
8
|
+
* effort: a developer message telling the model to delegate whenever work
|
|
9
|
+
* parallelizes. Pi's subagent policy is the opposite, set by two sentences
|
|
10
|
+
* pi-subagents puts in the system prompt: a tool guideline and a line in
|
|
11
|
+
* the `<advertised_subagents>` catalog. This rewrites exactly those two
|
|
12
|
+
* sentences and appends the Codex paragraph; the preflight instructions
|
|
13
|
+
* around them and the tool description's safety guidance stay as they are.
|
|
14
|
+
*
|
|
15
|
+
* Codex's Ultra also picks each subagent's model. pi-subagents' `models`
|
|
16
|
+
* action lists the whole registry and the tool description says to copy
|
|
17
|
+
* one, so the paragraph also carries the session's scoped models (the same
|
|
18
|
+
* set `/model` shows) and tells the model to choose the best fit per task.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
const GUIDELINE = "Use subagent only when delegation is needed.";
|
|
22
|
+
const CATALOG_SENTENCE =
|
|
23
|
+
"Their descriptions indicate available specializations, not instructions to delegate. Use subagent only when delegation is needed.";
|
|
24
|
+
|
|
25
|
+
const PROACTIVE_GUIDELINE =
|
|
26
|
+
"Delegate to subagents proactively whenever work parallelizes; see Multi-agent mode below.";
|
|
27
|
+
const PROACTIVE_CATALOG_SENTENCE =
|
|
28
|
+
"Their descriptions indicate available specializations; delegate to them proactively whenever work parallelizes.";
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Codex's `PROACTIVE_MULTI_AGENT_MODE_TEXT` retargeted at pi's tool, plus
|
|
32
|
+
* the boundaries and legibility line OpenAI's GPT-6 Astra model guide pairs
|
|
33
|
+
* with it: delegate independent, sizeable work; keep sequential, small, and
|
|
34
|
+
* same-area edits local; own synthesis; keep inter-agent messages readable.
|
|
35
|
+
*/
|
|
36
|
+
export const PROACTIVE_DELEGATION_TEXT = `# Multi-agent mode
|
|
37
|
+
|
|
38
|
+
Proactive multi-agent delegation is active. Any earlier instruction requiring an explicit user request before spawning subagents no longer applies. User requests override this mode.
|
|
39
|
+
|
|
40
|
+
If at any point you can parallelize work by delegating tasks to another agent (no matter if you are root or a subagent), you should do so with the subagent tool if it could save time or improve quality.
|
|
41
|
+
|
|
42
|
+
Delegate work that is independent and large enough to justify a fresh context; keep tightly sequential steps, small tasks where coordination costs more than it saves, and edits to the same area in this session. You own synthesis and the final answer: read every result and decide yourself, never hand a child "based on the findings, do X". Messages you send to other agents may be read by a human, so ensure they are legible and always put proper spaces between words and numbers.`;
|
|
43
|
+
|
|
44
|
+
const MODEL_CHOICE_HEADER =
|
|
45
|
+
"For every delegation choose the model best suited to that task's difficulty and cost, passing it as the subagent tool's exact provider/id model argument. If an active routing extension advertises a task-text override, include that override as well; model= alone does not pin a routed child. Bounded, well-specified subtasks suit cheaper or faster models; reserve the strongest models for decomposition, review, and hard reasoning. Only these models are enabled in this session; a model the subagent models action lists that is missing here must not be used:";
|
|
46
|
+
|
|
47
|
+
/** A scoped model as the delegation text names it. */
|
|
48
|
+
export type ScopedModelRef = { provider: string; id: string };
|
|
49
|
+
|
|
50
|
+
/** The placeholder is a routing entry point, not a concrete model choice. */
|
|
51
|
+
const PLACEHOLDER_PROVIDER = "llm-router";
|
|
52
|
+
|
|
53
|
+
function modelChoiceText(models: readonly ScopedModelRef[]): string {
|
|
54
|
+
const ids = [
|
|
55
|
+
...new Set(
|
|
56
|
+
models
|
|
57
|
+
.filter((m) => m.provider !== PLACEHOLDER_PROVIDER)
|
|
58
|
+
.map((m) => `${m.provider}/${m.id}`),
|
|
59
|
+
),
|
|
60
|
+
];
|
|
61
|
+
if (ids.length === 0) return "";
|
|
62
|
+
return `\n\n${MODEL_CHOICE_HEADER}\n${ids.map((id) => `- ${id}`).join("\n")}`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** `"proactiveDelegation": false` in the agent directory's `proper-base.json` turns it off. */
|
|
66
|
+
export function readProactiveDelegationEnabled(agentDir: string): boolean {
|
|
67
|
+
try {
|
|
68
|
+
const parsed = JSON.parse(
|
|
69
|
+
readFileSync(join(agentDir, "proper-base.json"), "utf8"),
|
|
70
|
+
) as Record<string, unknown> | null;
|
|
71
|
+
return parsed?.proactiveDelegation !== false;
|
|
72
|
+
} catch {
|
|
73
|
+
return true;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Change policy in its structured fields, preserving later contributions. */
|
|
78
|
+
export function applyProactiveDelegation(
|
|
79
|
+
options: NormalizedBuildSystemPromptOptions,
|
|
80
|
+
hasSubagentTool: boolean,
|
|
81
|
+
scopedModels: readonly ScopedModelRef[] = [],
|
|
82
|
+
): void {
|
|
83
|
+
if (
|
|
84
|
+
!hasSubagentTool ||
|
|
85
|
+
options.sections.proper_base_delegation ||
|
|
86
|
+
options.forceSystemPrompt?.includes(PROACTIVE_DELEGATION_TEXT)
|
|
87
|
+
)
|
|
88
|
+
return;
|
|
89
|
+
const rewrite = (text: string) =>
|
|
90
|
+
text
|
|
91
|
+
.replace(CATALOG_SENTENCE, PROACTIVE_CATALOG_SENTENCE)
|
|
92
|
+
.replace(GUIDELINE, PROACTIVE_GUIDELINE);
|
|
93
|
+
options.promptGuidelines = options.promptGuidelines.map(rewrite);
|
|
94
|
+
for (const [name, rules] of Object.entries(options.toolGuidelines)) {
|
|
95
|
+
options.toolGuidelines[name] = rules.map(rewrite);
|
|
96
|
+
}
|
|
97
|
+
for (const [name, text] of Object.entries(options.sections)) {
|
|
98
|
+
options.sections[name] = rewrite(text);
|
|
99
|
+
}
|
|
100
|
+
if (options.customPrompt !== undefined)
|
|
101
|
+
options.customPrompt = rewrite(options.customPrompt);
|
|
102
|
+
options.appendSystemPrompt = rewrite(options.appendSystemPrompt);
|
|
103
|
+
if (options.forceSystemPrompt !== undefined)
|
|
104
|
+
options.forceSystemPrompt = rewrite(options.forceSystemPrompt);
|
|
105
|
+
appendPromptSection(
|
|
106
|
+
options,
|
|
107
|
+
"proper_base_delegation",
|
|
108
|
+
`${PROACTIVE_DELEGATION_TEXT}${modelChoiceText(scopedModels)}`,
|
|
109
|
+
);
|
|
110
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
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
|
+
|
|
11
|
+
type Message = Parameters<SessionManager["appendMessage"]>[0];
|
|
12
|
+
type Manager = Pick<SessionManager, "getBranch">;
|
|
13
|
+
type Controller = { activate(manager: Manager): void; dispose(): void };
|
|
14
|
+
const INSTALLED = Symbol.for("pi-proper-base.prompt-display");
|
|
15
|
+
const host = globalThis as typeof globalThis & { [INSTALLED]?: Controller };
|
|
16
|
+
|
|
17
|
+
/** Pi 0.86 has neither input correlation nor message identity in Markdown hooks.
|
|
18
|
+
* Keep this adapter removable when those APIs exist. Never emulate expansion.
|
|
19
|
+
* @lat: [[lat.md/proper-base/lifecycle#Prompt history lifecycle#Prompt display]]
|
|
20
|
+
*/
|
|
21
|
+
export function installPromptDisplayHost(
|
|
22
|
+
display: PromptDisplayController,
|
|
23
|
+
commands: () => ReadonlyArray<{ name: string; source: string }>,
|
|
24
|
+
marker: MarkdownTransformer,
|
|
25
|
+
): Controller {
|
|
26
|
+
host[INSTALLED]?.dispose();
|
|
27
|
+
let active = true;
|
|
28
|
+
let manager: Manager | undefined;
|
|
29
|
+
const dispatch = new AsyncLocalStorage<{
|
|
30
|
+
raw: string | undefined;
|
|
31
|
+
bound: boolean;
|
|
32
|
+
}>();
|
|
33
|
+
const restorers: Array<() => void> = [];
|
|
34
|
+
const agents = new WeakSet<AgentSession["agent"]>();
|
|
35
|
+
const managers = new WeakSet<SessionManager>();
|
|
36
|
+
|
|
37
|
+
function bindSession(session: AgentSession): void {
|
|
38
|
+
const agent = session.agent;
|
|
39
|
+
if (!agents.has(agent)) {
|
|
40
|
+
agents.add(agent);
|
|
41
|
+
for (const name of ["prompt", "steer", "followUp"] as const) {
|
|
42
|
+
const original = agent[name];
|
|
43
|
+
const wrapped = function (this: typeof agent, ...args: unknown[]) {
|
|
44
|
+
const scope = dispatch.getStore();
|
|
45
|
+
if (active && scope?.raw !== undefined && !scope.bound) {
|
|
46
|
+
const values = (
|
|
47
|
+
Array.isArray(args[0]) ? args[0] : [args[0]]
|
|
48
|
+
) as Message[];
|
|
49
|
+
const message = values.find((value) => value?.role === "user");
|
|
50
|
+
if (message) {
|
|
51
|
+
display.bind(message, scope.raw);
|
|
52
|
+
scope.bound = true;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return Reflect.apply(original, this, args);
|
|
56
|
+
};
|
|
57
|
+
restorers.push(installWrapper(agent, name, wrapped));
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const store = session.sessionManager;
|
|
61
|
+
if (!managers.has(store)) {
|
|
62
|
+
managers.add(store);
|
|
63
|
+
const append = store.appendMessage;
|
|
64
|
+
const wrapped: typeof append = function (this: SessionManager, message) {
|
|
65
|
+
const id = append.call(this, message);
|
|
66
|
+
if (active) display.persist(message, id);
|
|
67
|
+
return id;
|
|
68
|
+
};
|
|
69
|
+
restorers.push(installWrapper(store, "appendMessage", wrapped));
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
for (const name of ["prompt", "steer", "followUp"] as const) {
|
|
74
|
+
const original = AgentSession.prototype[name];
|
|
75
|
+
const wrapped = function (this: AgentSession, ...args: unknown[]) {
|
|
76
|
+
if (!active || this.sessionManager !== manager)
|
|
77
|
+
return Reflect.apply(original, this, args);
|
|
78
|
+
bindSession(this);
|
|
79
|
+
const options = args[name === "prompt" ? 1 : 2] as
|
|
80
|
+
| { source?: string; expandPromptTemplates?: boolean }
|
|
81
|
+
| undefined;
|
|
82
|
+
const text = originalInput(args[0] as string, options);
|
|
83
|
+
const command = /^\/([^\s]+)/.exec(text)?.[1];
|
|
84
|
+
const raw =
|
|
85
|
+
(options?.source ?? "interactive") === "interactive" &&
|
|
86
|
+
options?.expandPromptTemplates !== false &&
|
|
87
|
+
command &&
|
|
88
|
+
commands().some(
|
|
89
|
+
(item) => item.name === command && item.source === "prompt",
|
|
90
|
+
)
|
|
91
|
+
? text
|
|
92
|
+
: undefined;
|
|
93
|
+
return dispatch.run({ raw, bound: false }, () =>
|
|
94
|
+
Reflect.apply(original, this, args),
|
|
95
|
+
);
|
|
96
|
+
};
|
|
97
|
+
restorers.push(installWrapper(AgentSession.prototype, name, wrapped));
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Swap only the text Pi gives its native user component, preserving images,
|
|
101
|
+
// layout and other transformers. Persisted and model-facing text is untouched.
|
|
102
|
+
type InteractiveHost = {
|
|
103
|
+
session: AgentSession;
|
|
104
|
+
getUserMessageText(message: Message): string;
|
|
105
|
+
getMarkdownTransformers(): MarkdownTransformer[];
|
|
106
|
+
};
|
|
107
|
+
const prototype = InteractiveMode.prototype as unknown as InteractiveHost;
|
|
108
|
+
const original = prototype.getUserMessageText;
|
|
109
|
+
const wrapped: typeof original = function (this: InteractiveHost, message) {
|
|
110
|
+
if (!active || !this.getMarkdownTransformers().includes(marker))
|
|
111
|
+
return original.call(this, message);
|
|
112
|
+
if (manager !== this.session.sessionManager) {
|
|
113
|
+
// Reload rebuilds chat before session_start. Resolve entry identities now.
|
|
114
|
+
manager = this.session.sessionManager;
|
|
115
|
+
display.restore(manager.getBranch());
|
|
116
|
+
}
|
|
117
|
+
return display.rawFor(message) ?? original.call(this, message);
|
|
118
|
+
};
|
|
119
|
+
restorers.push(installWrapper(prototype, "getUserMessageText", wrapped));
|
|
120
|
+
|
|
121
|
+
const controller: Controller = {
|
|
122
|
+
activate(next) {
|
|
123
|
+
manager = next;
|
|
124
|
+
display.restore(next.getBranch());
|
|
125
|
+
},
|
|
126
|
+
dispose() {
|
|
127
|
+
active = false;
|
|
128
|
+
for (const restore of restorers.reverse()) restore();
|
|
129
|
+
dispatch.disable();
|
|
130
|
+
display.clear();
|
|
131
|
+
if (host[INSTALLED] === controller) delete host[INSTALLED];
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
host[INSTALLED] = controller;
|
|
135
|
+
return controller;
|
|
136
|
+
}
|