pal-code 0.0.12 → 0.0.14
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 +2 -2
- package/packages/cli/src/commands/ext-registry.ts +83 -0
- package/packages/cli/src/commands/ext.ts +15 -1
- package/packages/cli/src/commands/update-check.ts +180 -0
- package/packages/cli/src/commands/update.ts +185 -0
- package/packages/cli/src/commands.ts +10 -0
- package/packages/cli/src/components/assistant-body.ts +88 -0
- package/packages/cli/src/components/render-history.ts +5 -4
- package/packages/cli/src/components/run-view.ts +7 -6
- package/packages/cli/src/index.ts +156 -40
- package/packages/cli/src/state.ts +60 -0
- package/packages/cli/src/turn.ts +2 -1
- package/packages/cli/src/utils/code-block.ts +123 -0
- package/packages/cli/src/utils/format.ts +6 -2
- package/packages/cli/src/utils/osc52.ts +55 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pal-code",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.14",
|
|
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.
|
|
65
|
+
"@pal-code/core": "0.0.14",
|
|
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
|
-
|
|
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
|
|
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
|
|
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) —
|
|
98
|
+
// assistant (with or without tool calls) — prose plus boxed code fences
|
|
98
99
|
if (m.content && m.content.trim()) {
|
|
99
|
-
container.addChild(new
|
|
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
|
|
10
|
+
import {Container, Text} from '@earendil-works/pi-tui';
|
|
11
11
|
import type {TUI} from '@earendil-works/pi-tui';
|
|
12
12
|
|
|
13
|
-
import {c
|
|
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:
|
|
44
|
-
private response:
|
|
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():
|
|
135
|
+
responseBlock(): AssistantBody {
|
|
135
136
|
if (!this.response) {
|
|
136
|
-
this.response = new
|
|
137
|
+
this.response = new AssistantBody('');
|
|
137
138
|
this.responses.push(this.response);
|
|
138
139
|
this.container.addChild(this.response);
|
|
139
140
|
}
|
|
@@ -38,11 +38,25 @@ 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 {
|
|
41
|
+
import {
|
|
42
|
+
dequeueMessage,
|
|
43
|
+
enqueueMessage,
|
|
44
|
+
queuedStatusText,
|
|
45
|
+
resetSessionTokenomics,
|
|
46
|
+
setSessionTokenomics,
|
|
47
|
+
state,
|
|
48
|
+
} from './state.js';
|
|
42
49
|
import {Sidebar} from './components/sidebar.js';
|
|
43
50
|
import {cmdHelp, cmdCost} from './commands.js';
|
|
51
|
+
import {
|
|
52
|
+
loadUpdateCache,
|
|
53
|
+
planStartupNotice,
|
|
54
|
+
refreshUpdateCheck,
|
|
55
|
+
saveUpdateCache,
|
|
56
|
+
} from './commands/update-check.js';
|
|
44
57
|
import {showSessionSelector, cmdResume} from './overlays/session-picker.js';
|
|
45
58
|
import {loadCostManifest, estimateCost, isPricedModel} from './utils/cost.js';
|
|
59
|
+
import {buildOsc52Sequence, lastAssistantText, lastCodeBlock} from './utils/osc52.js';
|
|
46
60
|
import {openAgentsPanel, closeAgentsPanel} from './agent-panel.js';
|
|
47
61
|
import {
|
|
48
62
|
createOpenRouterProvider,
|
|
@@ -88,7 +102,7 @@ import type {SessionStore as SessionStoreType} from '@pal-code/core';
|
|
|
88
102
|
// (see buildModelOptions). Static curated lists live in @pal-code/core PROVIDERS as fallback.
|
|
89
103
|
|
|
90
104
|
// Version synced from version.json via `node scripts/sync-version.js`.
|
|
91
|
-
const VERSION = '0.0.
|
|
105
|
+
const VERSION = '0.0.14';
|
|
92
106
|
|
|
93
107
|
import {showModelSelector} from './overlays/model-picker.js';
|
|
94
108
|
import {showKeyInput} from './overlays/key-input.js';
|
|
@@ -149,6 +163,12 @@ async function main() {
|
|
|
149
163
|
console.log(result.message);
|
|
150
164
|
process.exit(result.ok ? 0 : 1);
|
|
151
165
|
}
|
|
166
|
+
if (process.argv[2] === 'update' || process.argv[2] === 'upgrade') {
|
|
167
|
+
const {palUpdate} = await import('./commands/update.js');
|
|
168
|
+
const result = await palUpdate();
|
|
169
|
+
console.log(result.message);
|
|
170
|
+
process.exit(result.ok ? 0 : 1);
|
|
171
|
+
}
|
|
152
172
|
// ── BYOK gate: force setup when no key is configured ──
|
|
153
173
|
let allKeys = resolveAllKeys();
|
|
154
174
|
const forceSetup = process.argv.includes('--setup') || process.argv.includes('--login');
|
|
@@ -216,10 +236,9 @@ async function main() {
|
|
|
216
236
|
});
|
|
217
237
|
|
|
218
238
|
// ── Token / cost tracking ──
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
let totalCost = 0;
|
|
239
|
+
// Per-session stats live on `state.sessionTokenomics` (one state-owned
|
|
240
|
+
// object): accumulated per turn, zeroed on /new, restored on both resume
|
|
241
|
+
// paths, and persisted with the session row on every saveSession().
|
|
223
242
|
|
|
224
243
|
// ═══════════════════════════════════════════════════════════════
|
|
225
244
|
// TUI Setup
|
|
@@ -246,6 +265,24 @@ async function main() {
|
|
|
246
265
|
messagesContainer.addChild(
|
|
247
266
|
new Text(`${c.dim}Model: ${config.model} (${providerName})${c.reset}`, 1, 0),
|
|
248
267
|
);
|
|
268
|
+
|
|
269
|
+
// ── Update check ──
|
|
270
|
+
// Sync from the daily cache so startup never blocks; refresh below is
|
|
271
|
+
// fire-and-forget. Hint once per version (`notified`); yellow `critical`
|
|
272
|
+
// banner every launch until local catches up. Never auto-updates.
|
|
273
|
+
const updateCache = loadUpdateCache();
|
|
274
|
+
const updateNotice = planStartupNotice(updateCache, VERSION);
|
|
275
|
+
if (updateNotice.changed) saveUpdateCache({...updateCache, notified: updateNotice.notified});
|
|
276
|
+
if (updateNotice.banner) {
|
|
277
|
+
messagesContainer.addChild(new Text(`${c.yellow}${updateNotice.banner}${c.reset}`, 1, 0));
|
|
278
|
+
}
|
|
279
|
+
if (updateNotice.hint) {
|
|
280
|
+
messagesContainer.addChild(new Text(`${c.dim}${updateNotice.hint}${c.reset}`, 1, 0));
|
|
281
|
+
}
|
|
282
|
+
refreshUpdateCheck().catch(() => {
|
|
283
|
+
// silent by design — refreshUpdateCheck swallows its own errors
|
|
284
|
+
});
|
|
285
|
+
|
|
249
286
|
if (!hasAnyKey(allKeys)) {
|
|
250
287
|
messagesContainer.addChild(
|
|
251
288
|
new Text(`${c.yellow} No API key configured. Type /keys to see status.${c.reset}`, 1, 0),
|
|
@@ -543,15 +580,19 @@ async function main() {
|
|
|
543
580
|
`${c.cyan}↕ scrolled${c.reset} ${c.dim}· PgDn/↓ End or Esc to resume${c.reset}`,
|
|
544
581
|
);
|
|
545
582
|
} else {
|
|
583
|
+
// `queued (N)` — messages submitted while a turn runs (drained on
|
|
584
|
+
// settle). Empty at N=0, so the idle status line stays byte-identical.
|
|
585
|
+
const queuedText = queuedStatusText(state.pendingMessages.length);
|
|
586
|
+
const queuedStr = queuedText ? ` ${c.yellow}${queuedText}${c.reset}` : '';
|
|
546
587
|
statusLine.setText(
|
|
547
|
-
`${modelShort} ${c.dim}${providerName}${agentStr}${subStr}${c.reset} ${c.dim}/help${c.reset}`,
|
|
588
|
+
`${modelShort} ${c.dim}${providerName}${agentStr}${subStr}${queuedStr}${c.reset} ${c.dim}/help${c.reset}`,
|
|
548
589
|
);
|
|
549
590
|
}
|
|
550
591
|
sidebar.setStats({
|
|
551
|
-
inputTokens:
|
|
552
|
-
outputTokens:
|
|
553
|
-
cachedTokens:
|
|
554
|
-
cost:
|
|
592
|
+
inputTokens: state.sessionTokenomics.inputTokens,
|
|
593
|
+
outputTokens: state.sessionTokenomics.outputTokens,
|
|
594
|
+
cachedTokens: state.sessionTokenomics.cachedTokens,
|
|
595
|
+
cost: state.sessionTokenomics.cost,
|
|
555
596
|
contextPct,
|
|
556
597
|
priced: isPricedModel(config.model),
|
|
557
598
|
});
|
|
@@ -589,12 +630,7 @@ async function main() {
|
|
|
589
630
|
// ── Session persistence helper ──
|
|
590
631
|
function saveSession() {
|
|
591
632
|
if (messages.length > 0 && store) {
|
|
592
|
-
const tok = {
|
|
593
|
-
inputTokens: totalInputTokens,
|
|
594
|
-
outputTokens: totalOutputTokens,
|
|
595
|
-
cachedTokens: totalCachedTokens,
|
|
596
|
-
cost: totalCost,
|
|
597
|
-
};
|
|
633
|
+
const tok = {...state.sessionTokenomics};
|
|
598
634
|
// Metadata for repaint: tool names/status derived from the messages, plus
|
|
599
635
|
// the agent role recorded for each user turn.
|
|
600
636
|
const meta = deriveMessageMeta(messages).map((m, i) => {
|
|
@@ -675,12 +711,7 @@ async function main() {
|
|
|
675
711
|
const session = s.get(sessionId);
|
|
676
712
|
if (!session) return;
|
|
677
713
|
if (messages.length > 0 && currentSessionId) {
|
|
678
|
-
s.update(currentSessionId, messages, {
|
|
679
|
-
inputTokens: totalInputTokens,
|
|
680
|
-
outputTokens: totalOutputTokens,
|
|
681
|
-
cachedTokens: totalCachedTokens,
|
|
682
|
-
cost: totalCost,
|
|
683
|
-
});
|
|
714
|
+
s.update(currentSessionId, messages, {...state.sessionTokenomics});
|
|
684
715
|
}
|
|
685
716
|
messages.length = 0;
|
|
686
717
|
messages.push(...(session.messages as Message[]));
|
|
@@ -688,11 +719,7 @@ async function main() {
|
|
|
688
719
|
currentSessionId = session.id;
|
|
689
720
|
state.sessionTitle = session.title ?? null;
|
|
690
721
|
// Restore tokenomics from the resumed session.
|
|
691
|
-
|
|
692
|
-
totalInputTokens = tok.inputTokens;
|
|
693
|
-
totalOutputTokens = tok.outputTokens;
|
|
694
|
-
totalCachedTokens = tok.cachedTokens;
|
|
695
|
-
totalCost = tok.cost;
|
|
722
|
+
setSessionTokenomics(session.tokenomics);
|
|
696
723
|
// The in-memory todo plan belongs to the previous conversation.
|
|
697
724
|
clearTodos();
|
|
698
725
|
state.currentTodos = [];
|
|
@@ -966,12 +993,25 @@ async function main() {
|
|
|
966
993
|
let autoExecuted = false;
|
|
967
994
|
|
|
968
995
|
editor.onSubmit = async (text) => {
|
|
969
|
-
if (isProcessing) return;
|
|
970
996
|
// `let` so `/plan <task>` and `/execute <task>` can rewrite the input and
|
|
971
997
|
// fall through to the normal turn dispatch below.
|
|
972
998
|
let trimmed = text.trim();
|
|
973
999
|
if (!trimmed) return;
|
|
974
1000
|
|
|
1001
|
+
// A turn is running: the editor stays submittable — park the message on
|
|
1002
|
+
// the queue instead of starting a second turn. The settle path below
|
|
1003
|
+
// drains one message per settled turn (completion, error, or abort; an
|
|
1004
|
+
// abort never discards the queue). Slash commands queue the same way and
|
|
1005
|
+
// run in order when drained. A permission overlay consumes all keys
|
|
1006
|
+
// before this handler can run, so queueing never races the permission
|
|
1007
|
+
// prompt's own queue. Quitting the TUI (ctrl+c/d) drops whatever is
|
|
1008
|
+
// still queued — the queue is in-memory only.
|
|
1009
|
+
if (isProcessing) {
|
|
1010
|
+
enqueueMessage(state.pendingMessages, trimmed);
|
|
1011
|
+
state.refreshStatusLine();
|
|
1012
|
+
return;
|
|
1013
|
+
}
|
|
1014
|
+
|
|
975
1015
|
editor.setText('');
|
|
976
1016
|
|
|
977
1017
|
// ── Slash commands ──
|
|
@@ -1100,7 +1140,9 @@ async function main() {
|
|
|
1100
1140
|
clearTodos();
|
|
1101
1141
|
state.currentTodos = [];
|
|
1102
1142
|
state.permissionWhitelist = [];
|
|
1143
|
+
resetSessionTokenomics();
|
|
1103
1144
|
refreshSidebar();
|
|
1145
|
+
updateStatusLine();
|
|
1104
1146
|
messagesContainer.addChild(new Text(`${c.yellow}New session started.${c.reset}`, 1, 0));
|
|
1105
1147
|
tui.requestRender();
|
|
1106
1148
|
return;
|
|
@@ -1270,10 +1312,17 @@ async function main() {
|
|
|
1270
1312
|
messagesContainer,
|
|
1271
1313
|
tui,
|
|
1272
1314
|
);
|
|
1315
|
+
// cmdResume only swaps in the messages — pull the resumed session's
|
|
1316
|
+
// token stats too (zeros when the lookup failed and nothing resumed).
|
|
1317
|
+
const resumed = currentSessionId ? store.get(currentSessionId) : null;
|
|
1318
|
+
if (resumed) setSessionTokenomics(resumed.tokenomics);
|
|
1319
|
+
else resetSessionTokenomics();
|
|
1320
|
+
updateStatusLine();
|
|
1273
1321
|
return;
|
|
1274
1322
|
}
|
|
1275
1323
|
if (trimmed === '/cost') {
|
|
1276
|
-
|
|
1324
|
+
const tok = state.sessionTokenomics;
|
|
1325
|
+
cmdCost(tok.inputTokens, tok.outputTokens, tok.cost, config.model, messagesContainer, tui);
|
|
1277
1326
|
return;
|
|
1278
1327
|
}
|
|
1279
1328
|
if (trimmed === '/model' || trimmed === '/model ') {
|
|
@@ -1336,11 +1385,14 @@ async function main() {
|
|
|
1336
1385
|
new Text(`${result.ok ? c.green : c.red} ${result.message}${c.reset}`, 1, 0),
|
|
1337
1386
|
);
|
|
1338
1387
|
} else if (sub === 'search') {
|
|
1339
|
-
const {
|
|
1340
|
-
const result = await
|
|
1388
|
+
const {extSearchOrBrowse} = await import('./commands/ext.js');
|
|
1389
|
+
const result = await extSearchOrBrowse(parts.slice(1).join(' '));
|
|
1341
1390
|
messagesContainer.addChild(
|
|
1342
1391
|
new Text(`${result.ok ? c.green : c.red} ${result.message}${c.reset}`, 1, 0),
|
|
1343
1392
|
);
|
|
1393
|
+
} else if (sub === 'browse') {
|
|
1394
|
+
const {formatBrowse} = await import('./commands/ext-registry.js');
|
|
1395
|
+
messagesContainer.addChild(new Text(formatBrowse(c), 1, 0));
|
|
1344
1396
|
} else if (sub === 'remove' && pkg) {
|
|
1345
1397
|
const {extRemove} = await import('./commands/ext.js');
|
|
1346
1398
|
const result = extRemove(pkg);
|
|
@@ -1354,7 +1406,8 @@ async function main() {
|
|
|
1354
1406
|
return ` ${ext.name.padEnd(24)} ${status}`;
|
|
1355
1407
|
});
|
|
1356
1408
|
if (lines.length === 0) {
|
|
1357
|
-
|
|
1409
|
+
const {emptyListMessage} = await import('./commands/ext-registry.js');
|
|
1410
|
+
messagesContainer.addChild(new Text(`${c.dim} ${emptyListMessage()}${c.reset}`, 1, 0));
|
|
1358
1411
|
} else {
|
|
1359
1412
|
messagesContainer.addChild(
|
|
1360
1413
|
new Text(`${c.bold}Loaded extensions${c.reset}\n${lines.join('\n')}`, 1, 0),
|
|
@@ -1363,7 +1416,7 @@ async function main() {
|
|
|
1363
1416
|
} else {
|
|
1364
1417
|
messagesContainer.addChild(
|
|
1365
1418
|
new Text(
|
|
1366
|
-
`${c.dim} Usage: /ext add <name> | /ext remove <name> | /ext search <query> | /ext list${c.reset}`,
|
|
1419
|
+
`${c.dim} Usage: /ext add <name> | /ext remove <name> | /ext search <query> | /ext list | /ext browse${c.reset}`,
|
|
1367
1420
|
1,
|
|
1368
1421
|
0,
|
|
1369
1422
|
),
|
|
@@ -1504,6 +1557,35 @@ async function main() {
|
|
|
1504
1557
|
return;
|
|
1505
1558
|
}
|
|
1506
1559
|
|
|
1560
|
+
if (trimmed === '/copy' || trimmed.startsWith('/copy ')) {
|
|
1561
|
+
const target = trimmed.slice('/copy'.length).trim();
|
|
1562
|
+
if (target !== '' && target !== 'code') {
|
|
1563
|
+
messagesContainer.addChild(
|
|
1564
|
+
new Text(
|
|
1565
|
+
`${c.dim} Usage: /copy Copy the last assistant reply to the clipboard${c.reset}\n` +
|
|
1566
|
+
`${c.dim} /copy code Copy the last code block from the conversation${c.reset}`,
|
|
1567
|
+
1,
|
|
1568
|
+
0,
|
|
1569
|
+
),
|
|
1570
|
+
);
|
|
1571
|
+
} else {
|
|
1572
|
+
const text = target === 'code' ? lastCodeBlock(messages) : lastAssistantText(messages);
|
|
1573
|
+
if (text === null) {
|
|
1574
|
+
const empty = target === 'code' ? 'No code block found.' : 'Nothing to copy yet.';
|
|
1575
|
+
messagesContainer.addChild(new Text(`${c.dim} ${empty}${c.reset}`, 1, 0));
|
|
1576
|
+
} else {
|
|
1577
|
+
// pi-tui owns the screen but exposes its writer: OSC 52 must reach the
|
|
1578
|
+
// terminal verbatim (it is consumed by the terminal, not drawn).
|
|
1579
|
+
tui.terminal.write(buildOsc52Sequence(text));
|
|
1580
|
+
messagesContainer.addChild(
|
|
1581
|
+
new Text(`${c.green} Copied ${text.length} chars to clipboard${c.reset}`, 1, 0),
|
|
1582
|
+
);
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1585
|
+
tui.requestRender();
|
|
1586
|
+
return;
|
|
1587
|
+
}
|
|
1588
|
+
|
|
1507
1589
|
// ── Clear finished todos when user moves on to something new ──
|
|
1508
1590
|
if (state.currentTodos.length > 0) {
|
|
1509
1591
|
const allTerminal = state.currentTodos.every(
|
|
@@ -1530,8 +1612,9 @@ async function main() {
|
|
|
1530
1612
|
// ── Agent turn ──
|
|
1531
1613
|
// The selected primary agent shapes the turn itself (system prompt + tool
|
|
1532
1614
|
// set) rather than being described in the message — see agentLoop.
|
|
1615
|
+
// The editor is NOT submission-gated: a submit during the turn queues
|
|
1616
|
+
// (see onSubmit) and drains when the turn settles.
|
|
1533
1617
|
isProcessing = true;
|
|
1534
|
-
editor.disableSubmit = true;
|
|
1535
1618
|
autoExecuted = false;
|
|
1536
1619
|
|
|
1537
1620
|
/**
|
|
@@ -1577,16 +1660,17 @@ async function main() {
|
|
|
1577
1660
|
state.lastRun = state.activeRun; // ctrl+o can re-inflate this run
|
|
1578
1661
|
}
|
|
1579
1662
|
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1663
|
+
const tok = state.sessionTokenomics;
|
|
1664
|
+
tok.inputTokens += result.inputTokens;
|
|
1665
|
+
tok.cachedTokens += result.cachedTokens;
|
|
1666
|
+
tok.outputTokens += result.outputTokens;
|
|
1583
1667
|
const turnCost = estimateCost(
|
|
1584
1668
|
result.model,
|
|
1585
1669
|
result.inputTokens,
|
|
1586
1670
|
result.outputTokens,
|
|
1587
1671
|
result.cachedTokens,
|
|
1588
1672
|
);
|
|
1589
|
-
|
|
1673
|
+
tok.cost += turnCost;
|
|
1590
1674
|
|
|
1591
1675
|
updateStatusLine();
|
|
1592
1676
|
saveSession();
|
|
@@ -1648,8 +1732,40 @@ async function main() {
|
|
|
1648
1732
|
}
|
|
1649
1733
|
|
|
1650
1734
|
isProcessing = false;
|
|
1651
|
-
editor.disableSubmit = false;
|
|
1652
1735
|
tui.requestRender();
|
|
1736
|
+
|
|
1737
|
+
// ── Drain queued messages ──
|
|
1738
|
+
// Every settle — completion, error, or abort — hands the next queued
|
|
1739
|
+
// message back to the normal submit path (identical to a fresh
|
|
1740
|
+
// submission). A submission that actually starts a turn stops the drain;
|
|
1741
|
+
// that turn's settle drains the one after it, so exactly one turn runs
|
|
1742
|
+
// per settle. An abort settles like any other turn: it never eats the
|
|
1743
|
+
// queue. A permission overlay cannot be open here (the loop awaits each
|
|
1744
|
+
// prompt and the overlay closes before the turn resumes), so drain never
|
|
1745
|
+
// conflicts with the permission queue. Quitting the TUI with messages
|
|
1746
|
+
// still queued drops them — in-memory only, see the enqueue comment.
|
|
1747
|
+
const firstQueued = dequeueMessage(state.pendingMessages);
|
|
1748
|
+
if (firstQueued !== null) {
|
|
1749
|
+
let nextQueued: string | null = firstQueued;
|
|
1750
|
+
while (nextQueued !== null) {
|
|
1751
|
+
// The submit handler clears the input synchronously — preserve
|
|
1752
|
+
// whatever the user has typed since their last submission.
|
|
1753
|
+
const draft = editor.getText();
|
|
1754
|
+
// Keep the handler's promise: a queued message can suspend BEFORE it
|
|
1755
|
+
// sets isProcessing (e.g. /plan awaits ensureExtensionsLoaded, then
|
|
1756
|
+
// falls through to a turn), which would let this loop start a second
|
|
1757
|
+
// turn concurrently. Awaiting makes each submission fully settle —
|
|
1758
|
+
// turn, inline command, or its own nested drain — before the next.
|
|
1759
|
+
const submitted = editor.onSubmit?.(nextQueued) ?? Promise.resolve();
|
|
1760
|
+
if (draft.length > 0) editor.setText(draft);
|
|
1761
|
+
await submitted;
|
|
1762
|
+
// A user submit can win the race during an inline command's await;
|
|
1763
|
+
// its settle will drain the rest of the queue.
|
|
1764
|
+
if (isProcessing) break;
|
|
1765
|
+
nextQueued = dequeueMessage(state.pendingMessages);
|
|
1766
|
+
}
|
|
1767
|
+
state.refreshStatusLine(); // drop the `queued (N)` indicator
|
|
1768
|
+
}
|
|
1653
1769
|
};
|
|
1654
1770
|
|
|
1655
1771
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
* does belongs in `@pal-code/core` (see SYSTEM.md).
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
|
+
import type {SessionTokenomics} from '@pal-code/core';
|
|
19
20
|
import type {RunView} from './components/run-view.js';
|
|
20
21
|
import type {PermissionPrompt} from './components/permission-prompt.js';
|
|
21
22
|
|
|
@@ -80,6 +81,8 @@ export interface AppState {
|
|
|
80
81
|
activeAbort: AbortController | null;
|
|
81
82
|
/** The most recently collapsed run, for ctrl+o. */
|
|
82
83
|
lastRun: RunView | null;
|
|
84
|
+
/** Messages submitted while a turn was running; drained one per settled turn. */
|
|
85
|
+
pendingMessages: string[];
|
|
83
86
|
/** Loaded extensions and their status. */
|
|
84
87
|
extensions: ExtensionInfo[];
|
|
85
88
|
/** MCP servers discovered during startup. */
|
|
@@ -107,6 +110,15 @@ export interface AppState {
|
|
|
107
110
|
target: string;
|
|
108
111
|
summary: string;
|
|
109
112
|
}>;
|
|
113
|
+
|
|
114
|
+
// ── Session-scoped tokenomics ──
|
|
115
|
+
/**
|
|
116
|
+
* Accumulated token usage and cost for the *current* session only — the
|
|
117
|
+
* sidebar stats, `/cost`, and `saveSession` all read this single object.
|
|
118
|
+
* Zeroed on `/new`, restored when a session is resumed, and persisted with
|
|
119
|
+
* the session row on every save.
|
|
120
|
+
*/
|
|
121
|
+
sessionTokenomics: SessionTokenomics;
|
|
110
122
|
}
|
|
111
123
|
|
|
112
124
|
export const state: AppState = {
|
|
@@ -120,6 +132,7 @@ export const state: AppState = {
|
|
|
120
132
|
activeRun: null,
|
|
121
133
|
activeAbort: null,
|
|
122
134
|
lastRun: null,
|
|
135
|
+
pendingMessages: [],
|
|
123
136
|
extensions: [],
|
|
124
137
|
mcpServers: [],
|
|
125
138
|
currentAgentRole: 'pal',
|
|
@@ -130,4 +143,51 @@ export const state: AppState = {
|
|
|
130
143
|
pendingPermission: null,
|
|
131
144
|
permissionPrompt: null,
|
|
132
145
|
permissionQueue: [],
|
|
146
|
+
sessionTokenomics: {inputTokens: 0, outputTokens: 0, cachedTokens: 0, cost: 0},
|
|
133
147
|
};
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Park a message submitted while a turn is running. Pure over `queue` so the
|
|
151
|
+
* decision logic is testable without the TUI. Returns the new length for the
|
|
152
|
+
* `queued (N)` status-line indicator.
|
|
153
|
+
*/
|
|
154
|
+
export function enqueueMessage(queue: string[], message: string): number {
|
|
155
|
+
queue.push(message);
|
|
156
|
+
return queue.length;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Take the next message to run when a turn settles — completed, errored, or
|
|
161
|
+
* aborted alike. Returns null when nothing is queued.
|
|
162
|
+
*/
|
|
163
|
+
export function dequeueMessage(queue: string[]): string | null {
|
|
164
|
+
return queue.shift() ?? null;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Status-line fragment: '' at 0 so the idle status line stays byte-identical. */
|
|
168
|
+
export function queuedStatusText(count: number): string {
|
|
169
|
+
return count > 0 ? `queued (${count})` : '';
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Zero the current session's token stats — called by `/new` so a fresh
|
|
174
|
+
* session starts from a clean slate instead of inheriting the previous
|
|
175
|
+
* session's lifetime totals.
|
|
176
|
+
*/
|
|
177
|
+
export function resetSessionTokenomics(): void {
|
|
178
|
+
state.sessionTokenomics = {inputTokens: 0, outputTokens: 0, cachedTokens: 0, cost: 0};
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Overwrite the current session's token stats — called on resume so the
|
|
183
|
+
* sidebar and `/cost` show the persisted totals of the session being resumed.
|
|
184
|
+
* Copies the four fields so the state slot never aliases a caller-owned object.
|
|
185
|
+
*/
|
|
186
|
+
export function setSessionTokenomics(t: SessionTokenomics): void {
|
|
187
|
+
state.sessionTokenomics = {
|
|
188
|
+
inputTokens: t.inputTokens,
|
|
189
|
+
outputTokens: t.outputTokens,
|
|
190
|
+
cachedTokens: t.cachedTokens,
|
|
191
|
+
cost: t.cost,
|
|
192
|
+
};
|
|
193
|
+
}
|
package/packages/cli/src/turn.ts
CHANGED
|
@@ -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
|
+
}
|