@diousk/pi-subagents-fast 0.20.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 (183) hide show
  1. package/CHANGELOG.md +808 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1034 -0
  5. package/SECURITY.md +95 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/agent-color.d.ts +35 -0
  9. package/dist/agent-color.js +123 -0
  10. package/dist/agent-file-toggle.d.ts +125 -0
  11. package/dist/agent-file-toggle.js +260 -0
  12. package/dist/agent-manager.d.ts +472 -0
  13. package/dist/agent-manager.js +1338 -0
  14. package/dist/agent-runner.d.ts +312 -0
  15. package/dist/agent-runner.js +1034 -0
  16. package/dist/agent-types.d.ts +119 -0
  17. package/dist/agent-types.js +286 -0
  18. package/dist/child-context.d.ts +2 -0
  19. package/dist/child-context.js +12 -0
  20. package/dist/context.d.ts +12 -0
  21. package/dist/context.js +56 -0
  22. package/dist/cross-extension-rpc.d.ts +66 -0
  23. package/dist/cross-extension-rpc.js +138 -0
  24. package/dist/custom-agents.d.ts +54 -0
  25. package/dist/custom-agents.js +316 -0
  26. package/dist/default-agents.d.ts +7 -0
  27. package/dist/default-agents.js +122 -0
  28. package/dist/enabled-models.d.ts +49 -0
  29. package/dist/enabled-models.js +145 -0
  30. package/dist/env.d.ts +6 -0
  31. package/dist/env.js +28 -0
  32. package/dist/group-join.d.ts +32 -0
  33. package/dist/group-join.js +116 -0
  34. package/dist/index.d.ts +50 -0
  35. package/dist/index.js +3682 -0
  36. package/dist/invocation-config.d.ts +107 -0
  37. package/dist/invocation-config.js +83 -0
  38. package/dist/memory.d.ts +53 -0
  39. package/dist/memory.js +165 -0
  40. package/dist/mention-clone.d.ts +87 -0
  41. package/dist/mention-clone.js +153 -0
  42. package/dist/mention.d.ts +81 -0
  43. package/dist/mention.js +131 -0
  44. package/dist/model-resolver.d.ts +36 -0
  45. package/dist/model-resolver.js +95 -0
  46. package/dist/model-scope.d.ts +49 -0
  47. package/dist/model-scope.js +48 -0
  48. package/dist/nested-tools.d.ts +55 -0
  49. package/dist/nested-tools.js +299 -0
  50. package/dist/output-file.d.ts +43 -0
  51. package/dist/output-file.js +142 -0
  52. package/dist/prompts.d.ts +55 -0
  53. package/dist/prompts.js +91 -0
  54. package/dist/schedule-store.d.ts +38 -0
  55. package/dist/schedule-store.js +155 -0
  56. package/dist/schedule.d.ts +109 -0
  57. package/dist/schedule.js +359 -0
  58. package/dist/settings.d.ts +360 -0
  59. package/dist/settings.js +251 -0
  60. package/dist/skill-loader.d.ts +24 -0
  61. package/dist/skill-loader.js +93 -0
  62. package/dist/status-note.d.ts +61 -0
  63. package/dist/status-note.js +85 -0
  64. package/dist/structured-output.d.ts +61 -0
  65. package/dist/structured-output.js +112 -0
  66. package/dist/types.d.ts +371 -0
  67. package/dist/types.js +5 -0
  68. package/dist/ui/agent-mention.d.ts +82 -0
  69. package/dist/ui/agent-mention.js +187 -0
  70. package/dist/ui/agent-widget.d.ts +219 -0
  71. package/dist/ui/agent-widget.js +592 -0
  72. package/dist/ui/conversation-viewer.d.ts +120 -0
  73. package/dist/ui/conversation-viewer.js +578 -0
  74. package/dist/ui/fleet-list.d.ts +195 -0
  75. package/dist/ui/fleet-list.js +471 -0
  76. package/dist/ui/schedule-menu.d.ts +16 -0
  77. package/dist/ui/schedule-menu.js +94 -0
  78. package/dist/ui/select-item.d.ts +27 -0
  79. package/dist/ui/select-item.js +34 -0
  80. package/dist/ui/viewer-keys.d.ts +20 -0
  81. package/dist/ui/viewer-keys.js +17 -0
  82. package/dist/ui/workflow-card.d.ts +175 -0
  83. package/dist/ui/workflow-card.js +332 -0
  84. package/dist/ui/workflow-dialog.d.ts +305 -0
  85. package/dist/ui/workflow-dialog.js +843 -0
  86. package/dist/ui/workflow-menu.d.ts +60 -0
  87. package/dist/ui/workflow-menu.js +147 -0
  88. package/dist/usage.d.ts +135 -0
  89. package/dist/usage.js +120 -0
  90. package/dist/workflow/collisions.d.ts +95 -0
  91. package/dist/workflow/collisions.js +88 -0
  92. package/dist/workflow/entry.d.ts +32 -0
  93. package/dist/workflow/entry.js +29 -0
  94. package/dist/workflow/host.d.ts +62 -0
  95. package/dist/workflow/host.js +362 -0
  96. package/dist/workflow/journal.d.ts +97 -0
  97. package/dist/workflow/journal.js +120 -0
  98. package/dist/workflow/json-schema.d.ts +51 -0
  99. package/dist/workflow/json-schema.js +111 -0
  100. package/dist/workflow/meta.d.ts +67 -0
  101. package/dist/workflow/meta.js +317 -0
  102. package/dist/workflow/progress.d.ts +224 -0
  103. package/dist/workflow/progress.js +361 -0
  104. package/dist/workflow/runtime.d.ts +334 -0
  105. package/dist/workflow/runtime.js +830 -0
  106. package/dist/workflow/saved.d.ts +90 -0
  107. package/dist/workflow/saved.js +203 -0
  108. package/dist/workflow/task.d.ts +136 -0
  109. package/dist/workflow/task.js +207 -0
  110. package/dist/workflow/tool-description.d.ts +38 -0
  111. package/dist/workflow/tool-description.js +199 -0
  112. package/dist/workflow/worker-source.d.ts +47 -0
  113. package/dist/workflow/worker-source.js +778 -0
  114. package/dist/worktree.d.ts +52 -0
  115. package/dist/worktree.js +164 -0
  116. package/dist/xml.d.ts +10 -0
  117. package/dist/xml.js +12 -0
  118. package/docs/rpc.md +183 -0
  119. package/docs/workflows.md +437 -0
  120. package/examples/agent-tool-description.md +42 -0
  121. package/examples/workflows/compose.js +51 -0
  122. package/examples/workflows/fan-out-audit.js +47 -0
  123. package/examples/workflows/gated-fix.js +60 -0
  124. package/examples/workflows/lib/count-child.js +27 -0
  125. package/examples/workflows/review-panel.js +63 -0
  126. package/examples/workflows/structured-findings.js +78 -0
  127. package/package.json +68 -0
  128. package/src/abortable.ts +43 -0
  129. package/src/agent-color.ts +161 -0
  130. package/src/agent-file-toggle.ts +270 -0
  131. package/src/agent-manager.ts +1581 -0
  132. package/src/agent-runner.ts +1286 -0
  133. package/src/agent-types.ts +346 -0
  134. package/src/child-context.ts +15 -0
  135. package/src/context.ts +58 -0
  136. package/src/cross-extension-rpc.ts +198 -0
  137. package/src/custom-agents.ts +333 -0
  138. package/src/default-agents.ts +126 -0
  139. package/src/enabled-models.ts +180 -0
  140. package/src/env.ts +33 -0
  141. package/src/group-join.ts +141 -0
  142. package/src/index.ts +3991 -0
  143. package/src/invocation-config.ts +155 -0
  144. package/src/memory.ts +179 -0
  145. package/src/mention-clone.ts +196 -0
  146. package/src/mention.ts +141 -0
  147. package/src/model-resolver.ts +118 -0
  148. package/src/model-scope.ts +70 -0
  149. package/src/nested-tools.ts +422 -0
  150. package/src/output-file.ts +155 -0
  151. package/src/prompts.ts +142 -0
  152. package/src/schedule-store.ts +153 -0
  153. package/src/schedule.ts +386 -0
  154. package/src/settings.ts +587 -0
  155. package/src/skill-loader.ts +102 -0
  156. package/src/status-note.ts +90 -0
  157. package/src/structured-output.ts +130 -0
  158. package/src/types.ts +384 -0
  159. package/src/ui/agent-mention.ts +216 -0
  160. package/src/ui/agent-widget.ts +664 -0
  161. package/src/ui/conversation-viewer.ts +589 -0
  162. package/src/ui/fleet-list.ts +543 -0
  163. package/src/ui/schedule-menu.ts +105 -0
  164. package/src/ui/select-item.ts +45 -0
  165. package/src/ui/viewer-keys.ts +39 -0
  166. package/src/ui/workflow-card.ts +470 -0
  167. package/src/ui/workflow-dialog.ts +1115 -0
  168. package/src/ui/workflow-menu.ts +193 -0
  169. package/src/usage.ts +167 -0
  170. package/src/workflow/collisions.ts +123 -0
  171. package/src/workflow/entry.ts +47 -0
  172. package/src/workflow/host.ts +403 -0
  173. package/src/workflow/journal.ts +164 -0
  174. package/src/workflow/json-schema.ts +128 -0
  175. package/src/workflow/meta.ts +325 -0
  176. package/src/workflow/progress.ts +550 -0
  177. package/src/workflow/runtime.ts +1219 -0
  178. package/src/workflow/saved.ts +217 -0
  179. package/src/workflow/task.ts +302 -0
  180. package/src/workflow/tool-description.ts +200 -0
  181. package/src/workflow/worker-source.ts +781 -0
  182. package/src/worktree.ts +205 -0
  183. package/src/xml.ts +13 -0
@@ -0,0 +1,81 @@
1
+ /**
2
+ * mention.ts — the `@handle` grammar for messaging a subagent from the prompt.
3
+ *
4
+ * Claude Code lets you type `@code-review take another look` at the prompt and
5
+ * routes the message to that agent instead of the main model. Its grammar is
6
+ * reproduced here so the two behave identically:
7
+ *
8
+ * - suggestions fire on `@` at the start of the input or after whitespace,
9
+ * followed by `[\w-]*` (so `@src/foo.ts` is a file, never an agent);
10
+ * - a send is recognized only at the START of the input, and only with a
11
+ * non-empty message after the handle. That is why a bare `@code-review`
12
+ * goes to the main model rather than anywhere near the agent.
13
+ *
14
+ * A record's own identity is a UUID plus a deliberately non-unique description,
15
+ * neither of which is typeable, so the handle is derived from the agent type.
16
+ * Colliding handles are numbered (`explore`, `explore-2`), which is also what
17
+ * Claude Code's `allocateName` does — it recycles a name only once the task
18
+ * behind it is gone. Its SendMessage prompt describes the *registry* as
19
+ * latest-wins, which is a different thing and not how names are allocated.
20
+ */
21
+ /**
22
+ * Suggestion trigger: `@` at a token boundary plus the partial handle typed so
23
+ * far. Ported from Claude Code, including the CJK sentence-ending punctuation
24
+ * it accepts as a boundary.
25
+ */
26
+ export declare const MENTION_TRIGGER: RegExp;
27
+ /** Whether `@handle` names the main conversation rather than any subagent. */
28
+ export declare function isReservedHandle(handle: string): boolean;
29
+ /** Slug of an agent type or name, restricted to the `[\w-]` the grammar allows. */
30
+ export declare function handleBase(type: string): string;
31
+ /**
32
+ * `base`, else `base-2`, `base-3`, … — the first form that is neither `taken`
33
+ * nor reserved. Callers pass one shared `taken` set covering type-derived
34
+ * handles and model-supplied aliases alike, so the two can never collide.
35
+ */
36
+ export declare function assignHandle(base: string, taken: ReadonlySet<string>): string;
37
+ /**
38
+ * Map a typed handle back to a registered agent type, so `@explore fix it`
39
+ * reaches the Explore agent even when no instance has ever run. `handleBase` is
40
+ * the single source of truth in both directions, so a type is addressable by
41
+ * exactly the handle its instances would be given.
42
+ */
43
+ export declare function resolveHandleToType(handle: string, types: readonly string[]): string | undefined;
44
+ /**
45
+ * Claude Code documents `@agent-<name>` as the form you type by hand when the
46
+ * picker isn't involved. Accepted here as an exact synonym: the caller tries the
47
+ * handle as written first, so an agent genuinely called `agent-foo` still wins
48
+ * over `@agent-` + `foo`, and only falls back to this when that finds nothing.
49
+ * Returns undefined when the prefix is absent or is the whole handle.
50
+ */
51
+ export declare function stripAgentPrefix(handle: string): string | undefined;
52
+ /**
53
+ * A spawn needs the short description every agent surface renders. A mention
54
+ * carries no separate label, so the message itself becomes one: first line,
55
+ * whitespace collapsed, clipped to roughly the 3-5 words the Agent tool asks of
56
+ * the model.
57
+ */
58
+ export declare function describeMention(message: string): string;
59
+ /**
60
+ * What Claude Code sends the main model when a mention names an agent it could
61
+ * start. Its `@agent-<type>` mention is not a spawn at all: it becomes an
62
+ * `agent_mention` attachment, which renders to a synthetic `isMeta` user
63
+ * message placed after the user's own untouched text — no tool forcing, no
64
+ * allowed-tools narrowing, and the Task tool is not even named. The model reads
65
+ * this and calls the tool itself.
66
+ *
67
+ * Ported verbatim from the 2.1.233 bundle's attachment renderer, trailing space
68
+ * before the closing newline included, so the wording the model was trained
69
+ * against is the wording it gets. The one substitution is ours: pi's equivalent
70
+ * of Task is the `Agent` tool, and the agent listing that teaches valid
71
+ * `subagent_type` values is the tool spec rather than a separate attachment.
72
+ */
73
+ export declare function agentMentionReminder(type: string): string;
74
+ /**
75
+ * Split `@handle message` into its parts, or null when the text isn't a send —
76
+ * a bare handle, a leading file path, or a mention that isn't at the start.
77
+ */
78
+ export declare function parseMention(text: string): {
79
+ handle: string;
80
+ message: string;
81
+ } | null;
@@ -0,0 +1,131 @@
1
+ /**
2
+ * mention.ts — the `@handle` grammar for messaging a subagent from the prompt.
3
+ *
4
+ * Claude Code lets you type `@code-review take another look` at the prompt and
5
+ * routes the message to that agent instead of the main model. Its grammar is
6
+ * reproduced here so the two behave identically:
7
+ *
8
+ * - suggestions fire on `@` at the start of the input or after whitespace,
9
+ * followed by `[\w-]*` (so `@src/foo.ts` is a file, never an agent);
10
+ * - a send is recognized only at the START of the input, and only with a
11
+ * non-empty message after the handle. That is why a bare `@code-review`
12
+ * goes to the main model rather than anywhere near the agent.
13
+ *
14
+ * A record's own identity is a UUID plus a deliberately non-unique description,
15
+ * neither of which is typeable, so the handle is derived from the agent type.
16
+ * Colliding handles are numbered (`explore`, `explore-2`), which is also what
17
+ * Claude Code's `allocateName` does — it recycles a name only once the task
18
+ * behind it is gone. Its SendMessage prompt describes the *registry* as
19
+ * latest-wins, which is a different thing and not how names are allocated.
20
+ */
21
+ /**
22
+ * Suggestion trigger: `@` at a token boundary plus the partial handle typed so
23
+ * far. Ported from Claude Code, including the CJK sentence-ending punctuation
24
+ * it accepts as a boundary.
25
+ */
26
+ export const MENTION_TRIGGER = /(^|[\s。、?!])@([\w-]*)$/;
27
+ /** Send grammar: leading `@handle`, then a non-empty message. */
28
+ const MENTION_SEND = /^@([\w-]+)\s+([\s\S]+)$/;
29
+ /**
30
+ * Upper bound on a handle, matching Claude Code's `dSS`. Nothing here generates
31
+ * a name this long, but an agent type or a model-supplied name can be arbitrary
32
+ * text, and an unbounded handle would wrap the suggestion popup.
33
+ */
34
+ const MAX_HANDLE_LENGTH = 64;
35
+ /**
36
+ * Handles that address something other than a subagent, and so can never be
37
+ * allocated to one. Claude Code reserves exactly this name (`Vq = "main"`),
38
+ * refusing it at spawn and routing it to the main conversation instead.
39
+ */
40
+ const RESERVED_HANDLES = new Set(["main"]);
41
+ /** Whether `@handle` names the main conversation rather than any subagent. */
42
+ export function isReservedHandle(handle) {
43
+ return RESERVED_HANDLES.has(handle.toLowerCase());
44
+ }
45
+ /** Slug of an agent type or name, restricted to the `[\w-]` the grammar allows. */
46
+ export function handleBase(type) {
47
+ const slug = type.toLowerCase()
48
+ .replace(/[^a-z0-9_-]+/g, "-")
49
+ .replace(/^-+|-+$/g, "")
50
+ .slice(0, MAX_HANDLE_LENGTH)
51
+ // The slice can land mid-run and leave the trailing hyphen back.
52
+ .replace(/-+$/, "");
53
+ return slug || "agent";
54
+ }
55
+ /**
56
+ * `base`, else `base-2`, `base-3`, … — the first form that is neither `taken`
57
+ * nor reserved. Callers pass one shared `taken` set covering type-derived
58
+ * handles and model-supplied aliases alike, so the two can never collide.
59
+ */
60
+ export function assignHandle(base, taken) {
61
+ let candidate = base;
62
+ let n = 1;
63
+ while (taken.has(candidate) || RESERVED_HANDLES.has(candidate)) {
64
+ n++;
65
+ candidate = `${base}-${n}`;
66
+ }
67
+ return candidate;
68
+ }
69
+ /**
70
+ * Map a typed handle back to a registered agent type, so `@explore fix it`
71
+ * reaches the Explore agent even when no instance has ever run. `handleBase` is
72
+ * the single source of truth in both directions, so a type is addressable by
73
+ * exactly the handle its instances would be given.
74
+ */
75
+ export function resolveHandleToType(handle, types) {
76
+ const wanted = handle.toLowerCase();
77
+ // A type slugging to a reserved name is unaddressable rather than shadowing
78
+ // it — `assignHandle` refuses that name too, so its instances never hold one.
79
+ if (RESERVED_HANDLES.has(wanted))
80
+ return undefined;
81
+ return types.find(type => handleBase(type) === wanted);
82
+ }
83
+ /**
84
+ * Claude Code documents `@agent-<name>` as the form you type by hand when the
85
+ * picker isn't involved. Accepted here as an exact synonym: the caller tries the
86
+ * handle as written first, so an agent genuinely called `agent-foo` still wins
87
+ * over `@agent-` + `foo`, and only falls back to this when that finds nothing.
88
+ * Returns undefined when the prefix is absent or is the whole handle.
89
+ */
90
+ export function stripAgentPrefix(handle) {
91
+ const rest = /^agent-(.+)$/i.exec(handle)?.[1];
92
+ return rest || undefined;
93
+ }
94
+ /**
95
+ * A spawn needs the short description every agent surface renders. A mention
96
+ * carries no separate label, so the message itself becomes one: first line,
97
+ * whitespace collapsed, clipped to roughly the 3-5 words the Agent tool asks of
98
+ * the model.
99
+ */
100
+ export function describeMention(message) {
101
+ const oneLine = message.split("\n", 1)[0].replace(/\s+/g, " ").trim();
102
+ return oneLine.length > 40 ? `${oneLine.slice(0, 39).trimEnd()}…` : oneLine;
103
+ }
104
+ /**
105
+ * What Claude Code sends the main model when a mention names an agent it could
106
+ * start. Its `@agent-<type>` mention is not a spawn at all: it becomes an
107
+ * `agent_mention` attachment, which renders to a synthetic `isMeta` user
108
+ * message placed after the user's own untouched text — no tool forcing, no
109
+ * allowed-tools narrowing, and the Task tool is not even named. The model reads
110
+ * this and calls the tool itself.
111
+ *
112
+ * Ported verbatim from the 2.1.233 bundle's attachment renderer, trailing space
113
+ * before the closing newline included, so the wording the model was trained
114
+ * against is the wording it gets. The one substitution is ours: pi's equivalent
115
+ * of Task is the `Agent` tool, and the agent listing that teaches valid
116
+ * `subagent_type` values is the tool spec rather than a separate attachment.
117
+ */
118
+ export function agentMentionReminder(type) {
119
+ return `<system-reminder>\nThe user has expressed a desire to invoke the agent "${type}". Please invoke the agent appropriately, passing in the required context to it. \n</system-reminder>`;
120
+ }
121
+ /**
122
+ * Split `@handle message` into its parts, or null when the text isn't a send —
123
+ * a bare handle, a leading file path, or a mention that isn't at the start.
124
+ */
125
+ export function parseMention(text) {
126
+ const match = MENTION_SEND.exec(text);
127
+ if (!match)
128
+ return null;
129
+ const message = match[2].trim();
130
+ return message ? { handle: match[1], message } : null;
131
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Model resolution: exact match ("provider/modelId") with fuzzy fallback.
3
+ */
4
+ export interface ModelEntry {
5
+ id: string;
6
+ name: string;
7
+ provider: string;
8
+ }
9
+ export interface ModelRegistry {
10
+ find(provider: string, modelId: string): any;
11
+ getAll(): any[];
12
+ getAvailable?(): any[];
13
+ }
14
+ /**
15
+ * Both display forms of a model. The short one goes on tight rows (the widget,
16
+ * the Agent tool result), the canonical one where there is room to disambiguate
17
+ * two providers serving a similarly-named model (the conversation viewer).
18
+ *
19
+ * One function, because `index.ts` labels the model it resolved before the run
20
+ * and `agent-manager.ts` relabels it from the live session afterwards — the two
21
+ * must agree or the label would visibly change the moment the session starts.
22
+ */
23
+ export declare function describeModel(model: {
24
+ provider: string;
25
+ id: string;
26
+ name?: string;
27
+ }): {
28
+ modelName: string;
29
+ modelId: string;
30
+ };
31
+ /**
32
+ * Resolve a model string to a Model instance.
33
+ * Tries exact match first ("provider/modelId"), then fuzzy match against all available models.
34
+ * Returns the Model on success, or an error message string on failure.
35
+ */
36
+ export declare function resolveModel(input: string, registry: ModelRegistry): any | string;
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Model resolution: exact match ("provider/modelId") with fuzzy fallback.
3
+ */
4
+ /**
5
+ * Both display forms of a model. The short one goes on tight rows (the widget,
6
+ * the Agent tool result), the canonical one where there is room to disambiguate
7
+ * two providers serving a similarly-named model (the conversation viewer).
8
+ *
9
+ * One function, because `index.ts` labels the model it resolved before the run
10
+ * and `agent-manager.ts` relabels it from the live session afterwards — the two
11
+ * must agree or the label would visibly change the moment the session starts.
12
+ */
13
+ export function describeModel(model) {
14
+ return {
15
+ modelName: (model.name ?? model.id).replace(/^Claude\s+/i, "").toLowerCase(),
16
+ modelId: `${model.provider}/${model.id}`,
17
+ };
18
+ }
19
+ /**
20
+ * Resolve a model string to a Model instance.
21
+ * Tries exact match first ("provider/modelId"), then fuzzy match against all available models.
22
+ * Returns the Model on success, or an error message string on failure.
23
+ */
24
+ export function resolveModel(input, registry) {
25
+ // Available models (those with auth configured)
26
+ const all = (registry.getAvailable?.() ?? registry.getAll());
27
+ const availableSet = new Set(all.map(m => `${m.provider}/${m.id}`.toLowerCase()));
28
+ // 1. Exact match: "provider/modelId" — only if available (has auth)
29
+ const slashIdx = input.indexOf("/");
30
+ if (slashIdx !== -1) {
31
+ const provider = input.slice(0, slashIdx);
32
+ const modelId = input.slice(slashIdx + 1);
33
+ if (availableSet.has(input.toLowerCase())) {
34
+ const found = registry.find(provider, modelId);
35
+ if (found)
36
+ return found;
37
+ }
38
+ }
39
+ // 2. Fuzzy match against available models. Normalize separators so cosmetic
40
+ // punctuation differences still match — e.g. "claude-haiku-4.5" and
41
+ // "claude-haiku-4-5" (dot vs dash in the version) resolve to the same model.
42
+ const normalize = (s) => s.toLowerCase().replace(/\./g, "-");
43
+ const query = normalize(input);
44
+ // Score each model: prefer exact id match > id contains > name contains > provider+id contains
45
+ let bestMatch;
46
+ let bestScore = 0;
47
+ for (const m of all) {
48
+ const id = normalize(m.id);
49
+ const name = normalize(m.name);
50
+ const full = normalize(`${m.provider}/${m.id}`);
51
+ let score = 0;
52
+ if (id === query || full === query) {
53
+ score = 100; // exact
54
+ }
55
+ else if (id.includes(query) || full.includes(query)) {
56
+ score = 60 + (query.length / id.length) * 30; // substring, prefer tighter matches
57
+ }
58
+ else if (name.includes(query)) {
59
+ score = 40 + (query.length / name.length) * 20;
60
+ }
61
+ else if (
62
+ // A trailing date-stamp token (e.g. "20251001") is optional, so a
63
+ // date-pinned config like "claude-haiku-4-5-20251001" still matches an
64
+ // undated registry id like "claude-haiku-4-5".
65
+ query
66
+ .split(/[\s\-/]+/)
67
+ .every(part => /^\d{8}$/.test(part) || id.includes(part) || name.includes(part) || m.provider.toLowerCase().includes(part))) {
68
+ score = 20; // all parts present somewhere
69
+ }
70
+ if (score > bestScore) {
71
+ bestScore = score;
72
+ bestMatch = m;
73
+ }
74
+ }
75
+ if (bestMatch && bestScore >= 20) {
76
+ const found = registry.find(bestMatch.provider, bestMatch.id);
77
+ if (found)
78
+ return found;
79
+ }
80
+ // 3. Provider fallback: a "provider/modelId" query that didn't match under the
81
+ // named provider (exact or fuzzy above) retries against all providers. The
82
+ // named provider is preferred when present; this only kicks in when it isn't,
83
+ // so the same model from another provider beats falling back to "inherit".
84
+ if (slashIdx !== -1) {
85
+ const bare = resolveModel(input.slice(slashIdx + 1), registry);
86
+ if (typeof bare !== "string")
87
+ return bare;
88
+ }
89
+ // 4. No match — list available models
90
+ const modelList = all
91
+ .map(m => ` ${m.provider}/${m.id}`)
92
+ .sort()
93
+ .join("\n");
94
+ return `Model not found: "${input}".\n\nAvailable models:\n${modelList}`;
95
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * model-scope.ts — `scopeModels` policy, shared by the top-level Agent tool and
3
+ * the nested delegation tools so a nested spawn can't escape the allowlist the
4
+ * top-level path enforces.
5
+ *
6
+ * State lives here (rather than in an index.ts closure) for the same reason
7
+ * `disableDefaults` lives in agent-types.ts: both entry points need it.
8
+ */
9
+ import { type ModelRegistryRef } from "./enabled-models.js";
10
+ export declare function isScopeModelsEnabled(): boolean;
11
+ export declare function setScopeModelsEnabled(enabled: boolean): void;
12
+ export type ModelScopeVerdict =
13
+ /** In scope, or nothing to validate against (feature off / no allowlist). */
14
+ {
15
+ kind: "ok";
16
+ }
17
+ /** Caller-supplied out-of-scope choice — refuse the spawn with this message. */
18
+ | {
19
+ kind: "error";
20
+ message: string;
21
+ }
22
+ /** Frontmatter-pinned or parent-inherited — proceed, but tell the user. */
23
+ | {
24
+ kind: "warn";
25
+ message: string;
26
+ };
27
+ /**
28
+ * Check the effective resolved model against the user's enabledModels list.
29
+ *
30
+ * scopeModels guards against *runtime* LLM choices, not user-level config:
31
+ * - Caller-supplied out-of-scope → hard error (the orchestrator made an explicit
32
+ * out-of-scope choice; surface it so it picks differently).
33
+ * - Frontmatter-pinned or parent-inherited out-of-scope → warn but proceed (the
34
+ * user authored/installed this agent or chose the parent's model; trust it).
35
+ */
36
+ export declare function checkModelScope(args: {
37
+ model: {
38
+ provider: string;
39
+ id: string;
40
+ } | undefined;
41
+ cwd: string;
42
+ modelRegistry: ModelRegistryRef;
43
+ /** True when the model came from the tool call rather than frontmatter. */
44
+ callerSupplied: boolean;
45
+ /** Display name used in the warning toast. */
46
+ agentLabel: string;
47
+ /** The raw `model:` input, when there was one. */
48
+ modelInput?: string;
49
+ }): ModelScopeVerdict;
@@ -0,0 +1,48 @@
1
+ /**
2
+ * model-scope.ts — `scopeModels` policy, shared by the top-level Agent tool and
3
+ * the nested delegation tools so a nested spawn can't escape the allowlist the
4
+ * top-level path enforces.
5
+ *
6
+ * State lives here (rather than in an index.ts closure) for the same reason
7
+ * `disableDefaults` lives in agent-types.ts: both entry points need it.
8
+ */
9
+ import { isModelInScope, readEnabledModels, resolveEnabledModels } from "./enabled-models.js";
10
+ /**
11
+ * When enabled, subagent model choices are validated against `enabledModels`
12
+ * from pi's settings — both global `<agentDir>/settings.json` and project-local
13
+ * `<cwd>/.pi/settings.json` (project overrides global). Off by default; opt-in
14
+ * via `/agents → Settings`. See the SubagentsSettings.scopeModels docstring for
15
+ * the hard-error vs warn-and-proceed policy and its rationale.
16
+ */
17
+ let scopeModelsEnabled = false;
18
+ export function isScopeModelsEnabled() { return scopeModelsEnabled; }
19
+ export function setScopeModelsEnabled(enabled) { scopeModelsEnabled = enabled; }
20
+ /**
21
+ * Check the effective resolved model against the user's enabledModels list.
22
+ *
23
+ * scopeModels guards against *runtime* LLM choices, not user-level config:
24
+ * - Caller-supplied out-of-scope → hard error (the orchestrator made an explicit
25
+ * out-of-scope choice; surface it so it picks differently).
26
+ * - Frontmatter-pinned or parent-inherited out-of-scope → warn but proceed (the
27
+ * user authored/installed this agent or chose the parent's model; trust it).
28
+ */
29
+ export function checkModelScope(args) {
30
+ const { model, cwd, modelRegistry, callerSupplied, agentLabel, modelInput } = args;
31
+ if (!scopeModelsEnabled || !model)
32
+ return { kind: "ok" };
33
+ const allowed = resolveEnabledModels(readEnabledModels(cwd), modelRegistry, cwd);
34
+ if (!allowed || isModelInScope(model, allowed))
35
+ return { kind: "ok" };
36
+ if (callerSupplied) {
37
+ const list = [...allowed].sort().map(m => ` ${m}`).join("\n");
38
+ return {
39
+ kind: "error",
40
+ message: `Model not in scope: "${modelInput}".\n\nAllowed models (from enabledModels):\n${list}`,
41
+ };
42
+ }
43
+ const modelLabel = modelInput ?? `${model.provider}/${model.id}`;
44
+ return {
45
+ kind: "warn",
46
+ message: `Agent "${agentLabel}" using out-of-scope model "${modelLabel}"`,
47
+ };
48
+ }
@@ -0,0 +1,55 @@
1
+ import type { Model } from "@earendil-works/pi-ai";
2
+ import { type AgentSession, type ExtensionAPI, type ExtensionContext, type ToolDefinition } from "@earendil-works/pi-coding-agent";
3
+ import type { AgentInvocation, AgentRecord, IsolationMode, ThinkingLevel } from "./types.js";
4
+ export declare function getMaxSubagentDepth(): number;
5
+ export declare function setMaxSubagentDepth(n: number): void;
6
+ interface NestedSpawnOptions {
7
+ description: string;
8
+ model?: Model<any>;
9
+ maxTurns?: number;
10
+ isolated?: boolean;
11
+ inheritContext?: boolean;
12
+ thinkingLevel?: ThinkingLevel;
13
+ isBackground?: boolean;
14
+ isolation?: IsolationMode;
15
+ invocation?: AgentInvocation;
16
+ signal?: AbortSignal;
17
+ onAssistantUsage?: (usage: {
18
+ input: number;
19
+ output: number;
20
+ cacheWrite: number;
21
+ }) => void;
22
+ onSessionCreated?: (session: AgentSession) => void;
23
+ depth: number;
24
+ parentAgentId: string;
25
+ maxSubagentDepth: number;
26
+ configCwd?: string;
27
+ rootSessionId?: string;
28
+ }
29
+ export interface NestedAgentManager {
30
+ spawn(pi: ExtensionAPI, ctx: ExtensionContext, type: string, prompt: string, options: NestedSpawnOptions): string;
31
+ /** Resolves once the spawned agent is running; rejects on a startup failure. */
32
+ awaitStartup(id: string): Promise<void>;
33
+ spawnAndWait(pi: ExtensionAPI, ctx: ExtensionContext, type: string, prompt: string, options: Omit<NestedSpawnOptions, "isBackground">,
34
+ /** Fires synchronously after spawn, before the session exists — where the transcript is attached. */
35
+ onSpawned?: (id: string) => void): Promise<{
36
+ id: string;
37
+ record: AgentRecord;
38
+ }>;
39
+ getRecord(id: string): AgentRecord | undefined;
40
+ resume(id: string, prompt: string, signal?: AbortSignal): Promise<AgentRecord | undefined>;
41
+ }
42
+ export interface NestedToolContext {
43
+ manager: NestedAgentManager;
44
+ pi: ExtensionAPI;
45
+ parentAgentId: string;
46
+ depth: number;
47
+ maxSubagentDepth: number;
48
+ /** "all" = any enabled agent; string[] = only those types. Never empty. */
49
+ allowedSubagents: "all" | string[];
50
+ /** Root used for agent/config discovery; may differ from the agent's working directory. */
51
+ configCwd: string;
52
+ }
53
+ /** Build child-safe orchestration tools scoped to one parent agent instance. */
54
+ export declare function createNestedSubagentTools(context: NestedToolContext): ToolDefinition[];
55
+ export {};