@xynogen/pix-display 0.1.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 +39 -0
- package/package.json +45 -0
- package/src/index.ts +20 -0
- package/src/paste-chips.ts +217 -0
- package/src/thinking.ts +207 -0
package/README.md
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# pix-display
|
|
2
|
+
|
|
3
|
+
Pi core extension — paste chip rendering and thinking block display.
|
|
4
|
+
|
|
5
|
+
## What it does
|
|
6
|
+
|
|
7
|
+
Two features, always on when installed:
|
|
8
|
+
|
|
9
|
+
**Paste chips.** Replaces Pi's paste markers (`[paste #1 2232 chars]`) with styled icon chips (`text 2.2k chars` for text, `image #1` for images). Collapses pasted image paths into markers in the buffer while showing human-readable labels on screen. The display rewrite is purely visual — the buffer keeps the real path for the model.
|
|
10
|
+
|
|
11
|
+
**Thinking blocks.** Converts leaked reasoning tags (`<think>`/`<thinking>`) from some providers into native Pi `thinking` content blocks, which render dim + italic via the `thinkingText` theme token. No ANSI injection, no markdown blockquote shim. Applies during streaming (`message_update`) and finalization (`message_end`).
|
|
12
|
+
|
|
13
|
+
Both features are registered at session start and cleaned up at session shutdown. In non-interactive (JSON/RPC) mode they are no-ops.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
pi install npm:@xynogen/pix-display
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
> Also included in [`@xynogen/pix-core`](https://www.npmjs.com/package/@xynogen/pix-core):
|
|
22
|
+
>
|
|
23
|
+
> ```bash
|
|
24
|
+
> pi install npm:@xynogen/pix-core
|
|
25
|
+
> ```
|
|
26
|
+
|
|
27
|
+
## Full distro
|
|
28
|
+
|
|
29
|
+
Source: [github.com/xynogen/pix-mono](https://github.com/xynogen/pix-mono)
|
|
30
|
+
|
|
31
|
+
To install the complete pix suite (all packages + Pi itself):
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
curl -fsSL https://raw.githubusercontent.com/xynogen/pix-mono/main/scripts/install.sh | sh
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## License
|
|
38
|
+
|
|
39
|
+
MIT
|
package/package.json
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@xynogen/pix-display",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Pi core extension — paste chip rendering and thinking block display",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "src/index.ts",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"test": "bun test"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"src",
|
|
12
|
+
"README.md",
|
|
13
|
+
"LICENSE"
|
|
14
|
+
],
|
|
15
|
+
"pi": {
|
|
16
|
+
"extensions": [
|
|
17
|
+
"src/index.ts"
|
|
18
|
+
]
|
|
19
|
+
},
|
|
20
|
+
"keywords": [
|
|
21
|
+
"pi",
|
|
22
|
+
"pi-package",
|
|
23
|
+
"pi-extension",
|
|
24
|
+
"paste-chips",
|
|
25
|
+
"thinking",
|
|
26
|
+
"display"
|
|
27
|
+
],
|
|
28
|
+
"author": "xynogen",
|
|
29
|
+
"license": "MIT",
|
|
30
|
+
"repository": {
|
|
31
|
+
"type": "git",
|
|
32
|
+
"url": "git+https://github.com/xynogen/pix-mono.git",
|
|
33
|
+
"directory": "packages/pix-display"
|
|
34
|
+
},
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"access": "public"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"@xynogen/pix-pretty": "*"
|
|
40
|
+
},
|
|
41
|
+
"peerDependencies": {
|
|
42
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
43
|
+
"@earendil-works/pi-tui": "*"
|
|
44
|
+
}
|
|
45
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pix-display — Pi core extension: paste chip rendering + thinking block display.
|
|
3
|
+
*
|
|
4
|
+
* Entry point: activates both paste-chips and thinking extensions at
|
|
5
|
+
* session start. In non-interactive modes (JSON/RPC) both are no-ops.
|
|
6
|
+
*
|
|
7
|
+
* Modules:
|
|
8
|
+
* paste-chips.ts ChipEditor overlay, marker restyling, image path collapse
|
|
9
|
+
* thinking.ts Leaked reasoning tag → native thinking content blocks
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
13
|
+
|
|
14
|
+
import pasteChipsExtension from "./paste-chips.js";
|
|
15
|
+
import thinkingExtension from "./thinking.js";
|
|
16
|
+
|
|
17
|
+
export default function pixDisplayExtension(pi: ExtensionAPI): void {
|
|
18
|
+
pasteChipsExtension(pi);
|
|
19
|
+
thinkingExtension(pi);
|
|
20
|
+
}
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* paste-chips — collapse pasted image paths into Pi paste markers, and
|
|
3
|
+
* re-render all paste markers with type-aware labels.
|
|
4
|
+
*
|
|
5
|
+
* /tmp/pi-clipboard-abc.png → buffer: [paste #1 58 chars]
|
|
6
|
+
* display: [paste image #1]
|
|
7
|
+
*
|
|
8
|
+
* long pasted text → buffer: [paste #2 +42 lines]
|
|
9
|
+
* display: [paste text +42]
|
|
10
|
+
*
|
|
11
|
+
* Atomic deletion + cursor handling come from Pi's marker grammar.
|
|
12
|
+
* On submit, getExpandedText() restores the real path/text for the model.
|
|
13
|
+
* The display rewrite is purely visual (render layer); buffer is untouched.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import type {
|
|
17
|
+
ExtensionAPI,
|
|
18
|
+
KeybindingsManager,
|
|
19
|
+
} from "@earendil-works/pi-coding-agent";
|
|
20
|
+
import { CustomEditor } from "@earendil-works/pi-coding-agent";
|
|
21
|
+
import type { EditorTheme, TUI } from "@earendil-works/pi-tui";
|
|
22
|
+
import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
23
|
+
import { BOLD, FG_BLUE, FG_DIM, FG_GREEN, RST } from "@xynogen/pix-pretty/ansi";
|
|
24
|
+
|
|
25
|
+
// Upstream stopped re-exporting `EditorFactory` from the package entry point,
|
|
26
|
+
// so we reconstruct its signature locally from the still-exported primitives.
|
|
27
|
+
// This matches ctx.ui.setEditorComponent's expected factory shape.
|
|
28
|
+
type EditorFactory = (
|
|
29
|
+
tui: TUI,
|
|
30
|
+
theme: EditorTheme,
|
|
31
|
+
keybindings: KeybindingsManager,
|
|
32
|
+
) => CustomEditor;
|
|
33
|
+
|
|
34
|
+
// ─── Constants ────────────────────────────────────────────────────────────────
|
|
35
|
+
|
|
36
|
+
const IMAGE_EXTS = new Set([
|
|
37
|
+
".png",
|
|
38
|
+
".jpg",
|
|
39
|
+
".jpeg",
|
|
40
|
+
".gif",
|
|
41
|
+
".webp",
|
|
42
|
+
".bmp",
|
|
43
|
+
".tif",
|
|
44
|
+
".tiff",
|
|
45
|
+
".heic",
|
|
46
|
+
".heif",
|
|
47
|
+
]);
|
|
48
|
+
|
|
49
|
+
// Group 1 = prefix char (or empty at start), Group 2 = path
|
|
50
|
+
const PATH_RE = /(^|[^\w/])((?:~|\/)[^\s,;'"(){}[\]]+)/g;
|
|
51
|
+
|
|
52
|
+
// Pi's marker grammar — must match exactly for atomic segmentation.
|
|
53
|
+
// e.g. `[paste #1 58 chars]` or `[paste #2 +42 lines]`
|
|
54
|
+
const MARKER_RE = /\[paste #(\d+)( (\+(\d+) lines|(\d+) chars))?\]/g;
|
|
55
|
+
|
|
56
|
+
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
|
57
|
+
|
|
58
|
+
function extOf(p: string): string {
|
|
59
|
+
const dot = p.lastIndexOf(".");
|
|
60
|
+
return dot >= 0 ? p.slice(dot).toLowerCase() : "";
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function isImagePath(p: string): boolean {
|
|
64
|
+
return IMAGE_EXTS.has(extOf(p));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function makeMarker(id: number, charCount: number): string {
|
|
68
|
+
return `[paste #${id} ${charCount} chars]`;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// ─── Editor internals (Pi's TS-private fields are runtime-public JS) ─────────
|
|
72
|
+
|
|
73
|
+
type EditorInternals = {
|
|
74
|
+
pastes: Map<number, string>;
|
|
75
|
+
pasteCounter: number;
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
// ─── Path → marker rewriter ──────────────────────────────────────────────────
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Walk `text`, for each image path: allocate a new paste ID, register the
|
|
82
|
+
* real path in editor.pastes, remember the ID as an image, and emit a
|
|
83
|
+
* Pi-format marker so deletion is atomic.
|
|
84
|
+
*/
|
|
85
|
+
function replaceImagePaths(
|
|
86
|
+
text: string,
|
|
87
|
+
internals: EditorInternals,
|
|
88
|
+
imageIds: Set<number>,
|
|
89
|
+
): string {
|
|
90
|
+
return text.replace(PATH_RE, (_, prefix: string, rawPath: string) => {
|
|
91
|
+
if (!isImagePath(rawPath)) return prefix + rawPath;
|
|
92
|
+
internals.pasteCounter += 1;
|
|
93
|
+
const id = internals.pasteCounter;
|
|
94
|
+
internals.pastes.set(id, rawPath);
|
|
95
|
+
imageIds.add(id);
|
|
96
|
+
return prefix + makeMarker(id, rawPath.length);
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// ─── Display rewriter ────────────────────────────────────────────────────────
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Re-style every paste marker in a rendered line:
|
|
104
|
+
* image → ` image #N` with blue icon/label
|
|
105
|
+
* text → ` text Lines lines` or ` text Chars chars` with green icon/label
|
|
106
|
+
*
|
|
107
|
+
* Width-preserving is not required — Pi re-wraps each render call.
|
|
108
|
+
*/
|
|
109
|
+
export function restyleMarkers(line: string, imageIds: Set<number>): string {
|
|
110
|
+
return line.replace(
|
|
111
|
+
MARKER_RE,
|
|
112
|
+
(_full, idStr, _g2, _g3, linesStr, charsStr) => {
|
|
113
|
+
const id = Number.parseInt(idStr, 10);
|
|
114
|
+
if (imageIds.has(id)) {
|
|
115
|
+
return chip(FG_BLUE, "", "image", `#${id}`);
|
|
116
|
+
}
|
|
117
|
+
if (linesStr) {
|
|
118
|
+
return chip(FG_GREEN, "", "text", `${linesStr} lines`);
|
|
119
|
+
}
|
|
120
|
+
if (charsStr) {
|
|
121
|
+
return chip(FG_GREEN, "", "text", `${compactNumber(charsStr)} chars`);
|
|
122
|
+
}
|
|
123
|
+
return chip(FG_GREEN, "", "text", `#${id}`);
|
|
124
|
+
},
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function chip(
|
|
129
|
+
color: string,
|
|
130
|
+
icon: string,
|
|
131
|
+
label: string,
|
|
132
|
+
meta: string,
|
|
133
|
+
): string {
|
|
134
|
+
return `${color}${BOLD}${icon} ${label}${RST}${FG_DIM} ${meta}${RST}`;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** True when `text` ends with a Pi paste marker (chip), e.g. `[paste #1 58 chars]`. */
|
|
138
|
+
export function endsWithMarker(text: string): boolean {
|
|
139
|
+
return /\[paste #\d+[^\]]*\]$/.test(text);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function compactNumber(raw: string): string {
|
|
143
|
+
const n = Number.parseInt(raw, 10);
|
|
144
|
+
if (!Number.isFinite(n)) return raw;
|
|
145
|
+
if (n < 1_000) return `${n}`;
|
|
146
|
+
if (n < 1_000_000) return `${(n / 1_000).toFixed(1).replace(/\.0$/, "")}k`;
|
|
147
|
+
return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, "")}m`;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// ─── Custom editor ────────────────────────────────────────────────────────────
|
|
151
|
+
|
|
152
|
+
// handlePaste is TS-private in CustomEditor but runtime-public JS. We patch it
|
|
153
|
+
// per-instance, capturing the base implementation, so large text pastes get the
|
|
154
|
+
// same trailing-space treatment as image chips.
|
|
155
|
+
type PasteHandler = { handlePaste(text: string): void };
|
|
156
|
+
|
|
157
|
+
class ChipEditor extends CustomEditor {
|
|
158
|
+
private readonly imageIds = new Set<number>();
|
|
159
|
+
|
|
160
|
+
constructor(...args: ConstructorParameters<typeof CustomEditor>) {
|
|
161
|
+
super(...args);
|
|
162
|
+
this.patchHandlePaste();
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
override insertTextAtCursor(text: string): void {
|
|
166
|
+
const internals = this as unknown as EditorInternals;
|
|
167
|
+
const replaced = replaceImagePaths(text, internals, this.imageIds);
|
|
168
|
+
// Append a trailing space when the insertion ends with a paste marker so
|
|
169
|
+
// the cursor lands after the chip rather than inside it.
|
|
170
|
+
super.insertTextAtCursor(
|
|
171
|
+
endsWithMarker(replaced) ? `${replaced} ` : replaced,
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
private patchHandlePaste(): void {
|
|
176
|
+
const self = this as unknown as PasteHandler;
|
|
177
|
+
const base = self.handlePaste.bind(self);
|
|
178
|
+
self.handlePaste = (pastedText: string) => {
|
|
179
|
+
const before = this.getText();
|
|
180
|
+
base(pastedText);
|
|
181
|
+
const after = this.getText();
|
|
182
|
+
// Only nudge a space when the paste collapsed into a marker chip;
|
|
183
|
+
// inline small pastes (no marker) are left untouched.
|
|
184
|
+
if (endsWithMarker(after) && after !== before) {
|
|
185
|
+
super.insertTextAtCursor(" ");
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
override render(width: number): string[] {
|
|
191
|
+
const raw = super.render(width);
|
|
192
|
+
return raw.map((line) => {
|
|
193
|
+
const restyled = restyleMarkers(line, this.imageIds);
|
|
194
|
+
// Restyling may widen lines (e.g. "#1" → "text"), so clamp to width.
|
|
195
|
+
if (visibleWidth(restyled) > width) {
|
|
196
|
+
return truncateToWidth(restyled, width, "");
|
|
197
|
+
}
|
|
198
|
+
return restyled;
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// ─── Extension ────────────────────────────────────────────────────────────────
|
|
204
|
+
|
|
205
|
+
export default function (pi: ExtensionAPI) {
|
|
206
|
+
pi.on("session_start", (_event, ctx) => {
|
|
207
|
+
if (!ctx.hasUI) return;
|
|
208
|
+
const factory: EditorFactory = (tui, theme, keybindings) =>
|
|
209
|
+
new ChipEditor(tui, theme, keybindings);
|
|
210
|
+
ctx.ui.setEditorComponent(factory);
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
pi.on("session_shutdown", (_event, ctx) => {
|
|
214
|
+
if (!ctx.hasUI) return;
|
|
215
|
+
ctx.ui.setEditorComponent(undefined);
|
|
216
|
+
});
|
|
217
|
+
}
|
package/src/thinking.ts
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Convert leaked reasoning tags into native `thinking` content blocks.
|
|
3
|
+
*
|
|
4
|
+
* Some openai-compatible providers leak raw <think>/<thinking> tags into the
|
|
5
|
+
* visible assistant `content[].text` (the real reasoning travels the proper
|
|
6
|
+
* `reasoning_content` channel). Instead of stripping or restyling them, we
|
|
7
|
+
* split each affected text block into ordered `text` + `thinking` content
|
|
8
|
+
* blocks. Pi renders `thinking` blocks dim + italic via the `thinkingText`
|
|
9
|
+
* theme token natively (see assistant-message.ts) — no ANSI injection, no
|
|
10
|
+
* markdown blockquote shim.
|
|
11
|
+
*
|
|
12
|
+
* Approach:
|
|
13
|
+
* - During streaming (`message_update`), rebuild the event's message so a
|
|
14
|
+
* reasoning block appears the moment the open tag streams in — no waiting
|
|
15
|
+
* for the close tag. splitThinking() captures the dangling-open case, and
|
|
16
|
+
* a trailing half-streamed tag (e.g. "<thin") is stripped so it never
|
|
17
|
+
* flashes as literal text.
|
|
18
|
+
*
|
|
19
|
+
* Safety: `event.message` is a per-event shallow copy, but its content
|
|
20
|
+
* blocks are the provider's LIVE accumulating objects (providers do
|
|
21
|
+
* `block.text += delta`). We therefore never mutate text blocks in
|
|
22
|
+
* place — we replace `message.content` with fresh block objects. The
|
|
23
|
+
* TUI receives the same event object after extensions run, so the rebuilt
|
|
24
|
+
* content is what gets rendered live.
|
|
25
|
+
*
|
|
26
|
+
* - On `message_end`, split every affected text block and return the
|
|
27
|
+
* replacement via the supported channel. (The finalized message comes
|
|
28
|
+
* from `response.result()` — a fresh object that never saw the streaming
|
|
29
|
+
* rebuild — so this step is still required for persistence.)
|
|
30
|
+
*
|
|
31
|
+
* Persistence trade-off: the replacement is persisted and round-trips to the
|
|
32
|
+
* provider next turn. The synthesized `thinking` blocks carry no
|
|
33
|
+
* thinkingSignature (none was received — the reasoning leaked into the text
|
|
34
|
+
* channel), so signature-validating APIs (e.g. Anthropic) may reject or drop
|
|
35
|
+
* them on multi-turn. Accepted in exchange for native dim+italic rendering.
|
|
36
|
+
*
|
|
37
|
+
* To add a new tag variant, append to TAG_NAMES below.
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
41
|
+
|
|
42
|
+
// Reasoning tag names to render. Add new variants here.
|
|
43
|
+
const TAG_NAMES = ["think", "thinking"] as const;
|
|
44
|
+
const TAG_ALT = TAG_NAMES.join("|");
|
|
45
|
+
|
|
46
|
+
// Closed block: <think>...</think>
|
|
47
|
+
const CLOSED_BLOCK_RE = new RegExp(`<(${TAG_ALT})>([\\s\\S]*?)<\\/\\1>`, "gi");
|
|
48
|
+
// Dangling open block with no close (stream cut off, or close never emitted)
|
|
49
|
+
const OPEN_TAIL_RE = new RegExp(`<(${TAG_ALT})>([\\s\\S]*)$`, "i");
|
|
50
|
+
// Any orphan tags left over.
|
|
51
|
+
const ORPHAN_TAG_RE = new RegExp(`<\\/?(${TAG_ALT})>`, "gi");
|
|
52
|
+
|
|
53
|
+
interface TextBlock {
|
|
54
|
+
type: "text";
|
|
55
|
+
text: string;
|
|
56
|
+
}
|
|
57
|
+
interface ThinkingBlock {
|
|
58
|
+
type: "thinking";
|
|
59
|
+
thinking: string;
|
|
60
|
+
}
|
|
61
|
+
type Block = TextBlock | ThinkingBlock | { type: string; [k: string]: unknown };
|
|
62
|
+
interface Msg {
|
|
63
|
+
role?: string;
|
|
64
|
+
content?: Block[];
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Trailing half-streamed tag, e.g. "<", "</", "<thin", "</thinkin".
|
|
68
|
+
// Only used during streaming so an incomplete tag never flashes as text.
|
|
69
|
+
const PARTIAL_TAIL_RE = /<\/?([a-zA-Z]*)$/;
|
|
70
|
+
|
|
71
|
+
function stripPartialTailTag(text: string): string {
|
|
72
|
+
const match = text.match(PARTIAL_TAIL_RE);
|
|
73
|
+
if (!match) return text;
|
|
74
|
+
const fragment = match[1].toLowerCase();
|
|
75
|
+
if (TAG_NAMES.some((tag) => tag.startsWith(fragment))) {
|
|
76
|
+
return text.slice(0, match.index);
|
|
77
|
+
}
|
|
78
|
+
return text;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Push a text block only when it has visible content. Surrounding whitespace
|
|
82
|
+
// between reasoning and answer text is dropped so the native renderer doesn't
|
|
83
|
+
// emit stray blank paragraphs.
|
|
84
|
+
// True when the text contains any reasoning tag (open, close, or orphan).
|
|
85
|
+
function hasReasoningTag(text: string): boolean {
|
|
86
|
+
ORPHAN_TAG_RE.lastIndex = 0;
|
|
87
|
+
return ORPHAN_TAG_RE.test(text);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function pushText(blocks: Block[], text: string): void {
|
|
91
|
+
const trimmed = text.trim();
|
|
92
|
+
if (trimmed) blocks.push({ type: "text", text: trimmed });
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function pushThinking(blocks: Block[], thinking: string): void {
|
|
96
|
+
const trimmed = thinking.trim();
|
|
97
|
+
if (trimmed) blocks.push({ type: "thinking", thinking: trimmed });
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Split leaked reasoning text into ordered native content blocks.
|
|
102
|
+
*
|
|
103
|
+
* Reasoning spans (`<think>…</think>`, plus a trailing unclosed `<think>…`)
|
|
104
|
+
* become real `thinking` blocks, which pi renders dim + italic via the
|
|
105
|
+
* `thinkingText` theme token — no ANSI injection, no markdown blockquote.
|
|
106
|
+
* Everything else stays a `text` block. Returns the original single text
|
|
107
|
+
* block unchanged when no reasoning tags are present.
|
|
108
|
+
*/
|
|
109
|
+
function splitThinking(text: string): Block[] {
|
|
110
|
+
if (!hasReasoningTag(text)) {
|
|
111
|
+
return [{ type: "text", text }];
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const blocks: Block[] = [];
|
|
115
|
+
let rest = text;
|
|
116
|
+
|
|
117
|
+
// Consume closed reasoning blocks left-to-right, preserving order with the
|
|
118
|
+
// surrounding answer text.
|
|
119
|
+
CLOSED_BLOCK_RE.lastIndex = 0;
|
|
120
|
+
let match = CLOSED_BLOCK_RE.exec(rest);
|
|
121
|
+
while (match) {
|
|
122
|
+
pushText(blocks, rest.slice(0, match.index));
|
|
123
|
+
pushThinking(blocks, match[2]);
|
|
124
|
+
rest = rest.slice(match.index + match[0].length);
|
|
125
|
+
CLOSED_BLOCK_RE.lastIndex = 0;
|
|
126
|
+
match = CLOSED_BLOCK_RE.exec(rest);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// A dangling open block (close tag not yet streamed / never emitted): the
|
|
130
|
+
// remainder after the open tag is reasoning.
|
|
131
|
+
const openMatch = OPEN_TAIL_RE.exec(rest);
|
|
132
|
+
if (openMatch) {
|
|
133
|
+
// Leading text may still carry orphan tags (e.g. a stray `</think>`).
|
|
134
|
+
pushText(
|
|
135
|
+
blocks,
|
|
136
|
+
openMatch.input.slice(0, openMatch.index).replace(ORPHAN_TAG_RE, ""),
|
|
137
|
+
);
|
|
138
|
+
pushThinking(blocks, openMatch[2].replace(ORPHAN_TAG_RE, ""));
|
|
139
|
+
} else {
|
|
140
|
+
// Strip any orphan tags from the trailing text.
|
|
141
|
+
pushText(blocks, rest.replace(ORPHAN_TAG_RE, ""));
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// All-empty (e.g. `<think></think>`) collapses to a single empty text block
|
|
145
|
+
// so the message never becomes contentless.
|
|
146
|
+
return blocks.length > 0 ? blocks : [{ type: "text", text: "" }];
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// Export for testing
|
|
150
|
+
export { splitThinking, stripPartialTailTag };
|
|
151
|
+
|
|
152
|
+
export default function thinkingExtension(pi: ExtensionAPI) {
|
|
153
|
+
// Live conversion during streaming: rebuild the event's message so a native
|
|
154
|
+
// thinking block appears as soon as the open tag streams in, token by token.
|
|
155
|
+
pi.on("message_update", (event) => {
|
|
156
|
+
const ev = event as {
|
|
157
|
+
message?: Msg;
|
|
158
|
+
assistantMessageEvent?: { type?: string };
|
|
159
|
+
};
|
|
160
|
+
const msg = ev.message;
|
|
161
|
+
if (msg?.role !== "assistant" || !Array.isArray(msg.content)) return;
|
|
162
|
+
|
|
163
|
+
// Only text stream events can change text blocks; skip toolcall/thinking
|
|
164
|
+
// channel deltas to avoid pointless re-renders.
|
|
165
|
+
const streamType = ev.assistantMessageEvent?.type;
|
|
166
|
+
if (streamType && !streamType.startsWith("text_")) return;
|
|
167
|
+
|
|
168
|
+
msg.content = msg.content.flatMap((block): Block[] => {
|
|
169
|
+
if (block.type !== "text") return [block];
|
|
170
|
+
const tb = block as TextBlock;
|
|
171
|
+
if (typeof tb.text !== "string" || !tb.text.includes("<")) return [block];
|
|
172
|
+
// Strip a half-streamed tag so it never flashes as literal text.
|
|
173
|
+
const stripped = stripPartialTailTag(tb.text);
|
|
174
|
+
// Nothing reasoning-related: leave unrelated "<" text alone entirely.
|
|
175
|
+
if (!hasReasoningTag(stripped) && stripped === tb.text) return [block];
|
|
176
|
+
// New objects — never mutate the provider's accumulating block.
|
|
177
|
+
return splitThinking(stripped);
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
pi.on("message_end", (event) => {
|
|
182
|
+
const msg = (event as { message?: Msg }).message;
|
|
183
|
+
if (msg?.role !== "assistant" || !Array.isArray(msg.content)) return;
|
|
184
|
+
|
|
185
|
+
let changed = false;
|
|
186
|
+
const content = msg.content.flatMap((block): Block[] => {
|
|
187
|
+
if (block.type !== "text") return [block];
|
|
188
|
+
const tb = block as TextBlock;
|
|
189
|
+
if (typeof tb.text !== "string") return [block];
|
|
190
|
+
if (!hasReasoningTag(tb.text)) return [block];
|
|
191
|
+
changed = true;
|
|
192
|
+
return splitThinking(tb.text);
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
// Return the replacement so the native thinking blocks are persisted.
|
|
196
|
+
// Persistence note: this rewrites leaked reasoning from `text` into real
|
|
197
|
+
// `thinking` content blocks, which round-trip to the provider next turn.
|
|
198
|
+
// The blocks carry no thinkingSignature (we never received one — the
|
|
199
|
+
// reasoning leaked into the text channel), so signature-validating APIs
|
|
200
|
+
// may reject or drop them on multi-turn. Accepted trade-off for native
|
|
201
|
+
// dim+italic rendering via the `thinkingText` theme token.
|
|
202
|
+
if (changed) {
|
|
203
|
+
msg.content = content;
|
|
204
|
+
return { message: msg as unknown as never };
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
}
|