pal-code 0.0.16 → 0.0.18
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 +9 -6
- package/SYSTEM.md +17 -2
- package/package.json +10 -5
- package/packages/cli/src/agent-panel.ts +1 -1
- package/packages/cli/src/agent-ui.ts +66 -0
- package/packages/cli/src/commands/ext-registry.ts +7 -0
- package/packages/cli/src/commands.ts +32 -102
- package/packages/cli/src/components/assistant-body.ts +4 -3
- package/packages/cli/src/components/message-box.ts +2 -2
- package/packages/cli/src/components/permission-prompt.ts +3 -3
- package/packages/cli/src/components/render-history.ts +13 -12
- package/packages/cli/src/components/run-view.ts +109 -33
- package/packages/cli/src/components/sidebar.ts +81 -14
- package/packages/cli/src/components/status-line.ts +3 -3
- package/packages/cli/src/config.ts +6 -129
- package/packages/cli/src/index.ts +194 -69
- package/packages/cli/src/overlays/key-input.ts +142 -121
- package/packages/cli/src/overlays/model-picker.ts +19 -56
- package/packages/cli/src/overlays/select.ts +102 -0
- package/packages/cli/src/overlays/session-picker.ts +14 -40
- package/packages/cli/src/overlays/wizard.ts +107 -42
- package/packages/cli/src/prompt/select.ts +181 -0
- package/packages/cli/src/slash-commands.ts +105 -0
- package/packages/cli/src/state.ts +32 -74
- package/packages/cli/src/theme.ts +13 -1
- package/packages/cli/src/themes/github-dark.ts +14 -3
- package/packages/cli/src/themes/types.ts +26 -2
- package/packages/cli/src/themes/vanilla-pi.ts +23 -9
- package/packages/cli/src/tui/components/text.ts +102 -0
- package/packages/cli/src/tui/render/code-block.ts +325 -0
- package/packages/cli/src/{utils → tui/render}/format.ts +31 -24
- package/packages/cli/src/{utils → tui/render}/highlight.ts +94 -2
- package/packages/cli/src/tui/render/markdown.ts +529 -0
- package/packages/cli/src/tui/surface/index.ts +9 -0
- package/packages/cli/src/tui/{paint-panel.ts → surface/paint-panel.ts} +1 -1
- package/packages/cli/src/tui/theme-types.ts +59 -0
- package/packages/cli/src/tui/tty-width.ts +20 -0
- package/packages/cli/src/tui/types.ts +53 -0
- package/packages/cli/src/turn.ts +0 -292
- package/packages/cli/src/utils/code-block.ts +0 -200
package/packages/cli/src/turn.ts
DELETED
|
@@ -1,292 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* One agent turn: drive `runWithFallback` and translate its events into
|
|
3
|
-
* RunView calls. The reliability policy itself lives in @pal-code/core.
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
import {
|
|
7
|
-
getAllTools,
|
|
8
|
-
validateRequiredArgs,
|
|
9
|
-
registerExtensionTools,
|
|
10
|
-
executeTool,
|
|
11
|
-
registerExtensionHandlers,
|
|
12
|
-
registerExtensionLifecycle,
|
|
13
|
-
loadExtensions,
|
|
14
|
-
importExtensionModule,
|
|
15
|
-
runWithFallback,
|
|
16
|
-
shortModel,
|
|
17
|
-
buildRolesPrompt,
|
|
18
|
-
buildSkillsPrompt,
|
|
19
|
-
clearFileRolesCache,
|
|
20
|
-
clearSkillsCache,
|
|
21
|
-
listPrimaries,
|
|
22
|
-
resolvePrimary,
|
|
23
|
-
defaultPrimaryName,
|
|
24
|
-
type Provider,
|
|
25
|
-
type ProviderKeys,
|
|
26
|
-
type ConversationMessage as Message,
|
|
27
|
-
type LoadedExtensions,
|
|
28
|
-
type ToolResult,
|
|
29
|
-
} from '@pal-code/core';
|
|
30
|
-
import type {TUI, Container} from '@earendil-works/pi-tui';
|
|
31
|
-
|
|
32
|
-
import type {Config} from './config.js';
|
|
33
|
-
import {RunView} from './components/run-view.js';
|
|
34
|
-
import {state, type McpServerInfo} from './state.js';
|
|
35
|
-
import {checkToolPermission} from './utils/permissions.js';
|
|
36
|
-
|
|
37
|
-
export interface TurnResult {
|
|
38
|
-
inputTokens: number;
|
|
39
|
-
outputTokens: number;
|
|
40
|
-
cachedTokens: number;
|
|
41
|
-
/** The model that actually served this turn (may differ from config.model after a fallback). */
|
|
42
|
-
model: string;
|
|
43
|
-
/** Set when this turn compacted older history into a checkpoint. */
|
|
44
|
-
compaction?: {boundary: number; summary: string};
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
let extensionsLoaded = false;
|
|
48
|
-
|
|
49
|
-
/** Default extension set when the user hasn't configured one. */
|
|
50
|
-
export const DEFAULT_EXTENSIONS = ['@pal-code/web-search', '@pal-code/agents', '@pal-code/mcp'];
|
|
51
|
-
|
|
52
|
-
/**
|
|
53
|
-
* Apply a successful load to the process: register tools, handlers and
|
|
54
|
-
* lifecycle hooks centrally, record status for the sidebar, and adopt the
|
|
55
|
-
* configured default primary.
|
|
56
|
-
*/
|
|
57
|
-
async function applyLoaded(requested: string[], result: LoadedExtensions): Promise<void> {
|
|
58
|
-
registerExtensionHandlers(result.handlers);
|
|
59
|
-
registerExtensionTools(result.tools);
|
|
60
|
-
registerExtensionLifecycle(result.lifecycle);
|
|
61
|
-
|
|
62
|
-
const active = new Set(result.loaded);
|
|
63
|
-
const failedByPkg = new Map(result.failed.map((f) => [f.pkg, f.reason]));
|
|
64
|
-
state.extensions = requested.map((pkg) => ({
|
|
65
|
-
name: pkg.replace(/^@pal-code\//, ''),
|
|
66
|
-
active: active.has(pkg),
|
|
67
|
-
reason: failedByPkg.get(pkg),
|
|
68
|
-
}));
|
|
69
|
-
|
|
70
|
-
// Populate MCP server status for the sidebar (live from manager).
|
|
71
|
-
//
|
|
72
|
-
// Resolved through core rather than a bare import: `pal add` installs the
|
|
73
|
-
// extension under ~/.pal/extensions/node_modules, which a plain
|
|
74
|
-
// `import('@pal-code/mcp')` from here would not search. `importExtensionModule`
|
|
75
|
-
// also handles the compiled binary, where that bare import cannot resolve at
|
|
76
|
-
// all — treating that as "not installed" would leave the server list empty.
|
|
77
|
-
try {
|
|
78
|
-
const mcpMod = (await importExtensionModule('@pal-code/mcp')) as {
|
|
79
|
-
mcpManager?: {getServerDetails(): McpServerInfo[]};
|
|
80
|
-
};
|
|
81
|
-
if (mcpMod?.mcpManager) {
|
|
82
|
-
state.mcpServers = mcpMod.mcpManager.getServerDetails();
|
|
83
|
-
state.refreshSidebar();
|
|
84
|
-
}
|
|
85
|
-
} catch {
|
|
86
|
-
// MCP extension not available — skip silently
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
// Primaries are registered by the extension's setup hook during load.
|
|
90
|
-
// Adopt the configured default unless the user already picked one.
|
|
91
|
-
const primaries = listPrimaries();
|
|
92
|
-
if (primaries.length > 0 && !primaries.some((p) => p.name === state.currentAgentRole)) {
|
|
93
|
-
state.currentAgentRole = defaultPrimaryName();
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
state.refreshStatusLine();
|
|
97
|
-
state.refreshRoleIndicator();
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
export async function ensureExtensionsLoaded(extensions?: string[]): Promise<void> {
|
|
101
|
-
if (extensionsLoaded) return;
|
|
102
|
-
|
|
103
|
-
const requested = extensions ?? DEFAULT_EXTENSIONS;
|
|
104
|
-
const result = await loadExtensions(requested);
|
|
105
|
-
extensionsLoaded = true;
|
|
106
|
-
await applyLoaded(requested, result);
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
/**
|
|
110
|
-
* Re-import extensions without restarting pal. Called by `/reload`.
|
|
111
|
-
*
|
|
112
|
-
* Uses the loader's `cacheBust` option so edited extension source is picked up.
|
|
113
|
-
* `@pal-code/core` is not re-imported, so a re-registered role provider lands in the
|
|
114
|
-
* one registry core already holds.
|
|
115
|
-
*/
|
|
116
|
-
export async function reloadExtensions(extensions?: string[]): Promise<number> {
|
|
117
|
-
const requested = extensions ?? DEFAULT_EXTENSIONS;
|
|
118
|
-
const result = await loadExtensions(requested, {
|
|
119
|
-
cacheBust: true,
|
|
120
|
-
});
|
|
121
|
-
extensionsLoaded = true;
|
|
122
|
-
clearFileRolesCache();
|
|
123
|
-
clearSkillsCache();
|
|
124
|
-
await applyLoaded(requested, result);
|
|
125
|
-
return result.tools.length;
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
/**
|
|
129
|
-
* Compose the system prompt for a turn: the base prompt, an optional primary
|
|
130
|
-
* agent preamble, the role-awareness block, and the skill listing (only when
|
|
131
|
-
* skill files exist). Every piece is skipped when absent, so users with no
|
|
132
|
-
* extensions or skills pay nothing in tokens.
|
|
133
|
-
*/
|
|
134
|
-
function composeSystemPrompt(base: string, primaryName?: string): string {
|
|
135
|
-
const parts: string[] = [];
|
|
136
|
-
const primary = primaryName ? resolvePrimary(primaryName) : null;
|
|
137
|
-
if (primary?.systemPrompt) parts.push(primary.systemPrompt);
|
|
138
|
-
parts.push(base);
|
|
139
|
-
const roles = buildRolesPrompt();
|
|
140
|
-
if (roles) parts.push(roles);
|
|
141
|
-
const skills = buildSkillsPrompt();
|
|
142
|
-
if (skills) parts.push(skills);
|
|
143
|
-
return parts.join('\n\n');
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
/** Tools the turn may use, narrowed to the primary agent's set when it declares one. */
|
|
147
|
-
function toolsForPrimary(primaryName?: string): import('@pal-code/core').ToolDef[] {
|
|
148
|
-
const all = getAllTools();
|
|
149
|
-
const primary = primaryName ? resolvePrimary(primaryName) : null;
|
|
150
|
-
if (!primary?.tools) return all;
|
|
151
|
-
const allowed = new Set(primary.tools);
|
|
152
|
-
return all.filter((t) => allowed.has(t.function.name));
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
/**
|
|
156
|
-
* Whether the active primary is a read-only agent.
|
|
157
|
-
*
|
|
158
|
-
* A primary that declares a `tools` list is deliberately narrowed (that is how
|
|
159
|
-
* plan mode is enforced); one without is unrestricted. Propagating this stops a
|
|
160
|
-
* read-only turn from reaching a writer through `delegate`.
|
|
161
|
-
*/
|
|
162
|
-
export function isReadOnlyPrimary(primaryName?: string): boolean {
|
|
163
|
-
const primary = primaryName ? resolvePrimary(primaryName) : null;
|
|
164
|
-
return Array.isArray(primary?.tools);
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
/**
|
|
168
|
-
* The tool names the turn is permitted to dispatch, or `undefined` when the
|
|
169
|
-
* primary is unrestricted.
|
|
170
|
-
*
|
|
171
|
-
* Returned to core so `executeTool` can enforce it. Filtering the definitions
|
|
172
|
-
* handed to the model is not sufficient on its own — a model can emit a call for
|
|
173
|
-
* a tool it was never offered.
|
|
174
|
-
*/
|
|
175
|
-
export function allowedToolsForPrimary(primaryName?: string): string[] | undefined {
|
|
176
|
-
return resolvePrimary(primaryName ?? '')?.tools;
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
/**
|
|
180
|
-
* Permission-gated wrapper around core's `executeTool`. Checks rules before
|
|
181
|
-
* dispatching — if a tool call needs approval, the overlay pauses the turn
|
|
182
|
-
* until the user responds.
|
|
183
|
-
*/
|
|
184
|
-
async function gatedExecuteTool(
|
|
185
|
-
name: string,
|
|
186
|
-
argsStr: string,
|
|
187
|
-
toolCallId: string,
|
|
188
|
-
providerConfigOverride?: {
|
|
189
|
-
model: string;
|
|
190
|
-
apiKey: string;
|
|
191
|
-
baseUrl: string;
|
|
192
|
-
keys?: Record<string, string>;
|
|
193
|
-
headers?: Record<string, string>;
|
|
194
|
-
systemPromptAppend?: string;
|
|
195
|
-
readOnly?: boolean;
|
|
196
|
-
allowedTools?: string[];
|
|
197
|
-
},
|
|
198
|
-
signal?: AbortSignal,
|
|
199
|
-
): Promise<ToolResult> {
|
|
200
|
-
// Parse args for permission check
|
|
201
|
-
let args: Record<string, unknown> = {};
|
|
202
|
-
try {
|
|
203
|
-
args = argsStr && argsStr.trim() ? JSON.parse(argsStr) : {};
|
|
204
|
-
} catch {
|
|
205
|
-
// If args can't be parsed, let executeTool handle the error
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
// Reject schema-incomplete calls before the permission gate, so a call
|
|
209
|
-
// missing required arguments can't trigger an approval prompt and then fail.
|
|
210
|
-
const validationError = validateRequiredArgs(name, args);
|
|
211
|
-
if (validationError) {
|
|
212
|
-
return {toolCallId, content: validationError, error: true};
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
const decision = await checkToolPermission(name, args);
|
|
216
|
-
|
|
217
|
-
if (!decision.allowed) {
|
|
218
|
-
return {
|
|
219
|
-
toolCallId,
|
|
220
|
-
content: `Error: ${decision.reason}`,
|
|
221
|
-
error: true,
|
|
222
|
-
};
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
return executeTool(name, argsStr, toolCallId, providerConfigOverride, signal);
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
export async function agentLoop(
|
|
229
|
-
userMessage: string,
|
|
230
|
-
messages: Message[],
|
|
231
|
-
config: Config,
|
|
232
|
-
tui: TUI,
|
|
233
|
-
messagesContainer: Container,
|
|
234
|
-
allKeys: ProviderKeys,
|
|
235
|
-
createProvider: (model: string) => Provider,
|
|
236
|
-
primaryName?: string,
|
|
237
|
-
compactedSeq = 0,
|
|
238
|
-
compactionNote = '',
|
|
239
|
-
): Promise<TurnResult> {
|
|
240
|
-
await ensureExtensionsLoaded(config.extensions);
|
|
241
|
-
|
|
242
|
-
messages.push({role: 'user', content: userMessage});
|
|
243
|
-
|
|
244
|
-
const run = new RunView(messagesContainer, tui, shortModel(config.model));
|
|
245
|
-
state.activeRun = run;
|
|
246
|
-
|
|
247
|
-
let usage = {inputTokens: 0, outputTokens: 0, cachedTokens: 0};
|
|
248
|
-
let activeModel = config.model;
|
|
249
|
-
let compaction: {boundary: number; summary: string} | undefined;
|
|
250
|
-
|
|
251
|
-
for await (const ev of runWithFallback({
|
|
252
|
-
messages,
|
|
253
|
-
tools: toolsForPrimary(primaryName),
|
|
254
|
-
model: config.model,
|
|
255
|
-
systemPrompt: composeSystemPrompt(config.systemPrompt, primaryName),
|
|
256
|
-
maxToolRounds: config.maxToolRounds,
|
|
257
|
-
contextLimit: config.contextLimit,
|
|
258
|
-
reasoningEffort: config.reasoningEffort,
|
|
259
|
-
compactedSeq,
|
|
260
|
-
compactionNote,
|
|
261
|
-
maxRetries: config.maxRetries,
|
|
262
|
-
retryBaseMs: config.retryBaseMs,
|
|
263
|
-
keys: allKeys,
|
|
264
|
-
executeTool: gatedExecuteTool,
|
|
265
|
-
childExecuteTool: gatedExecuteTool,
|
|
266
|
-
signal: state.activeAbort?.signal,
|
|
267
|
-
primary: primaryName,
|
|
268
|
-
readOnly: isReadOnlyPrimary(primaryName),
|
|
269
|
-
allowedTools: allowedToolsForPrimary(primaryName),
|
|
270
|
-
createProvider: (spec: string) => createProvider(spec),
|
|
271
|
-
})) {
|
|
272
|
-
if (ev.type === 'model-start') {
|
|
273
|
-
activeModel = ev.model;
|
|
274
|
-
run.setModel(shortModel(ev.model));
|
|
275
|
-
} else if (ev.type === 'round-start') run.beginRound(ev.round, ev.max);
|
|
276
|
-
else if (ev.type === 'text-delta') run.streamText(ev.content);
|
|
277
|
-
else if (ev.type === 'tool-start') run.addTool(ev.id, ev.name, ev.argsSummary);
|
|
278
|
-
else if (ev.type === 'tool-end') run.endTool(ev.id, ev.ok, ev.content);
|
|
279
|
-
else if (ev.type === 'notice') run.notice(ev.text);
|
|
280
|
-
else if (ev.type === 'compacted') compaction = {boundary: ev.boundary, summary: ev.summary};
|
|
281
|
-
else if (ev.type === 'aborted') run.aborted();
|
|
282
|
-
else if (ev.type === 'done') usage = ev.usage;
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
return {
|
|
286
|
-
inputTokens: usage.inputTokens,
|
|
287
|
-
outputTokens: usage.outputTokens,
|
|
288
|
-
cachedTokens: usage.cachedTokens,
|
|
289
|
-
model: activeModel,
|
|
290
|
-
compaction,
|
|
291
|
-
};
|
|
292
|
-
}
|
|
@@ -1,200 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Fenced code blocks in the transcript: segmentation + boxed rendering.
|
|
3
|
-
*
|
|
4
|
-
* Both exports are pure and deterministic — same input bytes → same output
|
|
5
|
-
* bytes, no clock or randomness. Hover/success paint arrives as explicit
|
|
6
|
-
* `opts` parameters, never as ambient state, so the TUI can repaint
|
|
7
|
-
* differentially and the components can cache by width without desyncing
|
|
8
|
-
* the screen from the cache.
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
import {truncateToWidth} from '../tui/tty-width.js';
|
|
12
|
-
|
|
13
|
-
import {c, codebox} from '../theme.js';
|
|
14
|
-
import {buildHeader, displayWidth, wrapText} from './format.js';
|
|
15
|
-
import {highlightCode} from './highlight.js';
|
|
16
|
-
|
|
17
|
-
/** One piece of an assistant message: prose, or a fenced code block. */
|
|
18
|
-
export type CodeSegment =
|
|
19
|
-
| {readonly kind: 'text'; readonly text: string}
|
|
20
|
-
| {readonly kind: 'code'; readonly lang: string; readonly lines: readonly string[]};
|
|
21
|
-
|
|
22
|
-
/** Right-edge copy affordance drawn in rendered code-block headers. */
|
|
23
|
-
export const COPY_LABEL = '⧉ copy';
|
|
24
|
-
|
|
25
|
-
/** Header label once the copy succeeded — wider than COPY_LABEL, so the
|
|
26
|
-
* dash run and copy zone must recompute from it. */
|
|
27
|
-
export const SUCCESS_LABEL = '✓ copied';
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* Screen geometry of the header copy zone: the rightmost columns of the
|
|
31
|
-
* header row — the label plus the closing corner (`⧉ copy╮`). Returns null
|
|
32
|
-
* when disabled or when the box is too narrow for the label plus at least
|
|
33
|
-
* one dash. Measured with `displayWidth` (=== `visibleWidth`), so the
|
|
34
|
-
* renderer and the click hit-test always agree on the same columns even if
|
|
35
|
-
* the label's ambiguous-width glyph is measured differently than expected.
|
|
36
|
-
* `label` defaults to COPY_LABEL; pass SUCCESS_LABEL while the success
|
|
37
|
-
* chip is painted so the hit-test follows the reflowed zone.
|
|
38
|
-
*/
|
|
39
|
-
export function copyZoneRect(
|
|
40
|
-
W: number,
|
|
41
|
-
tag: string,
|
|
42
|
-
enabled: boolean,
|
|
43
|
-
label = COPY_LABEL,
|
|
44
|
-
): {startCol: number; width: number} | null {
|
|
45
|
-
const tagW = displayWidth(tag.trim());
|
|
46
|
-
const tagged = tag.trim() !== '' && tagW + 6 <= W;
|
|
47
|
-
const dashes = tagged ? W - tagW - 5 : W - 2;
|
|
48
|
-
const labelW = displayWidth(label);
|
|
49
|
-
if (!enabled || dashes - labelW < 1) return null;
|
|
50
|
-
return {startCol: W - labelW - 1, width: labelW + 1};
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
/**
|
|
54
|
-
* Re-open the surface fill after every full reset inside a row, so a
|
|
55
|
-
* mid-line `\x1b[0m` (highlightCode emits them around every token) never
|
|
56
|
-
* leaves a cell on the terminal default background. Callers append the
|
|
57
|
-
* row's single final reset after this pass.
|
|
58
|
-
*/
|
|
59
|
-
function keepSurface(s: string): string {
|
|
60
|
-
return s.split(c.reset).join(c.reset + codebox.surfaceBg);
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
// Opening fence: up to 3 leading spaces, 3+ backticks, then an info string
|
|
64
|
-
// that must not itself contain backticks (CommonMark) — so a line like
|
|
65
|
-
// "```code```" mid-paragraph stays prose.
|
|
66
|
-
const OPEN_FENCE = /^ {0,3}(`{3,})([^`]*)$/;
|
|
67
|
-
// Closing fence: backticks and whitespace only, and never shorter than the opener.
|
|
68
|
-
const CLOSE_FENCE = /^ {0,3}(`{3,})[ \t]*$/;
|
|
69
|
-
|
|
70
|
-
function trimBlankEdges(lines: readonly string[]): readonly string[] {
|
|
71
|
-
let start = 0;
|
|
72
|
-
let end = lines.length;
|
|
73
|
-
while (start < end && (lines[start] ?? '').trim() === '') start++;
|
|
74
|
-
while (end > start && (lines[end - 1] ?? '').trim() === '') end--;
|
|
75
|
-
return lines.slice(start, end);
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
/**
|
|
79
|
-
* Split markdown into prose and fenced code segments.
|
|
80
|
-
*
|
|
81
|
-
* Handles the edge cases that show up in real model output: an unclosed
|
|
82
|
-
* fence at the end of the message (runs to end), no language tag, padded or
|
|
83
|
-
* mixed-case tags, fences that interrupt a paragraph, CRLF endings, and
|
|
84
|
-
* longer (````) fences whose content contains triple backticks.
|
|
85
|
-
*/
|
|
86
|
-
export function parseCodeSegments(text: string): CodeSegment[] {
|
|
87
|
-
const segments: CodeSegment[] = [];
|
|
88
|
-
let textLines: string[] = [];
|
|
89
|
-
let fence: {ticks: number; lang: string; lines: string[]} | null = null;
|
|
90
|
-
|
|
91
|
-
const flushText = (): void => {
|
|
92
|
-
const kept = trimBlankEdges(textLines);
|
|
93
|
-
textLines = [];
|
|
94
|
-
if (kept.length > 0) segments.push({kind: 'text', text: kept.join('\n')});
|
|
95
|
-
};
|
|
96
|
-
|
|
97
|
-
for (const line of text.split(/\r\n|\r|\n/)) {
|
|
98
|
-
if (fence) {
|
|
99
|
-
const close = CLOSE_FENCE.exec(line);
|
|
100
|
-
if (close && (close[1] ?? '').length >= fence.ticks) {
|
|
101
|
-
segments.push({kind: 'code', lang: fence.lang, lines: fence.lines});
|
|
102
|
-
fence = null;
|
|
103
|
-
} else {
|
|
104
|
-
fence.lines.push(line);
|
|
105
|
-
}
|
|
106
|
-
continue;
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
const open = OPEN_FENCE.exec(line);
|
|
110
|
-
if (open) {
|
|
111
|
-
flushText();
|
|
112
|
-
const info = (open[2] ?? '').trim();
|
|
113
|
-
fence = {
|
|
114
|
-
ticks: (open[1] ?? '').length,
|
|
115
|
-
lang: info.split(/\s+/)[0] ?? '',
|
|
116
|
-
lines: [],
|
|
117
|
-
};
|
|
118
|
-
continue;
|
|
119
|
-
}
|
|
120
|
-
textLines.push(line);
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
if (fence) segments.push({kind: 'code', lang: fence.lang, lines: fence.lines});
|
|
124
|
-
flushText();
|
|
125
|
-
return segments;
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
/**
|
|
129
|
-
* Render one fenced code segment as a bordered, language-tagged box:
|
|
130
|
-
*
|
|
131
|
-
* ╭─ typescript ────────╮
|
|
132
|
-
* │ const x = 1; │
|
|
133
|
-
* ╰─────────────────────╯
|
|
134
|
-
*
|
|
135
|
-
* Geometry mirrors `userMessageBox` (same W/inner/textWidth clamps, same
|
|
136
|
-
* `buildHeader` degradation on narrow widths) so every transcript box lines
|
|
137
|
-
* up. Code is syntax-highlighted via the existing `highlightCode` helper,
|
|
138
|
-
* then wrapped and hard-truncated to the box — no row ever exceeds `width`.
|
|
139
|
-
*/
|
|
140
|
-
export function codeBlockBox(
|
|
141
|
-
code: string,
|
|
142
|
-
width: number,
|
|
143
|
-
lang = '',
|
|
144
|
-
opts?: {copy?: boolean; hover?: boolean; success?: boolean},
|
|
145
|
-
): string {
|
|
146
|
-
// One clamp before anything is derived, so header/body/footer agree.
|
|
147
|
-
const W = Math.max(6, Math.floor(width));
|
|
148
|
-
const inner = W - 4; // columns between "│ " and " │"
|
|
149
|
-
const textWidth = Math.max(1, inner - 1); // reserve the last inner column
|
|
150
|
-
|
|
151
|
-
const tag = lang.trim();
|
|
152
|
-
const hover = opts?.hover === true;
|
|
153
|
-
const success = opts?.success === true;
|
|
154
|
-
// Every row opens the surface fill once; `paint` switches only the
|
|
155
|
-
// foreground role, and `finish` re-opens the fill after any embedded
|
|
156
|
-
// reset before closing the row with a single trailing reset.
|
|
157
|
-
const bg = codebox.surfaceBg;
|
|
158
|
-
const paint = (s: string): string => `${bg}${codebox.borderFg}${s}`;
|
|
159
|
-
const finish = (line: string): string => `${keepSurface(line)}${c.reset}`;
|
|
160
|
-
|
|
161
|
-
// Copy affordance: pin the label at the right edge of the header (zone
|
|
162
|
-
// includes the closing ╮) while the visible width stays exactly W.
|
|
163
|
-
// Chip precedence: success > hover > idle — success swaps both the
|
|
164
|
-
// label and the fg, and the zone reflows from the wider label.
|
|
165
|
-
const labelText = success ? SUCCESS_LABEL : COPY_LABEL;
|
|
166
|
-
const zone = copyZoneRect(W, tag, opts?.copy === true, labelText);
|
|
167
|
-
const tagW = displayWidth(tag);
|
|
168
|
-
const labelW = displayWidth(labelText);
|
|
169
|
-
const chipBg = hover && !success ? codebox.chipBgHover : codebox.chipBgIdle;
|
|
170
|
-
const chipFg = success ? codebox.successFg : hover ? codebox.chipFgHover : codebox.chipFgIdle;
|
|
171
|
-
const chip = `${chipBg}${chipFg}${labelText}`;
|
|
172
|
-
|
|
173
|
-
let header: string;
|
|
174
|
-
if (!zone) {
|
|
175
|
-
header = tag
|
|
176
|
-
? finish(buildHeader(W, tag, tagW, codebox.langFg, paint, ''))
|
|
177
|
-
: finish(paint(`╭${'─'.repeat(W - 2)}╮`));
|
|
178
|
-
} else if (tag !== '' && tagW + 6 <= W) {
|
|
179
|
-
const dashes = W - tagW - 5 - labelW;
|
|
180
|
-
header = finish(
|
|
181
|
-
`${paint('╭─')} ${codebox.langFg}${tag}${c.reset} ${paint('─'.repeat(dashes))}` +
|
|
182
|
-
`${chip}${paint('╮')}`,
|
|
183
|
-
);
|
|
184
|
-
} else {
|
|
185
|
-
const dashes = W - 2 - labelW;
|
|
186
|
-
header = finish(`${paint(`╭${'─'.repeat(dashes)}`)}${chip}${paint('╮')}`);
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
const body = wrapText(highlightCode(code, tag || undefined).join('\n'), textWidth)
|
|
190
|
-
.map((line) => {
|
|
191
|
-
const safe = truncateToWidth(line.trimEnd(), textWidth, '');
|
|
192
|
-
const pad = Math.max(0, inner - displayWidth(safe));
|
|
193
|
-
return finish(`${paint('│')} ${safe}${c.reset}${' '.repeat(pad)} ${paint('│')}`);
|
|
194
|
-
})
|
|
195
|
-
.join('\n');
|
|
196
|
-
|
|
197
|
-
const footer = finish(paint(`╰${'─'.repeat(W - 2)}╯`));
|
|
198
|
-
|
|
199
|
-
return `${header}\n${body}\n${footer}`;
|
|
200
|
-
}
|