pal-code 0.0.11 → 0.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,17 +8,22 @@ import {
8
8
  registerExtensionTools,
9
9
  executeTool,
10
10
  registerExtensionHandlers,
11
+ registerExtensionLifecycle,
11
12
  loadExtensions,
12
13
  resolveExtensionSpecifier,
13
14
  runWithFallback,
14
15
  shortModel,
15
16
  buildRolesPrompt,
17
+ buildSkillsPrompt,
18
+ clearFileRolesCache,
19
+ clearSkillsCache,
16
20
  listPrimaries,
17
21
  resolvePrimary,
18
22
  defaultPrimaryName,
19
23
  type Provider,
20
24
  type ProviderKeys,
21
25
  type ConversationMessage as Message,
26
+ type LoadedExtensions,
22
27
  type ToolResult,
23
28
  } from '@pal-code/core';
24
29
  import type {TUI, Container} from '@earendil-works/pi-tui';
@@ -44,21 +49,17 @@ let extensionsLoaded = false;
44
49
  export const DEFAULT_EXTENSIONS = ['@pal-code/web-search', '@pal-code/agents', '@pal-code/mcp'];
45
50
 
46
51
  /**
47
- * Apply a successful load to the process: register tools + handlers centrally,
48
- * record status for the sidebar, and adopt the configured default primary.
52
+ * Apply a successful load to the process: register tools, handlers and
53
+ * lifecycle hooks centrally, record status for the sidebar, and adopt the
54
+ * configured default primary.
49
55
  */
50
- async function applyLoaded(
51
- requested: string[],
52
- loaded: string[],
53
- failed: Array<{pkg: string; reason: string}>,
54
- tools: import('@pal-code/core').ToolDef[],
55
- handlers: Record<string, import('@pal-code/core').ToolHandler>,
56
- ): Promise<void> {
57
- registerExtensionHandlers(handlers);
58
- registerExtensionTools(tools);
56
+ async function applyLoaded(requested: string[], result: LoadedExtensions): Promise<void> {
57
+ registerExtensionHandlers(result.handlers);
58
+ registerExtensionTools(result.tools);
59
+ registerExtensionLifecycle(result.lifecycle);
59
60
 
60
- const active = new Set(loaded);
61
- const failedByPkg = new Map(failed.map((f) => [f.pkg, f.reason]));
61
+ const active = new Set(result.loaded);
62
+ const failedByPkg = new Map(result.failed.map((f) => [f.pkg, f.reason]));
62
63
  state.extensions = requested.map((pkg) => ({
63
64
  name: pkg.replace(/^@pal-code\//, ''),
64
65
  active: active.has(pkg),
@@ -95,9 +96,9 @@ export async function ensureExtensionsLoaded(extensions?: string[]): Promise<voi
95
96
  if (extensionsLoaded) return;
96
97
 
97
98
  const requested = extensions ?? DEFAULT_EXTENSIONS;
98
- const {tools, handlers, loaded, failed} = await loadExtensions(requested);
99
+ const result = await loadExtensions(requested);
99
100
  extensionsLoaded = true;
100
- await applyLoaded(requested, loaded, failed, tools, handlers);
101
+ await applyLoaded(requested, result);
101
102
  }
102
103
 
103
104
  /**
@@ -109,19 +110,21 @@ export async function ensureExtensionsLoaded(extensions?: string[]): Promise<voi
109
110
  */
110
111
  export async function reloadExtensions(extensions?: string[]): Promise<number> {
111
112
  const requested = extensions ?? DEFAULT_EXTENSIONS;
112
- const {tools, handlers, loaded, failed} = await loadExtensions(requested, {
113
+ const result = await loadExtensions(requested, {
113
114
  cacheBust: true,
114
115
  });
115
116
  extensionsLoaded = true;
116
- await applyLoaded(requested, loaded, failed, tools, handlers);
117
- return tools.length;
117
+ clearFileRolesCache();
118
+ clearSkillsCache();
119
+ await applyLoaded(requested, result);
120
+ return result.tools.length;
118
121
  }
119
122
 
120
123
  /**
121
124
  * Compose the system prompt for a turn: the base prompt, an optional primary
122
- * agent preamble, and the role-awareness block (only when an orchestration
123
- * extension registered roles). Every piece is skipped when absent, so users
124
- * with no extensions pay nothing in tokens.
125
+ * agent preamble, the role-awareness block, and the skill listing (only when
126
+ * skill files exist). Every piece is skipped when absent, so users with no
127
+ * extensions or skills pay nothing in tokens.
125
128
  */
126
129
  function composeSystemPrompt(base: string, primaryName?: string): string {
127
130
  const parts: string[] = [];
@@ -130,6 +133,8 @@ function composeSystemPrompt(base: string, primaryName?: string): string {
130
133
  parts.push(base);
131
134
  const roles = buildRolesPrompt();
132
135
  if (roles) parts.push(roles);
136
+ const skills = buildSkillsPrompt();
137
+ if (skills) parts.push(skills);
133
138
  return parts.join('\n\n');
134
139
  }
135
140
 
@@ -185,6 +190,7 @@ async function gatedExecuteTool(
185
190
  readOnly?: boolean;
186
191
  allowedTools?: string[];
187
192
  },
193
+ signal?: AbortSignal,
188
194
  ): Promise<ToolResult> {
189
195
  // Parse args for permission check
190
196
  let args: Record<string, unknown> = {};
@@ -204,7 +210,7 @@ async function gatedExecuteTool(
204
210
  };
205
211
  }
206
212
 
207
- return executeTool(name, argsStr, toolCallId, providerConfigOverride);
213
+ return executeTool(name, argsStr, toolCallId, providerConfigOverride, signal);
208
214
  }
209
215
 
210
216
  export async function agentLoop(
@@ -246,6 +252,7 @@ export async function agentLoop(
246
252
  executeTool: gatedExecuteTool,
247
253
  childExecuteTool: gatedExecuteTool,
248
254
  signal: state.activeAbort?.signal,
255
+ primary: primaryName,
249
256
  readOnly: isReadOnlyPrimary(primaryName),
250
257
  allowedTools: allowedToolsForPrimary(primaryName),
251
258
  createProvider: (spec: string) => createProvider(spec),
@@ -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,
@@ -154,7 +158,10 @@ function buildHeader(
154
158
  // Fixed columns: ╭(1) ─(1) ␠(1) tag ␠(1) [dashes] ╮(1)
155
159
  const dashes = W - tagWidth - 5;
156
160
  if (dashes >= 1) {
157
- return `${paint('╭─')} ${roleColor}${tagText}${c.reset} ` + `${paint('─'.repeat(dashes))}${paint('╮')}`;
161
+ return (
162
+ `${paint('╭─')} ${roleColor}${tagText}${c.reset} ` +
163
+ `${paint('─'.repeat(dashes))}${paint('╮')}`
164
+ );
158
165
  }
159
166
  return '';
160
167
  };
@@ -246,3 +253,18 @@ export function formatMessageTimestamp(epochMs: number, now = Date.now()): strin
246
253
 
247
254
  return `${weekday} ${day} ${month} ${year} ${time}`;
248
255
  }
256
+
257
+ /**
258
+ * Live fan-out indicator for the status line: `⟳ 2 subagents running… 4s`.
259
+ * Returns an empty string while no child is running, so the caller can splice
260
+ * it in unconditionally and the idle status line stays byte-identical.
261
+ *
262
+ * `startedAt` is the burst clock from core's subagent status (epoch ms of the
263
+ * first spawn); `now` is injectable so tests can pin the elapsed seconds.
264
+ */
265
+ export function subagentStatusText(active: number, startedAt: number, now = Date.now()): string {
266
+ if (active <= 0) return '';
267
+ const elapsed = Math.max(0, Math.floor((now - startedAt) / 1000));
268
+ const noun = active === 1 ? 'subagent' : 'subagents';
269
+ return `⟳ ${active} ${noun} running… ${elapsed}s`;
270
+ }
@@ -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
+ }