@oh-my-pi/pi-coding-agent 15.10.8 → 15.10.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 (52) hide show
  1. package/CHANGELOG.md +41 -1
  2. package/dist/types/config/model-registry.d.ts +13 -0
  3. package/dist/types/config/settings-schema.d.ts +0 -9
  4. package/dist/types/debug/terminal-info.d.ts +0 -1
  5. package/dist/types/extensibility/custom-tools/loader.d.ts +22 -3
  6. package/dist/types/extensibility/extensions/index.d.ts +1 -1
  7. package/dist/types/extensibility/extensions/loader.d.ts +17 -1
  8. package/dist/types/extensibility/plugins/legacy-pi-compat.d.ts +8 -0
  9. package/dist/types/mcp/transports/stdio.d.ts +12 -0
  10. package/dist/types/modes/components/custom-editor.d.ts +3 -2
  11. package/dist/types/modes/components/transcript-container.d.ts +12 -26
  12. package/dist/types/sdk.d.ts +42 -2
  13. package/dist/types/task/discovery.d.ts +1 -2
  14. package/dist/types/task/executor.d.ts +16 -0
  15. package/dist/types/tiny/title-client.d.ts +1 -1
  16. package/dist/types/tools/index.d.ts +17 -0
  17. package/dist/types/tools/todo.d.ts +2 -0
  18. package/dist/types/tui/hyperlink.d.ts +8 -0
  19. package/package.json +9 -9
  20. package/src/cli/list-models.ts +5 -11
  21. package/src/config/model-registry.ts +91 -20
  22. package/src/config/settings-schema.ts +0 -10
  23. package/src/debug/terminal-info.ts +0 -3
  24. package/src/edit/diff.ts +48 -15
  25. package/src/eval/js/shared/rewrite-imports.ts +9 -1
  26. package/src/extensibility/custom-tools/loader.ts +43 -19
  27. package/src/extensibility/extensions/index.ts +1 -0
  28. package/src/extensibility/extensions/loader.ts +29 -6
  29. package/src/extensibility/plugins/legacy-pi-compat.ts +30 -6
  30. package/src/internal-urls/docs-index.generated.ts +4 -4
  31. package/src/mcp/transports/stdio.ts +139 -3
  32. package/src/modes/components/custom-editor.ts +69 -9
  33. package/src/modes/components/model-selector.ts +62 -52
  34. package/src/modes/components/transcript-container.ts +204 -125
  35. package/src/modes/controllers/event-controller.ts +0 -45
  36. package/src/modes/controllers/input-controller.ts +5 -5
  37. package/src/modes/controllers/mcp-command-controller.ts +2 -2
  38. package/src/modes/controllers/selector-controller.ts +0 -4
  39. package/src/modes/interactive-mode.ts +2 -10
  40. package/src/prompts/system/system-prompt.md +3 -3
  41. package/src/prompts/tools/bash.md +3 -3
  42. package/src/prompts/tools/todo.md +5 -1
  43. package/src/sdk.ts +138 -56
  44. package/src/ssh/ssh-executor.ts +60 -4
  45. package/src/task/discovery.ts +17 -24
  46. package/src/task/executor.ts +19 -0
  47. package/src/task/index.ts +4 -0
  48. package/src/tiny/title-client.ts +6 -3
  49. package/src/tools/index.ts +17 -0
  50. package/src/tools/todo.ts +16 -7
  51. package/src/tui/hyperlink.ts +27 -3
  52. package/src/web/search/providers/anthropic.ts +8 -2
@@ -409,7 +409,6 @@ export class InteractiveMode implements InteractiveModeContext {
409
409
  }
410
410
 
411
411
  this.ui = new TUI(new ProcessTerminal(), settings.get("showHardwareCursor"));
412
- this.ui.setClearOnShrink(settings.get("clearOnShrink"));
413
412
  this.ui.setMaxInlineImages(settings.get("tui.maxInlineImages"));
414
413
  // OSC 66 text-sizing is Kitty-only; resolve the setting against the terminal's
415
414
  // capability (`TERMINAL.textSizing` defaults on for Kitty) so it stays off
@@ -429,7 +428,7 @@ export class InteractiveMode implements InteractiveModeContext {
429
428
  this.ui.requestRender(true);
430
429
  };
431
430
  this.editor.onAutocompleteUpdate = () => {
432
- this.ui.requestRender(false, { allowUnknownViewportMutation: true });
431
+ this.ui.requestRender();
433
432
  };
434
433
  this.#syncEditorMaxHeight();
435
434
  this.#resizeHandler = () => {
@@ -959,13 +958,6 @@ export class InteractiveMode implements InteractiveModeContext {
959
958
  }
960
959
  this.editor.setText("");
961
960
  this.editor.imageLinks = undefined;
962
- // Reconciliation checkpoint: only retire frozen block snapshots after TUI
963
- // proves the native viewport is at the tail and replays scrollback safely.
964
- // Unknown host viewports stay frozen; thawing them would expose live rows
965
- // over stale native history and can yank or duplicate when ED3 is unsafe.
966
- if (this.ui.refreshNativeScrollbackIfDirty()) {
967
- this.chatContainer.thaw();
968
- }
969
961
  this.ensureLoadingAnimation();
970
962
  this.ui.requestRender();
971
963
  return submission;
@@ -2587,7 +2579,7 @@ export class InteractiveMode implements InteractiveModeContext {
2587
2579
  this.ui.requestRender(true);
2588
2580
  };
2589
2581
  nextEditor.onAutocompleteUpdate = () => {
2590
- this.ui.requestRender(false, { allowUnknownViewportMutation: true });
2582
+ this.ui.requestRender();
2591
2583
  };
2592
2584
  nextEditor.setMaxHeight(this.#computeEditorMaxHeight());
2593
2585
  if (this.historyStorage) {
@@ -60,10 +60,10 @@ You MUST use the specialized tool over its shell equivalent:
60
60
  {{#has tools "search"}}- regex search → `{{toolRefs.search}}`, not `grep`/`rg`/`awk`{{/has}}
61
61
  {{#has tools "find"}}- file globbing → `{{toolRefs.find}}`, not `ls **/*.ext`/`fd`{{/has}}
62
62
  {{#has tools "eval"}}- Then, you MAY use `{{toolRefs.eval}}` for quick compute, but you SHOULD go step by step.{{/has}}
63
- {{#has tools "bash"}}- Finally, you MAY use `{{toolRefs.bash}}` for simple one-liners only. But this is a last resort. Bash commands matching the patterns above are intercepted and blocked at runtime.
63
+ {{#has tools "bash"}}- Finally, you MAY use `{{toolRefs.bash}}` for terminal work — builds, tests, git, package managers — and for pipelines that COMPUTE a new fact: `wc -l`, `sort | uniq -c`, `comm`, `diff a b`, checksums. Commands shadowing the tools above are intercepted and blocked at runtime.
64
+ - Litmus: produces a count, frequency table, set difference, or checksum no tool returns → bash. Merely moves, pages, or trims bytes a tool can fetch → use the tool.
64
65
  - You NEVER read line ranges with `sed -n 'A,Bp'`, `awk 'NR≥A && NR≤B'`, or `head | tail` pipelines. Use `{{toolRefs.read}}` with `offset`/`limit`.
65
- - You NEVER use `2>&1` or `2>/dev/null` stdout and stderr are already merged.
66
- - You NEVER suffix commands with `| head -n N` or `| tail -n N` — the harness already streams output and returns a truncated view, with the full result available via `artifact://<id>`.
66
+ - You NEVER trim or silence output: no `| head -n N`, `| tail -n N`, `2>&1`, `2>/dev/null`. stderr is already merged; long output is auto-truncated with the full capture kept at `artifact://<id>`. Trimming destroys data the artifact would have saved.
67
67
  - If you catch yourself typing `cat`, `head`, `tail`, `less`, `more`, `ls`, `grep`, `rg`, `find`, `fd`, `sed -i`, `awk -i`, or a heredoc redirect inside a Bash call, stop and switch to the dedicated tool.{{/has}}
68
68
  {{#has tools "report_tool_issue"}}
69
69
  <critical>
@@ -13,9 +13,9 @@ Executes bash command in shell session for terminal operations like git, bun, ca
13
13
  </instruction>
14
14
 
15
15
  <critical>
16
- - NEVER use Linux coreutils (`cat`, `head`, `tail`, `less`, `more`, `ls`, `grep`, `rg`, `awk`, `sed`, `find`, `fd`, etc.) when a dedicated tool suffices ALWAYS prefer `read`, `search`, `find`, `edit`, `write`.
17
- - NEVER pipe through `| head -n N` or `| tail -n N` output is already truncated with the full result available via `artifact://<id>`.
18
- - NEVER redirect with `2>&1` or `2>/dev/null` stdout and stderr are already merged.
16
+ - NEVER use shell to fetch, display, list, page, or search content a dedicated tool serves: `cat`/`head`/`tail`/`less`/`more`/`ls` `read`; `grep`/`rg`/`ag`/`ack` `search`; `find`/`fd` `find`; `sed -i`/`perl -i`/`awk -i` `edit`; `echo >`/heredoc `write`. The tools keep gitignore semantics, line anchors, and structured output that shell loses.
17
+ - NEVER trim or silence output: no `| head -n N`, `| tail -n N`, `| less`, `2>&1`, `2>/dev/null`. stderr is already merged; long output is auto-truncated with the FULL capture kept at `artifact://<id>`. Defensive trimming is a habit from harnesses without artifact recovery — here it only destroys data the artifact would have saved.
18
+ - Pipelines that COMPUTE a new fact are correct bash: `wc -l`, `sort | uniq -c`, `comm`, `cut`, `diff a b`, `shasum`. Litmus: produces a count, frequency table, set difference, or checksum no tool returns → bash. Merely moves or trims bytes a tool can fetch → use the tool.
19
19
  </critical>
20
20
 
21
21
  <output>
@@ -2,7 +2,7 @@
2
2
 
3
3
  Manages a phased task list. Pass `ops`: a flat array of operations.
4
4
  The next pending task is auto-promoted to `in_progress` after each completion.
5
- Allowed `op` values are only `init`, `start`, `done`, `drop`, `rm`, `append`, and `note`. `pending` is a task status, not an `op`; leave not-yet-started tasks implicit in `init`/`append` lists.
5
+ Allowed `op` values are only `init`, `start`, `done`, `drop`, `rm`, `append`, `note`, and `view`. `pending` is a task status, not an `op`; leave not-yet-started tasks implicit in `init`/`append` lists.
6
6
 
7
7
  ## Operations
8
8
 
@@ -15,6 +15,7 @@ Allowed `op` values are only `init`, `start`, `done`, `drop`, `rm`, `append`, an
15
15
  |`rm`|`task` or `phase`|Remove|
16
16
  |`append`|`phase`, `items: string[]`|Append tasks to `phase`; lazily creates phase|
17
17
  |`note`|`task`, `text`|Append a note to a task. Reminders for future-you only.|
18
+ |`view`|—|Read-only: echo the current list without modifying it|
18
19
 
19
20
  ## Anatomy
20
21
  - **Task content**: 5–10 words, what is being done, not how. Used as the task identifier — unique.
@@ -25,6 +26,7 @@ Allowed `op` values are only `init`, `start`, `done`, `drop`, `rm`, `append`, an
25
26
  - Complete phases in order.
26
27
  - On blockers, `append` a new task to the active phase to unblock yourself, or `drop`.
27
28
  - `task` and `phase` fields reference content/name verbatim; keep them stable once introduced.
29
+ - Lost track of exact task text? `view` echoes the full list — NEVER guess content from memory; a mismatched `task` string is an error.
28
30
 
29
31
  ## When to create a list
30
32
  - Task requires 3+ distinct steps
@@ -35,6 +37,8 @@ Allowed `op` values are only `init`, `start`, `done`, `drop`, `rm`, `append`, an
35
37
  <examples>
36
38
  # Initial setup (multi-phase)
37
39
  `{"ops":[{"op":"init","list":[{"phase":"Foundation","items":["Scaffold crate","Wire workspace"]},{"phase":"Auth","items":["Port credential store","Wire OAuth providers"]},{"phase":"Verification","items":["Run cargo test"]}]}]}`
40
+ # View current state (read-only)
41
+ `{"ops":[{"op":"view"}]}`
38
42
  # Initial setup (single phase)
39
43
  `{"ops":[{"op":"init","list":[{"phase":"Implementation","items":["Apply fix","Run tests"]}]}]}`
40
44
  # Complete one task
package/src/sdk.ts CHANGED
@@ -62,10 +62,11 @@ import {
62
62
  type LoadedCustomCommand,
63
63
  loadCustomCommands as loadCustomCommandsInternal,
64
64
  } from "./extensibility/custom-commands";
65
- import { discoverAndLoadCustomTools } from "./extensibility/custom-tools";
65
+ import { discoverCustomToolPaths, loadCustomTools, type ToolPathWithSource } from "./extensibility/custom-tools";
66
66
  import type { CustomTool, CustomToolContext, CustomToolSessionEvent } from "./extensibility/custom-tools/types";
67
67
  import {
68
68
  discoverAndLoadExtensions,
69
+ discoverExtensionPaths,
69
70
  type ExtensionContext,
70
71
  type ExtensionFactory,
71
72
  ExtensionRunner,
@@ -337,10 +338,41 @@ export interface CreateAgentSessionOptions {
337
338
  /** Disable extension discovery (explicit paths still load). */
338
339
  disableExtensionDiscovery?: boolean;
339
340
  /**
340
- * Pre-loaded extensions (skips file discovery).
341
- * @internal Used by CLI when extensions are loaded early to parse custom flags.
341
+ * Pre-loaded extensions (skips file discovery and the per-session factory
342
+ * call). Used by the CLI when extensions are loaded early to parse custom
343
+ * flags — the same process owns the returned instances, so reusing them is
344
+ * safe.
345
+ *
346
+ * NEVER pass this across session boundaries (e.g. parent → subagent).
347
+ * `Extension` instances close over a parent-bound `ExtensionAPI` (cwd,
348
+ * eventBus, runtime), and reusing them would route tools/handlers/commands
349
+ * back through the parent. For subagents, forward
350
+ * {@link preloadedExtensionPaths} instead.
351
+ *
352
+ * @internal
342
353
  */
343
354
  preloadedExtensions?: LoadExtensionsResult;
355
+ /**
356
+ * Pre-discovered extension source paths. When provided, the filesystem-scan
357
+ * inside `discoverExtensionPaths()` is skipped — the session still calls
358
+ * `loadExtensions()` itself so each `Extension` is bound to THIS session's
359
+ * `ExtensionAPI` (cwd, eventBus, runtime).
360
+ *
361
+ * This is the safe pass-through for parent → subagent forwarding.
362
+ */
363
+ preloadedExtensionPaths?: string[];
364
+ /**
365
+ * Pre-discovered custom-tool source paths from `.omp/tools/`, `.claude/tools/`,
366
+ * plugins, etc. When provided, the filesystem-scan inside
367
+ * `discoverCustomToolPaths()` is skipped — subagents inherit the parent's
368
+ * scan result and call `loadCustomTools()` themselves so each session binds
369
+ * tools to its OWN `CustomToolAPI` (cwd, exec, pushPendingAction, UI).
370
+ *
371
+ * Forwarding the loaded `LoadedCustomTool[]` instances directly would reuse
372
+ * the parent's session-bound API and route tool execution back through the
373
+ * parent — wrong for isolated tasks and for pending-action routing.
374
+ */
375
+ preloadedCustomToolPaths?: ToolPathWithSource[];
344
376
 
345
377
  /** Shared event bus for tool/extension communication. Default: creates new bus. */
346
378
  eventBus?: EventBus;
@@ -565,6 +597,26 @@ export async function discoverExtensions(cwd?: string): Promise<LoadExtensionsRe
565
597
  return discoverAndLoadExtensions([], resolvedCwd);
566
598
  }
567
599
 
600
+ /**
601
+ * Path-only counterpart of {@link loadSessionExtensions}: the FS-heavy scan
602
+ * without the per-session module load. Subagents reuse the parent's path list
603
+ * (cached on {@link ToolSession.extensionPaths}) and rebuild Extension
604
+ * instances themselves so each session's `ExtensionAPI` (cwd, eventBus,
605
+ * runtime) is its own.
606
+ */
607
+ export async function discoverSessionExtensionPaths(
608
+ options: Pick<CreateAgentSessionOptions, "disableExtensionDiscovery" | "additionalExtensionPaths">,
609
+ cwd: string,
610
+ settings: Settings,
611
+ ): Promise<string[]> {
612
+ if (options.disableExtensionDiscovery) {
613
+ return options.additionalExtensionPaths ?? [];
614
+ }
615
+ const configuredPaths = [...(options.additionalExtensionPaths ?? []), ...(settings.get("extensions") ?? [])];
616
+ const disabledExtensionIds = settings.get("disabledExtensions") ?? [];
617
+ return discoverExtensionPaths(configuredPaths, cwd, disabledExtensionIds);
618
+ }
619
+
568
620
  /**
569
621
  * Load the discovered/configured extensions for a session — everything {@link
570
622
  * createAgentSession} would load except the inline factory extensions it appends
@@ -580,23 +632,8 @@ export async function loadSessionExtensions(
580
632
  settings: Settings,
581
633
  eventBus: EventBus,
582
634
  ): Promise<LoadExtensionsResult> {
583
- let result: LoadExtensionsResult;
584
- if (options.disableExtensionDiscovery) {
585
- const configuredPaths = options.additionalExtensionPaths ?? [];
586
- result = await logger.time("loadExtensions", loadExtensions, configuredPaths, cwd, eventBus);
587
- } else {
588
- // Merge CLI extension paths with settings extension paths.
589
- const configuredPaths = [...(options.additionalExtensionPaths ?? []), ...(settings.get("extensions") ?? [])];
590
- const disabledExtensionIds = settings.get("disabledExtensions") ?? [];
591
- result = await logger.time(
592
- "discoverAndLoadExtensions",
593
- discoverAndLoadExtensions,
594
- configuredPaths,
595
- cwd,
596
- eventBus,
597
- disabledExtensionIds,
598
- );
599
- }
635
+ const paths = await discoverSessionExtensionPaths(options, cwd, settings);
636
+ const result = await logger.time("loadExtensions", loadExtensions, paths, cwd, eventBus);
600
637
  for (const { path, error } of result.errors) {
601
638
  logger.error("Failed to load extension", { path, error });
602
639
  }
@@ -1193,23 +1230,26 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
1193
1230
  }
1194
1231
 
1195
1232
  // Discover rules and bucket them in one pass to avoid repeated scans over large rule sets.
1196
- const { ttsrManager, rulebookRules, alwaysApplyRules } = await logger.time("discoverTtsrRules", async () => {
1197
- const { TtsrManager } = await import("./export/ttsr");
1198
- const ttsrSettings = settings.getGroup("ttsr");
1199
- const ttsrManager = new TtsrManager(ttsrSettings);
1200
- const rulesResult =
1201
- options.rules !== undefined
1202
- ? { items: options.rules, warnings: undefined }
1203
- : await loadCapability<Rule>(ruleCapability.id, { cwd });
1204
- const { rulebookRules, alwaysApplyRules } = bucketRules(rulesResult.items, ttsrManager, {
1205
- builtinRules: ttsrSettings.builtinRules,
1206
- disabledRules: ttsrSettings.disabledRules,
1207
- });
1208
- if (existingSession.injectedTtsrRules.length > 0) {
1209
- ttsrManager.restoreInjected(existingSession.injectedTtsrRules);
1210
- }
1211
- return { ttsrManager, rulebookRules, alwaysApplyRules };
1212
- });
1233
+ const { ttsrManager, rulebookRules, alwaysApplyRules, allRules } = await logger.time(
1234
+ "discoverTtsrRules",
1235
+ async () => {
1236
+ const { TtsrManager } = await import("./export/ttsr");
1237
+ const ttsrSettings = settings.getGroup("ttsr");
1238
+ const ttsrManager = new TtsrManager(ttsrSettings);
1239
+ const rulesResult =
1240
+ options.rules !== undefined
1241
+ ? { items: options.rules, warnings: undefined }
1242
+ : await loadCapability<Rule>(ruleCapability.id, { cwd });
1243
+ const { rulebookRules, alwaysApplyRules } = bucketRules(rulesResult.items, ttsrManager, {
1244
+ builtinRules: ttsrSettings.builtinRules,
1245
+ disabledRules: ttsrSettings.disabledRules,
1246
+ });
1247
+ if (existingSession.injectedTtsrRules.length > 0) {
1248
+ ttsrManager.restoreInjected(existingSession.injectedTtsrRules);
1249
+ }
1250
+ return { ttsrManager, rulebookRules, alwaysApplyRules, allRules: rulesResult.items };
1251
+ },
1252
+ );
1213
1253
 
1214
1254
  // Resolve contextFiles up-front (it's needed before tool creation). The
1215
1255
  // workspace tree scan is slow on large repos and we MUST NOT block startup on
@@ -1331,6 +1371,7 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
1331
1371
  contextFiles,
1332
1372
  workspaceTree: resolvedWorkspaceTree,
1333
1373
  skills,
1374
+ rules: allRules,
1334
1375
  eventBus,
1335
1376
  outputSchema: options.outputSchema,
1336
1377
  requireYieldTool: options.requireYieldTool,
@@ -1514,22 +1555,29 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
1514
1555
  customTools.push(...getSearchTools());
1515
1556
  }
1516
1557
 
1517
- // Discover and load custom tools from .omp/tools/, .claude/tools/, etc.
1558
+ // Discover custom tools from `.omp/tools/`, `.claude/tools/`, plugins, etc.
1559
+ // Subagents reuse the parent's scan via `preloadedCustomToolPaths` to skip
1560
+ // the FS walk, but ALWAYS re-call `loadCustomTools` here so factories bind
1561
+ // to THIS session's `CustomToolAPI` (cwd, exec, pushPendingAction, UI).
1562
+ // Forwarding the parent's `LoadedCustomTool[]` directly would route tool
1563
+ // execution back through the parent — wrong for isolated tasks and for
1564
+ // pending-action queueing.
1518
1565
  const builtInToolNames = builtinTools.map(t => t.name);
1519
- const discoveredCustomTools = await logger.time(
1520
- "discoverAndLoadCustomTools",
1521
- discoverAndLoadCustomTools,
1522
- [],
1523
- cwd,
1524
- builtInToolNames,
1525
- action => queueResolveHandler(toolSession, action),
1566
+ const customToolPaths: ToolPathWithSource[] =
1567
+ options.preloadedCustomToolPaths ??
1568
+ (await logger.time("discoverCustomToolPaths", () => discoverCustomToolPaths([], cwd)));
1569
+ const customToolsLoadResult = await logger.time("loadCustomTools", () =>
1570
+ loadCustomTools(customToolPaths, cwd, builtInToolNames, action => queueResolveHandler(toolSession, action)),
1526
1571
  );
1527
- for (const { path, error } of discoveredCustomTools.errors) {
1572
+ for (const { path, error } of customToolsLoadResult.errors) {
1528
1573
  logger.error("Custom tool load failed", { path, error });
1529
1574
  }
1530
- if (discoveredCustomTools.tools.length > 0) {
1531
- customTools.push(...discoveredCustomTools.tools.map(loaded => loaded.tool));
1575
+ if (customToolsLoadResult.tools.length > 0) {
1576
+ customTools.push(...customToolsLoadResult.tools.map(loaded => loaded.tool));
1532
1577
  }
1578
+ // Forward the path list (NOT the loaded tools) to subagents so they
1579
+ // re-bind under their own `CustomToolAPI` while skipping the FS scan.
1580
+ toolSession.customToolPaths = customToolPaths;
1533
1581
 
1534
1582
  const inlineExtensions: ExtensionFactory[] = options.extensions ? [...options.extensions] : [];
1535
1583
  inlineExtensions.push((await import("./autoresearch")).createAutoresearchExtension);
@@ -1537,14 +1585,48 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
1537
1585
  inlineExtensions.push(createCustomToolsExtension(customTools));
1538
1586
  }
1539
1587
 
1540
- // Load extensions. A preloaded result (e.g. resolved by the CLI before
1541
- // session creation so it can classify `@file` args extension-aware without
1542
- // a session/breadcrumb existing yet) is reused as-is; otherwise discover now
1543
- // through the shared helper. Preloaded wins over `disableExtensionDiscovery`
1544
- // because the preloaded result already reflects that choice — re-running the
1545
- // loader here would double-load.
1546
- const extensionsResult: LoadExtensionsResult =
1547
- options.preloadedExtensions ?? (await loadSessionExtensions(options, cwd, settings, eventBus));
1588
+ // Load extensions. Three paths:
1589
+ // 1. `preloadedExtensions` (CLI): caller already loaded reuse the
1590
+ // Extension instances. Shallow-clone `extensions` so the inline
1591
+ // push below cannot mutate the caller's array. `runtime` is shared
1592
+ // so flag values set pre-creation flow into the live session.
1593
+ // 2. `preloadedExtensionPaths` (subagent): caller resolved paths;
1594
+ // skip the FS scan but always re-call `loadExtensions` here so
1595
+ // each `Extension` binds to THIS session's `ExtensionAPI`
1596
+ // (cwd, eventBus, runtime).
1597
+ // 3. No preload: run the full session discovery.
1598
+ // `disableExtensionDiscovery` is honored implicitly: a caller that set
1599
+ // the flag and pre-resolved the result already reflects that choice.
1600
+ let extensionPaths: string[];
1601
+ let extensionsResult: LoadExtensionsResult;
1602
+ if (options.preloadedExtensions) {
1603
+ extensionsResult = {
1604
+ ...options.preloadedExtensions,
1605
+ extensions: [...options.preloadedExtensions.extensions],
1606
+ };
1607
+ // Capture paths for downstream forwarding; filter inline-factory
1608
+ // entries (`<inline-N>`) — those are per-session, not source paths.
1609
+ extensionPaths = extensionsResult.extensions
1610
+ .map(ext => ext.resolvedPath)
1611
+ .filter(p => !p.startsWith("<inline"));
1612
+ } else if (options.preloadedExtensionPaths) {
1613
+ extensionPaths = options.preloadedExtensionPaths;
1614
+ extensionsResult = await logger.time("loadExtensions", loadExtensions, extensionPaths, cwd, eventBus);
1615
+ for (const { path, error } of extensionsResult.errors) {
1616
+ logger.error("Failed to load extension", { path, error });
1617
+ }
1618
+ } else {
1619
+ extensionPaths = await logger.time("discoverSessionExtensionPaths", () =>
1620
+ discoverSessionExtensionPaths(options, cwd, settings),
1621
+ );
1622
+ extensionsResult = await logger.time("loadExtensions", loadExtensions, extensionPaths, cwd, eventBus);
1623
+ for (const { path, error } of extensionsResult.errors) {
1624
+ logger.error("Failed to load extension", { path, error });
1625
+ }
1626
+ }
1627
+ // Forward the source-path list (NOT the loaded instances) so subagents
1628
+ // rebuild their own session-scoped extensions.
1629
+ toolSession.extensionPaths = extensionPaths;
1548
1630
 
1549
1631
  // Load inline extensions from factories
1550
1632
  if (inlineExtensions.length > 0) {
@@ -42,6 +42,42 @@ export interface SSHResult {
42
42
  artifactId?: string;
43
43
  }
44
44
 
45
+ type SSHExitEvent = { kind: "exit"; exitCode: number } | { kind: "error"; error: unknown };
46
+
47
+ function sshExitEvent(exitCode: number): SSHExitEvent {
48
+ return { kind: "exit", exitCode };
49
+ }
50
+
51
+ function sshErrorEvent(error: unknown): SSHExitEvent {
52
+ return { kind: "error", error };
53
+ }
54
+
55
+ function createAbortWaiter(
56
+ signal: AbortSignal | undefined,
57
+ streamAbort: AbortController,
58
+ ): { promise: Promise<ptree.AbortError> | undefined; cleanup: () => void } {
59
+ if (!signal) {
60
+ return { promise: undefined, cleanup: () => {} };
61
+ }
62
+
63
+ const { promise, resolve } = Promise.withResolvers<ptree.AbortError>();
64
+ const onAbort = () => {
65
+ const error = new ptree.AbortError(signal.reason, "<cancelled>");
66
+ if (!streamAbort.signal.aborted) {
67
+ streamAbort.abort(error);
68
+ }
69
+ resolve(error);
70
+ };
71
+
72
+ if (signal.aborted) {
73
+ onAbort();
74
+ return { promise, cleanup: () => {} };
75
+ }
76
+
77
+ signal.addEventListener("abort", onAbort, { once: true });
78
+ return { promise, cleanup: () => signal.removeEventListener("abort", onAbort) };
79
+ }
80
+
45
81
  function quoteForCompatShell(command: string): string {
46
82
  if (command.length === 0) {
47
83
  return "''";
@@ -94,19 +130,37 @@ export async function executeSSH(
94
130
  maxColumns: resolveOutputMaxColumns(settings),
95
131
  });
96
132
 
97
- const streams = [child.stdout.pipeTo(sink.createInput())];
133
+ const streamAbort = new AbortController();
134
+ const abortWaiter = createAbortWaiter(options?.signal, streamAbort);
135
+ const streamOptions = { signal: streamAbort.signal };
136
+ const streams = [child.stdout.pipeTo(sink.createInput(), streamOptions)];
98
137
  if (child.stderr) {
99
- streams.push(child.stderr.pipeTo(sink.createInput()));
138
+ streams.push(child.stderr.pipeTo(sink.createInput(), streamOptions));
100
139
  }
101
- await Promise.allSettled(streams).catch(() => {});
140
+ const streamsSettled = Promise.allSettled(streams).then(() => {});
102
141
 
103
142
  try {
143
+ const exitEvent = child.exited.then(sshExitEvent, sshErrorEvent);
144
+ const abortEvent = abortWaiter.promise?.then(sshErrorEvent);
145
+ const event = await (abortEvent ? Promise.race([exitEvent, abortEvent]) : exitEvent);
146
+ if (event.kind === "error") {
147
+ throw event.error;
148
+ }
149
+
150
+ const streamEvent = await (abortEvent ? Promise.race([streamsSettled, abortEvent]) : streamsSettled);
151
+ if (streamEvent?.kind === "error") {
152
+ throw streamEvent.error;
153
+ }
104
154
  return {
105
- exitCode: await child.exited,
155
+ exitCode: event.exitCode,
106
156
  cancelled: false,
107
157
  ...(await sink.dump()),
108
158
  };
109
159
  } catch (err) {
160
+ if (!streamAbort.signal.aborted) {
161
+ streamAbort.abort(err);
162
+ }
163
+ void streamsSettled;
110
164
  if (err instanceof ptree.Exception) {
111
165
  if (err instanceof ptree.TimeoutError) {
112
166
  return {
@@ -129,5 +183,7 @@ export async function executeSSH(
129
183
  };
130
184
  }
131
185
  throw err;
186
+ } finally {
187
+ abortWaiter.cleanup();
132
188
  }
133
189
  }
@@ -1,13 +1,14 @@
1
1
  /**
2
2
  * Agent discovery from filesystem.
3
3
  *
4
- * Discovers agent definitions from:
5
- * - ~/.omp/agent/agents/*.md (user-level, primary)
6
- * - ~/.pi/agent/agents/*.md (user-level, legacy)
7
- * - ~/.claude/agents/*.md (user-level, legacy)
8
- * - .omp/agents/*.md (project-level, primary)
9
- * - .pi/agents/*.md (project-level, legacy)
10
- * - .claude/agents/*.md (project-level, legacy)
4
+ * Discovers agent definitions from OMP-native task-agent roots:
5
+ * - ~/.omp/agent/agents/*.md (user-level)
6
+ * - .omp/agents/*.md (project-level)
7
+ *
8
+ * Claude Code marketplace plugin agents are discovered separately via the
9
+ * claude-plugins provider. Direct cross-harness roots such as .claude/agents
10
+ * are intentionally skipped because their frontmatter schema is not the OMP
11
+ * task-agent contract.
11
12
  *
12
13
  * Agent files use markdown with YAML frontmatter.
13
14
  */
@@ -21,6 +22,8 @@ import { listClaudePluginRoots } from "../discovery/helpers";
21
22
  import { loadBundledAgents, parseAgent } from "./agents";
22
23
  import type { AgentDefinition, AgentSource } from "./types";
23
24
 
25
+ const TASK_AGENT_CONFIG_SOURCE = ".omp";
26
+
24
27
  /** Result of agent discovery */
25
28
  export interface DiscoveryResult {
26
29
  agents: AgentDefinition[];
@@ -52,41 +55,31 @@ async function loadAgentsFromDir(dir: string, source: AgentSource): Promise<Agen
52
55
  /**
53
56
  * Discover agents from filesystem and merge with bundled agents.
54
57
  *
55
- * Precedence (highest wins): .omp > .pi > .claude (project before user), then bundled
56
- *
58
+ * Precedence (highest wins): project .omp, user .omp, Claude plugin agents, then bundled
57
59
  * @param cwd - Current working directory for project agent discovery
58
60
  */
59
61
  export async function discoverAgents(cwd: string, home: string = os.homedir()): Promise<DiscoveryResult> {
60
62
  const resolvedCwd = path.resolve(cwd);
61
- const agentSources = Array.from(new Set(getConfigDirs("", { project: false }).map(entry => entry.source)));
62
63
 
63
- // Get user directories (priority order: .omp, .pi, .claude, ...)
64
64
  const userDirs = getConfigDirs("agents", { project: false })
65
- .filter(entry => agentSources.includes(entry.source))
65
+ .filter(entry => entry.source === TASK_AGENT_CONFIG_SOURCE)
66
66
  .map(entry => ({
67
67
  ...entry,
68
68
  path: path.resolve(entry.path),
69
69
  }));
70
70
 
71
- // Get project directories by walking up from cwd (priority order)
72
71
  const projectDirs = findAllNearestProjectConfigDirs("agents", resolvedCwd)
73
- .filter(entry => agentSources.includes(entry.source))
72
+ .filter(entry => entry.source === TASK_AGENT_CONFIG_SOURCE)
74
73
  .map(entry => ({
75
74
  ...entry,
76
75
  path: path.resolve(entry.path),
77
76
  }));
78
77
 
79
- const orderedSources = agentSources.filter(
80
- source => userDirs.some(entry => entry.source === source) || projectDirs.some(entry => entry.source === source),
81
- );
82
-
83
78
  const orderedDirs: Array<{ dir: string; source: AgentSource }> = [];
84
- for (const source of orderedSources) {
85
- const project = projectDirs.find(entry => entry.source === source);
86
- if (project) orderedDirs.push({ dir: project.path, source: "project" });
87
- const user = userDirs.find(entry => entry.source === source);
88
- if (user) orderedDirs.push({ dir: user.path, source: "user" });
89
- }
79
+ const project = projectDirs[0];
80
+ if (project) orderedDirs.push({ dir: project.path, source: "project" });
81
+ const user = userDirs[0];
82
+ if (user) orderedDirs.push({ dir: user.path, source: "user" });
90
83
 
91
84
  // Load agents from Claude Code marketplace plugins (respects disabledProviders)
92
85
  const { roots: pluginRoots } = isProviderEnabled("claude-plugins")
@@ -8,11 +8,13 @@ import path from "node:path";
8
8
  import type { AgentEvent, AgentIdentity, AgentTelemetryConfig, ThinkingLevel } from "@oh-my-pi/pi-agent-core";
9
9
  import { recordHandoff, resolveTelemetry } from "@oh-my-pi/pi-agent-core";
10
10
  import { logger, prompt, untilAborted } from "@oh-my-pi/pi-utils";
11
+ import type { Rule } from "../capability/rule";
11
12
  import { ModelRegistry } from "../config/model-registry";
12
13
  import { resolveModelOverrideWithAuthFallback } from "../config/model-resolver";
13
14
  import type { PromptTemplate } from "../config/prompt-templates";
14
15
  import { Settings } from "../config/settings";
15
16
  import { SETTINGS_SCHEMA, type SettingPath } from "../config/settings-schema";
17
+ import type { ToolPathWithSource } from "../extensibility/custom-tools";
16
18
  import type { CustomTool } from "../extensibility/custom-tools/types";
17
19
  import { runExtensionCompact, runExtensionSetModel } from "../extensibility/extensions/compact-handler";
18
20
  import { getSessionSlashCommands } from "../extensibility/extensions/get-commands-handler";
@@ -190,6 +192,20 @@ export interface ExecutorOptions {
190
192
  skills?: Skill[];
191
193
  promptTemplates?: PromptTemplate[];
192
194
  workspaceTree?: WorkspaceTree;
195
+ /** Parent-discovered rules, forwarded to skip rule discovery in the subagent. */
196
+ rules?: Rule[];
197
+ /**
198
+ * Parent's discovered extension source paths. Forwarded to skip the
199
+ * extension FS scan in the subagent; the subagent then re-binds each
200
+ * extension against its own `ExtensionAPI` (cwd, eventBus, runtime).
201
+ */
202
+ preloadedExtensionPaths?: string[];
203
+ /**
204
+ * Parent's discovered custom-tool source paths. Forwarded to skip the
205
+ * `.omp/tools/` FS scan in the subagent; the subagent then re-binds each
206
+ * tool against its own `CustomToolAPI` (cwd, exec, pushPendingAction, UI).
207
+ */
208
+ preloadedCustomToolPaths?: ToolPathWithSource[];
193
209
  mcpManager?: MCPManager;
194
210
  authStorage?: AuthStorage;
195
211
  modelRegistry?: ModelRegistry;
@@ -1284,6 +1300,9 @@ export async function runSubprocess(options: ExecutorOptions): Promise<SingleRes
1284
1300
  skills: options.skills,
1285
1301
  promptTemplates: options.promptTemplates,
1286
1302
  workspaceTree: options.workspaceTree,
1303
+ rules: options.rules,
1304
+ preloadedExtensionPaths: options.preloadedExtensionPaths,
1305
+ preloadedCustomToolPaths: options.preloadedCustomToolPaths,
1287
1306
  systemPrompt: defaultPrompt => {
1288
1307
  const subagentPrompt = prompt.render(subagentSystemPromptTemplate, {
1289
1308
  agent: agent.systemPrompt,
package/src/task/index.ts CHANGED
@@ -990,6 +990,9 @@ export class TaskTool implements AgentTool<TaskToolSchemaInstance, TaskToolDetai
990
990
  autoloadSkills: resolvedAutoloadSkills,
991
991
  workspaceTree: this.session.workspaceTree,
992
992
  promptTemplates,
993
+ rules: this.session.rules,
994
+ preloadedExtensionPaths: this.session.extensionPaths,
995
+ preloadedCustomToolPaths: this.session.customToolPaths,
993
996
  localProtocolOptions,
994
997
  parentArtifactManager,
995
998
  parentHindsightSessionState: this.session.getHindsightSessionState?.(),
@@ -1048,6 +1051,7 @@ export class TaskTool implements AgentTool<TaskToolSchemaInstance, TaskToolDetai
1048
1051
  autoloadSkills: resolvedAutoloadSkills,
1049
1052
  workspaceTree: this.session.workspaceTree,
1050
1053
  promptTemplates,
1054
+ rules: this.session.rules,
1051
1055
  localProtocolOptions,
1052
1056
  parentArtifactManager,
1053
1057
  parentHindsightSessionState: this.session.getHindsightSessionState?.(),
@@ -122,7 +122,7 @@ function tinyWorkerSpawnCmd(): string[] {
122
122
  }
123
123
 
124
124
  interface SpawnedSubprocess {
125
- proc: Subprocess<"ignore", "inherit", "inherit">;
125
+ proc: Subprocess<"ignore", "ignore", "ignore">;
126
126
  inbound: Set<(message: TinyTitleWorkerOutbound) => void>;
127
127
  errors: Set<(error: Error) => void>;
128
128
  /**
@@ -147,10 +147,13 @@ export function createTinyTitleSubprocess(): SpawnedSubprocess {
147
147
  cmd: tinyWorkerSpawnCmd(),
148
148
  env: tinyWorkerEnv(),
149
149
  stdin: "ignore",
150
- stdout: "inherit",
151
- stderr: "inherit",
150
+ stdout: "ignore",
151
+ stderr: "ignore",
152
152
  serialization: "advanced",
153
153
  windowsHide: true,
154
+ // The worker is an implementation detail of the interactive TUI. Native
155
+ // model runtimes may print progress or decoded text directly; never let
156
+ // those bytes inherit the terminal and corrupt the chat scrollback.
154
157
  ipc(message) {
155
158
  for (const handler of inbound) handler(message as TinyTitleWorkerOutbound);
156
159
  },