@herbertgao/pi-extensions 2026.11.1 → 2026.11.3

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 (76) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +14 -14
  3. package/THIRD_PARTY_NOTICES.md +2 -2
  4. package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +6 -0
  5. package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +1 -1
  6. package/node_modules/@herbertgao/pi-cc-extensions/README.md +1 -1
  7. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/compact-mode.ts +109 -16
  8. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/diff/write-execution.ts +5 -1
  9. package/node_modules/@herbertgao/pi-cc-extensions/package.json +4 -4
  10. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +12 -0
  11. package/node_modules/@herbertgao/pi-subagents/README.md +54 -42
  12. package/node_modules/@herbertgao/pi-subagents/docs/rpc.md +1 -1
  13. package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +2 -0
  14. package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
  15. package/node_modules/@herbertgao/pi-subagents/src/agent-file-toggle.ts +9 -8
  16. package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +70 -9
  17. package/node_modules/@herbertgao/pi-subagents/src/agent-record-entry.ts +183 -0
  18. package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +156 -13
  19. package/node_modules/@herbertgao/pi-subagents/src/custom-agents.ts +52 -8
  20. package/node_modules/@herbertgao/pi-subagents/src/default-agents.ts +3 -4
  21. package/node_modules/@herbertgao/pi-subagents/src/index.ts +158 -56
  22. package/node_modules/@herbertgao/pi-subagents/src/settings.ts +3 -2
  23. package/node_modules/@herbertgao/pi-subagents/src/status-note.ts +3 -1
  24. package/node_modules/@herbertgao/pi-subagents/src/types.ts +5 -0
  25. package/node_modules/@herbertgao/pi-subagents/src/ui/conversation-viewer.ts +167 -7
  26. package/node_modules/@herbertgao/pi-subagents/src/ui/viewer-keys.ts +8 -4
  27. package/node_modules/@herbertgao/pi-subagents/src/workflow/host.ts +88 -6
  28. package/node_modules/@herbertgao/pi-subagents/src/workflow/progress.ts +3 -2
  29. package/node_modules/@narumitw/pi-btw/CHANGELOG.md +259 -0
  30. package/node_modules/@narumitw/pi-btw/package.json +6 -5
  31. package/node_modules/@narumitw/pi-caffeinate/CHANGELOG.md +70 -0
  32. package/node_modules/@narumitw/pi-caffeinate/package.json +5 -4
  33. package/node_modules/pi-commandcode-provider/CHANGELOG.md +21 -0
  34. package/node_modules/pi-commandcode-provider/README.md +18 -6
  35. package/node_modules/pi-commandcode-provider/index.ts +11 -5
  36. package/node_modules/pi-commandcode-provider/package.json +1 -1
  37. package/node_modules/pi-commandcode-provider/src/api-key.ts +26 -10
  38. package/node_modules/pi-commandcode-provider/src/auth-server.ts +33 -24
  39. package/node_modules/pi-commandcode-provider/src/commandcode-catalog.ts +2 -2
  40. package/node_modules/pi-commandcode-provider/src/converters.ts +3 -61
  41. package/node_modules/pi-commandcode-provider/src/core.ts +29 -4
  42. package/node_modules/pi-commandcode-provider/src/cost.ts +32 -12
  43. package/node_modules/pi-commandcode-provider/src/oauth.ts +40 -6
  44. package/node_modules/pi-commandcode-provider/src/pricing.ts +5 -3
  45. package/node_modules/pi-commandcode-provider/src/runtime.ts +14 -7
  46. package/node_modules/pi-commandcode-provider/src/transport.ts +6 -3
  47. package/node_modules/pi-provider-qoder/README.md +40 -0
  48. package/node_modules/pi-provider-qoder/dist/index.js +64 -0
  49. package/node_modules/pi-provider-qoder/package.json +4 -3
  50. package/node_modules/pi-typesafe/README.md +3 -3
  51. package/node_modules/pi-typesafe/dist/auth.d.ts +21 -4
  52. package/node_modules/pi-typesafe/dist/auth.js +32 -7
  53. package/node_modules/pi-typesafe/dist/backends.d.ts +2 -2
  54. package/node_modules/pi-typesafe/dist/backends.js +9 -0
  55. package/node_modules/pi-typesafe/dist/client.js +7 -12
  56. package/node_modules/pi-typesafe/dist/errors.d.ts +3 -2
  57. package/node_modules/pi-typesafe/dist/errors.js +12 -10
  58. package/node_modules/pi-typesafe/dist/extension.js +14 -10
  59. package/node_modules/pi-typesafe/package.json +1 -1
  60. package/node_modules/pi-web-access/CHANGELOG.md +22 -0
  61. package/node_modules/pi-web-access/README.md +31 -12
  62. package/node_modules/pi-web-access/curator-page.ts +5 -1
  63. package/node_modules/pi-web-access/curator-server.ts +2 -0
  64. package/node_modules/pi-web-access/dist/index.js +673 -308
  65. package/node_modules/pi-web-access/dist/mcp-cli.js +666 -309
  66. package/node_modules/pi-web-access/gemini-search.ts +12 -4
  67. package/node_modules/pi-web-access/github-api.ts +1 -1
  68. package/node_modules/pi-web-access/github-extract.ts +3 -2
  69. package/node_modules/pi-web-access/index.ts +7 -3
  70. package/node_modules/pi-web-access/mcp-tool-definitions.ts +1 -1
  71. package/node_modules/pi-web-access/outcrawl.ts +204 -0
  72. package/node_modules/pi-web-access/package.json +2 -2
  73. package/node_modules/pi-web-access/sofya.ts +201 -0
  74. package/node_modules/pi-web-access/utils.ts +16 -6
  75. package/node_modules/pi-web-access/web-tool-core.ts +4 -0
  76. package/package.json +11 -11
@@ -0,0 +1,183 @@
1
+ /**
2
+ * agent-record-entry.ts — what a finished top-level agent leaves behind in the session.
3
+ *
4
+ * The live record is evicted about ten minutes after the agent finishes, read or
5
+ * not, and is gone after a reload or a restart. Its completion notification
6
+ * carries only a preview of the result and points at `get_subagent_result` for
7
+ * the rest, so that pointer has to outlive the record: the final record is
8
+ * appended to the session as this entry, and `get_subagent_result` falls back
9
+ * to it.
10
+ *
11
+ * It is also what lets `Agent({ resume })` reopen an evicted agent: the entry
12
+ * names the session file the conversation lives in, so the id the model holds
13
+ * still leads somewhere after eviction, a reload or a restart.
14
+ */
15
+
16
+ import { existsSync } from "node:fs"
17
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent"
18
+ import { resolveSpawnType } from "./agent-types.js"
19
+ import type { AgentRecord, SubagentType } from "./types.js"
20
+
21
+ /** `customType` of the session entry a finished top-level agent appends. */
22
+ export const AGENT_RECORD_ENTRY_TYPE = "subagents:record"
23
+
24
+ /** The persisted snapshot of a finished agent. */
25
+ export interface AgentRecordEntryData {
26
+ id: string
27
+ type: AgentRecord["type"]
28
+ description: string
29
+ status: AgentRecord["status"]
30
+ result?: string
31
+ error?: string
32
+ startedAt: number
33
+ completedAt?: number
34
+ /**
35
+ * The agent's persisted pi session, when it has one — what a resume reopens.
36
+ * Absent for an in-memory session (`rememberAgents` off, or
37
+ * `persist_session: false`), which leaves nothing to come back to.
38
+ */
39
+ sessionFile?: string
40
+ /** Names to give back to the reopened agent, as the `@handle` path does. */
41
+ handle?: string
42
+ alias?: string
43
+ /** Set when the agent's work lived in a worktree that is now gone — see {@link worktreeLost}. */
44
+ worktreeLost?: boolean
45
+ }
46
+
47
+ /**
48
+ * Whether the agent ran in a worktree that held its work and has since been
49
+ * removed. Settling always removes the worktree, committing any changes to a
50
+ * branch first, so only a clean one (`hasChanges: false`) leaves nothing
51
+ * behind; a run that failed before cleanup reported nothing and counts as lost.
52
+ * Claude Code draws the same line: it resumes an isolated agent outside its
53
+ * worktree only when the worktree was removed clean, and never builds a fresh
54
+ * one on resume.
55
+ */
56
+ export function worktreeLost(
57
+ record: Pick<AgentRecord, "worktree" | "worktreeResult">,
58
+ ): boolean {
59
+ return (
60
+ record.worktree !== undefined && record.worktreeResult?.hasChanges !== false
61
+ )
62
+ }
63
+
64
+ /** Snapshot a finished record for {@link AGENT_RECORD_ENTRY_TYPE}. */
65
+ export function agentRecordEntryData(
66
+ record: AgentRecord,
67
+ ): AgentRecordEntryData {
68
+ return {
69
+ id: record.id,
70
+ type: record.type,
71
+ description: record.description,
72
+ status: record.status,
73
+ result: record.result,
74
+ error: record.error,
75
+ startedAt: record.startedAt,
76
+ completedAt: record.completedAt,
77
+ sessionFile: record.sessionFile,
78
+ handle: record.handle,
79
+ alias: record.alias,
80
+ worktreeLost: worktreeLost(record) || undefined,
81
+ }
82
+ }
83
+
84
+ function isAgentRecordEntryData(data: unknown): data is AgentRecordEntryData {
85
+ if (typeof data !== "object" || data === null) return false
86
+ const { id, type, status, startedAt } = data as Record<string, unknown>
87
+ return (
88
+ typeof id === "string" &&
89
+ typeof type === "string" &&
90
+ typeof status === "string" &&
91
+ typeof startedAt === "number"
92
+ )
93
+ }
94
+
95
+ /**
96
+ * The latest persisted record of `id` on the current branch. A resumed agent
97
+ * appends a new entry on each finish, so the last one wins; an entry on an
98
+ * abandoned branch is not this conversation's.
99
+ *
100
+ * When `matchHandle` is set, the handle and alias match too, case-insensitively
101
+ * like `@handle`, and only if no entry's id is `id`. Resume leaves it off: it
102
+ * reopens whatever this returns, and a handle would reopen a saved session
103
+ * while that agent's live record still exists.
104
+ */
105
+ export function findAgentRecordEntry(
106
+ ctx: ExtensionContext,
107
+ id: string,
108
+ matchHandle = false,
109
+ ): AgentRecordEntryData | undefined {
110
+ const entries = ctx.sessionManager.getBranch()
111
+ const wanted = id.toLowerCase()
112
+ let named: AgentRecordEntryData | undefined
113
+ for (let i = entries.length - 1; i >= 0; i--) {
114
+ const entry = entries[i]
115
+ if (entry.type !== "custom" || entry.customType !== AGENT_RECORD_ENTRY_TYPE)
116
+ continue
117
+ if (!isAgentRecordEntryData(entry.data)) continue
118
+ if (entry.data.id === id) return entry.data
119
+ if (
120
+ matchHandle &&
121
+ named === undefined &&
122
+ (entry.data.handle?.toLowerCase() === wanted ||
123
+ entry.data.alias?.toLowerCase() === wanted)
124
+ ) {
125
+ named = entry.data
126
+ }
127
+ }
128
+ return named
129
+ }
130
+
131
+ /**
132
+ * Whether an evicted agent's saved conversation can be reopened, and the
133
+ * agent type to reopen it under. Shared by `@handle`, `Agent({ resume })` and
134
+ * a workflow's `resume`, so all three refuse the same cases in the same words;
135
+ * `reason` completes "Could not resume X —" and "cannot be resumed —".
136
+ *
137
+ * The file is checked here rather than left to SessionManager.open: that runs
138
+ * inside runAgent, whose rejection lands on the record as an agent error, not
139
+ * as a refusal. A `/new` in another pi window or a manual delete makes the
140
+ * conversation unrecoverable (Claude Code's `not_reachable`); `gone` marks
141
+ * that, and the no-file case, as refusals that can never clear.
142
+ *
143
+ * The Agent tool deliberately falls back to general-purpose for a type it
144
+ * cannot resolve (#183), which covers a deleted file AND a merely disabled
145
+ * one. A resume must not inherit that: reopening this conversation under a
146
+ * different agent's prompt and tools is not continuing it, and the new record
147
+ * would re-tombstone under the substitute, so the handle would never find its
148
+ * way back. `@handle` and the Agent tool reload the agent files first.
149
+ *
150
+ * `worktreeLost` refuses for good, as Claude Code does ("its worktree no
151
+ * longer exists"): the conversation's edits were made in a directory that is
152
+ * gone, and reopening it in the parent's checkout or a fresh worktree would
153
+ * continue that work somewhere it never happened.
154
+ */
155
+ export function reopenTarget(
156
+ type: string,
157
+ sessionFile: string | undefined,
158
+ worktreeLost?: boolean,
159
+ ):
160
+ | { ok: true; type: SubagentType; sessionFile: string }
161
+ | { ok: false; reason: string; gone: boolean } {
162
+ if (sessionFile === undefined) {
163
+ return {
164
+ ok: false,
165
+ reason:
166
+ "its conversation was not saved (`rememberAgents` or `persist_session` was off)",
167
+ gone: true,
168
+ }
169
+ }
170
+ if (!existsSync(sessionFile))
171
+ return { ok: false, reason: "its session is gone", gone: true }
172
+ if (worktreeLost)
173
+ return { ok: false, reason: "its worktree no longer exists", gone: true }
174
+ const dispatch = resolveSpawnType(type)
175
+ if (!dispatch.ok || dispatch.fellBackFrom !== undefined) {
176
+ return {
177
+ ok: false,
178
+ reason: `the ${type} agent is no longer available`,
179
+ gone: false,
180
+ }
181
+ }
182
+ return { ok: true, type: dispatch.type, sessionFile }
183
+ }
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { readFileSync } from "node:fs"
6
6
  import { homedir } from "node:os"
7
- import { basename, dirname, isAbsolute, join, resolve } from "node:path"
7
+ import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path"
8
8
  import type { Model } from "@earendil-works/pi-ai"
9
9
  import type {
10
10
  ExtensionContext,
@@ -102,11 +102,12 @@ export function extensionCanonicalName(extPath: string): string {
102
102
  * - a `node_modules` directory: a package never spans one (it's where OTHER
103
103
  * packages live), so reaching it means we've climbed out of the package —
104
104
  * stop before reading a consumer's or parent package's manifest.
105
- * The name is then taken only when that root's `pi.extensions` manifest actually
106
- * lists this entry. That "declares this entry" check is deliberate: our own test
107
- * fixtures live under this repo, whose root manifest declares `./src/index.ts`
108
- * as `@tintinweb/pi-subagents`, so a looser rule would misattribute every
109
- * co-located file to `pi-subagents`.
105
+ * The name is then taken only when that root's `pi.extensions` manifest declares
106
+ * this entry, either as the file itself or as a directory containing it (pi
107
+ * expands `"./dist"` to `dist/index.js`). That "declares this entry" check is
108
+ * deliberate: our own test fixtures live under this repo, whose root manifest
109
+ * declares `./src/index.ts` as `@tintinweb/pi-subagents`, so a looser rule would
110
+ * misattribute every co-located file to `pi-subagents`.
110
111
  */
111
112
  function extensionPackageName(extPath: string): string | undefined {
112
113
  // `builtin:<name>` names no file; climbing from it would read the process cwd's manifest.
@@ -130,7 +131,15 @@ function extensionPackageName(extPath: string): string | undefined {
130
131
  if (
131
132
  typeof pkg.name === "string" &&
132
133
  Array.isArray(entries) &&
133
- entries.some((e) => typeof e === "string" && resolve(dir, e) === entry)
134
+ entries.some((e) => {
135
+ if (typeof e !== "string") return false
136
+ // A declaration may name a directory (`"./dist"`) that pi resolves to
137
+ // `dist/index.js`, so an entry belongs to this package when it equals the
138
+ // declaration or lives underneath it. The `${sep}` boundary keeps that
139
+ // prefix test platform-correct (`dist-v2` never matches `"./dist"`).
140
+ const declared = resolve(dir, e)
141
+ return declared === entry || entry.startsWith(`${declared}${sep}`)
142
+ })
134
143
  ) {
135
144
  const short = pkg.name.startsWith("@")
136
145
  ? pkg.name.slice(pkg.name.indexOf("/") + 1)
@@ -237,6 +246,36 @@ export function parseExtSelectors(entries: string[]): {
237
246
  return { extNames, narrowing }
238
247
  }
239
248
 
249
+ /** pi's MCP resource tools, which it counts as MCP tools alongside `mcp__<server>__<tool>`. */
250
+ const MCP_RESOURCE_TOOL_NAMES = new Set([
251
+ "list_mcp_resources",
252
+ "list_mcp_resource_templates",
253
+ "read_mcp_resource",
254
+ ])
255
+
256
+ /** The tools that reach `codemode`/`deferred` MCP tools: neither is declared to the model. */
257
+ const MCP_BRIDGE_TOOL_NAMES = new Set(["codemode", "tool_search"])
258
+
259
+ const isMcpToolName = (name: string) =>
260
+ name.startsWith("mcp__") || MCP_RESOURCE_TOOL_NAMES.has(name)
261
+
262
+ /** Whether `name` matches one of the `tools:` `mcp__` entries: an exact name or a `*` pattern. */
263
+ function matchesToolPattern(
264
+ name: string,
265
+ patterns: readonly string[],
266
+ ): boolean {
267
+ return patterns.some((p) =>
268
+ p.includes("*")
269
+ ? new RegExp(
270
+ `^${p
271
+ .split("*")
272
+ .map((s) => s.replace(/[.+?^${}()|[\]\\]/g, "\\$&"))
273
+ .join(".*")}$`,
274
+ ).test(name)
275
+ : p === name,
276
+ )
277
+ }
278
+
240
279
  /**
241
280
  * Keep a subagent's tool scope correct as extensions register tools over time.
242
281
  *
@@ -270,6 +309,8 @@ export function installExtensionToolScope(
270
309
  disallowedSet: Set<string> | undefined
271
310
  extNames: Set<string>
272
311
  narrowing: Map<string, Set<string>>
312
+ /** Bare `mcp__` entries from `tools:`; undefined leaves MCP tools to the rules above. */
313
+ mcpToolPatterns: string[] | undefined
273
314
  /**
274
315
  * Injected `customTools` to keep active regardless of the built-in list.
275
316
  *
@@ -289,6 +330,7 @@ export function installExtensionToolScope(
289
330
  disallowedSet,
290
331
  extNames,
291
332
  narrowing,
333
+ mcpToolPatterns,
292
334
  readmitToolNames,
293
335
  nestedCallGate,
294
336
  } = ctx
@@ -312,6 +354,25 @@ export function installExtensionToolScope(
312
354
  keep.add(name)
313
355
  }
314
356
  }
357
+ // Bare `mcp__` entries, as in pi's `--tools`: only matching MCP tools stay, from
358
+ // whichever extension serves them (pi's MCP or an adapter), even one the `ext:`
359
+ // opt-in left out — and so do the bridges that reach them.
360
+ if (mcpToolPatterns) {
361
+ for (const name of keep) {
362
+ if (isMcpToolName(name) && !matchesToolPattern(name, mcpToolPatterns))
363
+ keep.delete(name)
364
+ }
365
+ for (const extension of loader.getExtensions().extensions) {
366
+ for (const name of extension.tools.keys()) {
367
+ if (disallowedSet?.has(name)) continue
368
+ if (
369
+ MCP_BRIDGE_TOOL_NAMES.has(name) ||
370
+ matchesToolPattern(name, mcpToolPatterns)
371
+ )
372
+ keep.add(name)
373
+ }
374
+ }
375
+ }
315
376
  for (const name of EXCLUDED_TOOL_NAMES) keep.delete(name)
316
377
  // Injected tools are legitimately active for this agent — re-admit them so
317
378
  // the renarrow keeps them in the active set and beforeToolCall doesn't
@@ -321,13 +382,14 @@ export function installExtensionToolScope(
321
382
  return keep
322
383
  }
323
384
 
324
- // Names this agent selects explicitly: its built-ins, injected tools, and
325
- // `ext:foo/bar` narrowings. pi activates a named tool even when it is
385
+ // Names this agent selects explicitly: its built-ins, injected tools, `ext:foo/bar`
386
+ // narrowings and exact `mcp__` entries. pi activates a named tool even when it is
326
387
  // `defaultActive: false`, as `--tools` does.
327
388
  const named = new Set([
328
389
  ...toolNames,
329
390
  ...readmitToolNames,
330
391
  ...[...narrowing.values()].flatMap((s) => [...s]),
392
+ ...(mcpToolPatterns ?? []).filter((p) => !p.includes("*")),
331
393
  ])
332
394
 
333
395
  // Activate what pi itself would: only tools declared to the model (`direct`/
@@ -836,6 +898,32 @@ function resolveConfiguredSessionDir(
836
898
  return resolve(cwd, sessionDir)
837
899
  }
838
900
 
901
+ /**
902
+ * Open an agent's saved session to continue it — or a copy of it, when the
903
+ * session belongs to another parent.
904
+ *
905
+ * pi's `/fork` and `/clone` copy the parent's entries, saved agent records
906
+ * included, so two parent sessions can each resume the same agent. Appending
907
+ * both continuations to one file would interleave two histories in it. The
908
+ * child's header names the parent that spawned it; a resume from any other
909
+ * parent forks the child alongside, exactly as pi forked the parent, and the
910
+ * copy is that parent's from then on. A header with no parent (a child
911
+ * spawned from a context without a session file) gives nothing to compare,
912
+ * so it opens in place as before.
913
+ */
914
+ function reopenSession(
915
+ file: string,
916
+ parentSessionFile: string | undefined,
917
+ sessionDir: string | undefined,
918
+ ): SessionManager {
919
+ const opened = SessionManager.open(file, sessionDir)
920
+ const owner = opened.getHeader()?.parentSession
921
+ if (owner === undefined || owner === parentSessionFile) return opened
922
+ return SessionManager.forkFrom(file, opened.getCwd(), sessionDir, {
923
+ parentSession: parentSessionFile,
924
+ })
925
+ }
926
+
839
927
  export async function runAgent(
840
928
  ctx: ExtensionContext,
841
929
  type: SubagentType,
@@ -1104,6 +1192,13 @@ export async function runAgent(
1104
1192
  }
1105
1193
  }
1106
1194
  }
1195
+ // MCP tools come from extensions, so with none loaded these entries cannot match.
1196
+ if (agentConfig?.mcpToolPatterns && noExtensions) {
1197
+ options.onToolActivity?.({
1198
+ type: "end",
1199
+ toolName: `tools-error:${agentConfig.mcpToolPatterns.join(", ")} requested by agent "${type}" need extensions, but it loads none`,
1200
+ })
1201
+ }
1107
1202
 
1108
1203
  // A subagent spawns mid-task, so a bad `extensions:`/`ext:` entry warns rather
1109
1204
  // than aborts. Two distinct misconfigurations to catch:
@@ -1234,6 +1329,49 @@ export async function runAgent(
1234
1329
  ...structuredToolNames,
1235
1330
  ])
1236
1331
 
1332
+ // As in Claude Code, refuse an agent whose `tools:` list resolved to nothing: with
1333
+ // no tool it can only narrate calls it cannot make. Extension tools register after
1334
+ // spawn (MCP once its servers connect), so they count as possible whenever an
1335
+ // extension they could come from loaded, or any `mcp__` entry can reach a bridge.
1336
+ const loadedNames = new Set(
1337
+ loader
1338
+ .getExtensions()
1339
+ .extensions.filter((e) => e.path !== `<inline:${SCOPE_GATE_NAME}>`)
1340
+ .flatMap((e) => extensionCanonicalNames(e.path)),
1341
+ )
1342
+ const unrecognized =
1343
+ agentConfig?.builtinToolNames?.filter(
1344
+ (n) => !BUILTIN_TOOL_NAMES.includes(n),
1345
+ ) ?? []
1346
+ const unmatched = [...extNames].filter((n) => !loadedNames.has(n))
1347
+ // `extensions: false` and `isolated` load nothing, so `loadedNames` is empty then.
1348
+ const extensionToolsPossible =
1349
+ loadedNames.size > 0 &&
1350
+ (extNames.size === 0 ||
1351
+ unmatched.length < extNames.size ||
1352
+ !!agentConfig?.mcpToolPatterns)
1353
+ if (
1354
+ (unrecognized.length > 0 || unmatched.length > 0) &&
1355
+ toolNames.every(
1356
+ (n) => !BUILTIN_TOOL_NAMES.includes(n) || disallowedSet?.has(n),
1357
+ ) &&
1358
+ readmitToolNames.size === 0 &&
1359
+ !extensionToolsPossible
1360
+ ) {
1361
+ const reasons = [
1362
+ unrecognized.length > 0
1363
+ ? `unrecognized [${unrecognized.join(", ")}]`
1364
+ : "",
1365
+ unmatched.length > 0
1366
+ ? `recognized but matched no tools in this session [${unmatched.map((n) => `ext:${n}`).join(", ")}]`
1367
+ : "",
1368
+ ].filter(Boolean)
1369
+ throw new Error(
1370
+ `Agent '${type}' would be spawned with zero tools — refusing. Its tools list resolved to nothing: ` +
1371
+ `${reasons.join("; ")}. Fix the agent's tools frontmatter or pass a different subagent_type.`,
1372
+ )
1373
+ }
1374
+
1237
1375
  // ─── Tool scoping ───────────────────────────────────────────────────────
1238
1376
  //
1239
1377
  // Some extensions register their tools ASYNCHRONOUSLY, long after the
@@ -1310,12 +1448,14 @@ export async function runAgent(
1310
1448
  // as `outputTranscript`.
1311
1449
  const persistSession =
1312
1450
  agentConfig?.persistSession ?? (options.nested ? false : rememberAgents)
1451
+ const parentSessionFile = ctx.sessionManager?.getSessionFile?.()
1313
1452
  const sessionManager = options.resumeSessionFile
1314
1453
  ? // Reopening an existing conversation: the file already carries its own
1315
1454
  // header (cwd, parent) and history, so none of the create-time options
1316
1455
  // apply. `sessionDir` still matters for a later /new or /branch off it.
1317
- SessionManager.open(
1456
+ reopenSession(
1318
1457
  options.resumeSessionFile,
1458
+ parentSessionFile,
1319
1459
  configuredSessionDir ?? defaultSessionDir,
1320
1460
  )
1321
1461
  : persistSession
@@ -1328,7 +1468,7 @@ export async function runAgent(
1328
1468
  // `persist_session: true` agent; now it runs for every spawn, so a
1329
1469
  // context without a session manager (a bare programmatic ctx) must
1330
1470
  // still persist rather than take the whole spawn down.
1331
- parentSession: ctx.sessionManager?.getSessionFile?.(),
1471
+ parentSession: parentSessionFile,
1332
1472
  },
1333
1473
  )
1334
1474
  : SessionManager.inMemory(effectiveCwd)
@@ -1406,6 +1546,7 @@ export async function runAgent(
1406
1546
  disallowedSet,
1407
1547
  extNames,
1408
1548
  narrowing,
1549
+ mcpToolPatterns: isolated ? undefined : agentConfig?.mcpToolPatterns,
1409
1550
  readmitToolNames,
1410
1551
  nestedCallGate,
1411
1552
  })
@@ -1421,9 +1562,11 @@ export async function runAgent(
1421
1562
  const collector = collectResponseText(session)
1422
1563
  const cleanupAbort = forwardAbortSignal(session, options.signal)
1423
1564
 
1424
- // Build the effective prompt: optionally prepend parent context
1565
+ // Build the effective prompt: optionally prepend parent context. Only for a
1566
+ // fresh conversation — a reopened one already holds its history, and a live
1567
+ // resume never re-sends the parent's either.
1425
1568
  let effectivePrompt = prompt
1426
- if (options.inheritContext) {
1569
+ if (options.inheritContext && !options.resumeSessionFile) {
1427
1570
  const parentContext = buildParentContext(ctx)
1428
1571
  if (parentContext) {
1429
1572
  effectivePrompt = parentContext + prompt
@@ -195,7 +195,9 @@ function loadOneFile(
195
195
  // filename-derived one down with it.
196
196
  const name = declared || filenameType
197
197
 
198
- const { builtinToolNames, extSelectors } = parseToolsField(fm.tools)
198
+ const { builtinToolNames, extSelectors, mcpToolPatterns } = parseToolsField(
199
+ fm.tools,
200
+ )
199
201
 
200
202
  agents.set(name, {
201
203
  name,
@@ -207,7 +209,13 @@ function loadOneFile(
207
209
  description: str(fm.description) ?? name,
208
210
  builtinToolNames,
209
211
  extSelectors,
210
- disallowedTools: csvListOptional(fm.disallowed_tools),
212
+ mcpToolPatterns,
213
+ // `disallowedTools` is Claude Code's spelling of the key. Each entry denies the tool
214
+ // with exactly that name, as in Claude Code, and the pi built-in it maps to, so an
215
+ // extension tool named `glob` stays denied rather than becoming `find`.
216
+ disallowedTools: csvListOptional(
217
+ fm.disallowed_tools ?? fm.disallowedTools,
218
+ )?.flatMap((n) => [...new Set([n, normalizeToolName(n)])]),
211
219
  extensions: inheritField(fm.extensions ?? fm.inherit_extensions),
212
220
  excludeExtensions: csvListOptional(fm.exclude_extensions),
213
221
  skills: inheritField(fm.skills ?? fm.inherit_skills),
@@ -388,27 +396,63 @@ function csvList(val: unknown, defaults: string[]): string[] {
388
396
  return parseCsvField(val) ?? []
389
397
  }
390
398
 
399
+ /** Claude Code tool names whose pi built-in is named differently. Keys are lowercase. */
400
+ const CLAUDE_CODE_TOOL_ALIASES: Record<string, string> = {
401
+ glob: "find",
402
+ multiedit: "edit",
403
+ }
404
+
391
405
  /**
392
- * Partition the `tools:` CSV into the built-in tool allowlist and raw `ext:` selectors.
393
- * `*` (and the case-insensitive alias `all`, for `tools: all`) expands to all
394
- * built-ins; plain entries are built-in names; `ext:` entries are extension-tool
395
- * selectors parsed later by the runner. omitted → all built-ins, no selectors.
396
- * `tools:` present with only `ext:` entries → zero built-ins (use `*`).
406
+ * A tool name as pi spells it. Built-ins match case-insensitively, so Claude Code's
407
+ * `Read` and `LS` work, and a Claude Code name with a differently named pi built-in
408
+ * maps to it. Anything else comes back unchanged, so runAgent still warns about it.
409
+ */
410
+ function normalizeToolName(name: string): string {
411
+ const lower = name.toLowerCase()
412
+ return (
413
+ BUILTIN_TOOL_NAMES.find((b) => b === lower) ??
414
+ CLAUDE_CODE_TOOL_ALIASES[lower] ??
415
+ name
416
+ )
417
+ }
418
+
419
+ /**
420
+ * Partition the `tools:` CSV into the built-in tool allowlist, raw `ext:` selectors
421
+ * and bare `mcp__` entries. `*` (and the case-insensitive alias `all`, for
422
+ * `tools: all`) expands to all built-ins; plain entries are built-in names, in pi's
423
+ * or Claude Code's spelling; `ext:` entries are extension-tool selectors parsed
424
+ * later by the runner; `mcp__<server>__<tool>` entries (exact or `*` patterns)
425
+ * narrow MCP tools, as pi's `--tools` does. omitted → all built-ins, no selectors.
426
+ * `tools:` present with only `ext:` or `mcp__` entries → zero built-ins (use `*`).
397
427
  */
398
428
  function parseToolsField(val: unknown): {
399
429
  builtinToolNames: string[]
400
430
  extSelectors: string[] | undefined
431
+ mcpToolPatterns: string[] | undefined
401
432
  } {
402
433
  const entries = csvList(val, BUILTIN_TOOL_NAMES)
403
434
  const isWildcard = (e: string) => e === "*" || e.toLowerCase() === "all"
435
+ const isMcp = (e: string) => e.startsWith("mcp__")
404
436
  const hasWildcard = entries.some(isWildcard)
405
- const plain = entries.filter((e) => !isWildcard(e) && !e.startsWith("ext:"))
437
+ const plain = [
438
+ ...new Set(
439
+ entries
440
+ .filter((e) => !isWildcard(e) && !e.startsWith("ext:") && !isMcp(e))
441
+ .map(normalizeToolName),
442
+ ),
443
+ ]
406
444
  const extEntries = entries.filter((e) => e.startsWith("ext:"))
445
+ // A server-level `mcp__<server>` means every tool of that server, as in Claude Code.
446
+ const mcpEntries = entries.filter(isMcp).map((e) => {
447
+ const server = e.slice("mcp__".length)
448
+ return server && !server.includes("__") ? `${e}__*` : e
449
+ })
407
450
  return {
408
451
  builtinToolNames: hasWildcard
409
452
  ? [...new Set([...BUILTIN_TOOL_NAMES, ...plain])]
410
453
  : plain,
411
454
  extSelectors: extEntries.length > 0 ? extEntries : undefined,
455
+ mcpToolPatterns: mcpEntries.length > 0 ? mcpEntries : undefined,
412
456
  }
413
457
  }
414
458
 
@@ -36,10 +36,9 @@ export const DEFAULT_AGENTS: Map<string, AgentConfig> = new Map([
36
36
  builtinToolNames: READ_ONLY_TOOLS,
37
37
  extensions: true,
38
38
  skills: true,
39
- // Fast/cheap model for read-only search. Provider-preferred but resilient:
40
- // resolveModel matches this fuzzily (date-stamp optional) and falls back to
41
- // the same model under another provider if anthropic doesn't expose it.
42
- model: "anthropic/claude-haiku-4-5",
39
+ // No model: Explore inherits the session's, as in Claude Code. A pin here
40
+ // outranked the caller and resolved through any provider with a key
41
+ // (#175, #350); a same-named agent file can still pin one.
43
42
  systemPrompt: `# CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS
44
43
  You are a file search specialist. You excel at thoroughly navigating and exploring codebases.
45
44
  Your role is EXCLUSIVELY to search and analyze existing code. You do NOT have access to file editing tools.