pal-code 0.0.12 → 0.0.13

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pal-code",
3
- "version": "0.0.12",
3
+ "version": "0.0.13",
4
4
  "description": "A terminal coding agent with BYOK, tool use, and extensions",
5
5
  "license": "MIT",
6
6
  "engines": {
@@ -62,7 +62,7 @@
62
62
  "gemini"
63
63
  ],
64
64
  "dependencies": {
65
- "@pal-code/core": "0.0.12",
65
+ "@pal-code/core": "0.0.13",
66
66
  "@earendil-works/pi-tui": "^0.85.1"
67
67
  },
68
68
  "devDependencies": {
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Curated extension registry — the official `@pal-code/*` packages.
3
+ *
4
+ * A handpicked list for users who don't know what to search for. It backs
5
+ * /ext browse, the empty-/ext-list next-step hint, and the blank-/ext-search
6
+ * featured list — discovery without npm keyword knowledge.
7
+ *
8
+ * Data only: no imports, no network. To add an extension, append to the
9
+ * REGISTRY array below.
10
+ * Format: { name, description, package, tags }
11
+ */
12
+
13
+ export interface ExtRegistryEntry {
14
+ /** Display name. */
15
+ name: string;
16
+ /** One-line why-install description. */
17
+ description: string;
18
+ /** npm package installed by `pal add <package>`. */
19
+ package: string;
20
+ /** Tags for search matching. */
21
+ tags: string[];
22
+ }
23
+
24
+ export const REGISTRY: ExtRegistryEntry[] = [
25
+ {
26
+ name: 'Agents',
27
+ description: 'Two-agent roles plus delegate / delegate_parallel orchestration',
28
+ package: '@pal-code/agents',
29
+ tags: ['agents', 'orchestration', 'delegate', 'delegate_parallel', 'roles', 'subagent'],
30
+ },
31
+ {
32
+ name: 'Web Search',
33
+ description: 'web_search and fetch_url tools for the main agent',
34
+ package: '@pal-code/web-search',
35
+ tags: ['web', 'search', 'fetch', 'fetch_url', 'internet', 'browser'],
36
+ },
37
+ {
38
+ name: 'MCP',
39
+ description: 'Bridge MCP servers into pal as tools',
40
+ package: '@pal-code/mcp',
41
+ tags: ['mcp', 'model context protocol', 'server', 'bridge', 'integrations'],
42
+ },
43
+ ];
44
+
45
+ /** ANSI codes used when rendering the browse list (omit for plain text). */
46
+ export interface BrowseColors {
47
+ bold: string;
48
+ cyan: string;
49
+ dim: string;
50
+ green: string;
51
+ reset: string;
52
+ }
53
+
54
+ const PLAIN: BrowseColors = {bold: '', cyan: '', dim: '', green: '', reset: ''};
55
+
56
+ /**
57
+ * Render the curated registry as the /ext browse listing — also reused as
58
+ * the featured list for a blank /ext search.
59
+ *
60
+ * Plain by default so tests can assert on the text; pass the CLI colour
61
+ * palette to mirror the /mcp browse presentation.
62
+ */
63
+ export function formatBrowse(colors: BrowseColors = PLAIN): string {
64
+ const c = colors;
65
+ const lines: string[] = [`${c.bold}Featured extensions${c.reset}`, ''];
66
+ for (const entry of REGISTRY) {
67
+ lines.push(` ${c.cyan}${entry.name}${c.reset} ${c.dim}${entry.package}${c.reset}`);
68
+ lines.push(` ${c.dim}${entry.description}${c.reset}`);
69
+ lines.push(` ${c.green}pal add ${entry.package}${c.reset}`);
70
+ lines.push('');
71
+ }
72
+ lines.push(`${c.dim}Search npm with /ext search <query>.${c.reset}`);
73
+ return lines.join('\n');
74
+ }
75
+
76
+ /**
77
+ * /ext list with nothing configured or loaded: point at a first install
78
+ * instead of dead-ending at "No extensions loaded."
79
+ */
80
+ export function emptyListMessage(): string {
81
+ const starter = REGISTRY[0].package;
82
+ return `No extensions loaded. Start with: /ext add ${starter} — or /ext browse`;
83
+ }
@@ -16,7 +16,9 @@ import {existsSync, mkdirSync, writeFileSync} from 'node:fs';
16
16
  import {execSync} from 'node:child_process';
17
17
  import {readPalConfig, saveSetting} from '@pal-code/core';
18
18
 
19
- const EXTENSIONS_DIR = join(homedir(), '.pal', 'extensions');
19
+ import {formatBrowse} from './ext-registry.js';
20
+
21
+ export const EXTENSIONS_DIR = join(homedir(), '.pal', 'extensions');
20
22
 
21
23
  const NPM_SEARCH_URL = 'https://registry.npmjs.org/-/v1/search';
22
24
  const NPM_REGISTRY_URL = 'https://registry.npmjs.org';
@@ -128,6 +130,18 @@ export async function extSearch(query: string): Promise<ExtSearchResult> {
128
130
  };
129
131
  }
130
132
 
133
+ /**
134
+ * /ext search entry point. A blank query shows the curated featured list so a
135
+ * user who doesn't know what to search for still gets a next step; a real
136
+ * query goes to npm via extSearch unchanged.
137
+ */
138
+ export async function extSearchOrBrowse(query: string): Promise<ExtSearchResult> {
139
+ if (!query.trim()) {
140
+ return {ok: true, message: formatBrowse(), results: []};
141
+ }
142
+ return extSearch(query);
143
+ }
144
+
131
145
  /** 404 → package is absent from npm; other failures → unknown (offline-tolerant). */
132
146
  async function lookupNpmPackage(pkg: string): Promise<'found' | 'missing' | 'unknown'> {
133
147
  const url = `${NPM_REGISTRY_URL}/${pkg.replaceAll('/', '%2F')}`;
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Daily-cached startup version check for pal-code.
3
+ *
4
+ * Cache: ~/.pal/update-check.json — {lastCheck, latest?, critical?, notified[]}
5
+ * The startup path is synchronous and pure: it renders whatever the cache says.
6
+ * refreshUpdateCheck() runs fire-and-forget and only writes on a successful
7
+ * fetch, so offline/corporate/mid-task sessions are never disturbed.
8
+ *
9
+ * Severity comes from npm's explicit `critical` dist-tag — 0.0.x semver cannot
10
+ * signal it — and nothing here ever forces an update:
11
+ * - dim hint when `latest` is ahead (once per version, via `notified`)
12
+ * - yellow banner when `critical` is ahead (every launch until local catches up)
13
+ */
14
+
15
+ import {mkdirSync, readFileSync, writeFileSync} from 'node:fs';
16
+ import {homedir} from 'node:os';
17
+ import {dirname, join} from 'node:path';
18
+
19
+ const NPM_REGISTRY_URL = 'https://registry.npmjs.org';
20
+ const PAL_PACKAGE = 'pal-code';
21
+ const UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
22
+
23
+ export const UPDATE_CHECK_CACHE_PATH = join(homedir(), '.pal', 'update-check.json');
24
+
25
+ export interface UpdateCheckCache {
26
+ lastCheck: number;
27
+ latest?: string;
28
+ critical?: string;
29
+ notified: string[];
30
+ }
31
+
32
+ export interface DistTags {
33
+ latest?: string;
34
+ critical?: string;
35
+ }
36
+
37
+ export interface StartupNotice {
38
+ /** Dim one-liner to show once for this exact `latest` version, or null. */
39
+ hint: string | null;
40
+ /** Yellow banner shown every launch while `critical` is ahead, or null. */
41
+ banner: string | null;
42
+ /** `notified` with the announced hint version appended (unchanged when no hint). */
43
+ notified: string[];
44
+ /** True when `notified` gained an entry and the cache should be rewritten. */
45
+ changed: boolean;
46
+ }
47
+
48
+ /** True when `candidate` is strictly newer than `reference` (numeric dot segments). */
49
+ export function isNewer(candidate: string, reference: string): boolean {
50
+ const a = candidate.split('.');
51
+ const b = reference.split('.');
52
+ const len = Math.max(a.length, b.length);
53
+ for (let i = 0; i < len; i++) {
54
+ const x = segment(a[i]);
55
+ const y = segment(b[i]);
56
+ if (x !== y) return x > y;
57
+ }
58
+ return false;
59
+ }
60
+
61
+ /** Missing segments count as 0; non-numeric garbage degrades to 0 rather than NaN. */
62
+ function segment(part: string | undefined): number {
63
+ if (part === undefined) return 0;
64
+ const n = Number.parseInt(part, 10);
65
+ return Number.isNaN(n) ? 0 : n;
66
+ }
67
+
68
+ /** Tolerant parse — corrupt/partial cache files degrade to an empty cache. */
69
+ export function parseUpdateCache(raw: string): UpdateCheckCache {
70
+ let data: unknown;
71
+ try {
72
+ data = JSON.parse(raw);
73
+ } catch {
74
+ return {lastCheck: 0, notified: []};
75
+ }
76
+ if (typeof data !== 'object' || data === null || Array.isArray(data)) {
77
+ return {lastCheck: 0, notified: []};
78
+ }
79
+ const record = data as Record<string, unknown>;
80
+ const lastCheck =
81
+ typeof record.lastCheck === 'number' && Number.isFinite(record.lastCheck)
82
+ ? record.lastCheck
83
+ : 0;
84
+ const cache: UpdateCheckCache = {lastCheck, notified: []};
85
+ if (typeof record.latest === 'string') cache.latest = record.latest;
86
+ if (typeof record.critical === 'string') cache.critical = record.critical;
87
+ if (Array.isArray(record.notified)) {
88
+ cache.notified = record.notified.filter((entry): entry is string => typeof entry === 'string');
89
+ }
90
+ return cache;
91
+ }
92
+
93
+ /** Never throws — a missing or unreadable cache just means "check fresh". */
94
+ export function loadUpdateCache(path: string = UPDATE_CHECK_CACHE_PATH): UpdateCheckCache {
95
+ try {
96
+ return parseUpdateCache(readFileSync(path, 'utf-8'));
97
+ } catch {
98
+ return {lastCheck: 0, notified: []};
99
+ }
100
+ }
101
+
102
+ /** Never throws — a read-only home skips persisting instead of breaking startup. */
103
+ export function saveUpdateCache(
104
+ cache: UpdateCheckCache,
105
+ path: string = UPDATE_CHECK_CACHE_PATH,
106
+ ): void {
107
+ try {
108
+ mkdirSync(dirname(path), {recursive: true});
109
+ writeFileSync(path, `${JSON.stringify(cache, null, 2)}\n`, 'utf-8');
110
+ } catch {
111
+ // Best-effort persistence; the next launch re-derives whatever is missing.
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Pure startup decision — what the transcript shows this launch.
117
+ * The hint is gated by `notified` (once per version, ever); the critical banner
118
+ * is not gated at all, so it repaints every startup until local >= critical.
119
+ */
120
+ export function planStartupNotice(cache: UpdateCheckCache, localVersion: string): StartupNotice {
121
+ const {latest, critical} = cache;
122
+ let notified = cache.notified;
123
+ let hint: string | null = null;
124
+
125
+ if (latest && isNewer(latest, localVersion) && !notified.includes(latest)) {
126
+ hint = `pal-code ${latest} available — run: pal update`;
127
+ notified = [...notified, latest];
128
+ }
129
+
130
+ const banner =
131
+ critical && isNewer(critical, localVersion)
132
+ ? `pal-code ${critical} critical update available — run: pal update`
133
+ : null;
134
+
135
+ return {hint, banner, notified, changed: notified.length !== cache.notified.length};
136
+ }
137
+
138
+ /**
139
+ * Read a package's `dist-tags` from the npm registry.
140
+ * 404/offline/malformed → null (never throws), mirroring ext.ts lookupNpmPackage.
141
+ */
142
+ export async function fetchDistTags(pkg: string): Promise<DistTags | null> {
143
+ try {
144
+ const res = await fetch(`${NPM_REGISTRY_URL}/${pkg.replaceAll('/', '%2F')}`);
145
+ if (!res.ok) return null;
146
+ const data: unknown = await res.json();
147
+ if (typeof data !== 'object' || data === null) return null;
148
+ const tags = (data as Record<string, unknown>)['dist-tags'];
149
+ if (typeof tags !== 'object' || tags === null) return null;
150
+ const record = tags as Record<string, unknown>;
151
+ const distTags: DistTags = {};
152
+ if (typeof record.latest === 'string') distTags.latest = record.latest;
153
+ if (typeof record.critical === 'string') distTags.critical = record.critical;
154
+ return distTags.latest || distTags.critical ? distTags : null;
155
+ } catch {
156
+ return null;
157
+ }
158
+ }
159
+
160
+ /**
161
+ * Fire-and-forget refresh — at most one registry hit per 24h, and only ever
162
+ * written on success, so a failed check retries on the next launch. Never rejects.
163
+ */
164
+ export async function refreshUpdateCheck(
165
+ cachePath: string = UPDATE_CHECK_CACHE_PATH,
166
+ now: number = Date.now(),
167
+ ): Promise<void> {
168
+ try {
169
+ const cache = loadUpdateCache(cachePath);
170
+ if (now - cache.lastCheck < UPDATE_CHECK_INTERVAL_MS) return;
171
+ const tags = await fetchDistTags(PAL_PACKAGE);
172
+ if (!tags) return;
173
+ saveUpdateCache(
174
+ {lastCheck: now, latest: tags.latest, critical: tags.critical, notified: cache.notified},
175
+ cachePath,
176
+ );
177
+ } catch {
178
+ // Startup must stay silent — any failure simply means "retry next launch".
179
+ }
180
+ }
@@ -0,0 +1,185 @@
1
+ /**
2
+ * `pal update` / `pal upgrade` — refresh pal-code itself and its extensions.
3
+ *
4
+ * Self-update is install-method aware (see detectInstallMethod): npm-global
5
+ * runs `npm i -g pal-code@latest`, bun-global runs `bun add -g pal-code@latest`,
6
+ * a dev checkout is never mutated (git-pull instructions instead), and an
7
+ * unknown install exits non-zero with both suggestions.
8
+ *
9
+ * Extension updates read the same config list /ext uses, compare each installed
10
+ * package against npm's `latest` dist-tag, and `bun update` the outdated ones —
11
+ * offline/404 lookups skip quietly, mirroring commands/ext.ts. Nothing here
12
+ * ever force-updates: the user asked, so we report and exit like ext.ts does.
13
+ */
14
+
15
+ import {execSync} from 'node:child_process';
16
+ import {existsSync, readFileSync} from 'node:fs';
17
+ import {dirname, join} from 'node:path';
18
+ import {readPalConfig} from '@pal-code/core';
19
+
20
+ import {EXTENSIONS_DIR, type ExtCommandResult} from './ext.js';
21
+ import {fetchDistTags, isNewer} from './update-check.js';
22
+
23
+ /** How the running copy of pal-code was installed. */
24
+ export type InstallMethod = 'npm-global' | 'bun-global' | 'dev' | 'unknown';
25
+
26
+ export interface InstallMethodHints {
27
+ /** Path hints, compared normalized (backslashes folded, lowercased). */
28
+ paths: readonly string[];
29
+ /** True when version.json and .git both sit near the package root (dev checkout). */
30
+ devCheckout: boolean;
31
+ }
32
+
33
+ interface SectionResult {
34
+ ok: boolean;
35
+ lines: string[];
36
+ }
37
+
38
+ type SelfUpdateAction =
39
+ | {kind: 'run'; command: string; success: string}
40
+ | {kind: 'note'; line: string}
41
+ | {kind: 'manual'; lines: string[]};
42
+
43
+ /** Compile-time exhaustive map — a new InstallMethod variant fails tsc until handled. */
44
+ const SELF_UPDATE_ACTIONS: Record<InstallMethod, SelfUpdateAction> = {
45
+ 'npm-global': {
46
+ kind: 'run',
47
+ command: 'npm i -g pal-code@latest',
48
+ success: 'Updated pal-code (npm i -g pal-code@latest).',
49
+ },
50
+ 'bun-global': {
51
+ kind: 'run',
52
+ command: 'bun add -g pal-code@latest',
53
+ success: 'Updated pal-code (bun add -g pal-code@latest).',
54
+ },
55
+ dev: {kind: 'note', line: 'Development checkout — run: git pull && bun install'},
56
+ unknown: {
57
+ kind: 'manual',
58
+ lines: [
59
+ 'Could not determine how pal was installed. Run one of:',
60
+ ' npm i -g pal-code@latest',
61
+ ' bun add -g pal-code@latest',
62
+ ],
63
+ },
64
+ };
65
+
66
+ /**
67
+ * Classify the install from path hints alone (pure — unit-testable).
68
+ * Order matters: bun-global paths also contain `node_modules/pal-code`, so the
69
+ * `.bun/install/global` marker wins first; the `node_modules/pal-code` marker
70
+ * also matches platform packages (`pal-code-win32-x64`) of compiled binaries.
71
+ */
72
+ export function detectInstallMethod(hints: InstallMethodHints): InstallMethod {
73
+ const paths = hints.paths.map((p) => p.replaceAll('\\', '/').toLowerCase());
74
+ if (paths.some((p) => p.includes('/.bun/install/global'))) return 'bun-global';
75
+ if (paths.some((p) => p.includes('node_modules/pal-code'))) return 'npm-global';
76
+ if (hints.devCheckout) return 'dev';
77
+ return 'unknown';
78
+ }
79
+
80
+ /** Walk up from `startDir` for a directory holding BOTH version.json and .git. */
81
+ function isDevCheckout(startDir: string): boolean {
82
+ let dir = startDir;
83
+ for (let i = 0; i < 12; i++) {
84
+ if (existsSync(join(dir, 'version.json')) && existsSync(join(dir, '.git'))) return true;
85
+ const parent = dirname(dir);
86
+ if (parent === dir) break;
87
+ dir = parent;
88
+ }
89
+ return false;
90
+ }
91
+
92
+ function collectInstallHints(): InstallMethodHints {
93
+ return {
94
+ paths: [process.execPath, import.meta.dir],
95
+ // Compiled binaries live in dist/ (dev) or <prefix>/node_modules/... (global),
96
+ // so probe both the module dir and the executable's directory.
97
+ devCheckout: isDevCheckout(import.meta.dir) || isDevCheckout(dirname(process.execPath)),
98
+ };
99
+ }
100
+
101
+ function applySelfUpdate(method: InstallMethod): SectionResult {
102
+ const action = SELF_UPDATE_ACTIONS[method];
103
+ if (action.kind === 'run') {
104
+ try {
105
+ execSync(action.command, {stdio: 'inherit'});
106
+ return {ok: true, lines: [action.success]};
107
+ } catch (err) {
108
+ const msg = err instanceof Error ? err.message : String(err);
109
+ return {ok: false, lines: [`Self-update failed: ${msg}`]};
110
+ }
111
+ }
112
+ if (action.kind === 'manual') {
113
+ return {ok: false, lines: action.lines};
114
+ }
115
+ return {ok: true, lines: [action.line]};
116
+ }
117
+
118
+ /** Installed on-disk version, or null when absent/unreadable (→ skip). */
119
+ function installedVersion(pkg: string): string | null {
120
+ const manifest = join(EXTENSIONS_DIR, 'node_modules', pkg, 'package.json');
121
+ if (!existsSync(manifest)) return null;
122
+ try {
123
+ const data: unknown = JSON.parse(readFileSync(manifest, 'utf-8'));
124
+ if (typeof data === 'object' && data !== null) {
125
+ const version = (data as {version?: unknown}).version;
126
+ if (typeof version === 'string' && version.length > 0) return version;
127
+ }
128
+ } catch {
129
+ return null; // unreadable/corrupt manifest — treat as not installed
130
+ }
131
+ return null;
132
+ }
133
+
134
+ /** Compare every configured extension against npm `latest`; bun-update outdated. */
135
+ async function updateExtensions(): Promise<SectionResult> {
136
+ const config = readPalConfig();
137
+ const extensions = Array.isArray(config.extensions) ? (config.extensions as string[]) : [];
138
+ if (extensions.length === 0) return {ok: true, lines: []};
139
+
140
+ const updated: string[] = [];
141
+ const failed: string[] = [];
142
+ let upToDate = 0;
143
+ let skipped = 0;
144
+
145
+ for (const pkg of extensions) {
146
+ const current = installedVersion(pkg);
147
+ if (current === null) continue; // configured but not installed — skip
148
+ const tags = await fetchDistTags(pkg);
149
+ if (!tags?.latest) {
150
+ skipped += 1; // offline or absent from npm — tolerant skip
151
+ continue;
152
+ }
153
+ if (!isNewer(tags.latest, current)) {
154
+ upToDate += 1;
155
+ continue;
156
+ }
157
+ try {
158
+ execSync(`bun update ${pkg}`, {cwd: EXTENSIONS_DIR, stdio: 'pipe'});
159
+ updated.push(` ${pkg} ${current} → ${tags.latest}`);
160
+ } catch (err) {
161
+ const msg = err instanceof Error ? err.message : String(err);
162
+ failed.push(` ${pkg}: update failed — ${msg}`);
163
+ }
164
+ }
165
+
166
+ const lines: string[] = ['', 'Extensions:'];
167
+ if (updated.length > 0) lines.push(...updated);
168
+ else if (failed.length === 0 && skipped === 0 && upToDate > 0) lines.push(' all up to date.');
169
+ if (failed.length > 0) lines.push(...failed);
170
+ if (skipped > 0) lines.push(` ${skipped} skipped — npm registry unreachable.`);
171
+ if (updated.length === 0 && failed.length === 0 && upToDate === 0 && skipped === 0) {
172
+ lines.push(' nothing installed to check.');
173
+ }
174
+ return {ok: failed.length === 0, lines};
175
+ }
176
+
177
+ /** `pal update` / `pal upgrade` entry point — argv fast-exit, runs before the TUI. */
178
+ export async function palUpdate(): Promise<ExtCommandResult> {
179
+ const selfUpdate = applySelfUpdate(detectInstallMethod(collectInstallHints()));
180
+ const extensions = await updateExtensions();
181
+ return {
182
+ ok: selfUpdate.ok && extensions.ok,
183
+ message: [...selfUpdate.lines, ...extensions.lines].join('\n'),
184
+ };
185
+ }
@@ -86,6 +86,9 @@ export function cmdHelp(container: Container, tui: TUI): void {
86
86
  container.addChild(
87
87
  new Text(` ${c.cyan}/ext list${c.reset} List loaded extensions`, 1, 0),
88
88
  );
89
+ container.addChild(
90
+ new Text(` ${c.cyan}/ext browse${c.reset} Browse curated extensions`, 1, 0),
91
+ );
89
92
  container.addChild(
90
93
  new Text(` ${c.cyan}/mcp add${c.reset} <name> <cmd> [args] Add a local MCP server`, 1, 0),
91
94
  );
@@ -105,6 +108,13 @@ export function cmdHelp(container: Container, tui: TUI): void {
105
108
  container.addChild(
106
109
  new Text(` ${c.cyan}/permission${c.reset} Show permission rules and whitelist`, 1, 0),
107
110
  );
111
+ container.addChild(
112
+ new Text(
113
+ ` ${c.cyan}/copy${c.reset} [code] Copy last reply (or code block) to clipboard`,
114
+ 1,
115
+ 0,
116
+ ),
117
+ );
108
118
  if (isDebugEnabled()) {
109
119
  container.addChild(
110
120
  new Text(` ${c.cyan}/reload${c.reset} Hot-reload extensions (dev)`, 1, 0),
@@ -0,0 +1,88 @@
1
+ /**
2
+ * AssistantBody — the static rendering of one assistant message.
3
+ *
4
+ * Prose is handed to pi-tui's Markdown exactly as before; fenced code
5
+ * segments are extracted and drawn as language-tagged boxes
6
+ * (`codeBlockBox`) so snippets read as distinct blocks instead of running
7
+ * into the surrounding text.
8
+ *
9
+ * Rendering must be a pure function of (content, width): pi-tui repaints
10
+ * differentially and this component caches by width, so any clock or
11
+ * randomness would desync the screen from the cache on repaint/resize.
12
+ */
13
+
14
+ import {Markdown, type Component} from '@earendil-works/pi-tui';
15
+
16
+ import {markdownTheme} from '../theme.js';
17
+ import {codeBlockBox, parseCodeSegments} from '../utils/code-block.js';
18
+ import type {CodeSegment} from '../utils/code-block.js';
19
+
20
+ type BodySegment =
21
+ | {readonly kind: 'text'; readonly md: Markdown}
22
+ | {readonly kind: 'code'; readonly code: string; readonly lang: string};
23
+
24
+ function assertNever(x: never): never {
25
+ throw new Error(`unhandled code segment: ${JSON.stringify(x)}`);
26
+ }
27
+
28
+ function toBodySegment(seg: CodeSegment): BodySegment {
29
+ switch (seg.kind) {
30
+ case 'text':
31
+ return {kind: 'text', md: new Markdown(seg.text, 1, 0, markdownTheme)};
32
+ case 'code':
33
+ return {kind: 'code', code: seg.lines.join('\n'), lang: seg.lang};
34
+ default:
35
+ return assertNever(seg);
36
+ }
37
+ }
38
+
39
+ export class AssistantBody implements Component {
40
+ private segments: readonly BodySegment[];
41
+ private cached: string[] | null = null;
42
+ private cachedWidth = -1;
43
+
44
+ constructor(content: string) {
45
+ this.segments = parseCodeSegments(content).map(toBodySegment);
46
+ }
47
+
48
+ /**
49
+ * Swap the message content (streaming path) — re-parse segments and drop
50
+ * the width cache so the next render rebuilds. Callers repaint via
51
+ * `requestRender()`; an open trailing fence boxes immediately and closes
52
+ * when the closing fence streams in.
53
+ */
54
+ setText(content: string): void {
55
+ this.segments = parseCodeSegments(content).map(toBodySegment);
56
+ this.invalidate();
57
+ }
58
+
59
+ invalidate(): void {
60
+ this.cached = null;
61
+ this.cachedWidth = -1;
62
+ }
63
+
64
+ render(width: number): string[] {
65
+ if (this.cached && this.cachedWidth === width) return this.cached;
66
+
67
+ const out: string[] = [];
68
+ for (const seg of this.segments) {
69
+ if (out.length > 0) out.push(''); // one blank line between blocks
70
+ out.push(...renderSegment(seg, width));
71
+ }
72
+
73
+ this.cached = out;
74
+ this.cachedWidth = width;
75
+ return out;
76
+ }
77
+ }
78
+
79
+ function renderSegment(seg: BodySegment, width: number): string[] {
80
+ switch (seg.kind) {
81
+ case 'text':
82
+ return seg.md.render(width);
83
+ case 'code':
84
+ return codeBlockBox(seg.code, width, seg.lang).split('\n');
85
+ default:
86
+ return assertNever(seg);
87
+ }
88
+ }
@@ -10,10 +10,11 @@
10
10
  * than replaying hundreds of blocks at once.
11
11
  */
12
12
 
13
- import {Container, Text, Markdown} from '@earendil-works/pi-tui';
13
+ import {type Container, Text} from '@earendil-works/pi-tui';
14
14
  import type {StoredMessage, CompactionRecord} from '@pal-code/core';
15
15
 
16
- import {c, markdownTheme} from '../theme.js';
16
+ import {c} from '../theme.js';
17
+ import {AssistantBody} from './assistant-body.js';
17
18
  import {MessageBox} from './message-box.js';
18
19
  import {formatMessageTimestamp} from '../utils/format.js';
19
20
  import type {AgentRole} from '../state.js';
@@ -94,9 +95,9 @@ function renderMessage(container: Container, m: StoredMessage): void {
94
95
  return;
95
96
  }
96
97
 
97
- // assistant (with or without tool calls) — render the prose it produced
98
+ // assistant (with or without tool calls) — prose plus boxed code fences
98
99
  if (m.content && m.content.trim()) {
99
- container.addChild(new Markdown(m.content, 1, 0, markdownTheme));
100
+ container.addChild(new AssistantBody(m.content));
100
101
  }
101
102
  if (m.toolCalls?.length) {
102
103
  for (const tc of m.toolCalls) {
@@ -7,11 +7,12 @@
7
7
  * `finish()` collapses it to a one-line summary; `expand()` re-inflates it.
8
8
  */
9
9
 
10
- import {Container, Text, Markdown} from '@earendil-works/pi-tui';
10
+ import {Container, Text} from '@earendil-works/pi-tui';
11
11
  import type {TUI} from '@earendil-works/pi-tui';
12
12
 
13
- import {c, markdownTheme} from '../theme.js';
13
+ import {c} from '../theme.js';
14
14
  import {truncate} from '../utils/format.js';
15
+ import {AssistantBody} from './assistant-body.js';
15
16
  // ═══════════════════════════════════════════════════════════════════════════════
16
17
  // Live run view — one mutable block per turn instead of an append-only log
17
18
  // ═══════════════════════════════════════════════════════════════════════════════
@@ -40,8 +41,8 @@ export class RunView {
40
41
  private readonly rowTexts: Text[] = [];
41
42
  private summaryText: Text | null = null;
42
43
  /** All streaming answer blocks from every round — only the last is active. */
43
- private responses: Markdown[] = [];
44
- private response: Markdown | null = null;
44
+ private responses: AssistantBody[] = [];
45
+ private response: AssistantBody | null = null;
45
46
  /** True after finish() re-parented responses to `this.parent`. */
46
47
  private reParented = false;
47
48
  private roundNo = 0;
@@ -131,9 +132,9 @@ export class RunView {
131
132
  }
132
133
 
133
134
  /** The streaming answer block for the current round, created on first use. */
134
- responseBlock(): Markdown {
135
+ responseBlock(): AssistantBody {
135
136
  if (!this.response) {
136
- this.response = new Markdown('', 1, 0, markdownTheme);
137
+ this.response = new AssistantBody('');
137
138
  this.responses.push(this.response);
138
139
  this.container.addChild(this.response);
139
140
  }
@@ -38,11 +38,18 @@ import {renderHistory} from './components/render-history.js';
38
38
  import {loadConfig} from './config.js';
39
39
  import {StatusLine} from './components/status-line.js';
40
40
  import {PermissionPrompt} from './components/permission-prompt.js';
41
- import {state} from './state.js';
41
+ import {dequeueMessage, enqueueMessage, queuedStatusText, state} from './state.js';
42
42
  import {Sidebar} from './components/sidebar.js';
43
43
  import {cmdHelp, cmdCost} from './commands.js';
44
+ import {
45
+ loadUpdateCache,
46
+ planStartupNotice,
47
+ refreshUpdateCheck,
48
+ saveUpdateCache,
49
+ } from './commands/update-check.js';
44
50
  import {showSessionSelector, cmdResume} from './overlays/session-picker.js';
45
51
  import {loadCostManifest, estimateCost, isPricedModel} from './utils/cost.js';
52
+ import {buildOsc52Sequence, lastAssistantText, lastCodeBlock} from './utils/osc52.js';
46
53
  import {openAgentsPanel, closeAgentsPanel} from './agent-panel.js';
47
54
  import {
48
55
  createOpenRouterProvider,
@@ -88,7 +95,7 @@ import type {SessionStore as SessionStoreType} from '@pal-code/core';
88
95
  // (see buildModelOptions). Static curated lists live in @pal-code/core PROVIDERS as fallback.
89
96
 
90
97
  // Version synced from version.json via `node scripts/sync-version.js`.
91
- const VERSION = '0.0.12';
98
+ const VERSION = '0.0.13';
92
99
 
93
100
  import {showModelSelector} from './overlays/model-picker.js';
94
101
  import {showKeyInput} from './overlays/key-input.js';
@@ -149,6 +156,12 @@ async function main() {
149
156
  console.log(result.message);
150
157
  process.exit(result.ok ? 0 : 1);
151
158
  }
159
+ if (process.argv[2] === 'update' || process.argv[2] === 'upgrade') {
160
+ const {palUpdate} = await import('./commands/update.js');
161
+ const result = await palUpdate();
162
+ console.log(result.message);
163
+ process.exit(result.ok ? 0 : 1);
164
+ }
152
165
  // ── BYOK gate: force setup when no key is configured ──
153
166
  let allKeys = resolveAllKeys();
154
167
  const forceSetup = process.argv.includes('--setup') || process.argv.includes('--login');
@@ -246,6 +259,24 @@ async function main() {
246
259
  messagesContainer.addChild(
247
260
  new Text(`${c.dim}Model: ${config.model} (${providerName})${c.reset}`, 1, 0),
248
261
  );
262
+
263
+ // ── Update check ──
264
+ // Sync from the daily cache so startup never blocks; refresh below is
265
+ // fire-and-forget. Hint once per version (`notified`); yellow `critical`
266
+ // banner every launch until local catches up. Never auto-updates.
267
+ const updateCache = loadUpdateCache();
268
+ const updateNotice = planStartupNotice(updateCache, VERSION);
269
+ if (updateNotice.changed) saveUpdateCache({...updateCache, notified: updateNotice.notified});
270
+ if (updateNotice.banner) {
271
+ messagesContainer.addChild(new Text(`${c.yellow}${updateNotice.banner}${c.reset}`, 1, 0));
272
+ }
273
+ if (updateNotice.hint) {
274
+ messagesContainer.addChild(new Text(`${c.dim}${updateNotice.hint}${c.reset}`, 1, 0));
275
+ }
276
+ refreshUpdateCheck().catch(() => {
277
+ // silent by design — refreshUpdateCheck swallows its own errors
278
+ });
279
+
249
280
  if (!hasAnyKey(allKeys)) {
250
281
  messagesContainer.addChild(
251
282
  new Text(`${c.yellow} No API key configured. Type /keys to see status.${c.reset}`, 1, 0),
@@ -543,8 +574,12 @@ async function main() {
543
574
  `${c.cyan}↕ scrolled${c.reset} ${c.dim}· PgDn/↓ End or Esc to resume${c.reset}`,
544
575
  );
545
576
  } else {
577
+ // `queued (N)` — messages submitted while a turn runs (drained on
578
+ // settle). Empty at N=0, so the idle status line stays byte-identical.
579
+ const queuedText = queuedStatusText(state.pendingMessages.length);
580
+ const queuedStr = queuedText ? ` ${c.yellow}${queuedText}${c.reset}` : '';
546
581
  statusLine.setText(
547
- `${modelShort} ${c.dim}${providerName}${agentStr}${subStr}${c.reset} ${c.dim}/help${c.reset}`,
582
+ `${modelShort} ${c.dim}${providerName}${agentStr}${subStr}${queuedStr}${c.reset} ${c.dim}/help${c.reset}`,
548
583
  );
549
584
  }
550
585
  sidebar.setStats({
@@ -966,12 +1001,25 @@ async function main() {
966
1001
  let autoExecuted = false;
967
1002
 
968
1003
  editor.onSubmit = async (text) => {
969
- if (isProcessing) return;
970
1004
  // `let` so `/plan <task>` and `/execute <task>` can rewrite the input and
971
1005
  // fall through to the normal turn dispatch below.
972
1006
  let trimmed = text.trim();
973
1007
  if (!trimmed) return;
974
1008
 
1009
+ // A turn is running: the editor stays submittable — park the message on
1010
+ // the queue instead of starting a second turn. The settle path below
1011
+ // drains one message per settled turn (completion, error, or abort; an
1012
+ // abort never discards the queue). Slash commands queue the same way and
1013
+ // run in order when drained. A permission overlay consumes all keys
1014
+ // before this handler can run, so queueing never races the permission
1015
+ // prompt's own queue. Quitting the TUI (ctrl+c/d) drops whatever is
1016
+ // still queued — the queue is in-memory only.
1017
+ if (isProcessing) {
1018
+ enqueueMessage(state.pendingMessages, trimmed);
1019
+ state.refreshStatusLine();
1020
+ return;
1021
+ }
1022
+
975
1023
  editor.setText('');
976
1024
 
977
1025
  // ── Slash commands ──
@@ -1336,11 +1384,14 @@ async function main() {
1336
1384
  new Text(`${result.ok ? c.green : c.red} ${result.message}${c.reset}`, 1, 0),
1337
1385
  );
1338
1386
  } else if (sub === 'search') {
1339
- const {extSearch} = await import('./commands/ext.js');
1340
- const result = await extSearch(parts.slice(1).join(' '));
1387
+ const {extSearchOrBrowse} = await import('./commands/ext.js');
1388
+ const result = await extSearchOrBrowse(parts.slice(1).join(' '));
1341
1389
  messagesContainer.addChild(
1342
1390
  new Text(`${result.ok ? c.green : c.red} ${result.message}${c.reset}`, 1, 0),
1343
1391
  );
1392
+ } else if (sub === 'browse') {
1393
+ const {formatBrowse} = await import('./commands/ext-registry.js');
1394
+ messagesContainer.addChild(new Text(formatBrowse(c), 1, 0));
1344
1395
  } else if (sub === 'remove' && pkg) {
1345
1396
  const {extRemove} = await import('./commands/ext.js');
1346
1397
  const result = extRemove(pkg);
@@ -1354,7 +1405,8 @@ async function main() {
1354
1405
  return ` ${ext.name.padEnd(24)} ${status}`;
1355
1406
  });
1356
1407
  if (lines.length === 0) {
1357
- messagesContainer.addChild(new Text(`${c.dim} No extensions loaded.${c.reset}`, 1, 0));
1408
+ const {emptyListMessage} = await import('./commands/ext-registry.js');
1409
+ messagesContainer.addChild(new Text(`${c.dim} ${emptyListMessage()}${c.reset}`, 1, 0));
1358
1410
  } else {
1359
1411
  messagesContainer.addChild(
1360
1412
  new Text(`${c.bold}Loaded extensions${c.reset}\n${lines.join('\n')}`, 1, 0),
@@ -1363,7 +1415,7 @@ async function main() {
1363
1415
  } else {
1364
1416
  messagesContainer.addChild(
1365
1417
  new Text(
1366
- `${c.dim} Usage: /ext add <name> | /ext remove <name> | /ext search <query> | /ext list${c.reset}`,
1418
+ `${c.dim} Usage: /ext add <name> | /ext remove <name> | /ext search <query> | /ext list | /ext browse${c.reset}`,
1367
1419
  1,
1368
1420
  0,
1369
1421
  ),
@@ -1504,6 +1556,35 @@ async function main() {
1504
1556
  return;
1505
1557
  }
1506
1558
 
1559
+ if (trimmed === '/copy' || trimmed.startsWith('/copy ')) {
1560
+ const target = trimmed.slice('/copy'.length).trim();
1561
+ if (target !== '' && target !== 'code') {
1562
+ messagesContainer.addChild(
1563
+ new Text(
1564
+ `${c.dim} Usage: /copy Copy the last assistant reply to the clipboard${c.reset}\n` +
1565
+ `${c.dim} /copy code Copy the last code block from the conversation${c.reset}`,
1566
+ 1,
1567
+ 0,
1568
+ ),
1569
+ );
1570
+ } else {
1571
+ const text = target === 'code' ? lastCodeBlock(messages) : lastAssistantText(messages);
1572
+ if (text === null) {
1573
+ const empty = target === 'code' ? 'No code block found.' : 'Nothing to copy yet.';
1574
+ messagesContainer.addChild(new Text(`${c.dim} ${empty}${c.reset}`, 1, 0));
1575
+ } else {
1576
+ // pi-tui owns the screen but exposes its writer: OSC 52 must reach the
1577
+ // terminal verbatim (it is consumed by the terminal, not drawn).
1578
+ tui.terminal.write(buildOsc52Sequence(text));
1579
+ messagesContainer.addChild(
1580
+ new Text(`${c.green} Copied ${text.length} chars to clipboard${c.reset}`, 1, 0),
1581
+ );
1582
+ }
1583
+ }
1584
+ tui.requestRender();
1585
+ return;
1586
+ }
1587
+
1507
1588
  // ── Clear finished todos when user moves on to something new ──
1508
1589
  if (state.currentTodos.length > 0) {
1509
1590
  const allTerminal = state.currentTodos.every(
@@ -1530,8 +1611,9 @@ async function main() {
1530
1611
  // ── Agent turn ──
1531
1612
  // The selected primary agent shapes the turn itself (system prompt + tool
1532
1613
  // set) rather than being described in the message — see agentLoop.
1614
+ // The editor is NOT submission-gated: a submit during the turn queues
1615
+ // (see onSubmit) and drains when the turn settles.
1533
1616
  isProcessing = true;
1534
- editor.disableSubmit = true;
1535
1617
  autoExecuted = false;
1536
1618
 
1537
1619
  /**
@@ -1648,8 +1730,40 @@ async function main() {
1648
1730
  }
1649
1731
 
1650
1732
  isProcessing = false;
1651
- editor.disableSubmit = false;
1652
1733
  tui.requestRender();
1734
+
1735
+ // ── Drain queued messages ──
1736
+ // Every settle — completion, error, or abort — hands the next queued
1737
+ // message back to the normal submit path (identical to a fresh
1738
+ // submission). A submission that actually starts a turn stops the drain;
1739
+ // that turn's settle drains the one after it, so exactly one turn runs
1740
+ // per settle. An abort settles like any other turn: it never eats the
1741
+ // queue. A permission overlay cannot be open here (the loop awaits each
1742
+ // prompt and the overlay closes before the turn resumes), so drain never
1743
+ // conflicts with the permission queue. Quitting the TUI with messages
1744
+ // still queued drops them — in-memory only, see the enqueue comment.
1745
+ const firstQueued = dequeueMessage(state.pendingMessages);
1746
+ if (firstQueued !== null) {
1747
+ let nextQueued: string | null = firstQueued;
1748
+ while (nextQueued !== null) {
1749
+ // The submit handler clears the input synchronously — preserve
1750
+ // whatever the user has typed since their last submission.
1751
+ const draft = editor.getText();
1752
+ // Keep the handler's promise: a queued message can suspend BEFORE it
1753
+ // sets isProcessing (e.g. /plan awaits ensureExtensionsLoaded, then
1754
+ // falls through to a turn), which would let this loop start a second
1755
+ // turn concurrently. Awaiting makes each submission fully settle —
1756
+ // turn, inline command, or its own nested drain — before the next.
1757
+ const submitted = editor.onSubmit?.(nextQueued) ?? Promise.resolve();
1758
+ if (draft.length > 0) editor.setText(draft);
1759
+ await submitted;
1760
+ // A user submit can win the race during an inline command's await;
1761
+ // its settle will drain the rest of the queue.
1762
+ if (isProcessing) break;
1763
+ nextQueued = dequeueMessage(state.pendingMessages);
1764
+ }
1765
+ state.refreshStatusLine(); // drop the `queued (N)` indicator
1766
+ }
1653
1767
  };
1654
1768
 
1655
1769
  // ═══════════════════════════════════════════════════════════════════════════
@@ -80,6 +80,8 @@ export interface AppState {
80
80
  activeAbort: AbortController | null;
81
81
  /** The most recently collapsed run, for ctrl+o. */
82
82
  lastRun: RunView | null;
83
+ /** Messages submitted while a turn was running; drained one per settled turn. */
84
+ pendingMessages: string[];
83
85
  /** Loaded extensions and their status. */
84
86
  extensions: ExtensionInfo[];
85
87
  /** MCP servers discovered during startup. */
@@ -120,6 +122,7 @@ export const state: AppState = {
120
122
  activeRun: null,
121
123
  activeAbort: null,
122
124
  lastRun: null,
125
+ pendingMessages: [],
123
126
  extensions: [],
124
127
  mcpServers: [],
125
128
  currentAgentRole: 'pal',
@@ -131,3 +134,26 @@ export const state: AppState = {
131
134
  permissionPrompt: null,
132
135
  permissionQueue: [],
133
136
  };
137
+
138
+ /**
139
+ * Park a message submitted while a turn is running. Pure over `queue` so the
140
+ * decision logic is testable without the TUI. Returns the new length for the
141
+ * `queued (N)` status-line indicator.
142
+ */
143
+ export function enqueueMessage(queue: string[], message: string): number {
144
+ queue.push(message);
145
+ return queue.length;
146
+ }
147
+
148
+ /**
149
+ * Take the next message to run when a turn settles — completed, errored, or
150
+ * aborted alike. Returns null when nothing is queued.
151
+ */
152
+ export function dequeueMessage(queue: string[]): string | null {
153
+ return queue.shift() ?? null;
154
+ }
155
+
156
+ /** Status-line fragment: '' at 0 so the idle status line stays byte-identical. */
157
+ export function queuedStatusText(count: number): string {
158
+ return count > 0 ? `queued (${count})` : '';
159
+ }
@@ -190,6 +190,7 @@ async function gatedExecuteTool(
190
190
  readOnly?: boolean;
191
191
  allowedTools?: string[];
192
192
  },
193
+ signal?: AbortSignal,
193
194
  ): Promise<ToolResult> {
194
195
  // Parse args for permission check
195
196
  let args: Record<string, unknown> = {};
@@ -209,7 +210,7 @@ async function gatedExecuteTool(
209
210
  };
210
211
  }
211
212
 
212
- return executeTool(name, argsStr, toolCallId, providerConfigOverride);
213
+ return executeTool(name, argsStr, toolCallId, providerConfigOverride, signal);
213
214
  }
214
215
 
215
216
  export async function agentLoop(
@@ -0,0 +1,123 @@
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. pi-tui repaints differentially and the
6
+ * components cache by width, so a render that varies per call would desync
7
+ * the screen from the cache.
8
+ */
9
+
10
+ import {truncateToWidth} from '@earendil-works/pi-tui';
11
+
12
+ import {c} from '../theme.js';
13
+ import {buildHeader, displayWidth, wrapText} from './format.js';
14
+ import {highlightCode} from './highlight.js';
15
+
16
+ /** One piece of an assistant message: prose, or a fenced code block. */
17
+ export type CodeSegment =
18
+ | {readonly kind: 'text'; readonly text: string}
19
+ | {readonly kind: 'code'; readonly lang: string; readonly lines: readonly string[]};
20
+
21
+ // Opening fence: up to 3 leading spaces, 3+ backticks, then an info string
22
+ // that must not itself contain backticks (CommonMark) — so a line like
23
+ // "```code```" mid-paragraph stays prose.
24
+ const OPEN_FENCE = /^ {0,3}(`{3,})([^`]*)$/;
25
+ // Closing fence: backticks and whitespace only, and never shorter than the opener.
26
+ const CLOSE_FENCE = /^ {0,3}(`{3,})[ \t]*$/;
27
+
28
+ function trimBlankEdges(lines: readonly string[]): readonly string[] {
29
+ let start = 0;
30
+ let end = lines.length;
31
+ while (start < end && (lines[start] ?? '').trim() === '') start++;
32
+ while (end > start && (lines[end - 1] ?? '').trim() === '') end--;
33
+ return lines.slice(start, end);
34
+ }
35
+
36
+ /**
37
+ * Split markdown into prose and fenced code segments.
38
+ *
39
+ * Handles the edge cases that show up in real model output: an unclosed
40
+ * fence at the end of the message (runs to end), no language tag, padded or
41
+ * mixed-case tags, fences that interrupt a paragraph, CRLF endings, and
42
+ * longer (````) fences whose content contains triple backticks.
43
+ */
44
+ export function parseCodeSegments(text: string): CodeSegment[] {
45
+ const segments: CodeSegment[] = [];
46
+ let textLines: string[] = [];
47
+ let fence: {ticks: number; lang: string; lines: string[]} | null = null;
48
+
49
+ const flushText = (): void => {
50
+ const kept = trimBlankEdges(textLines);
51
+ textLines = [];
52
+ if (kept.length > 0) segments.push({kind: 'text', text: kept.join('\n')});
53
+ };
54
+
55
+ for (const line of text.split(/\r\n|\r|\n/)) {
56
+ if (fence) {
57
+ const close = CLOSE_FENCE.exec(line);
58
+ if (close && (close[1] ?? '').length >= fence.ticks) {
59
+ segments.push({kind: 'code', lang: fence.lang, lines: fence.lines});
60
+ fence = null;
61
+ } else {
62
+ fence.lines.push(line);
63
+ }
64
+ continue;
65
+ }
66
+
67
+ const open = OPEN_FENCE.exec(line);
68
+ if (open) {
69
+ flushText();
70
+ const info = (open[2] ?? '').trim();
71
+ fence = {
72
+ ticks: (open[1] ?? '').length,
73
+ lang: info.split(/\s+/)[0] ?? '',
74
+ lines: [],
75
+ };
76
+ continue;
77
+ }
78
+ textLines.push(line);
79
+ }
80
+
81
+ if (fence) segments.push({kind: 'code', lang: fence.lang, lines: fence.lines});
82
+ flushText();
83
+ return segments;
84
+ }
85
+
86
+ /**
87
+ * Render one fenced code segment as a bordered, language-tagged box:
88
+ *
89
+ * ╭─ typescript ────────╮
90
+ * │ const x = 1; │
91
+ * ╰─────────────────────╯
92
+ *
93
+ * Geometry mirrors `userMessageBox` (same W/inner/textWidth clamps, same
94
+ * `buildHeader` degradation on narrow widths) so every transcript box lines
95
+ * up. Code is syntax-highlighted via the existing `highlightCode` helper,
96
+ * then wrapped and hard-truncated to the box — no row ever exceeds `width`.
97
+ */
98
+ export function codeBlockBox(code: string, width: number, lang = ''): string {
99
+ // One clamp before anything is derived, so header/body/footer agree.
100
+ const W = Math.max(6, Math.floor(width));
101
+ const inner = W - 4; // columns between "│ " and " │"
102
+ const textWidth = Math.max(1, inner - 1); // reserve the last inner column
103
+
104
+ const tag = lang.trim();
105
+ // Border dimmed, language tag bright — same two-tier paint as the user box.
106
+ const paint = (s: string) => `${c.dim}${c.cyan}${s}${c.reset}`;
107
+
108
+ const header = tag
109
+ ? buildHeader(W, tag, displayWidth(tag), c.cyan, paint, '')
110
+ : paint(`╭${'─'.repeat(W - 2)}╮`);
111
+
112
+ const body = wrapText(highlightCode(code, tag || undefined).join('\n'), textWidth)
113
+ .map((line) => {
114
+ const safe = truncateToWidth(line.trimEnd(), textWidth, '');
115
+ const pad = Math.max(0, inner - displayWidth(safe));
116
+ return `${paint('│')} ${safe}${c.reset}${' '.repeat(pad)} ${paint('│')}`;
117
+ })
118
+ .join('\n');
119
+
120
+ const footer = paint(`╰${'─'.repeat(W - 2)}╯`);
121
+
122
+ return `${header}\n${body}\n${footer}`;
123
+ }
@@ -121,9 +121,13 @@ export function userMessageBox(
121
121
  * border can't drift — the failure mode when a tag was first added here.
122
122
  *
123
123
  * Both decorations are dropped, in order, when the box is too narrow:
124
- * timestamp first, then the tag, then a plain border.
124
+ * timestamp first, then the tag, then a plain border. Returns `''` when no
125
+ * tag fits at all, so callers that own a plain-border fallback can use it.
126
+ *
127
+ * Shared by `userMessageBox` and `codeBlockBox` so every transcript box
128
+ * frames its header the same way.
125
129
  */
126
- function buildHeader(
130
+ export function buildHeader(
127
131
  W: number,
128
132
  tagText: string,
129
133
  tagWidth: number,
@@ -0,0 +1,55 @@
1
+ /**
2
+ * OSC 52 clipboard yank helpers.
3
+ *
4
+ * Everything here is pure: which message/block counts as "last" and the exact
5
+ * bytes to put on the wire. The TUI branch only picks a payload and writes it,
6
+ * so the interesting logic is testable without a terminal.
7
+ */
8
+
9
+ import type {ConversationMessage} from '@pal-code/core';
10
+
11
+ /**
12
+ * Text of the most recent assistant reply, or null when there is none.
13
+ *
14
+ * An assistant message can be empty (tool-calls only), so scan backwards for
15
+ * the first one with something to copy rather than trusting the tail.
16
+ */
17
+ export function lastAssistantText(messages: readonly ConversationMessage[]): string | null {
18
+ for (let i = messages.length - 1; i >= 0; i--) {
19
+ const msg = messages[i];
20
+ if (msg.role === 'assistant' && msg.content.length > 0) return msg.content;
21
+ }
22
+ return null;
23
+ }
24
+
25
+ /**
26
+ * Inner text of the last fenced code block in the conversation, or null.
27
+ *
28
+ * Scans messages newest-first so the first message containing a block wins;
29
+ * the fence lines themselves are dropped — a clipboard yank wants the code.
30
+ * A fresh regex per call keeps `matchAll` free of shared lastIndex state.
31
+ */
32
+ export function lastCodeBlock(messages: readonly ConversationMessage[]): string | null {
33
+ for (let i = messages.length - 1; i >= 0; i--) {
34
+ const blocks = [...messages[i].content.matchAll(/```[^\n]*\n([\s\S]*?)```/g)];
35
+ if (blocks.length > 0) return blocks[blocks.length - 1][1];
36
+ }
37
+ return null;
38
+ }
39
+
40
+ /**
41
+ * Build the OSC 52 sequence that sets the system clipboard to `text`.
42
+ *
43
+ * tmux swallows OSC sequences emitted inside it, so under tmux the payload is
44
+ * wrapped in a DCS pass-through with every ESC doubled — otherwise the yank
45
+ * stops at tmux and never reaches the real terminal.
46
+ */
47
+ export function buildOsc52Sequence(
48
+ text: string,
49
+ env: Record<string, string | undefined> = process.env,
50
+ ): string {
51
+ const payload = `\x1b]52;c;${Buffer.from(text, 'utf8').toString('base64')}\x07`;
52
+ const tmuxTerm = env.TERM?.startsWith('tmux') ?? false;
53
+ if (!env.TMUX && !tmuxTerm) return payload;
54
+ return `\x1bPtmux;${payload.replaceAll('\x1b', '\x1b\x1b')}\x1b\\`;
55
+ }