@oh-my-pi/pi-coding-agent 16.3.11 → 16.3.12

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 (80) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/cli.js +3119 -3028
  3. package/dist/types/advisor/runtime.d.ts +11 -0
  4. package/dist/types/config/model-registry.d.ts +4 -0
  5. package/dist/types/config/settings-schema.d.ts +6 -0
  6. package/dist/types/config/settings.d.ts +2 -0
  7. package/dist/types/discovery/helpers.d.ts +9 -0
  8. package/dist/types/exec/bash-executor.d.ts +1 -0
  9. package/dist/types/extensibility/shared-events.d.ts +2 -2
  10. package/dist/types/internal-urls/__tests__/agent-protocol-nested.test.d.ts +1 -0
  11. package/dist/types/internal-urls/registry-helpers.d.ts +7 -5
  12. package/dist/types/modes/components/model-selector.d.ts +2 -1
  13. package/dist/types/modes/github-ref-autocomplete.d.ts +35 -0
  14. package/dist/types/modes/utils/context-usage.d.ts +0 -12
  15. package/dist/types/modes/workflow.d.ts +5 -1
  16. package/dist/types/session/agent-session.d.ts +5 -0
  17. package/dist/types/system-prompt.d.ts +1 -1
  18. package/dist/types/tools/bash-interactive.d.ts +1 -1
  19. package/dist/types/tools/bash-skill-urls.d.ts +1 -0
  20. package/dist/types/tools/bash.d.ts +2 -1
  21. package/dist/types/tools/browser/launch.d.ts +1 -0
  22. package/dist/types/tools/grep.d.ts +2 -0
  23. package/dist/types/tools/index.d.ts +4 -0
  24. package/dist/types/tools/path-utils.d.ts +24 -0
  25. package/dist/types/tools/read.d.ts +2 -0
  26. package/dist/types/utils/local-date.d.ts +2 -0
  27. package/package.json +12 -12
  28. package/src/advisor/__tests__/advisor.test.ts +145 -0
  29. package/src/advisor/runtime.ts +19 -0
  30. package/src/config/api-key-resolver.ts +7 -2
  31. package/src/config/model-registry.ts +9 -0
  32. package/src/config/settings-schema.ts +11 -1
  33. package/src/config/settings.ts +11 -0
  34. package/src/discovery/builtin.ts +2 -1
  35. package/src/discovery/claude-plugins.ts +167 -46
  36. package/src/discovery/helpers.ts +16 -1
  37. package/src/edit/renderer.ts +20 -6
  38. package/src/eval/js/worker-core.ts +163 -6
  39. package/src/exec/bash-executor.ts +14 -9
  40. package/src/extensibility/plugins/legacy-pi-compat.ts +6 -2
  41. package/src/extensibility/plugins/marketplace/fetcher.ts +15 -14
  42. package/src/extensibility/shared-events.ts +2 -2
  43. package/src/internal-urls/__tests__/agent-protocol-nested.test.ts +68 -0
  44. package/src/internal-urls/docs-index.generated.txt +1 -1
  45. package/src/internal-urls/registry-helpers.ts +9 -6
  46. package/src/modes/components/model-selector.ts +30 -6
  47. package/src/modes/components/settings-defs.ts +1 -1
  48. package/src/modes/components/status-line/component.ts +14 -2
  49. package/src/modes/controllers/command-controller.ts +13 -23
  50. package/src/modes/controllers/event-controller.ts +12 -12
  51. package/src/modes/controllers/extension-ui-controller.ts +6 -35
  52. package/src/modes/controllers/input-controller.ts +18 -2
  53. package/src/modes/controllers/mcp-command-controller.ts +10 -9
  54. package/src/modes/controllers/selector-controller.ts +16 -5
  55. package/src/modes/github-ref-autocomplete.ts +75 -0
  56. package/src/modes/interactive-mode.ts +54 -10
  57. package/src/modes/prompt-action-autocomplete.ts +35 -0
  58. package/src/modes/utils/context-usage.ts +58 -5
  59. package/src/modes/utils/hotkeys-markdown.ts +2 -1
  60. package/src/modes/utils/ui-helpers.ts +2 -2
  61. package/src/modes/workflow.ts +14 -8
  62. package/src/prompts/system/plan-mode-active.md +5 -2
  63. package/src/prompts/system/system-prompt.md +1 -2
  64. package/src/prompts/system/workflow-notice.md +69 -50
  65. package/src/prompts/tools/bash.md +18 -7
  66. package/src/prompts/tools/grep.md +1 -1
  67. package/src/prompts/tools/read.md +4 -3
  68. package/src/sdk.ts +11 -0
  69. package/src/session/agent-session.ts +128 -14
  70. package/src/system-prompt.ts +3 -2
  71. package/src/tools/bash-interactive.ts +1 -1
  72. package/src/tools/bash-skill-urls.ts +39 -7
  73. package/src/tools/bash.ts +69 -39
  74. package/src/tools/browser/launch.ts +31 -4
  75. package/src/tools/grep.ts +53 -14
  76. package/src/tools/index.ts +11 -0
  77. package/src/tools/path-utils.ts +46 -1
  78. package/src/tools/read.ts +108 -50
  79. package/src/utils/local-date.ts +7 -0
  80. package/src/utils/open.ts +36 -10
@@ -1367,7 +1367,17 @@ export const SETTINGS_SCHEMA = {
1367
1367
  description: "Allow retry recovery to switch to configured fallback models",
1368
1368
  },
1369
1369
  },
1370
- "retry.fallbackChains": { type: "record", default: {} as Record<string, string[]> },
1370
+ "retry.fallbackChains": {
1371
+ type: "record",
1372
+ default: {} as Record<string, string[]>,
1373
+ ui: {
1374
+ tab: "model",
1375
+ group: "Retry & Fallback",
1376
+ label: "Retry Fallback Chains",
1377
+ description:
1378
+ 'JSON object mapping model roles to ordered fallback model selectors, e.g. {"default":["openai/gpt-4o-mini"]}.',
1379
+ },
1380
+ },
1371
1381
  "retry.fallbackRevertPolicy": {
1372
1382
  type: "enum",
1373
1383
  values: ["cooldown-expiry", "never"] as const,
@@ -429,6 +429,9 @@ export class Settings {
429
429
  if (path === "statusLine.sessionAccent") {
430
430
  statusLineSessionAccentSignal.fire();
431
431
  }
432
+ if (path === "modelRoles") {
433
+ modelRolesSignal.fire();
434
+ }
432
435
  }
433
436
 
434
437
  /**
@@ -480,11 +483,13 @@ export class Settings {
480
483
  async reloadForCwd(cwd: string): Promise<void> {
481
484
  const normalized = path.normalize(cwd);
482
485
  if (normalized === this.#cwd) return;
486
+ const prevModelRoles = this.get("modelRoles");
483
487
  this.#cwd = normalized;
484
488
  if (this.#persist) {
485
489
  this.#project = await this.#loadProjectSettings();
486
490
  }
487
491
  this.#rebuildMerged();
492
+ this.#fireEffectiveSettingChanged("modelRoles", this.get("modelRoles"), prevModelRoles);
488
493
  this.#fireAllHooks();
489
494
  }
490
495
 
@@ -1477,6 +1482,12 @@ const appendOnlyModeSignal = new SettingSignal<[value: string]>("provider.append
1477
1482
  */
1478
1483
  export const onAppendOnlyModeChanged = (cb: (value: string) => void) => appendOnlyModeSignal.on(cb);
1479
1484
 
1485
+ /** Fires when any model role changes at runtime. */
1486
+ const modelRolesSignal = new SettingSignal("modelRoles");
1487
+
1488
+ /** Subscribe to model role changes. Returns an unsubscribe function. */
1489
+ export const onModelRolesChanged: (cb: () => void) => () => void = modelRolesSignal.on.bind(modelRolesSignal);
1490
+
1480
1491
  /** Fires when `statusLine.sessionAccent` changes at runtime. */
1481
1492
  const statusLineSessionAccentSignal = new SettingSignal("statusLine.sessionAccent");
1482
1493
 
@@ -401,7 +401,8 @@ async function loadStickyRulesFile(filePath: string, level: "user" | "project"):
401
401
  const content = await readFile(filePath);
402
402
  if (!content) return null;
403
403
  const source = createSourceMeta(PROVIDER_ID, filePath, level);
404
- const rule = buildRuleFromMarkdown("RULES.md", content, filePath, source, { ruleName: "RULES" });
404
+ const ruleName = level === "project" ? "RULES@project" : "RULES";
405
+ const rule = buildRuleFromMarkdown("RULES.md", content, filePath, source, { ruleName });
405
406
  // Force alwaysApply regardless of frontmatter — the whole point of RULES.md
406
407
  // is to be reattached every turn.
407
408
  return { ...rule, alwaysApply: true };
@@ -4,6 +4,7 @@
4
4
  * Loads configuration from ~/.claude/plugins/cache/ based on installed_plugins.json registry.
5
5
  * Priority: 70 (below claude.ts at 80, so user overrides in .claude/ take precedence)
6
6
  */
7
+ import * as fs from "node:fs/promises";
7
8
  import * as path from "node:path";
8
9
  import { logger } from "@oh-my-pi/pi-utils";
9
10
  import { registerProvider } from "../capability";
@@ -30,14 +31,14 @@ const DISPLAY_NAME = "Claude Code Marketplace";
30
31
  const PRIORITY = 70; // Below claude.ts (80) so user .claude/ overrides win
31
32
 
32
33
  interface ClaudePluginManifest {
33
- skills?: string;
34
- "slash-commands"?: string;
35
- commands?: string;
34
+ skills?: string | string[];
35
+ "slash-commands"?: string | string[];
36
+ commands?: string | string[];
36
37
  }
37
38
 
38
39
  interface ResolvedPluginDir {
39
- dir: string;
40
- warning?: string;
40
+ dirs: string[];
41
+ warnings: string[];
41
42
  }
42
43
 
43
44
  async function readPluginManifest(root: ClaudePluginRoot): Promise<ClaudePluginManifest | null> {
@@ -54,43 +55,116 @@ async function readPluginManifest(root: ClaudePluginRoot): Promise<ClaudePluginM
54
55
  }
55
56
  }
56
57
 
58
+ function isRecord(value: unknown): value is Record<string, unknown> {
59
+ return value !== null && typeof value === "object" && !Array.isArray(value);
60
+ }
61
+
62
+ async function skillsManifestReplacesFallback(root: ClaudePluginRoot): Promise<boolean> {
63
+ const raw = await readFile(path.join(root.path, "marketplace.json"));
64
+ if (raw === null) return false;
65
+
66
+ try {
67
+ const parsed: unknown = JSON.parse(raw);
68
+ if (!isRecord(parsed)) return false;
69
+ const plugins = parsed.plugins;
70
+ return (
71
+ Array.isArray(plugins) &&
72
+ plugins.some(entry => isRecord(entry) && entry.name === root.plugin && entry.source === "./")
73
+ );
74
+ } catch {
75
+ return false;
76
+ }
77
+ }
78
+
57
79
  function isWithinPluginRoot(rootPath: string, targetPath: string): boolean {
58
80
  const relative = path.relative(rootPath, targetPath);
59
81
  return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
60
82
  }
61
83
 
84
+ /**
85
+ * Resolve a manifest-declared directory field to absolute paths within the
86
+ * plugin root.
87
+ *
88
+ * Manifest path fields may be `string` or `string[]`
89
+ * (https://code.claude.com/docs/en/plugins-reference#path-behavior-rules);
90
+ * both shapes are normalized here. The first `manifestKeys` entry that
91
+ * supplies at least one non-empty path wins (later keys are ignored — used for
92
+ * the `commands` > `slash-commands` legacy fallback).
93
+ *
94
+ * `fallback` is the default subdirectory (e.g. `skills/`, `commands/`) and
95
+ * `includeFallback` controls the Claude-documented merge semantic per field:
96
+ *
97
+ * - `skills` **adds to** the default: `fallback` is always scanned, and any
98
+ * manifest entries load alongside it. Callers pass `includeFallback: true`.
99
+ * - `commands` / `slash-commands` **replace** the default: an explicit
100
+ * manifest key means the default `commands/` directory is not scanned.
101
+ * Callers pass `includeFallback: false` (the manifest itself may still
102
+ * list `./commands` explicitly to keep it).
103
+ *
104
+ * When no matching key is set, the fallback is used regardless. Entries that
105
+ * resolve outside the plugin root are dropped with a warning so misconfigured
106
+ * manifests remain observable and cannot escape via traversal.
107
+ */
62
108
  async function resolvePluginDir(
63
109
  root: ClaudePluginRoot,
64
110
  manifestKeys: ReadonlyArray<keyof ClaudePluginManifest>,
65
111
  fallback: string,
112
+ includeFallback: boolean,
66
113
  ): Promise<ResolvedPluginDir> {
67
114
  const manifest = await readPluginManifest(root);
68
115
  const fallbackDir = path.join(root.path, fallback);
69
116
 
70
- let configured: string | undefined;
117
+ let configured: string[] | undefined;
71
118
  let matchedKey: keyof ClaudePluginManifest | undefined;
72
119
  for (const key of manifestKeys) {
73
120
  const val = manifest?.[key];
74
- if (typeof val === "string" && val.trim()) {
75
- configured = val.trim();
121
+ const candidates: string[] = [];
122
+ if (typeof val === "string") {
123
+ const trimmed = val.trim();
124
+ if (trimmed) candidates.push(trimmed);
125
+ } else if (Array.isArray(val)) {
126
+ for (const entry of val) {
127
+ if (typeof entry !== "string") continue;
128
+ const trimmed = entry.trim();
129
+ if (trimmed) candidates.push(trimmed);
130
+ }
131
+ }
132
+ if (candidates.length > 0) {
133
+ configured = candidates;
76
134
  matchedKey = key;
77
135
  break;
78
136
  }
79
137
  }
80
138
 
81
139
  if (configured === undefined) {
82
- return { dir: fallbackDir };
140
+ return { dirs: [fallbackDir], warnings: [] };
83
141
  }
84
142
 
85
- const resolved = path.resolve(root.path, configured);
86
- if (isWithinPluginRoot(root.path, resolved)) {
87
- return { dir: resolved };
143
+ // Dedup preserves order: default entry (when included) first, then declared
144
+ // entries in manifest order. Deduping the paths themselves means a plugin
145
+ // author can still list `./commands` explicitly when they want the default
146
+ // alongside extras without producing double-loads.
147
+ const seen = new Set<string>();
148
+ const dirs: string[] = [];
149
+ const warnings: string[] = [];
150
+ if (includeFallback) {
151
+ seen.add(fallbackDir);
152
+ dirs.push(fallbackDir);
153
+ }
154
+ for (const entry of configured) {
155
+ const resolved = path.resolve(root.path, entry);
156
+ if (!isWithinPluginRoot(root.path, resolved)) {
157
+ warnings.push(
158
+ `[claude-plugins] Ignoring ${String(matchedKey)} path outside plugin root for ${root.id}: ${entry}`,
159
+ );
160
+ continue;
161
+ }
162
+ if (seen.has(resolved)) continue;
163
+ seen.add(resolved);
164
+ dirs.push(resolved);
88
165
  }
89
166
 
90
- return {
91
- dir: fallbackDir,
92
- warning: `[claude-plugins] Ignoring ${String(matchedKey)} path outside plugin root for ${root.id}: ${configured}`,
93
- };
167
+ return { dirs, warnings };
94
168
  }
95
169
 
96
170
  // =============================================================================
@@ -104,24 +178,37 @@ async function loadSkills(ctx: LoadContext): Promise<LoadResult<Skill>> {
104
178
  warnings.push(...rootWarnings);
105
179
  const results = await Promise.all(
106
180
  roots.map(async root => {
107
- const { dir: skillsDir, warning } = await resolvePluginDir(root, ["skills"], "skills");
108
- const result = await scanSkillsFromDir(ctx, {
109
- dir: skillsDir,
110
- providerId: PROVIDER_ID,
111
- level: root.scope,
112
- });
113
- return { root, result, warning };
181
+ const includeFallback = !(await skillsManifestReplacesFallback(root));
182
+ const { dirs: skillsDirs, warnings: resolveWarnings } = await resolvePluginDir(
183
+ root,
184
+ ["skills"],
185
+ "skills",
186
+ includeFallback,
187
+ );
188
+ const scanResults = await Promise.all(
189
+ skillsDirs.map(dir =>
190
+ scanSkillsFromDir(ctx, {
191
+ dir,
192
+ providerId: PROVIDER_ID,
193
+ level: root.scope,
194
+ includeSelf: true,
195
+ }),
196
+ ),
197
+ );
198
+ return { scanResults, resolveWarnings };
114
199
  }),
115
200
  );
116
- for (const { result, warning } of results) {
117
- if (warning) warnings.push(warning);
201
+ for (const { scanResults, resolveWarnings } of results) {
202
+ warnings.push(...resolveWarnings);
118
203
  // Intentionally do NOT prefix skill names with `root.plugin`.
119
204
  // The `plugin:name` format breaks skill:// URL parsing (colons are
120
205
  // ambiguous with port separators) and is unintuitive for callers.
121
206
  // Dedup-by-key in the capability layer already handles name collisions
122
207
  // across providers using priority ordering.
123
- items.push(...result.items);
124
- if (result.warnings) warnings.push(...result.warnings);
208
+ for (const result of scanResults) {
209
+ items.push(...result.items);
210
+ if (result.warnings) warnings.push(...result.warnings);
211
+ }
125
212
  }
126
213
  return { items, warnings };
127
214
  }
@@ -139,28 +226,62 @@ async function loadSlashCommands(ctx: LoadContext): Promise<LoadResult<SlashComm
139
226
 
140
227
  const results = await Promise.all(
141
228
  roots.map(async root => {
142
- const { dir: commandsDir, warning } = await resolvePluginDir(root, ["commands", "slash-commands"], "commands");
143
- const commandResult = await loadFilesFromDir<SlashCommand>(ctx, commandsDir, PROVIDER_ID, root.scope, {
144
- extensions: ["md"],
145
- transform: (name, content, filePath, source) => {
146
- const cmdName = name.replace(/\.md$/, "");
147
- return {
148
- name: root.plugin ? `${root.plugin}:${cmdName}` : cmdName,
149
- path: filePath,
150
- content,
151
- level: root.scope,
152
- _source: source,
153
- };
154
- },
155
- });
156
- return { commandResult, warning };
229
+ const { dirs: commandsDirs, warnings: resolveWarnings } = await resolvePluginDir(
230
+ root,
231
+ ["commands", "slash-commands"],
232
+ "commands",
233
+ false,
234
+ );
235
+ const commandResults = await Promise.all(
236
+ commandsDirs.map(async dir => {
237
+ try {
238
+ const stats = await fs.stat(dir);
239
+ if (stats.isFile()) {
240
+ if (path.extname(dir) !== ".md") return { items: [], warnings: [] };
241
+ const content = await readFile(dir);
242
+ if (content === null) return { items: [], warnings: [`Failed to read file: ${dir}`] };
243
+ const cmdName = path.basename(dir).replace(/\.md$/, "");
244
+ return {
245
+ items: [
246
+ {
247
+ name: root.plugin ? `${root.plugin}:${cmdName}` : cmdName,
248
+ path: dir,
249
+ content,
250
+ level: root.scope,
251
+ _source: createSourceMeta(PROVIDER_ID, dir, root.scope),
252
+ },
253
+ ],
254
+ warnings: [],
255
+ };
256
+ }
257
+ } catch {
258
+ // Missing entries behave like missing directories: no items, no warning.
259
+ }
260
+ return loadFilesFromDir<SlashCommand>(ctx, dir, PROVIDER_ID, root.scope, {
261
+ extensions: ["md"],
262
+ transform: (name, content, filePath, source) => {
263
+ const cmdName = name.replace(/\.md$/, "");
264
+ return {
265
+ name: root.plugin ? `${root.plugin}:${cmdName}` : cmdName,
266
+ path: filePath,
267
+ content,
268
+ level: root.scope,
269
+ _source: source,
270
+ };
271
+ },
272
+ });
273
+ }),
274
+ );
275
+ return { commandResults, resolveWarnings };
157
276
  }),
158
277
  );
159
278
 
160
- for (const { commandResult, warning } of results) {
161
- if (warning) warnings.push(warning);
162
- items.push(...commandResult.items);
163
- if (commandResult.warnings) warnings.push(...commandResult.warnings);
279
+ for (const { commandResults, resolveWarnings } of results) {
280
+ warnings.push(...resolveWarnings);
281
+ for (const commandResult of commandResults) {
282
+ items.push(...commandResult.items);
283
+ if (commandResult.warnings) warnings.push(...commandResult.warnings);
284
+ }
164
285
  }
165
286
 
166
287
  return { items, warnings };
@@ -312,6 +312,15 @@ export interface ScanSkillsFromDirOptions {
312
312
  providerId: string;
313
313
  level: "user" | "project";
314
314
  requireDescription?: boolean;
315
+ /**
316
+ * When true, treat a `SKILL.md` sitting directly under `dir` as a single skill in addition to
317
+ * scanning `<dir>/<name>/SKILL.md` children. Matches the Claude plugin manifest convention
318
+ * that lets a skill path point at a directory containing `SKILL.md` directly (e.g.
319
+ * `"skills": ["./"]`), where the frontmatter `name` determines the invocation name and the
320
+ * directory basename is the fallback. Default `false` preserves the strict child-scan
321
+ * semantic every non-Claude provider relies on.
322
+ */
323
+ includeSelf?: boolean;
315
324
  }
316
325
 
317
326
  // Stable ordering used for skill lists in prompts: name (case-insensitive), then name, then path.
@@ -368,7 +377,13 @@ export async function scanSkillsFromDir(
368
377
  }
369
378
  };
370
379
 
371
- const work = [];
380
+ const work: Promise<void>[] = [];
381
+ if (options.includeSelf) {
382
+ const selfSkillPath = path.join(dir, "SKILL.md");
383
+ if (fs.existsSync(selfSkillPath)) {
384
+ work.push(loadSkill(selfSkillPath));
385
+ }
386
+ }
372
387
  for (const entry of entries) {
373
388
  if (entry.name.startsWith(".")) continue;
374
389
  if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
@@ -679,21 +679,35 @@ function wrapEditRendererLine(line: string, width: number): string[] {
679
679
  const startAnsi = line.match(/^((?:\x1b\[[0-9;]*m)*)/)?.[1] ?? "";
680
680
  const bodyWithReset = line.slice(startAnsi.length);
681
681
  const body = bodyWithReset.endsWith("\x1b[39m") ? bodyWithReset.slice(0, -"\x1b[39m".length) : bodyWithReset;
682
- const diffMatch = /^([+\-\s])(\s*\d+)([|│])(.*)$/s.exec(body);
683
-
684
- if (!diffMatch) {
682
+ // Gutter shapes produced by formatCodeFrameLine: "-315│", " 313│", "+322│",
683
+ // plus the deduplicated forms " +│" and " │" whose repeated line number
684
+ // renderDiff blanked (single-line replacement pairs and insert-then-context
685
+ // runs) — all │-separated. ASCII "|" gutters exist only in raw canonical
686
+ // diff rows passed through by the plain fallback ("-42|old", " 42|ctx"),
687
+ // which always carry a marker column ("+"/"-"/space) and a line number. So
688
+ // the number is optional for "│", while "|" requires the full canonical
689
+ // shape; anything else (a body line merely starting with "|", error text
690
+ // like "123|…") is not a diff row and wraps generically.
691
+ const diffMatch = /^(\s*[+-]?\s*\d*)([|│])(.*)$/s.exec(body);
692
+
693
+ if (!diffMatch || diffMatch[1].length === 0 || (diffMatch[2] === "|" && !/^[+\-\s]\s*\d+$/.test(diffMatch[1]))) {
685
694
  return wrapTextWithAnsi(line, width);
686
695
  }
687
696
 
688
- const [, marker, lineNum, separator, content] = diffMatch;
689
- const prefix = `${marker}${lineNum}${separator}`;
697
+ const [, gutter, separator, content] = diffMatch;
698
+ const prefix = `${gutter}${separator}`;
690
699
  const prefixWidth = visibleWidth(prefix);
691
700
  const contentWidth = Math.max(1, width - prefixWidth);
692
701
  const continuationPrefix = `${" ".repeat(Math.max(0, prefixWidth - 1))}${separator}`;
693
702
  const wrappedContent = wrapTextWithAnsi(content ?? "", contentWidth);
694
703
 
704
+ // Each visual row is a standalone terminal line: wrapTextWithAnsi re-opens
705
+ // active SGR state at the next row's start, so a row that breaks inside an
706
+ // intra-line diff highlight still ends with inverse video active. Close it
707
+ // alongside the foreground reset — otherwise the frame padding appended
708
+ // after the row is painted as an inverse block (default-foreground cells).
695
709
  return wrappedContent.map(
696
- (segment, index) => `${startAnsi}${index === 0 ? prefix : continuationPrefix}${segment}\x1b[39m`,
710
+ (segment, index) => `${startAnsi}${index === 0 ? prefix : continuationPrefix}${segment}\x1b[27m\x1b[39m`,
697
711
  );
698
712
  }
699
713
 
@@ -1,6 +1,15 @@
1
+ import { isMainThread } from "node:worker_threads";
2
+ import { postmortem } from "@oh-my-pi/pi-utils";
1
3
  import { ToolError } from "../../tools/tool-errors";
2
4
  import { JsRuntime, type RuntimeHooks } from "./shared/runtime";
3
- import type { RunErrorPayload, SessionSnapshot, ToolReply, Transport, WorkerInbound } from "./worker-protocol";
5
+ import type {
6
+ RunErrorPayload,
7
+ SessionSnapshot,
8
+ ToolReply,
9
+ Transport,
10
+ WorkerInbound,
11
+ WorkerOutbound,
12
+ } from "./worker-protocol";
4
13
 
5
14
  interface PendingTool {
6
15
  runId: string;
@@ -10,9 +19,17 @@ interface PendingTool {
10
19
 
11
20
  interface ActiveRun {
12
21
  runId: string;
22
+ filename: string;
13
23
  pendingTools: Map<string, PendingTool>;
24
+ /** Rejections floated by this run's cell code, captured before its result was sent. */
25
+ floatingRejections: unknown[];
14
26
  }
15
27
 
28
+ type RunResult = Extract<WorkerOutbound, { type: "result" }>;
29
+
30
+ /** Finished-cell filenames retained for attributing rejections that surface after the run settled. */
31
+ const RECENT_CELL_FILES_MAX = 256;
32
+
16
33
  function errorPayload(error: unknown): RunErrorPayload {
17
34
  if (error instanceof Error) {
18
35
  return {
@@ -34,15 +51,134 @@ function errorFromPayload(payload: RunErrorPayload): Error {
34
51
  return error;
35
52
  }
36
53
 
54
+ /**
55
+ * Fold rejections floated by cell code into the run result: an otherwise
56
+ * successful run fails with the first floating rejection (an unawaited promise
57
+ * failing is a cell failure, not a success with noise); the rest surface as
58
+ * output text so nothing is silently dropped.
59
+ */
60
+ function foldFloatingRejections(active: ActiveRun, result: RunResult, hooks: RuntimeHooks): RunResult {
61
+ const rejections = active.floatingRejections;
62
+ if (rejections.length === 0) return result;
63
+ let folded = result;
64
+ let reported = rejections;
65
+ if (result.ok) {
66
+ const error = errorPayload(rejections[0]);
67
+ error.message = `Unhandled rejection (missing await?): ${error.message}`;
68
+ folded = { type: "result", runId: active.runId, ok: false, error };
69
+ reported = rejections.slice(1);
70
+ }
71
+ for (const reason of reported) {
72
+ const payload = errorPayload(reason);
73
+ hooks.onText(`[unhandled rejection] ${payload.name ?? "Error"}: ${payload.message}\n`);
74
+ }
75
+ return folded;
76
+ }
77
+
37
78
  export class WorkerCore {
38
79
  #transport: Transport;
39
80
  #runtime: JsRuntime | null = null;
40
81
  #runs = new Map<string, ActiveRun>();
82
+ #recentCellFiles = new Set<string>();
41
83
  #unsubscribe: () => void;
84
+ #uninstallRejectionGuard: () => void;
42
85
 
43
86
  constructor(transport: Transport) {
44
87
  this.#transport = transport;
45
88
  this.#unsubscribe = transport.onMessage(msg => this.#handle(msg));
89
+ this.#uninstallRejectionGuard = this.#installRejectionGuard();
90
+ }
91
+
92
+ /**
93
+ * Capture unhandled rejections floated by eval-cell code (unawaited async
94
+ * calls) so they fail the owning run instead of tearing down the worker or —
95
+ * via the global postmortem handler — the whole session. On the main thread
96
+ * (inline fallback) only cell-attributable rejections are consumed; in the
97
+ * dedicated worker realm a rejection during a live run is cell activity even
98
+ * without a usable stack, while anything else keeps its default fatality.
99
+ */
100
+ #installRejectionGuard(): () => void {
101
+ if (isMainThread) {
102
+ return postmortem.interceptUnhandledRejections(reason => this.#consumeRejection(reason));
103
+ }
104
+ const onRejection = (reason: unknown): void => {
105
+ if (this.#consumeRejection(reason)) return;
106
+ // Not cell-attributable: restore default fatality. Rethrowing from a
107
+ // timer surfaces it as an uncaught exception, which reaches the host
108
+ // as a worker `error` event exactly like an unhandled rejection did
109
+ // before this listener existed.
110
+ setTimeout(() => {
111
+ throw reason;
112
+ }, 0);
113
+ };
114
+ process.on("unhandledRejection", onRejection);
115
+ return () => {
116
+ process.off("unhandledRejection", onRejection);
117
+ };
118
+ }
119
+
120
+ /**
121
+ * Attribute an unhandled rejection to eval-cell code. Live runs are stashed
122
+ * on the run (folded into its result after the settle drain); finished cells
123
+ * downgrade to a host-side warn log. Returns false when the rejection is not
124
+ * cell activity and must keep the default fatal path.
125
+ */
126
+ #consumeRejection(reason: unknown): boolean {
127
+ const stack = reason instanceof Error && typeof reason.stack === "string" ? reason.stack : undefined;
128
+ if (stack) {
129
+ // The stack can name several cells (helper defined by an earlier cell,
130
+ // called from the live one); the outermost matching frame is the caller
131
+ // that owns the floating promise.
132
+ let owner: ActiveRun | undefined;
133
+ let ownerIndex = -1;
134
+ for (const run of this.#runs.values()) {
135
+ const index = stack.lastIndexOf(run.filename);
136
+ if (index > ownerIndex) {
137
+ ownerIndex = index;
138
+ owner = run;
139
+ }
140
+ }
141
+ if (owner) {
142
+ owner.floatingRejections.push(reason);
143
+ return true;
144
+ }
145
+ let recent: string | undefined;
146
+ let recentIndex = -1;
147
+ for (const filename of this.#recentCellFiles) {
148
+ const index = stack.lastIndexOf(filename);
149
+ if (index > recentIndex) {
150
+ recentIndex = index;
151
+ recent = filename;
152
+ }
153
+ }
154
+ if (recent) {
155
+ this.#transport.send({
156
+ type: "log",
157
+ level: "warn",
158
+ msg: "Unhandled rejection from a finished eval cell (missing await?)",
159
+ meta: { filename: recent, error: errorPayload(reason) },
160
+ });
161
+ return true;
162
+ }
163
+ }
164
+ if (!isMainThread && this.#runs.size > 0) {
165
+ // Dedicated eval worker: during a live run, a rejection without a cell
166
+ // frame (e.g. `Promise.reject("msg")` or a library-created reason) is
167
+ // still cell activity — nothing else runs user code in this realm.
168
+ if (this.#runs.size === 1) {
169
+ const only = this.#runs.values().next().value;
170
+ only?.floatingRejections.push(reason);
171
+ return true;
172
+ }
173
+ this.#transport.send({
174
+ type: "log",
175
+ level: "warn",
176
+ msg: "Unhandled rejection during concurrent eval runs; cannot attribute to a cell",
177
+ meta: { error: errorPayload(reason) },
178
+ });
179
+ return true;
180
+ }
181
+ return false;
46
182
  }
47
183
 
48
184
  #handle(msg: WorkerInbound): void {
@@ -77,23 +213,42 @@ export class WorkerCore {
77
213
  }
78
214
 
79
215
  async #runOne(runId: string, code: string, filename: string, snapshot: SessionSnapshot): Promise<void> {
80
- const runtime = this.#ensureRuntime(snapshot);
81
- runtime.setCwd(snapshot.cwd);
82
- const active: ActiveRun = { runId, pendingTools: new Map() };
216
+ const active: ActiveRun = { runId, filename, pendingTools: new Map(), floatingRejections: [] };
83
217
  this.#runs.set(runId, active);
84
218
  const hooks: RuntimeHooks = {
85
219
  onText: chunk => this.#transport.send({ type: "text", runId, chunk }),
86
220
  onDisplay: output => this.#transport.send({ type: "display", runId, output }),
87
221
  callTool: (name, args) => this.#callTool(active, name, args),
88
222
  };
223
+ let result: RunResult;
89
224
  try {
225
+ const runtime = this.#ensureRuntime(snapshot);
226
+ runtime.setCwd(snapshot.cwd);
90
227
  const value = await runtime.run(code, filename, hooks, { runId, cwd: snapshot.cwd });
91
228
  runtime.displayValue(value, hooks);
92
- this.#transport.send({ type: "result", runId, ok: true });
229
+ result = { type: "result", runId, ok: true };
93
230
  } catch (error) {
94
- this.#transport.send({ type: "result", runId, ok: false, error: errorPayload(error) });
231
+ result = { type: "result", runId, ok: false, error: errorPayload(error) };
232
+ }
233
+ try {
234
+ // One event-loop turn so rejections the cell already floated surface
235
+ // while this run can still own them (rejection callbacks run before
236
+ // timers fire).
237
+ await Bun.sleep(0);
238
+ result = foldFloatingRejections(active, result, hooks);
95
239
  } finally {
96
240
  this.#runs.delete(runId);
241
+ this.#rememberCellFile(filename);
242
+ this.#transport.send(result);
243
+ }
244
+ }
245
+
246
+ #rememberCellFile(filename: string): void {
247
+ this.#recentCellFiles.delete(filename);
248
+ this.#recentCellFiles.add(filename);
249
+ if (this.#recentCellFiles.size > RECENT_CELL_FILES_MAX) {
250
+ const oldest = this.#recentCellFiles.values().next().value;
251
+ if (oldest !== undefined) this.#recentCellFiles.delete(oldest);
97
252
  }
98
253
  }
99
254
 
@@ -127,6 +282,7 @@ export class WorkerCore {
127
282
  this.#runtime?.dispose?.();
128
283
  this.#runtime = null;
129
284
  this.#transport.send({ type: "closed" });
285
+ this.#uninstallRejectionGuard();
130
286
  this.#unsubscribe();
131
287
  this.#transport.close();
132
288
  }
@@ -141,6 +297,7 @@ export class WorkerCore {
141
297
  this.#runs.clear();
142
298
  this.#runtime?.dispose?.();
143
299
  this.#runtime = null;
300
+ this.#uninstallRejectionGuard();
144
301
  this.#unsubscribe();
145
302
  try {
146
303
  this.#transport.close();