@tintinweb/pi-subagents 0.7.3 → 0.9.0

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 (43) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +22 -1
  3. package/dist/agent-manager.d.ts +2 -2
  4. package/dist/agent-runner.d.ts +3 -3
  5. package/dist/agent-runner.js +1 -1
  6. package/dist/context.d.ts +1 -1
  7. package/dist/custom-agents.js +1 -1
  8. package/dist/default-agents.js +3 -3
  9. package/dist/enabled-models.d.ts +49 -0
  10. package/dist/enabled-models.js +145 -0
  11. package/dist/env.d.ts +1 -1
  12. package/dist/index.d.ts +1 -1
  13. package/dist/index.js +215 -84
  14. package/dist/output-file.d.ts +1 -1
  15. package/dist/schedule-store.d.ts +2 -0
  16. package/dist/schedule-store.js +12 -1
  17. package/dist/schedule.d.ts +1 -1
  18. package/dist/settings.d.ts +23 -0
  19. package/dist/settings.js +6 -1
  20. package/dist/skill-loader.js +1 -1
  21. package/dist/types.d.ts +2 -2
  22. package/dist/ui/agent-widget.js +1 -1
  23. package/dist/ui/conversation-viewer.d.ts +2 -2
  24. package/dist/ui/conversation-viewer.js +1 -1
  25. package/dist/ui/schedule-menu.d.ts +1 -1
  26. package/package.json +4 -4
  27. package/src/agent-manager.ts +2 -2
  28. package/src/agent-runner.ts +3 -3
  29. package/src/context.ts +1 -1
  30. package/src/custom-agents.ts +1 -1
  31. package/src/default-agents.ts +3 -3
  32. package/src/enabled-models.ts +180 -0
  33. package/src/env.ts +1 -1
  34. package/src/index.ts +238 -85
  35. package/src/output-file.ts +1 -1
  36. package/src/schedule-store.ts +11 -1
  37. package/src/schedule.ts +1 -1
  38. package/src/settings.ts +28 -1
  39. package/src/skill-loader.ts +1 -1
  40. package/src/types.ts +2 -2
  41. package/src/ui/agent-widget.ts +1 -1
  42. package/src/ui/conversation-viewer.ts +2 -2
  43. package/src/ui/schedule-menu.ts +1 -1
package/dist/index.js CHANGED
@@ -11,14 +11,15 @@
11
11
  */
12
12
  import { existsSync, mkdirSync, readFileSync, unlinkSync } from "node:fs";
13
13
  import { join } from "node:path";
14
- import { defineTool, getAgentDir } from "@mariozechner/pi-coding-agent";
15
- import { Text } from "@mariozechner/pi-tui";
14
+ import { defineTool, getAgentDir, getSettingsListTheme } from "@earendil-works/pi-coding-agent";
15
+ import { Container, Key, matchesKey, SettingsList, Spacer, Text } from "@earendil-works/pi-tui";
16
16
  import { Type } from "@sinclair/typebox";
17
17
  import { AgentManager } from "./agent-manager.js";
18
18
  import { getAgentConversation, getDefaultMaxTurns, getGraceTurns, normalizeMaxTurns, setDefaultMaxTurns, setGraceTurns, steerAgent } from "./agent-runner.js";
19
19
  import { BUILTIN_TOOL_NAMES, getAgentConfig, getAllTypes, getAvailableTypes, getDefaultAgentNames, getUserAgentNames, registerAgents, resolveType } from "./agent-types.js";
20
20
  import { registerRpcHandlers } from "./cross-extension-rpc.js";
21
21
  import { loadCustomAgents } from "./custom-agents.js";
22
+ import { isModelInScope, readEnabledModels, resolveEnabledModels } from "./enabled-models.js";
22
23
  import { GroupJoinManager } from "./group-join.js";
23
24
  import { resolveAgentInvocationConfig, resolveJoinMode } from "./invocation-config.js";
24
25
  import { resolveModel } from "./model-resolver.js";
@@ -459,6 +460,16 @@ export default function (pi) {
459
460
  let schedulingEnabled = true;
460
461
  function isSchedulingEnabled() { return schedulingEnabled; }
461
462
  function setSchedulingEnabled(b) { schedulingEnabled = b; }
463
+ // ---- Scope models configuration ----
464
+ // When enabled, subagent model choices are validated against `enabledModels`
465
+ // from pi's settings — both global `<agentDir>/settings.json` and
466
+ // project-local `<cwd>/.pi/settings.json` (project overrides global).
467
+ // Off by default; opt-in via `/agents → Settings`. See docstring on
468
+ // SubagentsSettings.scopeModels for the hard-error vs warn-and-proceed
469
+ // policy and its rationale.
470
+ let scopeModelsEnabled = false;
471
+ function isScopeModelsEnabled() { return scopeModelsEnabled; }
472
+ function setScopeModelsEnabled(enabled) { scopeModelsEnabled = enabled; }
462
473
  // ---- Batch tracking for smart join mode ----
463
474
  // Collects background agent IDs spawned in the current turn for smart grouping.
464
475
  // Uses a debounced timer: each new agent resets the 100ms window so that all
@@ -506,26 +517,24 @@ export default function (pi) {
506
517
  widget.setUICtx(ctx.ui);
507
518
  widget.onTurnStart();
508
519
  });
520
+ /** Format an agent's tool scope: "*" when it has all built-ins, else a comma-separated list. */
521
+ const formatToolsSuffix = (cfg) => {
522
+ const tools = cfg?.builtinToolNames;
523
+ if (!tools || tools.length === 0)
524
+ return "*";
525
+ const isFullSet = tools.length === BUILTIN_TOOL_NAMES.length
526
+ && BUILTIN_TOOL_NAMES.every((t) => tools.includes(t));
527
+ return isFullSet ? "*" : tools.join(", ");
528
+ };
509
529
  /** Build the full type list text dynamically from the unified registry. */
510
530
  const buildTypeListText = () => {
511
- const defaultNames = getDefaultAgentNames();
512
- const userNames = getUserAgentNames();
513
- const defaultDescs = defaultNames.map((name) => {
531
+ const allNames = [...getDefaultAgentNames(), ...getUserAgentNames()];
532
+ return allNames.map((name) => {
514
533
  const cfg = getAgentConfig(name);
515
534
  const modelSuffix = cfg?.model ? ` (${getModelLabelFromConfig(cfg.model)})` : "";
516
- return `- ${name}: ${cfg?.description ?? name}${modelSuffix}`;
517
- });
518
- const customDescs = userNames.map((name) => {
519
- const cfg = getAgentConfig(name);
520
- return `- ${name}: ${cfg?.description ?? name}`;
521
- });
522
- return [
523
- "Default agents:",
524
- ...defaultDescs,
525
- ...(customDescs.length > 0 ? ["", "Custom agents:", ...customDescs] : []),
526
- "",
527
- `Custom agents can be defined in .pi/agents/<name>.md (project) or ${getAgentDir()}/agents/<name>.md (global) — they are picked up automatically. Project-level agents override global ones. Creating a .md file with the same name as a default agent overrides it.`,
528
- ].join("\n");
535
+ const toolsSuffix = ` (Tools: ${formatToolsSuffix(cfg)})`;
536
+ return `- ${name}: ${cfg?.description ?? name}${modelSuffix}${toolsSuffix}`;
537
+ }).join("\n");
529
538
  };
530
539
  /** Derive a short model label from a model string. */
531
540
  function getModelLabelFromConfig(model) {
@@ -544,6 +553,7 @@ export default function (pi) {
544
553
  setGraceTurns,
545
554
  setDefaultJoinMode,
546
555
  setSchedulingEnabled,
556
+ setScopeModels: setScopeModelsEnabled,
547
557
  }, (event, payload) => pi.events.emit(event, payload));
548
558
  // ---- Agent tool ----
549
559
  // Schedule param + its guideline are gated on `schedulingEnabled` (read once
@@ -565,27 +575,48 @@ export default function (pi) {
565
575
  pi.registerTool(defineTool({
566
576
  name: "Agent",
567
577
  label: "Agent",
568
- description: `Launch a new agent to handle complex, multi-step tasks autonomously.
569
-
570
- The Agent tool launches specialized agents that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
578
+ description: `Launch a new agent to handle complex, multi-step tasks autonomously. Each agent type has specific capabilities and tools available to it.
571
579
 
572
- Available agent types:
580
+ Available agent types and the tools they have access to:
573
581
  ${typeListText}
574
582
 
575
- Guidelines:
576
- - For parallel work, use run_in_background: true on each agent. Foreground calls run sequentially — only one executes at a time.
577
- - Use Explore for codebase searches and code understanding.
578
- - Use Plan for architecture and implementation planning.
579
- - Use general-purpose for complex tasks that need file editing.
580
- - Provide clear, detailed prompts so the agent can work autonomously.
581
- - Agent results are returned as textsummarize them for the user.
582
- - Use run_in_background for work you don't need immediately. You will be notified when it completes.
583
- - Use resume with an agent ID to continue a previous agent's work.
583
+ Custom agents can be defined in .pi/agents/<name>.md (project) or ${getAgentDir()}/agents/<name>.md (global) — they are picked up automatically. Project-level agents override global ones. Creating a .md file with the same name as a default agent overrides it.
584
+
585
+ When using the Agent tool, specify a subagent_type parameter to select which agent type to use.
586
+
587
+ ## When not to use
588
+
589
+ If the target is already known, use a direct tool \`read\` for a known path, \`grep\`/\`find\` for a specific symbol or string. Reserve this tool for open-ended questions that span the codebase, or tasks that match an available agent type.
590
+
591
+ ## Usage notes
592
+
593
+ - Always include a short (3-5 word) description summarizing what the agent will do (shown in UI).
594
+ - When you launch multiple agents for independent work, send them in a single message with multiple tool uses, with run_in_background: true on each, so they run concurrently. If the user specifies that they want agents run "in parallel", you MUST send a single message with multiple tool calls. Foreground calls run sequentially — only one executes at a time.
595
+ - When the agent is done, it returns a single message back to you. The result is not visible to the user — to show the user, send a text message with a concise summary.
596
+ - Trust but verify: an agent's summary describes what it intended to do, not necessarily what it did. When an agent writes or edits code, check the actual changes before reporting work as done.
597
+ - Use run_in_background for work you don't need immediately. You will be notified when it completes — do NOT poll or sleep waiting for it. Continue with other work or respond to the user instead.
598
+ - Foreground vs background: use foreground (default) when you need the agent's results before you can proceed. Use background when you have genuinely independent work to do in parallel.
599
+ - Use resume with an agent ID to continue a previous agent's work. A new (non-resume) Agent call starts a fresh agent with no memory of prior runs, so the prompt must be self-contained.
584
600
  - Use steer_subagent to send mid-run messages to a running background agent.
601
+ - Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, etc.), since it is not aware of the user's intent.
602
+ - If an agent's description says it should be used proactively, try to use it without the user having to ask for it first.
585
603
  - Use model to specify a different model (as "provider/modelId", or fuzzy e.g. "haiku", "sonnet").
586
604
  - Use thinking to control extended thinking level.
587
605
  - Use inherit_context if the agent needs the parent conversation history.
588
- - Use isolation: "worktree" to run the agent in an isolated git worktree (safe parallel file modifications).${scheduleGuideline}`,
606
+ - Use isolation: "worktree" to run the agent in an isolated git worktree (safe parallel file modifications). The worktree is automatically cleaned up if the agent makes no changes; otherwise the path and branch are returned in the result.${scheduleGuideline}
607
+
608
+ ## Writing the prompt
609
+
610
+ Provide clear, detailed prompts so the agent can work autonomously. Brief it like a smart colleague who just walked into the room — it hasn't seen this conversation, doesn't know what you've tried, doesn't understand why this task matters.
611
+ - Explain what you're trying to accomplish and why.
612
+ - Describe what you've already learned or ruled out.
613
+ - Give enough context about the surrounding problem that the agent can make judgment calls rather than just following a narrow instruction.
614
+ - If you need a short response, say so ("report in under 200 words").
615
+ - Lookups: hand over the exact command. Investigations: hand over the question — prescribed steps become dead weight when the premise is wrong.
616
+
617
+ Terse command-style prompts produce shallow, generic work.
618
+
619
+ **Never delegate understanding.** Don't write "based on your findings, fix the bug" or "based on the research, implement it." Those phrases push synthesis onto the agent instead of doing it yourself. Write prompts that prove you understood: include file paths, line numbers, what specifically to change.`,
589
620
  parameters: Type.Object({
590
621
  prompt: Type.String({
591
622
  description: "The task for the agent to perform.",
@@ -734,6 +765,29 @@ Guidelines:
734
765
  model = resolved;
735
766
  }
736
767
  }
768
+ // Scope validation: the effective resolved model is checked against the
769
+ // user's enabledModels list (read in `enabled-models.ts`).
770
+ //
771
+ // Design: scopeModels guards against *runtime* LLM choices, not user-level config.
772
+ // - Caller-supplied out-of-scope → hard error (the orchestrator made an explicit
773
+ // out-of-scope choice; surface it so it picks differently).
774
+ // - Frontmatter-pinned or parent-inherited out-of-scope → warn but proceed (the
775
+ // user authored/installed this agent or chose the parent's model; trust it).
776
+ // See SubagentsSettings.scopeModels docstring for the full policy.
777
+ if (isScopeModelsEnabled() && model) {
778
+ const allowed = resolveEnabledModels(readEnabledModels(ctx.cwd), ctx.modelRegistry, ctx.cwd);
779
+ if (allowed && !isModelInScope(model, allowed)) {
780
+ if (resolvedConfig.modelFromParams) {
781
+ const list = [...allowed].sort().map(m => ` ${m}`).join("\n");
782
+ return textResult(`Model not in scope: "${resolvedConfig.modelInput}".\n\n` +
783
+ `Allowed models (from enabledModels):\n${list}`);
784
+ }
785
+ // Frontmatter-pinned or parent-inherited: warn + proceed.
786
+ const agentLabel = customConfig?.displayName ?? subagentType;
787
+ const modelLabel = resolvedConfig.modelInput ?? `${model.provider}/${model.id}`;
788
+ ctx.ui.notify(`Agent "${agentLabel}" using out-of-scope model "${modelLabel}"`, "warning");
789
+ }
790
+ }
737
791
  const thinking = resolvedConfig.thinking;
738
792
  const inheritContext = resolvedConfig.inheritContext;
739
793
  const runInBackground = resolvedConfig.runInBackground;
@@ -1352,7 +1406,7 @@ Guidelines:
1352
1406
  }
1353
1407
  // Build the .md file content
1354
1408
  const fmFields = [];
1355
- fmFields.push(`description: ${cfg.description}`);
1409
+ fmFields.push(`description: ${JSON.stringify(cfg.description)}`);
1356
1410
  if (cfg.displayName)
1357
1411
  fmFields.push(`display_name: ${cfg.displayName}`);
1358
1412
  fmFields.push(`tools: ${cfg.builtinToolNames?.join(", ") || "all"}`);
@@ -1630,35 +1684,70 @@ ${systemPrompt}
1630
1684
  graceTurns: getGraceTurns(),
1631
1685
  defaultJoinMode: getDefaultJoinMode(),
1632
1686
  schedulingEnabled: isSchedulingEnabled(),
1687
+ scopeModels: isScopeModelsEnabled(),
1633
1688
  };
1634
1689
  }
1690
+ const NUMERIC_IDS = new Set(["maxConcurrent", "defaultMaxTurns", "graceTurns"]);
1635
1691
  async function showSettings(ctx) {
1636
- const choice = await ctx.ui.select("Settings", [
1637
- `Max concurrency (current: ${manager.getMaxConcurrent()})`,
1638
- `Default max turns (current: ${getDefaultMaxTurns() ?? "unlimited"})`,
1639
- `Grace turns (current: ${getGraceTurns()})`,
1640
- `Join mode (current: ${getDefaultJoinMode()})`,
1641
- `Scheduling (current: ${isSchedulingEnabled() ? "enabled" : "disabled"})`,
1642
- ]);
1643
- if (!choice)
1644
- return;
1645
- if (choice.startsWith("Max concurrency")) {
1646
- const val = await ctx.ui.input("Max concurrent background agents", String(manager.getMaxConcurrent()));
1647
- if (val) {
1648
- const n = parseInt(val, 10);
1692
+ function buildItems() {
1693
+ const mc = manager.getMaxConcurrent();
1694
+ const dmt = getDefaultMaxTurns() ?? 0;
1695
+ const gt = getGraceTurns();
1696
+ return [
1697
+ {
1698
+ id: "maxConcurrent",
1699
+ label: "Max concurrency",
1700
+ description: "Max concurrent background agents (Enter to type)",
1701
+ currentValue: String(mc),
1702
+ values: [String(mc)],
1703
+ },
1704
+ {
1705
+ id: "defaultMaxTurns",
1706
+ label: "Default max turns",
1707
+ description: "Default max turns before wrap-up (0 = unlimited, Enter to type)",
1708
+ currentValue: String(dmt),
1709
+ values: [String(dmt)],
1710
+ },
1711
+ {
1712
+ id: "graceTurns",
1713
+ label: "Grace turns",
1714
+ description: "Grace turns after wrap-up steer (Enter to type)",
1715
+ currentValue: String(gt),
1716
+ values: [String(gt)],
1717
+ },
1718
+ {
1719
+ id: "joinMode",
1720
+ label: "Join mode",
1721
+ description: "Default join mode for background agents",
1722
+ currentValue: getDefaultJoinMode(),
1723
+ values: ["smart", "async", "group"],
1724
+ },
1725
+ {
1726
+ id: "schedulingEnabled",
1727
+ label: "Scheduling",
1728
+ description: "Schedule subagent feature (off removes `schedule` param from Agent tool spec on next pi session)",
1729
+ currentValue: isSchedulingEnabled() ? "on" : "off",
1730
+ values: ["on", "off"],
1731
+ },
1732
+ {
1733
+ id: "scopeModels",
1734
+ label: "Scope models",
1735
+ description: "Validate subagent models against scoped models (/scoped-models)",
1736
+ currentValue: isScopeModelsEnabled() ? "on" : "off",
1737
+ values: ["on", "off"],
1738
+ },
1739
+ ];
1740
+ }
1741
+ function applyValue(id, value) {
1742
+ if (id === "maxConcurrent") {
1743
+ const n = parseInt(value, 10);
1649
1744
  if (n >= 1) {
1650
1745
  manager.setMaxConcurrent(n);
1651
1746
  notifyApplied(ctx, `Max concurrency set to ${n}`);
1652
1747
  }
1653
- else {
1654
- ctx.ui.notify("Must be a positive integer.", "warning");
1655
- }
1656
1748
  }
1657
- }
1658
- else if (choice.startsWith("Default max turns")) {
1659
- const val = await ctx.ui.input("Default max turns before wrap-up (0 = unlimited)", String(getDefaultMaxTurns() ?? 0));
1660
- if (val) {
1661
- const n = parseInt(val, 10);
1749
+ else if (id === "defaultMaxTurns") {
1750
+ const n = parseInt(value, 10);
1662
1751
  if (n === 0) {
1663
1752
  setDefaultMaxTurns(undefined);
1664
1753
  notifyApplied(ctx, "Default max turns set to unlimited");
@@ -1667,43 +1756,20 @@ ${systemPrompt}
1667
1756
  setDefaultMaxTurns(n);
1668
1757
  notifyApplied(ctx, `Default max turns set to ${n}`);
1669
1758
  }
1670
- else {
1671
- ctx.ui.notify("Must be 0 (unlimited) or a positive integer.", "warning");
1672
- }
1673
1759
  }
1674
- }
1675
- else if (choice.startsWith("Grace turns")) {
1676
- const val = await ctx.ui.input("Grace turns after wrap-up steer", String(getGraceTurns()));
1677
- if (val) {
1678
- const n = parseInt(val, 10);
1760
+ else if (id === "graceTurns") {
1761
+ const n = parseInt(value, 10);
1679
1762
  if (n >= 1) {
1680
1763
  setGraceTurns(n);
1681
1764
  notifyApplied(ctx, `Grace turns set to ${n}`);
1682
1765
  }
1683
- else {
1684
- ctx.ui.notify("Must be a positive integer.", "warning");
1685
- }
1686
1766
  }
1687
- }
1688
- else if (choice.startsWith("Join mode")) {
1689
- const val = await ctx.ui.select("Default join mode for background agents", [
1690
- "smart — auto-group 2+ agents in same turn (default)",
1691
- "async — always notify individually",
1692
- "group — always group background agents",
1693
- ]);
1694
- if (val) {
1695
- const mode = val.split(" ")[0];
1696
- setDefaultJoinMode(mode);
1697
- notifyApplied(ctx, `Default join mode set to ${mode}`);
1767
+ else if (id === "joinMode") {
1768
+ setDefaultJoinMode(value);
1769
+ notifyApplied(ctx, `Default join mode set to ${value}`);
1698
1770
  }
1699
- }
1700
- else if (choice.startsWith("Scheduling")) {
1701
- const val = await ctx.ui.select("Schedule subagent feature", [
1702
- "enabled — Agent tool accepts a `schedule` param; /agents → Scheduled jobs visible",
1703
- "disabled — `schedule` removed from Agent tool spec (no LLM-context cost); menu hidden",
1704
- ]);
1705
- if (val) {
1706
- const enabled = val.startsWith("enabled");
1771
+ else if (id === "schedulingEnabled") {
1772
+ const enabled = value === "on";
1707
1773
  if (enabled === isSchedulingEnabled()) {
1708
1774
  ctx.ui.notify(`Scheduling already ${enabled ? "enabled" : "disabled"}.`, "info");
1709
1775
  }
@@ -1714,6 +1780,71 @@ ${systemPrompt}
1714
1780
  notifyApplied(ctx, `Scheduling ${enabled ? "enabled" : "disabled"}. Tool spec change takes effect on next pi session.`);
1715
1781
  }
1716
1782
  }
1783
+ else if (id === "scopeModels") {
1784
+ const enabled = value === "on";
1785
+ setScopeModelsEnabled(enabled);
1786
+ notifyApplied(ctx, `Scope models ${enabled ? "enabled" : "disabled"}`);
1787
+ }
1788
+ }
1789
+ let list;
1790
+ // Track current selection index directly (SettingsList doesn't expose it).
1791
+ // Updated on arrow keys so Enter knows which field is selected immediately.
1792
+ let currentIndex = 0;
1793
+ const result = await ctx.ui.custom((_tui, _theme, _kb, done) => {
1794
+ const items = buildItems();
1795
+ list = new SettingsList(items, items.length + 2, getSettingsListTheme(), (id, newValue) => {
1796
+ applyValue(id, newValue);
1797
+ }, () => done(undefined));
1798
+ const container = new Container();
1799
+ container.addChild(new Text("⚙ Subagent Settings", 0, 0));
1800
+ container.addChild(new Spacer(1));
1801
+ container.addChild(list);
1802
+ return {
1803
+ render: (w) => container.render(w),
1804
+ invalidate: () => container.invalidate(),
1805
+ handleInput: (data) => {
1806
+ // Track navigation so Enter knows the current field
1807
+ if (matchesKey(data, "up")) {
1808
+ currentIndex = Math.max(0, currentIndex - 1);
1809
+ }
1810
+ else if (matchesKey(data, "down")) {
1811
+ currentIndex = Math.min(items.length - 1, currentIndex + 1);
1812
+ }
1813
+ // Enter on numeric field → close and prompt for typed input
1814
+ if (matchesKey(data, Key.enter) && NUMERIC_IDS.has(items[currentIndex].id)) {
1815
+ done(items[currentIndex].id);
1816
+ return;
1817
+ }
1818
+ list.handleInput?.(data);
1819
+ },
1820
+ };
1821
+ });
1822
+ // If a numeric field ID was returned, prompt for typed input
1823
+ if (result && NUMERIC_IDS.has(result)) {
1824
+ const current = result === "maxConcurrent"
1825
+ ? String(manager.getMaxConcurrent())
1826
+ : result === "defaultMaxTurns"
1827
+ ? String(getDefaultMaxTurns() ?? 0)
1828
+ : String(getGraceTurns());
1829
+ const label = result === "maxConcurrent"
1830
+ ? "Max concurrency (1+)"
1831
+ : result === "defaultMaxTurns"
1832
+ ? "Default max turns (0 = unlimited)"
1833
+ : "Grace turns (1+)";
1834
+ // Loop until user enters a valid integer or cancels (Esc / null).
1835
+ // Silently trims whitespace; rejects non-numeric input by re-prompting.
1836
+ let input = await ctx.ui.input(label, current);
1837
+ while (input != null) {
1838
+ const trimmed = input.trim();
1839
+ const n = Number(trimmed);
1840
+ if (trimmed !== "" && Number.isInteger(n)) {
1841
+ applyValue(result, String(n));
1842
+ await showSettings(ctx);
1843
+ return;
1844
+ }
1845
+ // Invalid — re-prompt with the user's last entry so they can edit it
1846
+ input = await ctx.ui.input(label, trimmed);
1847
+ }
1717
1848
  }
1718
1849
  }
1719
1850
  // Persist the current snapshot, emit `subagents:settings_changed`, and surface
@@ -4,7 +4,7 @@
4
4
  * Creates a per-agent output file that streams conversation turns as JSONL,
5
5
  * matching Claude Code's task output file format.
6
6
  */
7
- import type { AgentSession } from "@mariozechner/pi-coding-agent";
7
+ import type { AgentSession } from "@earendil-works/pi-coding-agent";
8
8
  /**
9
9
  * Encode a cwd path as a filesystem-safe directory name. Handles:
10
10
  * - POSIX: "/home/user/project" → "home-user-project"
@@ -17,6 +17,8 @@ export declare class ScheduleStore {
17
17
  private lockPath;
18
18
  private jobs;
19
19
  constructor(filePath: string);
20
+ /** Create the backing directory lazily — only when we're about to persist. */
21
+ private ensureDir;
20
22
  /** Load from disk into the in-memory cache. Silent on parse errors. */
21
23
  private load;
22
24
  /** Atomic write via temp file + rename (POSIX-atomic). */
@@ -64,9 +64,12 @@ export class ScheduleStore {
64
64
  constructor(filePath) {
65
65
  this.filePath = filePath;
66
66
  this.lockPath = filePath + ".lock";
67
- mkdirSync(dirname(filePath), { recursive: true });
68
67
  this.load();
69
68
  }
69
+ /** Create the backing directory lazily — only when we're about to persist. */
70
+ ensureDir() {
71
+ mkdirSync(dirname(this.filePath), { recursive: true });
72
+ }
70
73
  /** Load from disk into the in-memory cache. Silent on parse errors. */
71
74
  load() {
72
75
  if (!existsSync(this.filePath))
@@ -88,6 +91,7 @@ export class ScheduleStore {
88
91
  }
89
92
  /** Acquire lock → reload → mutate → save → release. */
90
93
  withLock(fn) {
94
+ this.ensureDir();
91
95
  acquireLock(this.lockPath);
92
96
  try {
93
97
  this.load();
@@ -120,6 +124,10 @@ export class ScheduleStore {
120
124
  });
121
125
  }
122
126
  update(id, patch) {
127
+ // No-op fast path — an unknown id changes nothing, so don't lock or touch
128
+ // disk (which would otherwise lazily create the backing directory).
129
+ if (!this.jobs.has(id))
130
+ return undefined;
123
131
  return this.withLock(() => {
124
132
  const existing = this.jobs.get(id);
125
133
  if (!existing)
@@ -130,6 +138,9 @@ export class ScheduleStore {
130
138
  });
131
139
  }
132
140
  remove(id) {
141
+ // No-op fast path — see update().
142
+ if (!this.jobs.has(id))
143
+ return false;
133
144
  return this.withLock(() => this.jobs.delete(id));
134
145
  }
135
146
  /** Delete the backing file (used when no jobs remain, optional cleanup). */
@@ -14,7 +14,7 @@
14
14
  * - Result delivery is implicit: spawn → background completion → existing
15
15
  * `subagent-notification` followUp path. No new delivery code.
16
16
  */
17
- import type { ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";
17
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
18
18
  import type { AgentManager } from "./agent-manager.js";
19
19
  import type { ScheduleStore } from "./schedule-store.js";
20
20
  import type { IsolationMode, ScheduledSubagent, SubagentType, ThinkingLevel } from "./types.js";
@@ -18,6 +18,28 @@ export interface SubagentsSettings {
18
18
  * (next pi session); runtime menu/runtime-fire short-circuit is immediate.
19
19
  */
20
20
  schedulingEnabled?: boolean;
21
+ /**
22
+ * When true, the effective model of each subagent spawn is validated
23
+ * against `enabledModels` from pi's settings — both global
24
+ * (`<agentDir>/settings.json`) and project-local (`<cwd>/.pi/settings.json`),
25
+ * with project overriding global (mirrors pi's SettingsManager deep-merge).
26
+ *
27
+ * scopeModels guards against runtime LLM choices, not user-level config.
28
+ * Out-of-scope handling reflects this:
29
+ * - Caller-supplied via `Agent({ model: "..." })` (only when frontmatter
30
+ * has no `model:`, since frontmatter is authoritative): hard error
31
+ * returned to the orchestrator, listing the allowed models. The LLM
32
+ * made an explicit out-of-scope choice and gets explicit feedback.
33
+ * - Frontmatter-pinned: warning toast + the pinned model runs. The
34
+ * agent's author/installer chose this; trust it.
35
+ * - Parent-inherited (neither caller nor frontmatter sets a model):
36
+ * warning toast + parent's model runs. The user chose the parent's
37
+ * model when starting the session; trust it.
38
+ *
39
+ * No-op when pi's `enabledModels` is empty or absent — nothing to validate
40
+ * against. Defaults to false: subagents may use any model.
41
+ */
42
+ scopeModels?: boolean;
21
43
  }
22
44
  /** Setter hooks used by applySettings to wire persisted values into in-memory state. */
23
45
  export interface SettingsAppliers {
@@ -26,6 +48,7 @@ export interface SettingsAppliers {
26
48
  setGraceTurns: (n: number) => void;
27
49
  setDefaultJoinMode: (mode: JoinMode) => void;
28
50
  setSchedulingEnabled: (b: boolean) => void;
51
+ setScopeModels: (enabled: boolean) => void;
29
52
  }
30
53
  /** Emit callback — a subset of `pi.events.emit` to keep helpers testable. */
31
54
  export type SettingsEmit = (event: string, payload: unknown) => void;
package/dist/settings.js CHANGED
@@ -3,7 +3,7 @@
3
3
  // - Project: <cwd>/.pi/subagents.json — written by /agents → Settings; overrides global on load
4
4
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
5
  import { dirname, join } from "node:path";
6
- import { getAgentDir } from "@mariozechner/pi-coding-agent";
6
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
7
7
  const VALID_JOIN_MODES = new Set(["async", "group", "smart"]);
8
8
  // Sanity ceilings — prevent hand-edited configs from asking for values that
9
9
  // make no operational sense (e.g. 1e6 concurrent subagents). Permissive enough
@@ -38,6 +38,9 @@ function sanitize(raw) {
38
38
  if (typeof r.schedulingEnabled === "boolean") {
39
39
  out.schedulingEnabled = r.schedulingEnabled;
40
40
  }
41
+ if (typeof r.scopeModels === "boolean") {
42
+ out.scopeModels = r.scopeModels;
43
+ }
41
44
  return out;
42
45
  }
43
46
  function globalPath() {
@@ -95,6 +98,8 @@ export function applySettings(s, appliers) {
95
98
  appliers.setDefaultJoinMode(s.defaultJoinMode);
96
99
  if (typeof s.schedulingEnabled === "boolean")
97
100
  appliers.setSchedulingEnabled(s.schedulingEnabled);
101
+ if (typeof s.scopeModels === "boolean")
102
+ appliers.setScopeModels(s.scopeModels);
98
103
  }
99
104
  /**
100
105
  * Format the user-facing toast for a settings mutation. Pure function —
@@ -20,7 +20,7 @@
20
20
  import { existsSync, readdirSync } from "node:fs";
21
21
  import { homedir } from "node:os";
22
22
  import { join } from "node:path";
23
- import { getAgentDir } from "@mariozechner/pi-coding-agent";
23
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
24
24
  import { isSymlink, isUnsafeName, safeReadFile } from "./memory.js";
25
25
  export function preloadSkills(skillNames, cwd) {
26
26
  return skillNames.map((name) => ({ name, content: loadSkillContent(name, cwd) }));
package/dist/types.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * types.ts — Type definitions for the subagent system.
3
3
  */
4
- import type { ThinkingLevel } from "@mariozechner/pi-agent-core";
5
- import type { AgentSession } from "@mariozechner/pi-coding-agent";
4
+ import type { ThinkingLevel } from "@earendil-works/pi-ai";
5
+ import type { AgentSession } from "@earendil-works/pi-coding-agent";
6
6
  import type { LifetimeUsage } from "./usage.js";
7
7
  export type { ThinkingLevel };
8
8
  /** Agent type: any string name (built-in defaults or user-defined). */
@@ -4,7 +4,7 @@
4
4
  * Displays a tree of agents with animated spinners, live stats, and activity descriptions.
5
5
  * Uses the callback form of setWidget for themed rendering.
6
6
  */
7
- import { truncateToWidth } from "@mariozechner/pi-tui";
7
+ import { truncateToWidth } from "@earendil-works/pi-tui";
8
8
  import { getConfig } from "../agent-types.js";
9
9
  import { getLifetimeTotal, getSessionContextPercent } from "../usage.js";
10
10
  // ---- Constants ----
@@ -4,8 +4,8 @@
4
4
  * Displays a scrollable, live-updating view of an agent's conversation.
5
5
  * Subscribes to session events for real-time streaming updates.
6
6
  */
7
- import type { AgentSession } from "@mariozechner/pi-coding-agent";
8
- import { type Component, type TUI } from "@mariozechner/pi-tui";
7
+ import type { AgentSession } from "@earendil-works/pi-coding-agent";
8
+ import { type Component, type TUI } from "@earendil-works/pi-tui";
9
9
  import type { AgentRecord } from "../types.js";
10
10
  import type { Theme } from "./agent-widget.js";
11
11
  import { type AgentActivity } from "./agent-widget.js";
@@ -4,7 +4,7 @@
4
4
  * Displays a scrollable, live-updating view of an agent's conversation.
5
5
  * Subscribes to session events for real-time streaming updates.
6
6
  */
7
- import { matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@mariozechner/pi-tui";
7
+ import { matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
8
8
  import { extractText } from "../context.js";
9
9
  import { getLifetimeTotal, getSessionContextPercent } from "../usage.js";
10
10
  import { buildInvocationTags, describeActivity, formatDuration, formatSessionTokens, getDisplayName, getPromptModeLabel } from "./agent-widget.js";
@@ -7,7 +7,7 @@
7
7
  * "I scheduled something dumb, get rid of it"). Add management surfaces here
8
8
  * if real demand emerges.
9
9
  */
10
- import type { ExtensionCommandContext } from "@mariozechner/pi-coding-agent";
10
+ import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
11
11
  import type { SubagentScheduler } from "../schedule.js";
12
12
  /**
13
13
  * List scheduled jobs; selecting one opens a cancel-confirm with details.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tintinweb/pi-subagents",
3
- "version": "0.7.3",
3
+ "version": "0.9.0",
4
4
  "description": "A pi extension extension that brings smart Claude Code-style autonomous sub-agents to pi.",
5
5
  "author": "tintinweb",
6
6
  "license": "MIT",
@@ -21,9 +21,9 @@
21
21
  "autonomous"
22
22
  ],
23
23
  "peerDependencies": {
24
- "@mariozechner/pi-ai": ">=0.70.5",
25
- "@mariozechner/pi-coding-agent": ">=0.70.5",
26
- "@mariozechner/pi-tui": ">=0.70.5"
24
+ "@earendil-works/pi-ai": ">=0.74.0",
25
+ "@earendil-works/pi-coding-agent": ">=0.74.0",
26
+ "@earendil-works/pi-tui": ">=0.74.0"
27
27
  },
28
28
  "dependencies": {
29
29
  "@sinclair/typebox": "^0.34.49",
@@ -7,8 +7,8 @@
7
7
  */
8
8
 
9
9
  import { randomUUID } from "node:crypto";
10
- import type { Model } from "@mariozechner/pi-ai";
11
- import type { AgentSession, ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";
10
+ import type { Model } from "@earendil-works/pi-ai";
11
+ import type { AgentSession, ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
12
12
  import { resumeAgent, runAgent, type ToolActivity } from "./agent-runner.js";
13
13
  import type { AgentInvocation, AgentRecord, IsolationMode, SubagentType, ThinkingLevel } from "./types.js";
14
14
  import { addUsage } from "./usage.js";