@nredd/pi-subagents 0.0.0-stage → 0.22.0-nredd.5

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 (70) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1244 -2
  3. package/package.json +75 -4
  4. package/src/abortable.ts +43 -0
  5. package/src/agent-color.ts +161 -0
  6. package/src/agent-file-toggle.ts +297 -0
  7. package/src/agent-manager.ts +1874 -0
  8. package/src/agent-runner.ts +1552 -0
  9. package/src/agent-source-badge.ts +75 -0
  10. package/src/agent-types.ts +346 -0
  11. package/src/child-context.ts +15 -0
  12. package/src/clock.ts +25 -0
  13. package/src/completion-outbox.ts +125 -0
  14. package/src/context.ts +58 -0
  15. package/src/cross-extension-rpc.ts +221 -0
  16. package/src/custom-agents.ts +436 -0
  17. package/src/default-agents.ts +126 -0
  18. package/src/detached-results.ts +134 -0
  19. package/src/enabled-models.ts +180 -0
  20. package/src/enterprise-local.ts +66 -0
  21. package/src/env.ts +33 -0
  22. package/src/group-join.ts +148 -0
  23. package/src/index.ts +4423 -0
  24. package/src/invocation-config.ts +189 -0
  25. package/src/memory.ts +179 -0
  26. package/src/mention-clone.ts +195 -0
  27. package/src/mention.ts +141 -0
  28. package/src/model-call.ts +83 -0
  29. package/src/model-resolver.ts +266 -0
  30. package/src/model-scope.ts +70 -0
  31. package/src/nested-tools.ts +448 -0
  32. package/src/output-file.ts +164 -0
  33. package/src/package-resources.ts +624 -0
  34. package/src/prompts.ts +156 -0
  35. package/src/quota-admission.ts +99 -0
  36. package/src/schedule-store.ts +153 -0
  37. package/src/schedule.ts +446 -0
  38. package/src/settings.ts +728 -0
  39. package/src/skill-loader.ts +137 -0
  40. package/src/startup-error.ts +29 -0
  41. package/src/status-note.ts +90 -0
  42. package/src/structured-output.ts +130 -0
  43. package/src/types.ts +404 -0
  44. package/src/ui/agent-mention.ts +216 -0
  45. package/src/ui/agent-row.ts +235 -0
  46. package/src/ui/agent-widget.ts +692 -0
  47. package/src/ui/conversation-viewer.ts +832 -0
  48. package/src/ui/fleet-list.ts +675 -0
  49. package/src/ui/notification-view.ts +120 -0
  50. package/src/ui/schedule-menu.ts +105 -0
  51. package/src/ui/select-item.ts +45 -0
  52. package/src/ui/viewer-keys.ts +39 -0
  53. package/src/ui/workflow-card.ts +462 -0
  54. package/src/ui/workflow-dialog.ts +1115 -0
  55. package/src/ui/workflow-menu.ts +193 -0
  56. package/src/usage.ts +167 -0
  57. package/src/workflow/collisions.ts +123 -0
  58. package/src/workflow/entry.ts +47 -0
  59. package/src/workflow/host.ts +401 -0
  60. package/src/workflow/journal.ts +164 -0
  61. package/src/workflow/json-schema.ts +129 -0
  62. package/src/workflow/meta.ts +326 -0
  63. package/src/workflow/progress.ts +549 -0
  64. package/src/workflow/runtime.ts +1216 -0
  65. package/src/workflow/saved.ts +259 -0
  66. package/src/workflow/task.ts +302 -0
  67. package/src/workflow/tool-description.ts +200 -0
  68. package/src/workflow/worker-source.ts +781 -0
  69. package/src/worktree.ts +230 -0
  70. package/src/xml.ts +13 -0
package/src/mention.ts ADDED
@@ -0,0 +1,141 @@
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
+ /**
23
+ * Suggestion trigger: `@` at a token boundary plus the partial handle typed so
24
+ * far. Ported from Claude Code, including the CJK sentence-ending punctuation
25
+ * it accepts as a boundary.
26
+ */
27
+ export const MENTION_TRIGGER = /(^|[\s。、?!])@([\w-]*)$/;
28
+
29
+ /** Send grammar: leading `@handle`, then a non-empty message. */
30
+ const MENTION_SEND = /^@([\w-]+)\s+([\s\S]+)$/;
31
+
32
+ /**
33
+ * Upper bound on a handle, matching Claude Code's `dSS`. Nothing here generates
34
+ * a name this long, but an agent type or a model-supplied name can be arbitrary
35
+ * text, and an unbounded handle would wrap the suggestion popup.
36
+ */
37
+ const MAX_HANDLE_LENGTH = 64;
38
+
39
+ /**
40
+ * Handles that address something other than a subagent, and so can never be
41
+ * allocated to one. Claude Code reserves exactly this name (`Vq = "main"`),
42
+ * refusing it at spawn and routing it to the main conversation instead.
43
+ */
44
+ const RESERVED_HANDLES: ReadonlySet<string> = new Set(["main"]);
45
+
46
+ /** Whether `@handle` names the main conversation rather than any subagent. */
47
+ export function isReservedHandle(handle: string): boolean {
48
+ return RESERVED_HANDLES.has(handle.toLowerCase());
49
+ }
50
+
51
+ /** Slug of an agent type or name, restricted to the `[\w-]` the grammar allows. */
52
+ export function handleBase(type: string): string {
53
+ const slug = type.toLowerCase()
54
+ .replace(/[^a-z0-9_-]+/g, "-")
55
+ .replace(/^-+|-+$/g, "")
56
+ .slice(0, MAX_HANDLE_LENGTH)
57
+ // The slice can land mid-run and leave the trailing hyphen back.
58
+ .replace(/-+$/, "");
59
+ return slug || "agent";
60
+ }
61
+
62
+ /**
63
+ * `base`, else `base-2`, `base-3`, … — the first form that is neither `taken`
64
+ * nor reserved. Callers pass one shared `taken` set covering type-derived
65
+ * handles and model-supplied aliases alike, so the two can never collide.
66
+ */
67
+ export function assignHandle(base: string, taken: ReadonlySet<string>): string {
68
+ let candidate = base;
69
+ let n = 1;
70
+ while (taken.has(candidate) || RESERVED_HANDLES.has(candidate)) {
71
+ n++;
72
+ candidate = `${base}-${n}`;
73
+ }
74
+ return candidate;
75
+ }
76
+
77
+ /**
78
+ * Map a typed handle back to a registered agent type, so `@explore fix it`
79
+ * reaches the Explore agent even when no instance has ever run. `handleBase` is
80
+ * the single source of truth in both directions, so a type is addressable by
81
+ * exactly the handle its instances would be given.
82
+ */
83
+ export function resolveHandleToType(handle: string, types: readonly string[]): string | undefined {
84
+ const wanted = handle.toLowerCase();
85
+ // A type slugging to a reserved name is unaddressable rather than shadowing
86
+ // it — `assignHandle` refuses that name too, so its instances never hold one.
87
+ if (RESERVED_HANDLES.has(wanted)) return undefined;
88
+ return types.find(type => handleBase(type) === wanted);
89
+ }
90
+
91
+ /**
92
+ * Claude Code documents `@agent-<name>` as the form you type by hand when the
93
+ * picker isn't involved. Accepted here as an exact synonym: the caller tries the
94
+ * handle as written first, so an agent genuinely called `agent-foo` still wins
95
+ * over `@agent-` + `foo`, and only falls back to this when that finds nothing.
96
+ * Returns undefined when the prefix is absent or is the whole handle.
97
+ */
98
+ export function stripAgentPrefix(handle: string): string | undefined {
99
+ const rest = /^agent-(.+)$/i.exec(handle)?.[1];
100
+ return rest || undefined;
101
+ }
102
+
103
+ /**
104
+ * A spawn needs the short description every agent surface renders. A mention
105
+ * carries no separate label, so the message itself becomes one: first line,
106
+ * whitespace collapsed, clipped to roughly the 3-5 words the Agent tool asks of
107
+ * the model.
108
+ */
109
+ export function describeMention(message: string): string {
110
+ const oneLine = message.split("\n", 1)[0].replace(/\s+/g, " ").trim();
111
+ return oneLine.length > 40 ? `${oneLine.slice(0, 39).trimEnd()}…` : oneLine;
112
+ }
113
+
114
+ /**
115
+ * What Claude Code sends the main model when a mention names an agent it could
116
+ * start. Its `@agent-<type>` mention is not a spawn at all: it becomes an
117
+ * `agent_mention` attachment, which renders to a synthetic `isMeta` user
118
+ * message placed after the user's own untouched text — no tool forcing, no
119
+ * allowed-tools narrowing, and the Task tool is not even named. The model reads
120
+ * this and calls the tool itself.
121
+ *
122
+ * Ported verbatim from the 2.1.233 bundle's attachment renderer, trailing space
123
+ * before the closing newline included, so the wording the model was trained
124
+ * against is the wording it gets. The one substitution is ours: pi's equivalent
125
+ * of Task is the `Agent` tool, and the agent listing that teaches valid
126
+ * `subagent_type` values is the tool spec rather than a separate attachment.
127
+ */
128
+ export function agentMentionReminder(type: string): string {
129
+ 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>`;
130
+ }
131
+
132
+ /**
133
+ * Split `@handle message` into its parts, or null when the text isn't a send —
134
+ * a bare handle, a leading file path, or a mention that isn't at the start.
135
+ */
136
+ export function parseMention(text: string): { handle: string; message: string } | null {
137
+ const match = MENTION_SEND.exec(text);
138
+ if (!match) return null;
139
+ const message = match[2].trim();
140
+ return message ? { handle: match[1], message } : null;
141
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * model-call.ts -- what an agent's in-flight model call is doing right now.
3
+ *
4
+ * A single model call can sit silent for minutes (long thinking, a slow
5
+ * provider), and the widget used to say `thinking…` for all of it with nothing
6
+ * to tell a busy agent from a dead stream. This tracks the call from the
7
+ * session's streaming events so every surface can say how long it has been
8
+ * thinking, how much it has written, or that it has gone quiet.
9
+ */
10
+
11
+ /** One streaming event from an assistant message, as the runner reports it. */
12
+ export type ModelCallEvent =
13
+ | { type: "start" }
14
+ | { type: "delta"; kind: "thinking" | "writing"; chars: number }
15
+ /** A stream event that carries no text (block boundaries): proof of life only. */
16
+ | { type: "beat" }
17
+ | { type: "end" };
18
+
19
+ export interface ModelCallState {
20
+ startedAt: number;
21
+ /** The last stream event of any kind, which is what `stalled?` is measured from. */
22
+ lastEventAt: number;
23
+ kind: "thinking" | "writing";
24
+ /** Characters streamed as text or tool-call arguments this call. */
25
+ writtenChars: number;
26
+ }
27
+
28
+ /** Silence this long mid-call reads as stalled. */
29
+ export const STALL_MS = 2 * 60_000;
30
+
31
+ /** Rough characters per token, for a figure shown before the provider reports usage. */
32
+ const CHARS_PER_TOKEN = 4;
33
+
34
+ /** Fold one event into `current`; `undefined` means no call is in flight. */
35
+ export function applyModelCallEvent(
36
+ current: ModelCallState | undefined,
37
+ event: ModelCallEvent,
38
+ now: number,
39
+ ): ModelCallState | undefined {
40
+ switch (event.type) {
41
+ case "start":
42
+ return { startedAt: now, lastEventAt: now, kind: "thinking", writtenChars: 0 };
43
+ case "end":
44
+ return undefined;
45
+ case "beat":
46
+ return current ? { ...current, lastEventAt: now } : current;
47
+ case "delta": {
48
+ const base = current ?? { startedAt: now, lastEventAt: now, kind: "thinking" as const, writtenChars: 0 };
49
+ return {
50
+ ...base,
51
+ lastEventAt: now,
52
+ // Once it has started writing, a late thinking block does not flip it back.
53
+ kind: event.kind === "writing" ? "writing" : base.kind,
54
+ writtenChars: base.writtenChars + (event.kind === "writing" ? event.chars : 0),
55
+ };
56
+ }
57
+ }
58
+ }
59
+
60
+ /** `41s`, `2m41s`, `1h05m`. */
61
+ export function formatClock(ms: number): string {
62
+ const total = Math.max(0, Math.floor(ms / 1000));
63
+ if (total < 60) return `${total}s`;
64
+ const minutes = Math.floor(total / 60);
65
+ if (minutes < 60) return `${minutes}m${String(total % 60).padStart(2, "0")}s`;
66
+ return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, "0")}m`;
67
+ }
68
+
69
+ /**
70
+ * `thinking · 2m41s`, `writing · 3.2k tok`, or `stalled? · 2m41s`; undefined
71
+ * when no call is in flight.
72
+ */
73
+ export function describeModelCall(state: ModelCallState | undefined, now: number): string | undefined {
74
+ if (!state) return undefined;
75
+ const silent = now - state.lastEventAt;
76
+ if (silent >= STALL_MS) return `stalled? · ${formatClock(silent)}`;
77
+ if (state.kind === "writing") {
78
+ // `950`, `3.2k`.
79
+ const tokens = Math.round(state.writtenChars / CHARS_PER_TOKEN);
80
+ return `writing · ${tokens < 1_000 ? `${tokens}` : `${(tokens / 1_000).toFixed(1).replace(/\.0$/, "")}k`} tok`;
81
+ }
82
+ return `thinking · ${formatClock(now - state.startedAt)}`;
83
+ }
@@ -0,0 +1,266 @@
1
+ /**
2
+ * Model resolution: exact match ("provider/modelId") with fuzzy fallback.
3
+ */
4
+
5
+ export interface ModelEntry {
6
+ id: string;
7
+ name: string;
8
+ provider: string;
9
+ }
10
+
11
+ export interface ModelRegistry {
12
+ find(provider: string, modelId: string): any;
13
+ getAll(): any[];
14
+ getAvailable?(): any[];
15
+ }
16
+
17
+ /** Logical model aliases supplied only by trusted global machine configuration. */
18
+ let modelAliases = new Map<string, string[]>();
19
+
20
+ /**
21
+ * Replace the configured logical aliases. Alias keys are case-insensitive;
22
+ * candidates are canonical provider/model IDs and are resolved against the
23
+ * available registry at dispatch time.
24
+ */
25
+ export function setModelAliases(aliases: Record<string, string[]> | undefined): void {
26
+ modelAliases = new Map(
27
+ Object.entries(aliases ?? {}).map(([alias, candidates]) => [alias.toLowerCase(), [...candidates]]),
28
+ );
29
+ }
30
+
31
+ /**
32
+ * Per-agent model overrides from trusted global configuration: agent `type`
33
+ * (or `"*"`) -> model input. Resolved through `resolveModel`, so a value may be
34
+ * an alias, an exact `provider/id`, or a fuzzy name.
35
+ */
36
+ let agentModels = new Map<string, string>();
37
+
38
+ /** Replace the configured per-agent model map. Keys are matched case-insensitively. */
39
+ export function setAgentModels(models: Record<string, string> | undefined): void {
40
+ agentModels = new Map(Object.entries(models ?? {}).map(([type, model]) => [type.toLowerCase(), model]));
41
+ }
42
+
43
+ /**
44
+ * The model input a spawn of `type` should use when the caller named none:
45
+ * `agentModels[type]`, then `agentModels["*"]`, then the agent definition's own
46
+ * `model:` (`definitionModel`). The parent model is the floor, applied by the
47
+ * caller when this returns `undefined`.
48
+ */
49
+ export function configuredAgentModel(type: string, definitionModel: string | undefined): string | undefined {
50
+ return agentModels.get(type.toLowerCase()) ?? agentModels.get("*") ?? definitionModel;
51
+ }
52
+
53
+ /**
54
+ * Narrows fuzzy candidates to the models the user enabled (pi's `enabledModels`),
55
+ * as lowercase `provider/id` keys. Injected rather than imported so this module
56
+ * stays free of settings I/O; `undefined` means no scope is configured.
57
+ */
58
+ export type ModelScopeProvider = (registry: ModelRegistry) => ReadonlySet<string> | undefined;
59
+
60
+ let modelScopeProvider: ModelScopeProvider | undefined;
61
+
62
+ /** Install (or clear) the enabled-model scope used to rank fuzzy matches. */
63
+ export function setModelScopeProvider(provider: ModelScopeProvider | undefined): void {
64
+ modelScopeProvider = provider;
65
+ }
66
+
67
+ /** A copy for diagnostics and tests; callers cannot mutate resolver state. */
68
+ export function getModelAliases(): ReadonlyMap<string, readonly string[]> {
69
+ return new Map([...modelAliases].map(([alias, candidates]) => [alias, [...candidates]]));
70
+ }
71
+
72
+ /**
73
+ * Both display forms of a model. The short one goes on tight rows (the widget,
74
+ * the Agent tool result), the canonical one where there is room to disambiguate
75
+ * two providers serving a similarly-named model (the conversation viewer).
76
+ *
77
+ * One function, because `index.ts` labels the model it resolved before the run
78
+ * and `agent-manager.ts` relabels it from the live session afterwards — the two
79
+ * must agree or the label would visibly change the moment the session starts.
80
+ */
81
+ export function describeModel(
82
+ model: { provider: string; id: string; name?: string },
83
+ ): { modelName: string; modelId: string } {
84
+ return {
85
+ modelName: (model.name ?? model.id).replace(/^Claude\s+/i, "").toLowerCase(),
86
+ modelId: `${model.provider}/${model.id}`,
87
+ };
88
+ }
89
+
90
+ /** API id pi gives virtual catalog entries such as `router/default`; they never reach a provider. */
91
+ const VIRTUAL_MODEL_API = "pi-virtual";
92
+
93
+ /** Whether `model` is a virtual (router) selection rather than a physical model. */
94
+ export function isVirtualModel(model: { api?: string } | undefined): boolean {
95
+ return model?.api === VIRTUAL_MODEL_API;
96
+ }
97
+
98
+ /** The pre-response label of a virtual selection: no physical model has answered yet. */
99
+ export function describeVirtualModel(model: { provider: string; id: string; name?: string }): {
100
+ modelName: string;
101
+ modelId: string;
102
+ } {
103
+ const described = describeModel(model);
104
+ return { ...described, modelName: `${described.modelName} (routing)` };
105
+ }
106
+
107
+ /**
108
+ * The physical model behind an assistant message, or `undefined` when the
109
+ * message names none (an error from failed routing carries the virtual model).
110
+ *
111
+ * With a virtual selection (`agentModels["*"] = "router/default"`) the session
112
+ * model is the router; only responses record where a request actually went, so
113
+ * rows must be relabelled from them. `registry` supplies the display name, and
114
+ * is optional: without it the id stands in.
115
+ */
116
+ export function describePhysicalModel(
117
+ message: { api?: string; provider?: string; model?: string } | undefined,
118
+ registry?: { find?(provider: string, modelId: string): { name?: string } | undefined },
119
+ ): { modelName: string; modelId: string } | undefined {
120
+ if (!message?.provider || !message.model || isVirtualModel(message)) return undefined;
121
+ const found = registry?.find?.(message.provider, message.model);
122
+ return describeModel({ provider: message.provider, id: message.model, name: found?.name });
123
+ }
124
+
125
+ /** Parsed `[major, minor]` of a model id, or undefined when the family has no known scheme. */
126
+ export type ModelVersion = readonly [major: number, minor: number];
127
+
128
+ /**
129
+ * Pull a version out of a model id (provider prefix ignored):
130
+ * - `claude-<family>-<n>[-<n>]`, e.g. `claude-opus-4-6`, `claude-opus-5`
131
+ * - `claude-<n>[-<n>]-<family>`, e.g. `claude-3-5-sonnet-20241022`
132
+ * - `gpt-<n>[.<n>]-<variant>`, e.g. `gpt-6.1-sol`
133
+ * A minor is one or two digits, so a trailing `-20250514` date stamp is never
134
+ * read as one. Dots and dashes are interchangeable between the parts.
135
+ */
136
+ export function parseModelVersion(id: string): ModelVersion | undefined {
137
+ const bare = id.slice(id.lastIndexOf("/") + 1).toLowerCase();
138
+ const claude = /^claude-[a-z]+-(\d{1,2})(?:[-.](\d{1,2})(?!\d))?(?:-|$)/.exec(bare)
139
+ ?? /^claude-(\d{1,2})(?:[-.](\d{1,2})(?!\d))?-[a-z]/.exec(bare);
140
+ const match = claude ?? /^gpt-(\d+)(?:[.-](\d{1,2})(?!\d))?(?:-|$)/.exec(bare);
141
+ if (!match) return undefined;
142
+ return [Number(match[1]), Number(match[2] ?? 0)];
143
+ }
144
+
145
+ /** Descending version order; an unversioned model sorts after every versioned one. */
146
+ function compareVersionsDesc(a: ModelVersion | undefined, b: ModelVersion | undefined): number {
147
+ if (a && b) return b[0] - a[0] || b[1] - a[1];
148
+ return a ? -1 : b ? 1 : 0;
149
+ }
150
+
151
+ /**
152
+ * Resolve a model string to a Model instance.
153
+ * Tries exact match first ("provider/modelId"), then fuzzy match against all available models.
154
+ * Returns the Model on success, or an error message string on failure.
155
+ */
156
+ export function resolveModel(
157
+ input: string,
158
+ registry: ModelRegistry,
159
+ ): any | string {
160
+ const aliasCandidates = modelAliases.get(input.trim().toLowerCase());
161
+ if (aliasCandidates) {
162
+ for (const candidate of aliasCandidates) {
163
+ const resolved = resolveCanonicalModel(candidate, registry);
164
+ if (typeof resolved !== "string") return resolved;
165
+ }
166
+ return `Model alias "${input}" has no available candidate.\n\nCandidates:\n${aliasCandidates.map(candidate => ` ${candidate}`).join("\n")}`;
167
+ }
168
+ return resolveCanonicalModel(input, registry);
169
+ }
170
+
171
+ /**
172
+ * Pick among fuzzy candidates. Restricted to the enabled model scope when one is
173
+ * configured and any candidate is in it, then newest parsed version first, then
174
+ * match score. A bare family name like "opus" therefore means the newest opus
175
+ * the user has enabled, not whichever id happens to be shortest.
176
+ */
177
+ function rankFuzzy(matches: { entry: ModelEntry; score: number }[], registry: ModelRegistry): ModelEntry | undefined {
178
+ const scope = modelScopeProvider?.(registry);
179
+ const scoped = scope ? matches.filter(c => scope.has(`${c.entry.provider}/${c.entry.id}`.toLowerCase())) : [];
180
+ const pool = scoped.length > 0 ? scoped : matches;
181
+ const ranked = pool
182
+ .map(c => ({ ...c, version: parseModelVersion(c.entry.id) }))
183
+ .sort((a, b) => compareVersionsDesc(a.version, b.version) || b.score - a.score);
184
+ return ranked[0]?.entry;
185
+ }
186
+
187
+ /** Resolve an exact or fuzzy provider/model request without consulting aliases. */
188
+ function resolveCanonicalModel(
189
+ input: string,
190
+ registry: ModelRegistry,
191
+ ): any | string {
192
+ // Available models (those with auth configured)
193
+ const all = (registry.getAvailable?.() ?? registry.getAll()) as ModelEntry[];
194
+ const availableSet = new Set(all.map(m => `${m.provider}/${m.id}`.toLowerCase()));
195
+
196
+ // 1. Exact match: "provider/modelId" — only if available (has auth)
197
+ const slashIdx = input.indexOf("/");
198
+ if (slashIdx !== -1) {
199
+ const provider = input.slice(0, slashIdx);
200
+ const modelId = input.slice(slashIdx + 1);
201
+ if (availableSet.has(input.toLowerCase())) {
202
+ const found = registry.find(provider, modelId);
203
+ if (found) return found;
204
+ }
205
+ }
206
+
207
+ // 2. Fuzzy match against available models. Normalize separators so cosmetic
208
+ // punctuation differences still match — e.g. "claude-haiku-4.5" and
209
+ // "claude-haiku-4-5" (dot vs dash in the version) resolve to the same model.
210
+ const normalize = (s: string) => s.toLowerCase().replace(/\./g, "-");
211
+ const query = normalize(input);
212
+
213
+ // Score each model: prefer exact id match > id contains > name contains > provider+id contains
214
+ const matches: { entry: ModelEntry; score: number }[] = [];
215
+
216
+ for (const m of all) {
217
+ const id = normalize(m.id);
218
+ const name = normalize(m.name);
219
+ const full = normalize(`${m.provider}/${m.id}`);
220
+
221
+ let score = 0;
222
+ if (id === query || full === query) {
223
+ score = 100; // exact
224
+ } else if (id.includes(query) || full.includes(query)) {
225
+ score = 60 + (query.length / id.length) * 30; // substring, prefer tighter matches
226
+ } else if (name.includes(query)) {
227
+ score = 40 + (query.length / name.length) * 20;
228
+ } else if (
229
+ // A trailing date-stamp token (e.g. "20251001") is optional, so a
230
+ // date-pinned config like "claude-haiku-4-5-20251001" still matches an
231
+ // undated registry id like "claude-haiku-4-5".
232
+ query
233
+ .split(/[\s\-/]+/)
234
+ .every(part => /^\d{8}$/.test(part) || id.includes(part) || name.includes(part) || m.provider.toLowerCase().includes(part))
235
+ ) {
236
+ score = 20; // all parts present somewhere
237
+ }
238
+
239
+ if (score >= 20) matches.push({ entry: m, score });
240
+ }
241
+
242
+ // An exact id (or provider/id) is the caller naming a model, not describing
243
+ // one: it wins outright, whatever the scope or any newer sibling.
244
+ const exact = matches.find(c => c.score === 100);
245
+ const bestMatch = exact?.entry ?? rankFuzzy(matches, registry);
246
+ if (bestMatch) {
247
+ const found = registry.find(bestMatch.provider, bestMatch.id);
248
+ if (found) return found;
249
+ }
250
+
251
+ // 3. Provider fallback: a "provider/modelId" query that didn't match under the
252
+ // named provider (exact or fuzzy above) retries against all providers. The
253
+ // named provider is preferred when present; this only kicks in when it isn't,
254
+ // so the same model from another provider beats falling back to "inherit".
255
+ if (slashIdx !== -1) {
256
+ const bare = resolveCanonicalModel(input.slice(slashIdx + 1), registry);
257
+ if (typeof bare !== "string") return bare;
258
+ }
259
+
260
+ // 4. No match — list available models
261
+ const modelList = all
262
+ .map(m => ` ${m.provider}/${m.id}`)
263
+ .sort()
264
+ .join("\n");
265
+ return `Model not found: "${input}".\n\nAvailable models:\n${modelList}`;
266
+ }
@@ -0,0 +1,70 @@
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
+
10
+ import { isModelInScope, type ModelRegistryRef, readEnabledModels, resolveEnabledModels } from "./enabled-models.js";
11
+
12
+ /**
13
+ * When enabled, subagent model choices are validated against `enabledModels`
14
+ * from pi's settings — both global `<agentDir>/settings.json` and project-local
15
+ * `<cwd>/.pi/settings.json` (project overrides global). Off by default; opt-in
16
+ * via `/agents → Settings`. See the SubagentsSettings.scopeModels docstring for
17
+ * the hard-error vs warn-and-proceed policy and its rationale.
18
+ */
19
+ let scopeModelsEnabled = false;
20
+
21
+ export function isScopeModelsEnabled(): boolean { return scopeModelsEnabled; }
22
+ export function setScopeModelsEnabled(enabled: boolean): void { scopeModelsEnabled = enabled; }
23
+
24
+ export type ModelScopeVerdict =
25
+ /** In scope, or nothing to validate against (feature off / no allowlist). */
26
+ | { kind: "ok" }
27
+ /** Caller-supplied out-of-scope choice — refuse the spawn with this message. */
28
+ | { kind: "error"; message: string }
29
+ /** Frontmatter-pinned or parent-inherited — proceed, but tell the user. */
30
+ | { kind: "warn"; message: string };
31
+
32
+ /**
33
+ * Check the effective resolved model against the user's enabledModels list.
34
+ *
35
+ * scopeModels guards against *runtime* LLM choices, not user-level config:
36
+ * - Caller-supplied out-of-scope → hard error (the orchestrator made an explicit
37
+ * out-of-scope choice; surface it so it picks differently).
38
+ * - Frontmatter-pinned or parent-inherited out-of-scope → warn but proceed (the
39
+ * user authored/installed this agent or chose the parent's model; trust it).
40
+ */
41
+ export function checkModelScope(args: {
42
+ model: { provider: string; id: string } | undefined;
43
+ cwd: string;
44
+ modelRegistry: ModelRegistryRef;
45
+ /** True when the model came from the tool call rather than frontmatter. */
46
+ callerSupplied: boolean;
47
+ /** Display name used in the warning toast. */
48
+ agentLabel: string;
49
+ /** The raw `model:` input, when there was one. */
50
+ modelInput?: string;
51
+ }): ModelScopeVerdict {
52
+ const { model, cwd, modelRegistry, callerSupplied, agentLabel, modelInput } = args;
53
+ if (!scopeModelsEnabled || !model) return { kind: "ok" };
54
+
55
+ const allowed = resolveEnabledModels(readEnabledModels(cwd), modelRegistry, cwd);
56
+ if (!allowed || isModelInScope(model, allowed)) return { kind: "ok" };
57
+
58
+ if (callerSupplied) {
59
+ const list = [...allowed].sort().map(m => ` ${m}`).join("\n");
60
+ return {
61
+ kind: "error",
62
+ message: `Model not in scope: "${modelInput}".\n\nAllowed models (from enabledModels):\n${list}`,
63
+ };
64
+ }
65
+ const modelLabel = modelInput ?? `${model.provider}/${model.id}`;
66
+ return {
67
+ kind: "warn",
68
+ message: `Agent "${agentLabel}" using out-of-scope model "${modelLabel}"`,
69
+ };
70
+ }