pal-code 0.0.7 → 0.0.10

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.
Files changed (61) hide show
  1. package/README.md +3 -3
  2. package/SYSTEM.md +3 -3
  3. package/bin/pal-code.js +37 -11
  4. package/package.json +11 -11
  5. package/packages/cli/README.md +2 -2
  6. package/packages/cli/src/commands/ext.ts +1 -1
  7. package/packages/cli/src/commands.ts +1 -1
  8. package/packages/cli/src/components/render-history.ts +2 -2
  9. package/packages/cli/src/config.ts +2 -2
  10. package/packages/cli/src/index.ts +8 -10
  11. package/packages/cli/src/overlays/key-input.ts +1 -1
  12. package/packages/cli/src/overlays/model-picker.ts +2 -2
  13. package/packages/cli/src/overlays/session-picker.ts +1 -1
  14. package/packages/cli/src/overlays/wizard.ts +1 -1
  15. package/packages/cli/src/state.ts +2 -2
  16. package/packages/cli/src/turn.ts +14 -9
  17. package/packages/cli/src/utils/permissions.ts +3 -3
  18. package/packages/cli/src/utils/format.test.ts +0 -167
  19. package/packages/core/src/agent/events.ts +0 -36
  20. package/packages/core/src/agent/fallback.test.ts +0 -99
  21. package/packages/core/src/agent/fallback.ts +0 -344
  22. package/packages/core/src/agent/index.ts +0 -35
  23. package/packages/core/src/agent/protocol.test.ts +0 -136
  24. package/packages/core/src/agent/resume-compaction.test.ts +0 -116
  25. package/packages/core/src/agent/roles.ts +0 -188
  26. package/packages/core/src/agent/run.test.ts +0 -207
  27. package/packages/core/src/agent/run.ts +0 -713
  28. package/packages/core/src/agent/scope.ts +0 -34
  29. package/packages/core/src/agent/todos.ts +0 -66
  30. package/packages/core/src/compaction.protocol.test.ts +0 -90
  31. package/packages/core/src/compaction.test.ts +0 -101
  32. package/packages/core/src/compaction.ts +0 -243
  33. package/packages/core/src/config.test.ts +0 -40
  34. package/packages/core/src/config.ts +0 -387
  35. package/packages/core/src/extensions.ts +0 -178
  36. package/packages/core/src/index.ts +0 -157
  37. package/packages/core/src/logger.ts +0 -54
  38. package/packages/core/src/provider/auth.ts +0 -153
  39. package/packages/core/src/provider/complete.ts +0 -63
  40. package/packages/core/src/provider/index.ts +0 -6
  41. package/packages/core/src/provider/openrouter.test.ts +0 -59
  42. package/packages/core/src/provider/openrouter.ts +0 -304
  43. package/packages/core/src/provider/pick-model.ts +0 -43
  44. package/packages/core/src/provider/registry.ts +0 -222
  45. package/packages/core/src/provider/types.ts +0 -61
  46. package/packages/core/src/repo-map.ts +0 -177
  47. package/packages/core/src/session/index.ts +0 -2
  48. package/packages/core/src/session/migration.test.ts +0 -104
  49. package/packages/core/src/session/store-v2-repair.test.ts +0 -209
  50. package/packages/core/src/session/store.test.ts +0 -235
  51. package/packages/core/src/session/store.ts +0 -677
  52. package/packages/core/src/session/types.ts +0 -72
  53. package/packages/core/src/snapshots.ts +0 -107
  54. package/packages/core/src/tools/definitions.ts +0 -365
  55. package/packages/core/src/tools/executor.test.ts +0 -122
  56. package/packages/core/src/tools/executor.ts +0 -1363
  57. package/packages/core/src/tools/index.ts +0 -5
  58. package/packages/core/src/tools/search.ts +0 -201
  59. package/scripts/postinstall.js +0 -121
  60. package/scripts/preinstall.js +0 -51
  61. package/scripts/sync-version.js +0 -35
package/README.md CHANGED
@@ -74,8 +74,8 @@ key (or press Enter for a keyless provider like OpenCode Zen).
74
74
  Install extensions from any directory:
75
75
 
76
76
  ```bash
77
- pal add @pal/web-search # Web search tools (fetch_url, web_search)
78
- pal add @pal/agents # Multi-agent orchestration (delegate, explore, etc.)
77
+ pal add @pal-code/web-search # Web search tools (fetch_url, web_search)
78
+ pal add @pal-code/agents # Multi-agent orchestration (delegate, explore, etc.)
79
79
  ```
80
80
 
81
81
  Extensions are installed to `~/.pal/extensions/` and persist across sessions.
@@ -135,7 +135,7 @@ All user data lives in `~/.pal/`:
135
135
 
136
136
  ## Architecture
137
137
 
138
- **Logic lives in `@pal/core`; rendering lives in `@pal/cli`.**
138
+ **Logic lives in `@pal-code/core`; rendering lives in `@pal-code/cli`.**
139
139
 
140
140
  The one agent loop (`runAgent`) lives in core and streams events; the CLI only
141
141
  renders them. Full rules, the event protocol, and the termination/interrupt
package/SYSTEM.md CHANGED
@@ -4,12 +4,12 @@ How pal is put together, and the rules that keep it that way.
4
4
 
5
5
  ## The boundary rule
6
6
 
7
- **Logic lives in `@pal/core`. Rendering lives in `@pal/cli`.**
7
+ **Logic lives in `@pal-code/core`. Rendering lives in `@pal-code/cli`.**
8
8
 
9
9
  This is the single most important rule in the codebase. Every capability has
10
10
  exactly one home, and the split is by *responsibility*, not convenience:
11
11
 
12
- | Lives in `@pal/core` | Lives in `@pal/cli` |
12
+ | Lives in `@pal-code/core` | Lives in `@pal-code/cli` |
13
13
  |---|---|
14
14
  | The agent loop (`runAgent`) | The pi-tui `RunView`, todo panel, status bar |
15
15
  | Tool implementations + `executeTool` | Slash-command parsing and command output |
@@ -22,7 +22,7 @@ Consequences:
22
22
 
23
23
  - A front-end **must never reimplement engine behaviour**. If two front-ends
24
24
  would both need it, it belongs in core.
25
- - Core **must never import a TUI**. `@pal/core` has no knowledge of pi-tui.
25
+ - Core **must never import a TUI**. `@pal-code/core` has no knowledge of pi-tui.
26
26
  - The **only vocabulary** between the layers is the event stream below.
27
27
 
28
28
  If you are unsure where something goes, ask: *does this decide what the agent
package/bin/pal-code.js CHANGED
@@ -76,22 +76,48 @@ function findBinary() {
76
76
  return distBin;
77
77
  }
78
78
 
79
- // Fallback: check if bun is available and run source directly
79
+ // Fallback: run the bundled TypeScript source under Bun. No prebuilt binary
80
+ // is published for this platform (yet), so this is the normal path.
80
81
  const { execSync } = require('child_process');
82
+ const srcPath = join(__dirname, '../packages/cli/src/index.ts');
83
+
84
+ let bunVersion = null;
81
85
  try {
82
- execSync('bun --version', { stdio: 'ignore' });
83
- const srcPath = join(__dirname, '../packages/cli/src/index.ts');
84
- if (existsSync(srcPath)) {
85
- console.error('pal-code: Using Bun runtime (binary not found, falling back to source)');
86
- return 'bun';
87
- }
88
- } catch (e) {
89
- // Bun not available
86
+ bunVersion = execSync('bun --version', { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] })
87
+ .toString()
88
+ .trim();
89
+ } catch {
90
+ // Bun not installed, or not on PATH.
91
+ }
92
+
93
+ if (bunVersion && existsSync(srcPath)) {
94
+ console.error(`pal-code: running from source with Bun ${bunVersion}`);
95
+ return 'bun';
96
+ }
97
+
98
+ // No usable runtime. Report the actionable cause: a missing Bun, not a
99
+ // corrupt install. (This replaces the old preinstall/postinstall hooks, which
100
+ // npm and Bun increasingly refuse to run — Bun blocks them until the package
101
+ // is trusted, and warns on every install.)
102
+ if (!bunVersion) {
103
+ console.error('');
104
+ console.error(' pal-code requires Bun — it was not found on your PATH.');
105
+ console.error('');
106
+ console.error(' macOS / Linux:');
107
+ console.error(' curl -fsSL https://bun.sh/install | bash');
108
+ console.error('');
109
+ console.error(' Windows (PowerShell):');
110
+ console.error(' powershell -c "irm bun.sh/install.ps1 | iex"');
111
+ console.error('');
112
+ console.error(' Then run: pal');
113
+ console.error('');
114
+ console.error(' https://bun.sh');
115
+ console.error('');
116
+ process.exit(1);
90
117
  }
91
118
 
92
- console.error('Error: pal binary not found.');
119
+ console.error('Error: pal binary not found for this platform.');
93
120
  console.error('Please reinstall: npm install -g pal-code');
94
- console.error('Or install Bun and run from source: bun add -g pal-code');
95
121
  process.exit(1);
96
122
  }
97
123
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pal-code",
3
- "version": "0.0.7",
3
+ "version": "0.0.10",
4
4
  "description": "A terminal coding agent with BYOK, tool use, and extensions",
5
5
  "license": "MIT",
6
6
  "engines": {
@@ -11,20 +11,17 @@
11
11
  ],
12
12
  "repository": {
13
13
  "type": "git",
14
- "url": "https://github.com/fngadiyo/the-agent.git"
14
+ "url": "git+https://github.com/fngadiyo/the-agent.git"
15
15
  },
16
16
  "bin": {
17
- "pal": "./bin/pal-code.js"
17
+ "pal": "bin/pal-code.js"
18
18
  },
19
19
  "files": [
20
20
  "bin/",
21
- "scripts/",
22
21
  "packages/cli/src/**/*.ts",
23
22
  "packages/cli/src/**/*.tsx",
24
- "packages/core/src/**/*.ts",
25
- "packages/core/src/**/*.tsx",
26
- "!packages/core/src/**/*.test.db",
27
- "!packages/core/src/**/*.test-*.db",
23
+ "!**/*.test.ts",
24
+ "!**/*.test.js",
28
25
  "SYSTEM.md",
29
26
  "README.md",
30
27
  "LICENSE"
@@ -44,12 +41,11 @@
44
41
  "build:linux-x64": "bun build --compile packages/cli/src/index.ts --target=bun-linux-x64 --outfile dist/pal-linux-x64",
45
42
  "build:linux-arm64": "bun build --compile packages/cli/src/index.ts --target=bun-linux-arm64 --outfile dist/pal-linux-arm64",
46
43
  "build:windows-x64": "bun build --compile packages/cli/src/index.ts --target=bun-windows-x64 --outfile dist/pal-windows-x64.exe",
47
- "publish:all": "npm publish && npm run publish:web-search && npm run publish:agents && npm run publish:mcp",
44
+ "publish:all": "npm run publish:core && npm publish && npm run publish:web-search && npm run publish:agents && npm run publish:mcp",
45
+ "publish:core": "cd packages/core && npm publish",
48
46
  "publish:web-search": "cd packages/web-search && npm publish",
49
47
  "publish:agents": "cd packages/agents && npm publish",
50
48
  "publish:mcp": "cd packages/mcp && npm publish",
51
- "preinstall": "node scripts/preinstall.js",
52
- "postinstall": "node scripts/postinstall.js",
53
49
  "prepublishOnly": "node scripts/sync-version.js"
54
50
  },
55
51
  "keywords": [
@@ -64,6 +60,10 @@
64
60
  "anthropic",
65
61
  "gemini"
66
62
  ],
63
+ "dependencies": {
64
+ "@pal-code/core": "0.0.10",
65
+ "@earendil-works/pi-tui": "^0.85.1"
66
+ },
67
67
  "devDependencies": {
68
68
  "@biomejs/biome": "^2.5.13",
69
69
  "@types/bun": "latest",
@@ -1,8 +1,8 @@
1
- # @pal/cli
1
+ # @pal-code/cli
2
2
 
3
3
  Terminal UI for the [pal](../..) coding agent. This package provides the TUI
4
4
  interface — streaming markdown display, editor, model picker, session selector,
5
- and live status line — while [`@pal/core`](../core) supplies the provider
5
+ and live status line — while [`@pal-code/core`](../core) supplies the provider
6
6
  abstraction, session store, agent loop, and tools.
7
7
 
8
8
  ## Quick start
@@ -10,7 +10,7 @@ import {homedir} from 'node:os';
10
10
  import {join} from 'node:path';
11
11
  import {existsSync, mkdirSync, readFileSync, writeFileSync} from 'node:fs';
12
12
  import {execSync} from 'node:child_process';
13
- import {readPalConfig, saveSetting} from '@pal/core';
13
+ import {readPalConfig, saveSetting} from '@pal-code/core';
14
14
 
15
15
  const EXTENSIONS_DIR = join(homedir(), '.pal', 'extensions');
16
16
 
@@ -10,7 +10,7 @@ import type {TUI, Container} from '@earendil-works/pi-tui';
10
10
 
11
11
  import {c} from './theme.js';
12
12
  import {formatTokens, formatCost} from './utils/cost.js';
13
- import {isDebugEnabled} from '@pal/core';
13
+ import {isDebugEnabled} from '@pal-code/core';
14
14
 
15
15
  export function cmdHelp(container: Container, tui: TUI): void {
16
16
  container.addChild(new Text('', 0, 0));
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * renderHistory — replay a stored session transcript into the message area.
3
3
  *
4
- * Sessions are stored as an append-only, normalized log (see @pal/core's
4
+ * Sessions are stored as an append-only, normalized log (see @pal-code/core's
5
5
  * SessionStore), so resuming can show everything the user saw: user boxes,
6
6
  * assistant answers, tool activity, and a seam marker at each compaction
7
7
  * checkpoint. The model view is built separately; this is purely for the human.
@@ -11,7 +11,7 @@
11
11
  */
12
12
 
13
13
  import {Container, Text, Markdown} from '@earendil-works/pi-tui';
14
- import type {StoredMessage, CompactionRecord} from '@pal/core';
14
+ import type {StoredMessage, CompactionRecord} from '@pal-code/core';
15
15
 
16
16
  import {c, markdownTheme} from '../theme.js';
17
17
  import {MessageBox} from './message-box.js';
@@ -7,8 +7,8 @@
7
7
  * context limit).
8
8
  */
9
9
 
10
- import {readPalConfig, loadPermissionConfig} from '@pal/core';
11
- import type {PermissionConfig} from '@pal/core';
10
+ import {readPalConfig, loadPermissionConfig} from '@pal-code/core';
11
+ import type {PermissionConfig} from '@pal-code/core';
12
12
 
13
13
  export interface Config {
14
14
  model: string;
@@ -26,8 +26,6 @@ import {
26
26
  detectCapabilities,
27
27
  } from '@earendil-works/pi-tui';
28
28
  import type {TUI} from '@earendil-works/pi-tui';
29
- import pkg from '../package.json';
30
-
31
29
  import {c, editorTheme, agentColors, agentLabels, colorByName} from './theme.js';
32
30
  import {generateTitle, sanitizeTitle, formatMessageTimestamp} from './utils/format.js';
33
31
  import {MessageBox} from './components/message-box.js';
@@ -70,20 +68,20 @@ import {
70
68
  resolvePrimary,
71
69
  defaultPrimaryName,
72
70
  resolveProjectRoot,
73
- } from '@pal/core';
74
- import type {Provider, ConversationMessage as Message} from '@pal/core';
71
+ } from '@pal-code/core';
72
+ import type {Provider, ConversationMessage as Message} from '@pal-code/core';
75
73
  // SessionStore deferred — bun:sqlite import may break pi-tui stdin
76
- import type {SessionStore as SessionStoreType} from '@pal/core';
74
+ import type {SessionStore as SessionStoreType} from '@pal-code/core';
77
75
 
78
76
  // ═══════════════════════════════════════════════════════════════════════════════
79
77
  // Config
80
78
  // ═══════════════════════════════════════════════════════════════════════════════
81
79
 
82
80
  // Model lists are now resolved dynamically from each provider's /models endpoint
83
- // (see buildModelOptions). Static curated lists live in @pal/core PROVIDERS as fallback.
81
+ // (see buildModelOptions). Static curated lists live in @pal-code/core PROVIDERS as fallback.
84
82
 
85
- // Single source of truth — no more drift from package.json.
86
- const VERSION = pkg.version;
83
+ // Version synced from version.json via `node scripts/sync-version.js`.
84
+ const VERSION = '0.0.10';
87
85
 
88
86
  import {showModelSelector} from './overlays/model-picker.js';
89
87
  import {showKeyInput} from './overlays/key-input.js';
@@ -98,7 +96,7 @@ async function main() {
98
96
  // Fast exit for version flags (no config/project root needed)
99
97
  const flag = process.argv[2];
100
98
  if (flag === '--version' || flag === '--v' || flag === '-v' || flag === '-version') {
101
- console.log(`pal-code v${pkg.version}`);
99
+ console.log(`pal-code v${VERSION}`);
102
100
  process.exit(0);
103
101
  }
104
102
 
@@ -1574,7 +1572,7 @@ async function main() {
1574
1572
  ensureExtensionsLoaded(config.extensions).catch(() => {});
1575
1573
 
1576
1574
  // Initialize session store AFTER tui starts (bun:sqlite import must not run before pi-tui stdin setup)
1577
- const {SessionStore} = await import('@pal/core');
1575
+ const {SessionStore} = await import('@pal-code/core');
1578
1576
  store = new SessionStore();
1579
1577
  store.init();
1580
1578
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  import {Text, Input} from '@earendil-works/pi-tui';
4
4
  import type {TUI, Container, Editor} from '@earendil-works/pi-tui';
5
- import {PROVIDERS, detectProvider, saveKey, saveSetting} from '@pal/core';
5
+ import {PROVIDERS, detectProvider, saveKey, saveSetting} from '@pal-code/core';
6
6
  import type {Config} from '../config.js';
7
7
 
8
8
  import {c} from '../theme.js';
@@ -2,8 +2,8 @@
2
2
 
3
3
  import {Text, SelectList} from '@earendil-works/pi-tui';
4
4
  import type {TUI, Container, Editor, SelectItem} from '@earendil-works/pi-tui';
5
- import {PROVIDERS, resolveModelIds, saveSetting} from '@pal/core';
6
- import type {Provider, ProviderKeys} from '@pal/core';
5
+ import {PROVIDERS, resolveModelIds, saveSetting} from '@pal-code/core';
6
+ import type {Provider, ProviderKeys} from '@pal-code/core';
7
7
 
8
8
  import {c} from '../theme.js';
9
9
  import {state} from '../state.js';
@@ -10,7 +10,7 @@ import type {TUI, Container, Editor, SelectItem} from '@earendil-works/pi-tui';
10
10
 
11
11
  import {c} from '../theme.js';
12
12
  import {truncate} from '../utils/format.js';
13
- import type {ConversationMessage as Message, Session, SessionStore} from '@pal/core';
13
+ import type {ConversationMessage as Message, Session, SessionStore} from '@pal-code/core';
14
14
 
15
15
  export function groupByDate(sessions: readonly Session[]): Map<string, Session[]> {
16
16
  const now = new Date();
@@ -6,7 +6,7 @@
6
6
  * lets the wizard run without entering raw mode.
7
7
  */
8
8
 
9
- import {PROVIDERS, detectProvider, saveKey, saveSetting, configPath} from '@pal/core';
9
+ import {PROVIDERS, detectProvider, saveKey, saveSetting, configPath} from '@pal-code/core';
10
10
 
11
11
  import {c} from '../theme.js';
12
12
 
@@ -13,7 +13,7 @@
13
13
  * import site).
14
14
  *
15
15
  * Only *presentation* state lives here. Anything that decides what the agent
16
- * does belongs in `@pal/core` (see SYSTEM.md).
16
+ * does belongs in `@pal-code/core` (see SYSTEM.md).
17
17
  */
18
18
 
19
19
  import type {RunView} from './components/run-view.js';
@@ -26,7 +26,7 @@ export type OverlayMode = 'none' | 'model-select' | 'key-input' | 'agents' | 'pe
26
26
  * Tab). Populated from the orchestration extension at load time; defaults to
27
27
  * 'pal' (the orchestrator) when no extension provides primaries.
28
28
  *
29
- * Not to be confused with a delegation role — see `@pal/core`'s `PrimarySpec`.
29
+ * Not to be confused with a delegation role — see `@pal-code/core`'s `PrimarySpec`.
30
30
  */
31
31
  export type AgentRole = string;
32
32
 
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * One agent turn: drive `runWithFallback` and translate its events into
3
- * RunView calls. The reliability policy itself lives in @pal/core.
3
+ * RunView calls. The reliability policy itself lives in @pal-code/core.
4
4
  */
5
5
 
6
6
  import {
@@ -9,6 +9,7 @@ import {
9
9
  executeTool,
10
10
  registerExtensionHandlers,
11
11
  loadExtensions,
12
+ resolveExtensionSpecifier,
12
13
  runWithFallback,
13
14
  shortModel,
14
15
  buildRolesPrompt,
@@ -19,7 +20,7 @@ import {
19
20
  type ProviderKeys,
20
21
  type ConversationMessage as Message,
21
22
  type ToolResult,
22
- } from '@pal/core';
23
+ } from '@pal-code/core';
23
24
  import type {TUI, Container} from '@earendil-works/pi-tui';
24
25
 
25
26
  import type {Config} from './config.js';
@@ -50,8 +51,8 @@ async function applyLoaded(
50
51
  requested: string[],
51
52
  loaded: string[],
52
53
  failed: Array<{pkg: string; reason: string}>,
53
- tools: import('@pal/core').ToolDef[],
54
- handlers: Record<string, import('@pal/core').ToolHandler>,
54
+ tools: import('@pal-code/core').ToolDef[],
55
+ handlers: Record<string, import('@pal-code/core').ToolHandler>,
55
56
  ): Promise<void> {
56
57
  registerExtensionHandlers(handlers);
57
58
  registerExtensionTools(tools);
@@ -59,14 +60,18 @@ async function applyLoaded(
59
60
  const active = new Set(loaded);
60
61
  const failedByPkg = new Map(failed.map((f) => [f.pkg, f.reason]));
61
62
  state.extensions = requested.map((pkg) => ({
62
- name: pkg.replace(/^@pal\//, ''),
63
+ name: pkg.replace(/^@pal-code\//, ''),
63
64
  active: active.has(pkg),
64
65
  reason: failedByPkg.get(pkg),
65
66
  }));
66
67
 
67
- // Populate MCP server status for the sidebar (live from manager)
68
+ // Populate MCP server status for the sidebar (live from manager).
69
+ //
70
+ // Resolved through core rather than a bare import: `pal add` installs the
71
+ // extension under ~/.pal/extensions/node_modules, which a plain
72
+ // `import('@pal-code/mcp')` from here would not search.
68
73
  try {
69
- const mcpMod = await import('@pal-code/mcp').catch(() => null);
74
+ const mcpMod = await import(resolveExtensionSpecifier('@pal-code/mcp')).catch(() => null);
70
75
  if (mcpMod?.mcpManager) {
71
76
  state.mcpServers = mcpMod.mcpManager.getServerDetails();
72
77
  state.refreshSidebar();
@@ -99,7 +104,7 @@ export async function ensureExtensionsLoaded(extensions?: string[]): Promise<voi
99
104
  * Re-import extensions without restarting pal. Called by `/reload`.
100
105
  *
101
106
  * Uses the loader's `cacheBust` option so edited extension source is picked up.
102
- * `@pal/core` is not re-imported, so a re-registered role provider lands in the
107
+ * `@pal-code/core` is not re-imported, so a re-registered role provider lands in the
103
108
  * one registry core already holds.
104
109
  */
105
110
  export async function reloadExtensions(extensions?: string[]): Promise<number> {
@@ -129,7 +134,7 @@ function composeSystemPrompt(base: string, primaryName?: string): string {
129
134
  }
130
135
 
131
136
  /** Tools the turn may use, narrowed to the primary agent's set when it declares one. */
132
- function toolsForPrimary(primaryName?: string): import('@pal/core').ToolDef[] {
137
+ function toolsForPrimary(primaryName?: string): import('@pal-code/core').ToolDef[] {
133
138
  const all = getAllTools();
134
139
  const primary = primaryName ? resolvePrimary(primaryName) : null;
135
140
  if (!primary?.tools) return all;
@@ -6,9 +6,9 @@
6
6
  * The TUI key handler in index.ts routes y/n/a/Esc to the resolver.
7
7
  */
8
8
 
9
- import {checkPermission, loadPermissionConfig, detectDangerousBash} from '@pal/core';
10
- import type {PermissionConfig} from '@pal/core';
11
- import type {ToolResult} from '@pal/core';
9
+ import {checkPermission, loadPermissionConfig, detectDangerousBash} from '@pal-code/core';
10
+ import type {PermissionConfig} from '@pal-code/core';
11
+ import type {ToolResult} from '@pal-code/core';
12
12
 
13
13
  import {state} from '../state.js';
14
14
 
@@ -1,167 +0,0 @@
1
- import {describe, expect, test} from 'bun:test';
2
- import {stripTerminalSequences} from '@earendil-works/pi-tui';
3
-
4
- import {userMessageBox, wrapText, truncate, displayWidth} from './format.js';
5
-
6
- const plain = (s: string) => stripTerminalSequences(s);
7
-
8
- /** Every row of the box must be exactly `width` visible columns wide. */
9
- function expectRectangular(box: string, width: number) {
10
- const W = Math.max(6, Math.floor(width));
11
- const lines = box.split('\n');
12
- for (const line of lines) {
13
- expect(displayWidth(line)).toBe(W);
14
- }
15
- expect(plain(lines[0]!).startsWith('╭')).toBe(true);
16
- expect(plain(lines.at(-1)!).startsWith('╰')).toBe(true);
17
- }
18
-
19
- const ROLES = ['pal', 'build', 'architect', 'web-search', ''] as const;
20
-
21
- const INPUTS: Array<[string, string]> = [
22
- ['short', 'hello'],
23
- ['multiline', 'first line\nsecond line'],
24
- ['wraps', 'the quick brown fox jumps over the lazy dog and keeps running'],
25
- ['empty', ''],
26
- ['whitespace', ' '],
27
- ['trailing newline', 'done\n'],
28
- ['crlf', 'a\r\nb'],
29
- ['tabs', '\tindented\ttext'],
30
- ['ansi', `\x1b[31mred\x1b[0m and \x1b[1mbold\x1b[0m`],
31
- ['cjk', '你好世界,这是一个测试'],
32
- ['emoji', 'ship it 🚀🎉 with 👨‍👩‍👧 family'],
33
- ['long word', 'x'.repeat(120)],
34
- ];
35
-
36
- describe('userMessageBox', () => {
37
- test('every row is exactly `width` columns for all widths, roles and inputs', () => {
38
- for (const width of [2, 4, 6, 8, 12, 20, 40, 80]) {
39
- for (const role of ROLES) {
40
- for (const [name, input] of INPUTS) {
41
- const box = userMessageBox(input, width, role);
42
- try {
43
- expectRectangular(box, width);
44
- } catch (err) {
45
- throw new Error(`width=${width} role=${role || '(empty)'} input=${name}: ${err}`);
46
- }
47
- }
48
- }
49
- }
50
- });
51
-
52
- test('shows the role tag once it fits, and drops it when it does not', () => {
53
- expect(plain(userMessageBox('hi', 40, 'build'))).toContain('[builder]');
54
- // '[build]' is 9 wide; it needs width >= 15.
55
- expect(plain(userMessageBox('hi', 14, 'build'))).not.toContain('[builder]');
56
- });
57
-
58
- test('timestamped header stays rectangular across widths, roles and stamps', () => {
59
- const stamps = ['Mon 14:30', 'Mon 15 Jan 14:30', 'Mon 15 Jan 2025 14:30', ''];
60
- for (const width of [2, 4, 6, 8, 12, 20, 30, 40, 80, 120]) {
61
- for (const role of ROLES) {
62
- for (const ts of stamps) {
63
- const box = userMessageBox('hello', width, role, ts);
64
- try {
65
- expectRectangular(box, width);
66
- } catch (err) {
67
- throw new Error(`width=${width} role=${role || '(empty)'} ts="${ts}": ${err}`);
68
- }
69
- }
70
- }
71
- }
72
- });
73
-
74
- test('timestamp renders opposite the tag when there is room', () => {
75
- const box = plain(userMessageBox('hi', 60, 'build', 'Mon 14:30'));
76
- const header = box.split('\n')[0]!;
77
- expect(header).toContain('[builder]');
78
- expect(header).toContain('Mon 14:30');
79
- // tag left of timestamp
80
- expect(header.indexOf('[builder]')).toBeLessThan(header.indexOf('Mon 14:30'));
81
- });
82
-
83
- test('timestamp is dropped before the tag when the box is narrow', () => {
84
- // Wide enough for '[builder]' (needs 15) but not for tag + timestamp.
85
- const box = plain(userMessageBox('hi', 16, 'build', 'Mon 15 Jan 2025 14:30'));
86
- const header = box.split('\n')[0]!;
87
- expect(header).toContain('[builder]');
88
- expect(header).not.toContain('2025');
89
- });
90
-
91
- test('renders a golden box for a short message', () => {
92
- const expected =
93
- `╭─ [pal] ${'─'.repeat(10)}╮\n` + `│ hi${' '.repeat(14)} │\n` + `╰${'─'.repeat(18)}╯`;
94
- expect(plain(userMessageBox('hi', 20, 'pal'))).toBe(expected);
95
- });
96
-
97
- test('never throws on degenerate widths', () => {
98
- for (const width of [-10, 0, 1, 3, 5]) {
99
- expect(() => userMessageBox('hello world', width, 'pal')).not.toThrow();
100
- }
101
- });
102
- });
103
-
104
- describe('wrapText', () => {
105
- test('wraps words to the given width', () => {
106
- expect(wrapText('one two three four', 8)).toEqual(['one two', 'three', 'four']);
107
- });
108
-
109
- test('hard-breaks words longer than the width', () => {
110
- const lines = wrapText('abcdefghij', 4);
111
- expect(lines.every((l) => displayWidth(l) <= 4)).toBe(true);
112
- expect(lines.join('')).toBe('abcdefghij');
113
- });
114
-
115
- test('splits on CRLF, CR and LF alike', () => {
116
- expect(wrapText('a\r\nb\rc\nd', 10)).toEqual(['a', 'b', 'c', 'd']);
117
- });
118
-
119
- test('keeps a hanging indent on continuation lines', () => {
120
- const lines = wrapText(' alpha beta gamma delta', 12);
121
- for (const line of lines.slice(1)) expect(line.startsWith(' ')).toBe(true);
122
- });
123
-
124
- test('preserves ANSI styling across the wrap', () => {
125
- const lines = wrapText('\x1b[31mred red red red red\x1b[0m', 7);
126
- expect(lines.every((l) => displayWidth(l) <= 7)).toBe(true);
127
- expect(lines.join('')).toContain('red');
128
- });
129
-
130
- test('returns a single empty line for empty input', () => {
131
- expect(wrapText('', 10)).toEqual(['']);
132
- });
133
- });
134
-
135
- describe('truncate', () => {
136
- test('never returns more than `max` characters', () => {
137
- const text = 'hello world';
138
- for (let max = -2; max <= text.length + 2; max++) {
139
- expect(truncate(text, max).length).toBeLessThanOrEqual(Math.max(0, max));
140
- }
141
- });
142
-
143
- test('adds an ellipsis when there is room for one', () => {
144
- expect(truncate('hello world', 8)).toBe('hello...');
145
- });
146
-
147
- test('hard-cuts when the budget cannot fit an ellipsis', () => {
148
- expect(truncate('hello world', 3)).toBe('hel');
149
- expect(truncate('hello world', 0)).toBe('');
150
- expect(truncate('hello world', -5)).toBe('');
151
- });
152
-
153
- test('leaves short enough text untouched', () => {
154
- expect(truncate('hi', 5)).toBe('hi');
155
- expect(truncate('', 5)).toBe('');
156
- });
157
- });
158
-
159
- describe('displayWidth', () => {
160
- test('ignores ANSI codes', () => {
161
- expect(displayWidth('\x1b[31mred\x1b[0m')).toBe(3);
162
- });
163
-
164
- test('counts wide characters as two columns', () => {
165
- expect(displayWidth('你好')).toBe(4);
166
- });
167
- });
@@ -1,36 +0,0 @@
1
- /**
2
- * Agent lifecycle events — lets the UI observe sub-agents spawned by `delegate`
3
- * without the tool executor knowing anything about the TUI.
4
- */
5
-
6
- export type AgentEvent =
7
- | {type: 'delegate-start'; id: string; task: string}
8
- | {type: 'delegate-round'; id: string; round: number}
9
- | {type: 'delegate-tool'; id: string; tool: string}
10
- | {type: 'delegate-done'; id: string; summary: string; error?: boolean}
11
- | {type: 'todos-updated'; todos: readonly {content: string; status: string}[]}
12
- /** The agent asks the front-end to switch primary agent (e.g. → plan mode). */
13
- | {type: 'primary-request'; name: string; reason?: string};
14
-
15
- type Listener = (ev: AgentEvent) => void;
16
-
17
- const listeners = new Set<Listener>();
18
-
19
- /** Subscribe to agent events. Returns an unsubscribe function. */
20
- export function onAgentEvent(fn: Listener): () => void {
21
- listeners.add(fn);
22
- return () => {
23
- listeners.delete(fn);
24
- };
25
- }
26
-
27
- /** Emit an agent event to all subscribers. Never throws. */
28
- export function emitAgentEvent(ev: AgentEvent): void {
29
- for (const fn of [...listeners]) {
30
- try {
31
- fn(ev);
32
- } catch {
33
- /* a broken listener must not break the agent */
34
- }
35
- }
36
- }