@notrico/pi-fold 3.0.5 → 3.1.1
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/CHANGELOG.md +12 -0
- package/README.md +1 -1
- package/docs/compatibility-testing.md +17 -0
- package/docs/implementation.md +1 -1
- package/docs/renderer-reference.md +1 -1
- package/index.ts +37 -23
- package/package.json +3 -2
- package/scripts/compatibility-check.mjs +40 -0
- package/scripts/compatibility-cli-smoke.mjs +41 -0
- package/scripts/preview-scroll.mjs +9 -0
- package/scripts/preview-work-strip.mjs +15 -1
- package/scripts/test.mjs +2 -2
- package/src/action-intent.ts +5 -1
- package/src/display-card.ts +2 -1
- package/src/fold-command.ts +7 -3
- package/src/fullscreen-overlays.ts +13 -11
- package/src/inspection.ts +19 -12
- package/src/modern-native-tools.ts +13 -7
- package/src/modern-prompts-adapter.ts +9 -7
- package/src/modern-skill-prompts.ts +17 -10
- package/src/modern-subagent-messages.ts +16 -7
- package/src/modern-subagent-spacing.ts +8 -6
- package/src/modern-thinking-adapter.ts +13 -9
- package/src/modern-thinking.ts +1 -1
- package/src/modern-tool-images.ts +8 -6
- package/src/modern-tools.ts +74 -30
- package/src/modern-workflows.ts +12 -7
- package/src/permission-presentation.ts +2 -1
- package/src/runtime-compatibility.ts +53 -14
- package/src/work-strip.ts +11 -9
- package/tests/action-intent.test.mjs +2 -0
- package/tests/codemode-wheel.test.mjs +111 -0
- package/tests/codemode.test.mjs +1 -1
- package/tests/compatibility-fallbacks.test.mjs +99 -0
- package/tests/display-cache-lifecycle.test.mjs +3 -3
- package/tests/fold-command.test.mjs +4 -4
- package/tests/fullscreen-overlays.test.mjs +4 -2
- package/tests/inspection.test.mjs +1 -1
- package/tests/modern-prompts.test.mjs +2 -2
- package/tests/modern-subagent-messages.test.mjs +2 -2
- package/tests/modern-thinking.test.mjs +2 -2
- package/tests/modern-tools.test.mjs +17 -8
- package/tests/modern-workflows.test.mjs +2 -2
- package/tests/ordinary-prompts.test.mjs +0 -1
- package/tests/preview-example.test.mjs +2 -2
- package/tests/runtime-compatibility.test.mjs +48 -21
- package/tests/subagent-spacing.test.mjs +1 -1
- package/tests/work-strip-hierarchy.test.mjs +0 -1
- package/tests/work-strip.test.mjs +13 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# Release notes
|
|
2
2
|
|
|
3
|
+
## 3.1.1 — Clearer action headings
|
|
4
|
+
|
|
5
|
+
- Show a short description of a folded action group before the per-tool call counts.
|
|
6
|
+
- Show the failure reason directly in a failed tool heading. Keep an uncertain outcome visible, including when a timeout leaves a commit unconfirmed.
|
|
7
|
+
|
|
8
|
+
## 3.1.0
|
|
9
|
+
|
|
10
|
+
- Enable features by available Pi interfaces instead of an exact version list.
|
|
11
|
+
- Report full, partial, or unavailable support through `/fold status`; preserve native rendering when an adapter is unavailable.
|
|
12
|
+
- Keep tool results visible when subagent grouping or image adapters are unavailable.
|
|
13
|
+
- Check Pi 1.3.0 and the latest stable release in CI, including actual CLI extension startup.
|
|
14
|
+
|
|
3
15
|
## 3.0.5 — Pi 1.4 compatibility
|
|
4
16
|
|
|
5
17
|
- Enable the verified renderer adapters on Pi 1.4.0. Retain Pi 1.3.0 support and checks for unfamiliar component layouts.
|
package/README.md
CHANGED
|
@@ -12,7 +12,7 @@ Replies without tool or subagent activity skip the work strip.
|
|
|
12
12
|
|
|
13
13
|
## Install
|
|
14
14
|
|
|
15
|
-
Tested with **Pi 1.3.0 and 1.4.0**, and **Node.js 22.19.0 or later**.
|
|
15
|
+
Tested with **Pi 1.3.0 and 1.4.0**, and **Node.js 22.19.0 or later**. Fold checks each feature’s required interfaces, so compatible newer Pi releases can work without a Fold update. Run `/fold status` for full, partial, or unavailable support. Missing interfaces use native rendering. [Compatibility checks](docs/compatibility-testing.md) run against Pi 1.3.0 and the latest stable release.
|
|
16
16
|
|
|
17
17
|
```sh
|
|
18
18
|
pi install npm:@notrico/pi-fold@3.0.5
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Pi compatibility checks
|
|
2
|
+
|
|
3
|
+
The GitHub Actions workflow runs the native regression suite against Pi core 1.3.0, the oldest supported release, and the `latest` dist-tag resolved from npm at run time. Each matrix job installs Pi core, `pi-subagents` 0.79.2, `pi-prompt-jump` 0.1.0, and `pi-questions` into a fresh temporary directory. It verifies the installed core version, then sets `PI_RUNTIME` and `PI_INSTALL_ROOT` for the existing suite. It then starts the actual bundled CLI in an isolated RPC session and checks that `/fold` and `/inspect` register. No prompt is submitted. This keeps the selected core version explicit and prevents an unrelated peer dependency from silently choosing the test runtime.
|
|
4
|
+
|
|
5
|
+
The workflow runs on pushes, pull requests, manual dispatch, and weekly on Monday. It reads package metadata from the public npm registry. It does not publish packages, use credentials, call models, or invoke tools outside the test process. The regression suite uses local fixtures; no authentication or model configuration is needed. A failed install, version mismatch, or suite failure fails that matrix job.
|
|
6
|
+
|
|
7
|
+
Run one target locally with `node scripts/compatibility-check.mjs --pi oldest` or `--pi latest`. The runner needs Node.js 22.19.0 or newer, npm, and network access to npm. Each invocation removes its temporary runtime directory on exit.
|
|
8
|
+
|
|
9
|
+
## Runtime behavior
|
|
10
|
+
|
|
11
|
+
`/fold status` reports full, partial, or unavailable support and lists missing interfaces. Fold checks exports and prototype methods before loading each feature, then checks session and viewport interfaces when they attach. It keeps existing per-message shape checks. A different Pi version number alone never disables Fold.
|
|
12
|
+
|
|
13
|
+
Missing image adapters leave image-bearing tools native. Missing subagent message adapters disable cross-type grouping so tool results cannot become hidden followers of an unavailable group. Other supported features continue to work.
|
|
14
|
+
|
|
15
|
+
These checks reduce version coupling; they cannot prove that an unchanged method name still behaves the same. CI exercises real Pi behavior, but terminal appearance still needs visual review after UI changes. If Pi changes a private rendering contract, that adapter may still need an update. Public extension APIs are preferred; current thinking, work-strip, and overlay features still need guarded native interfaces.
|
|
16
|
+
|
|
17
|
+
Configuration validators can request the current report through `pi-fold:compatibility:v1` with `{ reply(report) {} }`. Fold replies synchronously with `{ version: 1, state, description }`. The report describes detected capability, not a promise about untested releases.
|
package/docs/implementation.md
CHANGED
|
@@ -6,7 +6,7 @@ Pi Fold changes transcript presentation. It does not replace tool executors, cha
|
|
|
6
6
|
|
|
7
7
|
`index.ts` creates one display mode and registers the tool, thinking, prompt, skill, workflow, permission, subagent, work-strip, and inspection modules. Registrations return cleanup functions. Disposal runs them in reverse order and clears the shared display cache.
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
Before loading a feature, Fold checks its required exports and prototype methods. It also checks session and viewport interfaces when they become available. Pi version numbers are diagnostic metadata, not enablement gates. Adapters retain their per-instance shape guards. Unsupported shapes retain native presentation. Mode changes, session switches, reloads, and shutdown release inspection focus and timers. Registration ownership prevents duplicate adapters after reload.
|
|
10
10
|
|
|
11
11
|
## Transcript projection
|
|
12
12
|
|
|
@@ -20,7 +20,7 @@ pi remove git:github.com/rrrrrrrrrricoxi/pi-fold@v3.0.0
|
|
|
20
20
|
|
|
21
21
|
- Questions use a bold purple heading, aligned with ordinary action headings, without a background or vertical rail. Recorded answers use a green checkmark inline with the options. Ordinary action headings stay blue. The `codemode` label uses native teal (`syntaxVariable`), while counts and timing stay muted; handled nested problems retain warning color; thinking headings stay muted and failures stay red. Expanded content remains unfilled. Keyboard focus has its own selection highlight. User prompts keep their blue surface. Subagent transcript activity uses the same compact headings and inspection controls.
|
|
22
22
|
- Running actions remain separate. Successful completed bash, file, and codemode calls can share one action group within visible conversation boundaries. Each outer codemode call counts as one action; nested calls stay inside its inspectable content. Nested errors, cancellations, unresolved calls, images, and unsupported codemode records stay separate. Pure thinking does not split an action group; visible assistant replies and user messages do.
|
|
23
|
-
- Successful group headings
|
|
23
|
+
- Successful group headings lead with a short phrase describing the recorded operations, followed by outer call counts, for example “4 actions · Edit files and read files · write ×2 · read ×2”. Up to four tool types are named in first-use order. Singleton headings show only the operation. Shell interpreter scripts use labels such as “Run Node.js script,” with a literal script filename when reliably available. Inline source stays in Arguments. A failure heading shows the recorded category, structured reason, or exit code when available. An explicitly unknown outcome stays visible in structured failure summaries. Exact errors stay in Output/Details. Labels describe recorded operations and do not infer a script’s purpose.
|
|
24
24
|
- Expanded source and diffs use Pi’s syntax colors. Recorded thinking and Markdown files use bounded Markdown rendering; shell stdout and unknown text remain literal. Formatting reads at most 2,048 source characters per block. Markdown uses one source line per block, so multiline tables, paragraphs, and cross-line inline formatting are not fully reconstructed. Very long code blocks can lose lexer context at block boundaries. The original recorded source remains unchanged.
|
|
25
25
|
- A single-action card opens directly to useful content without repeating a numbered action row. Successful native `write` actions show submitted content with syntax colors from the path. Only the exact standard acknowledgement is moved under Details. Reads and unknown tools keep their output visible. Known ordinary-tool OS diagnostics can show a short code/category while Details retains the exact error; unknown/custom failures keep full visible output. Status marks follow the title.
|
|
26
26
|
- Open a group to see tightly stacked actions without blank rows between siblings. Several actions and their inline Details can remain expanded independently in the same scrollable pane. Details contains exact arguments, secondary diagnostics, and any acknowledgement/error moved from the main content. Short scalar fields share a line; null and empty values remain explicit. Empty diagnostic objects do not add a section.
|
package/index.ts
CHANGED
|
@@ -1,22 +1,16 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { inspectRuntime, type FoldFeature } from './src/runtime-compatibility.ts';
|
|
2
2
|
import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
3
|
-
import { clearDisplayLineCache } from './src/display-card.ts';
|
|
4
3
|
import { createDisplayMode } from './src/display-mode.ts';
|
|
5
|
-
import { registerModernTools } from './src/modern-tools.ts';
|
|
6
|
-
import { registerModernThinking } from './src/modern-thinking.ts';
|
|
7
|
-
import { registerModernPrompts } from './src/modern-prompts.ts';
|
|
8
|
-
import { registerModernSkillPrompts } from './src/modern-skill-prompts.ts';
|
|
9
|
-
import { registerModernWorkflows } from './src/modern-workflows.ts';
|
|
10
|
-
import { registerModernSubagentMessages } from './src/modern-subagent-messages.ts';
|
|
11
|
-
import { registerInspection } from './src/inspection.ts';
|
|
12
|
-
import { registerPermissionPresentation } from './src/permission-presentation.ts';
|
|
13
|
-
import { registerWorkStrip } from './src/work-strip.ts';
|
|
14
4
|
import { registerFoldCommand } from './src/fold-command.ts';
|
|
5
|
+
import type { WorkStripControls } from './src/work-strip.ts';
|
|
15
6
|
|
|
16
|
-
export default function piFold(pi: ExtensionAPI): void {
|
|
17
|
-
|
|
7
|
+
export default async function piFold(pi: ExtensionAPI): Promise<void> {
|
|
8
|
+
const compatibility = inspectRuntime(pi);
|
|
9
|
+
// The entrypoint itself must load even when optional native exports disappear.
|
|
10
|
+
const clearDisplayLineCache = compatibility.state === 'unavailable' ? () => {} : (await import('./src/display-card.ts')).clearDisplayLineCache;
|
|
18
11
|
clearDisplayLineCache();
|
|
19
12
|
const mode = createDisplayMode();
|
|
13
|
+
const featureMode = (feature: FoldFeature) => ({ isEnabled: () => mode.isEnabled() && compatibility.available(feature), onChange: mode.onChange });
|
|
20
14
|
const disposers: Array<() => void> = [];
|
|
21
15
|
let disposed = false;
|
|
22
16
|
const dispose = () => {
|
|
@@ -31,22 +25,42 @@ export default function piFold(pi: ExtensionAPI): void {
|
|
|
31
25
|
if (errors.length) throw new AggregateError(errors, 'Pi Fold cleanup failed');
|
|
32
26
|
};
|
|
33
27
|
try {
|
|
28
|
+
const reportOff = pi.events?.on('pi-fold:compatibility:v1', (request: any) => {
|
|
29
|
+
if (!disposed && typeof request?.reply === 'function') request.reply({ version: 1, state: compatibility.state, description: compatibility.describe() });
|
|
30
|
+
});
|
|
31
|
+
if (typeof reportOff === 'function') disposers.push(reportOff);
|
|
32
|
+
const sessionProbe = pi.on('session_start', (_event, ctx) => {
|
|
33
|
+
if (!ctx.hasUI) return;
|
|
34
|
+
if (typeof ctx.ui.onTerminalInput !== 'function') {
|
|
35
|
+
for (const feature of ['tools', 'thinking', 'prompts', 'skills', 'workflows', 'subagents', 'work'] as FoldFeature[]) compatibility.disable(feature, 'ui.onTerminalInput missing');
|
|
36
|
+
}
|
|
37
|
+
if (typeof ctx.ui.setHiddenThinkingLabel !== 'function') compatibility.disable('thinking', 'ui.setHiddenThinkingLabel missing');
|
|
38
|
+
if (typeof ctx.sessionManager?.getBranch !== 'function') compatibility.disable('work', 'session branch reader missing');
|
|
39
|
+
if (typeof ctx.sessionManager?.getBranch !== 'function' && typeof ctx.sessionManager?.buildContextEntries !== 'function') compatibility.disable('thinking', 'session entries reader missing');
|
|
40
|
+
});
|
|
41
|
+
if (typeof sessionProbe === 'function') disposers.push(sessionProbe);
|
|
34
42
|
// All display features share the cache; its lifetime belongs to the extension.
|
|
35
43
|
for (const event of ['session_start', 'session_tree', 'session_compact', 'session_before_switch'] as const) {
|
|
36
44
|
const off = pi.on(event, () => { if (!disposed) clearDisplayLineCache(); });
|
|
37
45
|
if (typeof off === 'function') disposers.push(off);
|
|
38
46
|
}
|
|
39
|
-
disposers.push(registerModernTools(pi,
|
|
40
|
-
disposers.push(registerModernThinking(pi,
|
|
41
|
-
disposers.push(registerModernPrompts(pi,
|
|
42
|
-
disposers.push(registerModernSkillPrompts(pi,
|
|
43
|
-
disposers.push(registerModernWorkflows(pi,
|
|
44
|
-
disposers.push(registerPermissionPresentation(pi,
|
|
45
|
-
disposers.push(registerModernSubagentMessages(pi,
|
|
46
|
-
const work =
|
|
47
|
+
if (compatibility.available('tools')) disposers.push((await import('./src/modern-tools.ts')).registerModernTools(pi, featureMode('tools'), { images: compatibility.available('images'), subagents: compatibility.available('subagents') }));
|
|
48
|
+
if (compatibility.available('thinking')) disposers.push((await import('./src/modern-thinking.ts')).registerModernThinking(pi, featureMode('thinking')));
|
|
49
|
+
if (compatibility.available('prompts')) disposers.push((await import('./src/modern-prompts.ts')).registerModernPrompts(pi, featureMode('prompts')));
|
|
50
|
+
if (compatibility.available('skills')) disposers.push((await import('./src/modern-skill-prompts.ts')).registerModernSkillPrompts(pi, featureMode('skills')));
|
|
51
|
+
if (compatibility.available('workflows')) disposers.push((await import('./src/modern-workflows.ts')).registerModernWorkflows(pi, featureMode('workflows')));
|
|
52
|
+
if (compatibility.available('permissions')) disposers.push((await import('./src/permission-presentation.ts')).registerPermissionPresentation(pi, featureMode('permissions')));
|
|
53
|
+
if (compatibility.available('subagents')) disposers.push((await import('./src/modern-subagent-messages.ts')).registerModernSubagentMessages(pi, featureMode('subagents')));
|
|
54
|
+
const work: WorkStripControls = compatibility.available('work')
|
|
55
|
+
? (await import('./src/work-strip.ts')).registerWorkStrip(pi, featureMode('work'), undefined, reason => compatibility.disable('work', reason))
|
|
56
|
+
: { dispose() {}, setExpanded: () => false, isShortcutEnabled: () => false, setShortcutEnabled() {} };
|
|
47
57
|
disposers.push(work.dispose);
|
|
48
|
-
disposers.push(registerFoldCommand(pi, mode, work));
|
|
49
|
-
disposers.push(registerInspection(pi, mode));
|
|
58
|
+
disposers.push(registerFoldCommand(pi, mode, work, compatibility));
|
|
59
|
+
if (compatibility.available('inspection')) disposers.push((await import('./src/inspection.ts')).registerInspection(pi, mode, compatibility));
|
|
60
|
+
const off = pi.on('session_start', (_event, ctx) => {
|
|
61
|
+
if (ctx.hasUI && compatibility.state !== 'full') ctx.ui.notify?.(compatibility.describe(), 'warning');
|
|
62
|
+
});
|
|
63
|
+
if (typeof off === 'function') disposers.push(off);
|
|
50
64
|
} catch (error) {
|
|
51
65
|
dispose();
|
|
52
66
|
throw error;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@notrico/pi-fold",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.1.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Pi Fold: readable agent transcripts with collapsible work, inspectable details, and clear final replies",
|
|
6
6
|
"license": "MIT",
|
|
@@ -13,7 +13,8 @@
|
|
|
13
13
|
"preview": "node scripts/preview.mjs",
|
|
14
14
|
"preview:work": "node scripts/preview-work-strip.mjs",
|
|
15
15
|
"benchmark": "node --expose-gc scripts/performance-review.mjs",
|
|
16
|
-
"benchmark:memory": "node --expose-gc scripts/retained-memory-review.mjs"
|
|
16
|
+
"benchmark:memory": "node --expose-gc scripts/retained-memory-review.mjs",
|
|
17
|
+
"test:compatibility": "node scripts/compatibility-check.mjs --pi latest"
|
|
17
18
|
},
|
|
18
19
|
"pi": {
|
|
19
20
|
"extensions": [
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { spawnSync } from 'node:child_process';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
|
|
8
|
+
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
9
|
+
const selection = process.argv[process.argv.indexOf('--pi') + 1];
|
|
10
|
+
if (!['oldest', 'latest'].includes(selection)) throw new Error('Usage: node scripts/compatibility-check.mjs --pi oldest|latest');
|
|
11
|
+
const registry = 'https://registry.npmjs.org';
|
|
12
|
+
const packageName = '@earendil-works/pi-coding-agent';
|
|
13
|
+
const metadata = await fetch(`${registry}/${packageName.replace('/', '%2f')}`, { signal: AbortSignal.timeout(30000) }).then(r => {
|
|
14
|
+
if (!r.ok) throw new Error(`npm registry returned ${r.status}`);
|
|
15
|
+
return r.json();
|
|
16
|
+
});
|
|
17
|
+
const version = selection === 'oldest' ? '1.3.0' : metadata['dist-tags']?.latest;
|
|
18
|
+
if (!metadata.versions?.[version]) throw new Error(`Pi ${version} is absent from registry metadata`);
|
|
19
|
+
const installRoot = mkdtempSync(path.join(tmpdir(), 'pi-fold-compat-'));
|
|
20
|
+
try {
|
|
21
|
+
const manifest = { private: true, type: 'module', dependencies: {
|
|
22
|
+
[packageName]: version,
|
|
23
|
+
'pi-subagents': '0.79.2',
|
|
24
|
+
'pi-questions': 'latest',
|
|
25
|
+
'pi-prompt-jump': '0.1.0',
|
|
26
|
+
}};
|
|
27
|
+
writeFileSync(path.join(installRoot, 'package.json'), JSON.stringify(manifest, null, 2));
|
|
28
|
+
const install = spawnSync('npm', ['install', '--no-audit', '--no-fund', '--ignore-scripts'], { cwd: installRoot, stdio: 'inherit' });
|
|
29
|
+
if (install.status !== 0) throw new Error(`npm install failed (${install.status})`);
|
|
30
|
+
const actual = JSON.parse(await import('node:fs/promises').then(fs => fs.readFile(path.join(installRoot, 'node_modules', packageName, 'package.json'), 'utf8'))).version;
|
|
31
|
+
if (actual !== version) throw new Error(`Installed Pi core ${actual}; requested ${version}`);
|
|
32
|
+
console.log(`Compatibility target: ${packageName}@${actual} (${selection})`);
|
|
33
|
+
const env = { ...process.env, PI_RUNTIME: installRoot, PI_INSTALL_ROOT: path.join(installRoot, 'node_modules', packageName) };
|
|
34
|
+
const tests = spawnSync(process.execPath, [path.join(root, 'scripts/test.mjs')], { cwd: root, env, stdio: 'inherit' });
|
|
35
|
+
if (tests.status !== 0) throw new Error(`Regression suite failed (${tests.status})`);
|
|
36
|
+
const smoke = spawnSync(process.execPath, [path.join(root, 'scripts/compatibility-cli-smoke.mjs')], { cwd: root, env, stdio: 'inherit' });
|
|
37
|
+
if (smoke.status !== 0) throw new Error(`CLI smoke failed (${smoke.status})`);
|
|
38
|
+
} finally {
|
|
39
|
+
rmSync(installRoot, { recursive: true, force: true });
|
|
40
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Load the actual bundled CLI and extension through RPC. No prompt is submitted.
|
|
3
|
+
import { mkdtempSync, rmSync, readFileSync } from 'node:fs';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { spawn } from 'node:child_process';
|
|
8
|
+
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
9
|
+
const agent = process.env.PI_INSTALL_ROOT;
|
|
10
|
+
if (!agent) throw new Error('PI_INSTALL_ROOT must select the tested Pi package');
|
|
11
|
+
const manifest = JSON.parse(readFileSync(path.join(agent, 'package.json'), 'utf8'));
|
|
12
|
+
const bin = typeof manifest.bin === 'string' ? manifest.bin : manifest.bin.pi;
|
|
13
|
+
const home = mkdtempSync(path.join(tmpdir(), 'pi-fold-cli-'));
|
|
14
|
+
try {
|
|
15
|
+
await new Promise((resolve, reject) => {
|
|
16
|
+
const child = spawn(process.execPath, [path.join(agent, bin), '--mode', 'rpc', '--no-session', '--no-extensions', '--no-skills', '--no-prompt-templates', '--no-themes', '-e', path.join(root, 'index.ts')], {
|
|
17
|
+
cwd: home, env: { ...process.env, HOME: home, PI_CODING_AGENT_DIR: home }, stdio: ['pipe', 'pipe', 'pipe'],
|
|
18
|
+
});
|
|
19
|
+
let pending = '', errors = '', passed = false;
|
|
20
|
+
const timeout = setTimeout(() => { child.kill('SIGTERM'); reject(new Error(`CLI smoke timed out: ${errors}`)); }, 30000);
|
|
21
|
+
child.stderr.on('data', data => { errors += data.toString(); });
|
|
22
|
+
child.stdout.on('data', data => {
|
|
23
|
+
pending += data.toString();
|
|
24
|
+
let end;
|
|
25
|
+
while ((end = pending.indexOf('\n')) >= 0) {
|
|
26
|
+
const line = pending.slice(0, end); pending = pending.slice(end + 1);
|
|
27
|
+
let response; try { response = JSON.parse(line); } catch { continue; }
|
|
28
|
+
if (response.id !== 'fold-compat') continue;
|
|
29
|
+
const names = response.data?.commands?.map(command => command.name) || [];
|
|
30
|
+
if (!response.success || !names.includes('fold') || !names.includes('inspect')) {
|
|
31
|
+
clearTimeout(timeout); child.kill('SIGTERM'); reject(new Error(`CLI extension did not register: ${line}\n${errors}`)); return;
|
|
32
|
+
}
|
|
33
|
+
passed = true; child.kill('SIGTERM');
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
child.on('error', error => { clearTimeout(timeout); reject(error); });
|
|
37
|
+
child.on('exit', code => { clearTimeout(timeout); passed ? resolve() : reject(new Error(`CLI exited ${code}: ${errors}`)); });
|
|
38
|
+
child.stdin.write(JSON.stringify({ id: 'fold-compat', type: 'get_commands' }) + '\n');
|
|
39
|
+
});
|
|
40
|
+
console.log(`Pi ${manifest.version}: bundled CLI registered /fold and /inspect without model calls`);
|
|
41
|
+
} finally { rmSync(home, { recursive: true, force: true }); }
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Isolated recorded-content preview; no model or tool execution.
|
|
3
|
+
import { createWorkStripPreview } from './preview-work-strip.mjs';
|
|
4
|
+
const preview = await createWorkStripPreview({ inspection: true, standaloneCode: true });
|
|
5
|
+
let ui;
|
|
6
|
+
try {
|
|
7
|
+
ui = new preview.core.InteractiveMode(preview.runtime, { tuiMode: 'fullscreen' });
|
|
8
|
+
await ui.run();
|
|
9
|
+
} finally { ui?.stop(); await preview.cleanup(); }
|
|
@@ -5,7 +5,7 @@ import path from 'node:path';
|
|
|
5
5
|
import { fileURLToPath } from 'node:url';
|
|
6
6
|
import { createPreview } from './preview.mjs';
|
|
7
7
|
|
|
8
|
-
export async function createWorkStripPreview({ stepMs = 1000, inspection = false, actionGroups = false } = {}) {
|
|
8
|
+
export async function createWorkStripPreview({ stepMs = 1000, inspection = false, actionGroups = false, standaloneCode = false } = {}) {
|
|
9
9
|
const old = process.env.PI_PREVIEW_WORK_STRIP;
|
|
10
10
|
process.env.PI_PREVIEW_WORK_STRIP = '1';
|
|
11
11
|
const preview = await createPreview();
|
|
@@ -70,6 +70,20 @@ export async function createWorkStripPreview({ stepMs = 1000, inspection = false
|
|
|
70
70
|
const finalId = manager.getBranch().at(-1).id;
|
|
71
71
|
manager.appendCustomEntry('compact-renderer:work-settled:v1',{version:1,userId,finalId,endId:finalId,startedAt:base-45000,endedAt:base,outcome:'completed'});
|
|
72
72
|
}
|
|
73
|
+
if (standaloneCode) {
|
|
74
|
+
manager.appendMessage({ role: 'user', content: '独立代码输出滚动测试:保留原始结果,并检查更多内容。', timestamp: Date.now() });
|
|
75
|
+
const userId = manager.getBranch().at(-1).id;
|
|
76
|
+
manager.appendMessage(assistant('这条说明将独立代码与前一组工具分开。'));
|
|
77
|
+
const call = assistant('');
|
|
78
|
+
call.stopReason = 'toolUse';
|
|
79
|
+
call.content = [{ type: 'toolCall', id: 'standalone-wheel-code', name: 'codemode', arguments: { code: 'const results = await Promise.all([tools.read({ path: "/fixture/a" }), tools.read({ path: "/fixture/b" }), tools.read({ path: "/fixture/c" })]);\nfor (const result of results) text(result);' } }];
|
|
80
|
+
manager.appendMessage(call);
|
|
81
|
+
const escaped = JSON.stringify({ content: [{ type: 'text', text: Array.from({ length: 240 }, (_, i) => `记录 ${i + 1}:示例文字、原始说明与数据行。`).join('\n') }], end: 'ESCAPED_JSON_END' });
|
|
82
|
+
manager.appendMessage({ role: 'toolResult', toolCallId: 'standalone-wheel-code', toolName: 'codemode', content: [{ type: 'text', text: 'Script completed\nWall time 0.75 seconds\nOutput:\n' }, { type: 'text', text: escaped + '\nFINAL_OUTPUT_SENTINEL' }], details: { calls: ['a', 'b', 'c'].map(path => ({ name: 'read', args: JSON.stringify({ path: `/fixture/${path}` }), status: 'ok', durationMs: 10 })) }, isError: false, durationMs: 750, timestamp: Date.now() });
|
|
83
|
+
manager.appendMessage(assistant('检查完成。这条最终答复保持在工作区外。'));
|
|
84
|
+
const finalId = manager.getBranch().at(-1).id;
|
|
85
|
+
manager.appendCustomEntry('compact-renderer:work-settled:v1', { version: 1, userId, finalId, endId: finalId, startedAt: Date.now() - 2000, endedAt: Date.now(), outcome: 'completed' });
|
|
86
|
+
}
|
|
73
87
|
const emit = async event => {
|
|
74
88
|
if (stopped) return;
|
|
75
89
|
runtime.session._emit(event);
|
package/scripts/test.mjs
CHANGED
|
@@ -7,13 +7,13 @@ import { spawnSync } from 'node:child_process';
|
|
|
7
7
|
const directory = fileURLToPath(new URL('../tests/', import.meta.url));
|
|
8
8
|
const required = ['action-intent.test.mjs', 'modern-workflows.test.mjs', 'display-mode.test.mjs', 'modern-tools.test.mjs', 'modern-subagent-messages.test.mjs', 'subagent-spacing.test.mjs', 'modern-subagent-groups.test.mjs', 'modern-thinking.test.mjs', 'modern-prompts.test.mjs', 'permission-presentation.test.mjs', 'input-focus.test.mjs', 'inspection.test.mjs', 'codemode.test.mjs', 'preview-example.test.mjs'];
|
|
9
9
|
required.push('reload-lifecycle.test.mjs', 'ordinary-prompts.test.mjs', 'work-strip-hierarchy.test.mjs', 'work-strip-final-surface.test.mjs');
|
|
10
|
-
required.push('modern-skill-prompts.test.mjs', 'inspection-wheel.test.mjs');
|
|
10
|
+
required.push('modern-skill-prompts.test.mjs', 'inspection-wheel.test.mjs', 'codemode-wheel.test.mjs');
|
|
11
11
|
required.push('display-line-cache.test.mjs');
|
|
12
12
|
required.push('display-cache-lifecycle.test.mjs');
|
|
13
13
|
required.push('fold-command.test.mjs', 'fold-shortcut.test.mjs');
|
|
14
14
|
required.push('mixed-thinking.test.mjs', 'work-strip.test.mjs', 'work-strip-subagents.test.mjs', 'work-strip-preview.test.mjs', 'work-strip-spacing.test.mjs');
|
|
15
15
|
required.push('mixed-action-groups.test.mjs', 'action-group-preview.test.mjs');
|
|
16
|
-
required.push('fullscreen-overlays.test.mjs', 'runtime-compatibility.test.mjs');
|
|
16
|
+
required.push('fullscreen-overlays.test.mjs', 'runtime-compatibility.test.mjs', 'compatibility-fallbacks.test.mjs');
|
|
17
17
|
for (const name of required) {
|
|
18
18
|
if (!fs.existsSync(path.join(directory, name))) throw new Error(`Missing required regression suite: ${name}`);
|
|
19
19
|
const result = spawnSync(process.execPath, [path.join(directory, name)], { cwd: directory, env: process.env, stdio: 'inherit' });
|
package/src/action-intent.ts
CHANGED
|
@@ -77,13 +77,17 @@ export function actionIntent(name: string, args: unknown): string {
|
|
|
77
77
|
return combine(actionIntents(name, args));
|
|
78
78
|
}
|
|
79
79
|
|
|
80
|
-
export function groupIntent(actions: Action[]): string {
|
|
80
|
+
export function groupIntent(actions: Action[], format: "full" | "brief" = "full"): string {
|
|
81
81
|
if (!Array.isArray(actions)) return "Run tool actions";
|
|
82
82
|
const intents: string[] = [];
|
|
83
83
|
for (let i = 0; i < Math.min(actions.length, 64); i++) {
|
|
84
84
|
const action = field(actions, String(i));
|
|
85
85
|
intents.push(...actionIntents(field(action, "name"), field(action, "args")));
|
|
86
86
|
}
|
|
87
|
+
if (format === "brief") {
|
|
88
|
+
const specific = intents.filter(intent => intent !== "Run tool actions" && intent !== "Run code");
|
|
89
|
+
return combine([...new Set(specific.length ? specific : intents)].slice(0, 2));
|
|
90
|
+
}
|
|
87
91
|
return combine(intents, actions.length > 64);
|
|
88
92
|
}
|
|
89
93
|
|
package/src/display-card.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import
|
|
1
|
+
import * as nativeTui from "@earendil-works/pi-tui";
|
|
2
|
+
const { truncateToWidth, visibleWidth } = nativeTui;
|
|
2
3
|
import { DisplayLineCache } from "./display-line-cache.ts";
|
|
3
4
|
|
|
4
5
|
const lines = new DisplayLineCache();
|
package/src/fold-command.ts
CHANGED
|
@@ -2,10 +2,12 @@ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
|
2
2
|
import type { DisplayMode } from './display-mode.ts';
|
|
3
3
|
import type { WorkStripControls } from './work-strip.ts';
|
|
4
4
|
|
|
5
|
+
import type { RuntimeCompatibility } from './runtime-compatibility.ts';
|
|
6
|
+
|
|
5
7
|
type FoldMode = DisplayMode & { setEnabled(enabled: boolean): boolean };
|
|
6
8
|
|
|
7
9
|
/** One session-local command owns display mode, work expansion, and its shortcut. */
|
|
8
|
-
export function registerFoldCommand(pi: ExtensionAPI, mode: FoldMode, work: WorkStripControls): () => void {
|
|
10
|
+
export function registerFoldCommand(pi: ExtensionAPI, mode: FoldMode, work: WorkStripControls, compatibility?: RuntimeCompatibility): () => void {
|
|
9
11
|
let disposed = false;
|
|
10
12
|
pi.registerCommand('fold', {
|
|
11
13
|
description: 'Choose Pi Fold display, collapse or expand work, or set its shortcut',
|
|
@@ -20,19 +22,21 @@ export function registerFoldCommand(pi: ExtensionAPI, mode: FoldMode, work: Work
|
|
|
20
22
|
'collapse — collapse completed work sections',
|
|
21
23
|
'expand — expand all work sections',
|
|
22
24
|
'shortcut — choose Ctrl+Alt+W shortcut',
|
|
25
|
+
'status — show compatibility details',
|
|
23
26
|
];
|
|
24
27
|
const selected = await ctx.ui.select('Pi Fold — this session', choices);
|
|
25
28
|
if (disposed || selected === undefined) return;
|
|
26
29
|
const index = choices.indexOf(selected);
|
|
27
30
|
if (index < 0) return;
|
|
28
|
-
choice = ['on', 'off', 'collapse', 'expand', 'shortcut'][index];
|
|
31
|
+
choice = ['on', 'off', 'collapse', 'expand', 'shortcut', 'status'][index];
|
|
29
32
|
if (choice === current) return;
|
|
30
33
|
}
|
|
31
34
|
if (['', 'status', 'on', 'off', 'toggle'].includes(choice)) {
|
|
35
|
+
if (compatibility?.state === 'unavailable') { ctx.ui.notify(compatibility.describe() + '\nNative display remains active.', 'warning'); return; }
|
|
32
36
|
if (choice === 'on' || choice === 'off' || choice === 'toggle') {
|
|
33
37
|
mode.setEnabled(choice === 'toggle' ? !mode.isEnabled() : choice === 'on');
|
|
34
38
|
}
|
|
35
|
-
ctx.ui.notify(`Pi Fold ${mode.isEnabled() ? 'on' : 'off'}
|
|
39
|
+
ctx.ui.notify(`Pi Fold ${mode.isEnabled() ? 'on' : 'off'}` + (compatibility ? `\n${compatibility.describe()}` : ''), compatibility && compatibility.state !== 'full' ? 'warning' : 'info');
|
|
36
40
|
} else if (choice === 'collapse' || choice === 'expand') {
|
|
37
41
|
if (!mode.isEnabled()) {
|
|
38
42
|
ctx.ui.notify(`Turn Pi Fold on with /fold on before you ${choice} work sections.`, 'info');
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
3
|
-
|
|
1
|
+
import * as core from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import * as nativeTui from '@earendil-works/pi-tui';
|
|
3
|
+
const { TuiAltScreen } = nativeTui;
|
|
4
4
|
import { chainNativeMethod } from './native-method-chain.ts';
|
|
5
5
|
|
|
6
6
|
const promptZones = /\x1b\]133;[ABC](?:\x07|\x1b\\)/g;
|
|
@@ -10,15 +10,17 @@ const promptZones = /\x1b\]133;[ABC](?:\x07|\x1b\\)/g;
|
|
|
10
10
|
* suppress Kitty anchors while an overlay is visible so native placement cleanup
|
|
11
11
|
* and restoration work. Keep source rows, layout metadata, and settings intact.
|
|
12
12
|
*/
|
|
13
|
-
export function
|
|
14
|
-
if (!
|
|
15
|
-
|| typeof tui.hasOverlay !== 'function'
|
|
16
|
-
if (tui.mode === 'fullscreen' && typeof tui.prepareKittyScreen !== 'function') return
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
13
|
+
export function supportsOverlayHost(tui: any): boolean {
|
|
14
|
+
if (!['regular', 'fullscreen'].includes(tui?.mode) || typeof tui.compositeOverlays !== 'function'
|
|
15
|
+
|| typeof tui.hasOverlay !== 'function' || !tui.terminal) return false;
|
|
16
|
+
if (tui.mode === 'fullscreen' && typeof tui.prepareKittyScreen !== 'function') return false;
|
|
17
|
+
const proto = tui.mode === 'regular' ? TuiAltScreen?.prototype : Object.getPrototypeOf(tui);
|
|
18
|
+
return typeof proto?.compositeOverlays === 'function' && typeof proto?.prepareKittyScreen === 'function';
|
|
19
|
+
}
|
|
20
|
+
export function installFullscreenOverlayGuard(tui: any, version = core.VERSION): () => void {
|
|
21
|
+
if (!supportsOverlayHost(tui)) return () => {};
|
|
22
|
+
// UI handles are proxies. Patch the prototype only for this terminal.
|
|
20
23
|
const proto = tui.mode === 'regular' ? TuiAltScreen.prototype as any : Object.getPrototypeOf(tui), terminal = tui.terminal;
|
|
21
|
-
if (!terminal || typeof proto?.compositeOverlays !== 'function' || typeof proto.prepareKittyScreen !== 'function') return () => {};
|
|
22
24
|
const detach = chainNativeMethod(proto, 'compositeOverlays', function(this: any, native, lines: string[], ...args: any[]) {
|
|
23
25
|
if (this.terminal !== terminal || this.mode !== 'fullscreen') return native.call(this, lines, ...args);
|
|
24
26
|
// ponytail: Pi 1.3 fullscreen only; remove when native composition is fixed.
|
package/src/inspection.ts
CHANGED
|
@@ -1,18 +1,20 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { RuntimeCompatibility } from './runtime-compatibility.ts';
|
|
2
2
|
import type { DisplayMode } from './display-mode.ts';
|
|
3
|
-
import {
|
|
4
|
-
import
|
|
3
|
+
import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
4
|
+
import * as nativeTui from '@earendil-works/pi-tui';
|
|
5
|
+
import type { Component, ScrollView as NativeScrollView } from '@earendil-works/pi-tui';
|
|
6
|
+
const { Container, ScrollView, isViewportTUI } = nativeTui;
|
|
5
7
|
import { projectedChildren } from './work-strip-view.ts';
|
|
6
|
-
import { installFullscreenOverlayGuard } from './fullscreen-overlays.ts';
|
|
8
|
+
import { installFullscreenOverlayGuard, supportsOverlayHost } from './fullscreen-overlays.ts';
|
|
7
9
|
|
|
8
10
|
type Choice = { id: string; kind: string; label: string; focus(): void };
|
|
9
11
|
type Target = (component: Component) => boolean;
|
|
10
12
|
const children = (component: any): Component[] => [...(Array.isArray(component?.[projectedChildren]) ? component[projectedChildren] : Array.isArray(component?.children) ? component.children : []), ...(component?.child && typeof component.child.render === 'function' ? [component.child] : [])];
|
|
11
13
|
|
|
12
14
|
/** Pi 1.3 viewport seam. Read the mounted tree; never replace its layout/root. */
|
|
13
|
-
export function revealInspection(tui: any, target: Target, version
|
|
14
|
-
if (
|
|
15
|
-
const scrolls:
|
|
15
|
+
export function revealInspection(tui: any, target: Target, version?: string): boolean {
|
|
16
|
+
if (typeof isViewportTUI !== 'function' || typeof ScrollView !== 'function' || !tui || !isViewportTUI(tui) || typeof tui.getMountedRoots !== 'function') return false;
|
|
17
|
+
const scrolls: NativeScrollView[] = [], seen = new Set<Component>();
|
|
16
18
|
const find = (component: Component) => {
|
|
17
19
|
if (seen.has(component)) return; seen.add(component);
|
|
18
20
|
if (component instanceof ScrollView && component.primary) { scrolls.push(component); return; }
|
|
@@ -21,7 +23,7 @@ export function revealInspection(tui: any, target: Target, version = VERSION): b
|
|
|
21
23
|
for (const root of tui.getMountedRoots()) find(root);
|
|
22
24
|
if (scrolls.length !== 1) return false;
|
|
23
25
|
const scroll = scrolls[0], document = scroll.children[0];
|
|
24
|
-
if (!document) return false;
|
|
26
|
+
if (!document || typeof scroll.getContentWidth !== 'function' || typeof scroll.scrollTo !== 'function' || typeof tui.requestRender !== 'function' || !Number.isFinite(tui.terminal?.columns)) return false;
|
|
25
27
|
const width = scroll.getContentWidth(Math.max(1, tui.terminal.columns));
|
|
26
28
|
// Opening a work strip changes its projected child list. Measure before the
|
|
27
29
|
// traversal so nested inspection uses the same tree as native mouse layout.
|
|
@@ -46,7 +48,7 @@ export function revealInspection(tui: any, target: Target, version = VERSION): b
|
|
|
46
48
|
}
|
|
47
49
|
|
|
48
50
|
/** Native picker plus visible focus status. No model tools, transcript or editor mutation. */
|
|
49
|
-
export function registerInspection(pi: ExtensionAPI, mode: DisplayMode): () => void {
|
|
51
|
+
export function registerInspection(pi: ExtensionAPI, mode: DisplayMode, compatibility?: RuntimeCompatibility): () => void {
|
|
50
52
|
let ui: any, tui: any, disposed = false;
|
|
51
53
|
let restoreFullscreenOverlays: (() => void) | undefined;
|
|
52
54
|
let revealTimer: ReturnType<typeof setTimeout> | undefined;
|
|
@@ -55,9 +57,14 @@ export function registerInspection(pi: ExtensionAPI, mode: DisplayMode): () => v
|
|
|
55
57
|
const subscriptions = [
|
|
56
58
|
pi.on('session_start', (_event, ctx) => {
|
|
57
59
|
clear(); if (disposed || !ctx.hasUI) return; ui = ctx.ui;
|
|
60
|
+
if (typeof ui.select !== 'function') compatibility?.disable('inspection', 'ui.select missing');
|
|
61
|
+
if (typeof ui.setWidget !== 'function') { compatibility?.disable('reveal', 'ui.setWidget missing'); compatibility?.disable('overlays', 'TUI host unavailable'); }
|
|
58
62
|
// This zero-row widget only obtains the supported TUI handle. It owns no root.
|
|
59
63
|
ui.setWidget?.('compact-inspection-host', (host: any) => {
|
|
60
|
-
tui = host; restoreFullscreenOverlays?.();
|
|
64
|
+
tui = host; restoreFullscreenOverlays?.();
|
|
65
|
+
if (typeof isViewportTUI !== 'function' || !isViewportTUI(host) || typeof host?.getMountedRoots !== 'function' || typeof host?.requestRender !== 'function' || !Number.isFinite(host?.terminal?.columns)) compatibility?.disable('reveal', 'viewport host unavailable');
|
|
66
|
+
if (!supportsOverlayHost(host)) compatibility?.disable('overlays', 'overlay host unavailable');
|
|
67
|
+
if (!compatibility || compatibility.available('overlays')) restoreFullscreenOverlays = installFullscreenOverlayGuard(host);
|
|
61
68
|
return { render: () => [], invalidate() {} };
|
|
62
69
|
});
|
|
63
70
|
}),
|
|
@@ -78,7 +85,7 @@ export function registerInspection(pi: ExtensionAPI, mode: DisplayMode): () => v
|
|
|
78
85
|
pi.registerCommand('inspect', {
|
|
79
86
|
description: 'Select tools, subagent activity, thinking, or a prompt to inspect',
|
|
80
87
|
async handler(_args, ctx) {
|
|
81
|
-
if (!ctx.hasUI || disposed) return;
|
|
88
|
+
if (!ctx.hasUI || disposed || typeof ctx.ui.select !== 'function') return;
|
|
82
89
|
if (!mode.isEnabled()) { ctx.ui.notify('Use /fold on to inspect grouped blocks.', 'info'); return; }
|
|
83
90
|
const choices: Choice[] = [];
|
|
84
91
|
pi.events.emit('compact-renderer:inspect:v1', { add(choice: Choice) { if (choice && typeof choice.focus === 'function') choices.push(choice); } });
|
|
@@ -89,5 +96,5 @@ export function registerInspection(pi: ExtensionAPI, mode: DisplayMode): () => v
|
|
|
89
96
|
if (index >= 0 && !disposed && mode.isEnabled()) choices[index].focus();
|
|
90
97
|
},
|
|
91
98
|
});
|
|
92
|
-
return () => { if (disposed) return; disposed = true; clear(); subscriptions.forEach(off => off()); };
|
|
99
|
+
return () => { if (disposed) return; disposed = true; clear(); subscriptions.forEach(off => { if (typeof off === 'function') off(); }); };
|
|
93
100
|
}
|
|
@@ -1,12 +1,18 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
3
|
-
import {
|
|
1
|
+
import type { ToolRenderers } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import * as Pi from '@earendil-works/pi-coding-agent';
|
|
3
|
+
import type { Component } from '@earendil-works/pi-tui';
|
|
4
|
+
import * as Tui from '@earendil-works/pi-tui';
|
|
5
|
+
|
|
6
|
+
const { keyHint } = Pi;
|
|
7
|
+
const { Box, Container, Text, stripTerminalSequences } = Tui;
|
|
4
8
|
|
|
5
9
|
type Context = Parameters<NonNullable<ToolRenderers["renderCall"]>>[2];
|
|
6
|
-
/**
|
|
7
|
-
export const nativeToolsSupported =
|
|
10
|
+
/** Check the rendering surface once. Per-call context checks preserve stock rendering. */
|
|
11
|
+
export const nativeToolsSupported = [Box, Container, Text, stripTerminalSequences].every(value => typeof value === 'function') &&
|
|
12
|
+
['setBgFn', 'setPaddingX', 'clear', 'addChild', 'render'].every(key => typeof Box?.prototype?.[key] === 'function') &&
|
|
13
|
+
['clear', 'render'].every(key => typeof Container?.prototype?.[key] === 'function');
|
|
8
14
|
export const nativeToolContextSupported = (context: Context) => !!context && typeof context.toolCallId === "string" && typeof context.invalidate === "function" && !!context.state && typeof context.state === "object" && typeof context.cwd === "string" && typeof context.expanded === "boolean" && typeof context.executionStarted === "boolean" && typeof context.isPartial === "boolean";
|
|
9
|
-
export function nativeTextFallback(result: any, theme?: any, options = { expanded: true }): Text {
|
|
15
|
+
export function nativeTextFallback(result: any, theme?: any, options = { expanded: true }): InstanceType<typeof Text> {
|
|
10
16
|
const text = (Array.isArray(result?.content) ? result.content : []).filter((block: any) => block?.type === "text").map((block: any) => String(block.text ?? "")).join("\n");
|
|
11
17
|
const output = stripTerminalSequences(text).replace(/\r/g, "");
|
|
12
18
|
if (!theme) return new Text(output, 0, 0);
|
|
@@ -14,7 +20,7 @@ export function nativeTextFallback(result: any, theme?: any, options = { expande
|
|
|
14
20
|
const visible = options.expanded ? lines : lines.slice(0, 10);
|
|
15
21
|
let display = visible.map(line => theme.fg("toolOutput", line)).join("\n");
|
|
16
22
|
const remaining = lines.length - visible.length;
|
|
17
|
-
if (remaining > 0) display += `${theme.fg("muted", `\n... (${remaining} more lines,`)} ${keyHint("app.tools.expand", "to expand")}${theme.fg("muted", ")")}`;
|
|
23
|
+
if (remaining > 0) display += `${theme.fg("muted", `\n... (${remaining} more lines,`)} ${typeof keyHint === "function" ? keyHint("app.tools.expand", "to expand") : "expand tools to view"}${theme.fg("muted", ")")}`;
|
|
18
24
|
return new Text(display, 0, 0);
|
|
19
25
|
}
|
|
20
26
|
function callFallback(name: string, args: any, theme: any, expanded: boolean) {
|
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
3
|
-
|
|
1
|
+
import * as Pi from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import * as Tui from '@earendil-works/pi-tui';
|
|
3
|
+
|
|
4
|
+
const { UserMessageComponent, VERSION } = Pi;
|
|
5
|
+
const { Markdown } = Tui;
|
|
4
6
|
|
|
5
7
|
export function invalidateModernPrompt(component: any) {
|
|
6
|
-
for (const child of Array.isArray(component?.children) ? component.children : []) if (child instanceof Markdown) child.invalidate();
|
|
8
|
+
for (const child of Array.isArray(component?.children) ? component.children : []) if (typeof Markdown === "function" && child instanceof Markdown && typeof child.invalidate === "function") child.invalidate();
|
|
7
9
|
}
|
|
8
10
|
|
|
9
11
|
/** The transformer is public. This isolated Pi 1.3.0 seam supplies per-card
|
|
@@ -12,9 +14,9 @@ export function installModernPromptAdapter(hooks: {
|
|
|
12
14
|
render(component: any, markdown: string, original: () => string[]): string[];
|
|
13
15
|
mouse(component: any, event: any): any;
|
|
14
16
|
fallback?(component: any): void;
|
|
15
|
-
},
|
|
16
|
-
const proto = UserMessageComponent
|
|
17
|
-
if (!
|
|
17
|
+
}, _version = VERSION): (() => void) | undefined {
|
|
18
|
+
const proto = UserMessageComponent?.prototype as any;
|
|
19
|
+
if (typeof Markdown !== "function" || !proto || typeof proto.render !== "function" || typeof proto.rebuild !== "function") return;
|
|
18
20
|
const owner = Symbol.for("compact-renderer:prompt-adapter:v1");
|
|
19
21
|
proto[owner]?.();
|
|
20
22
|
const render = proto.render, mouse = proto.handleMouse;
|