pi-suite 0.0.0-stage → 0.3.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 (220) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +100 -2
  3. package/README.zh-CN.md +101 -0
  4. package/package.json +63 -4
  5. package/skills/pi-suite-jobs/SKILL.md +76 -0
  6. package/skills/pi-suite-workflow/SKILL.md +114 -0
  7. package/src/agents/catalog.ts +80 -0
  8. package/src/agents/child.ts +79 -0
  9. package/src/agents/commands.ts +17 -0
  10. package/src/agents/defaults.ts +78 -0
  11. package/src/agents/history.ts +112 -0
  12. package/src/agents/index.ts +211 -0
  13. package/src/agents/manager.ts +438 -0
  14. package/src/agents/mentions/clone.ts +51 -0
  15. package/src/agents/mentions/grammar.ts +64 -0
  16. package/src/agents/mentions/index.ts +76 -0
  17. package/src/agents/mentions/provider.ts +79 -0
  18. package/src/agents/model-editor.ts +95 -0
  19. package/src/agents/models.ts +43 -0
  20. package/src/agents/output/schema.ts +101 -0
  21. package/src/agents/output/tool.ts +98 -0
  22. package/src/agents/parent.ts +13 -0
  23. package/src/agents/questions.ts +63 -0
  24. package/src/agents/records.ts +90 -0
  25. package/src/agents/registry.ts +20 -0
  26. package/src/agents/render.ts +85 -0
  27. package/src/agents/resources/context.ts +48 -0
  28. package/src/agents/resources/loader.ts +86 -0
  29. package/src/agents/resources/memory.ts +67 -0
  30. package/src/agents/resources/packages.ts +96 -0
  31. package/src/agents/resources/paths.ts +8 -0
  32. package/src/agents/resources/prompts.ts +11 -0
  33. package/src/agents/resources/scope.ts +147 -0
  34. package/src/agents/resources/selectors.ts +186 -0
  35. package/src/agents/retry.ts +20 -0
  36. package/src/agents/rpc/handlers.ts +62 -0
  37. package/src/agents/rpc/index.ts +73 -0
  38. package/src/agents/rpc/options.ts +44 -0
  39. package/src/agents/run-groups.ts +16 -0
  40. package/src/agents/runner.ts +131 -0
  41. package/src/agents/runtime.ts +40 -0
  42. package/src/agents/schedules/index.ts +136 -0
  43. package/src/agents/schedules/menu.ts +38 -0
  44. package/src/agents/schedules/parse.ts +42 -0
  45. package/src/agents/schedules/store.ts +78 -0
  46. package/src/agents/schema.ts +5 -0
  47. package/src/agents/session.ts +29 -0
  48. package/src/agents/tools.ts +177 -0
  49. package/src/agents/types.ts +87 -0
  50. package/src/agents/ui/index.ts +42 -0
  51. package/src/agents/ui/runs.ts +122 -0
  52. package/src/agents/ui/types.ts +91 -0
  53. package/src/agents/viewer-info.ts +36 -0
  54. package/src/agents/viewer.ts +160 -0
  55. package/src/agents/workflow/collisions.ts +124 -0
  56. package/src/agents/workflow/entry.ts +93 -0
  57. package/src/agents/workflow/host.ts +119 -0
  58. package/src/agents/workflow/index.ts +100 -0
  59. package/src/agents/workflow/journal.ts +147 -0
  60. package/src/agents/workflow/literal.ts +57 -0
  61. package/src/agents/workflow/manager.ts +169 -0
  62. package/src/agents/workflow/meta.ts +323 -0
  63. package/src/agents/workflow/progress/format.ts +184 -0
  64. package/src/agents/workflow/progress/index.ts +3 -0
  65. package/src/agents/workflow/progress/model.ts +224 -0
  66. package/src/agents/workflow/progress/types.ts +144 -0
  67. package/src/agents/workflow/render.ts +46 -0
  68. package/src/agents/workflow/runtime/helpers.ts +236 -0
  69. package/src/agents/workflow/runtime/index.ts +3 -0
  70. package/src/agents/workflow/runtime/run.ts +646 -0
  71. package/src/agents/workflow/runtime/types.ts +273 -0
  72. package/src/agents/workflow/saved.ts +74 -0
  73. package/src/agents/workflow/store.ts +23 -0
  74. package/src/agents/workflow/task.ts +277 -0
  75. package/src/agents/workflow/tool-description.ts +32 -0
  76. package/src/agents/workflow/tools.ts +66 -0
  77. package/src/agents/workflow/ui/menu.ts +144 -0
  78. package/src/agents/workflow/ui/progress.ts +91 -0
  79. package/src/agents/workflow/worker/bootstrap.ts +316 -0
  80. package/src/agents/workflow/worker/flow.ts +218 -0
  81. package/src/agents/workflow/worker/index.ts +7 -0
  82. package/src/agents/workflow/worker/scope.ts +215 -0
  83. package/src/ask/.gitkeep +0 -0
  84. package/src/ask/form.ts +67 -0
  85. package/src/ask/index.ts +73 -0
  86. package/src/ask/keys.ts +32 -0
  87. package/src/ask/layout.ts +78 -0
  88. package/src/ask/queue.ts +40 -0
  89. package/src/ask/render.ts +62 -0
  90. package/src/ask/result.ts +56 -0
  91. package/src/ask/schema.ts +67 -0
  92. package/src/ask/tool-render.ts +49 -0
  93. package/src/ask/view.ts +406 -0
  94. package/src/goal/.gitkeep +0 -0
  95. package/src/goal/activity.ts +50 -0
  96. package/src/goal/commands.ts +75 -0
  97. package/src/goal/context.ts +36 -0
  98. package/src/goal/index.ts +38 -0
  99. package/src/goal/manager.ts +386 -0
  100. package/src/goal/presentation.ts +15 -0
  101. package/src/goal/render.ts +36 -0
  102. package/src/goal/snapshot.ts +78 -0
  103. package/src/goal/state.ts +39 -0
  104. package/src/goal/store.ts +59 -0
  105. package/src/goal/tools.ts +59 -0
  106. package/src/goal/wait.ts +39 -0
  107. package/src/index.ts +20 -0
  108. package/src/jobs/backends/linux-tree.ts +87 -0
  109. package/src/jobs/backends/pipe.ts +74 -0
  110. package/src/jobs/backends/process.ts +79 -0
  111. package/src/jobs/backends/pty-job.ts +45 -0
  112. package/src/jobs/backends/pty.ts +502 -0
  113. package/src/jobs/backends/windows-tree.ts +289 -0
  114. package/src/jobs/commands.ts +7 -0
  115. package/src/jobs/control.ts +13 -0
  116. package/src/jobs/index.ts +331 -0
  117. package/src/jobs/launch/config.ts +26 -0
  118. package/src/jobs/launch/name.ts +16 -0
  119. package/src/jobs/launch/presets.ts +61 -0
  120. package/src/jobs/log-viewer.ts +147 -0
  121. package/src/jobs/manager.ts +507 -0
  122. package/src/jobs/monitors/compile.ts +101 -0
  123. package/src/jobs/monitors/hands-free.ts +108 -0
  124. package/src/jobs/monitors/runtime.ts +165 -0
  125. package/src/jobs/output.ts +54 -0
  126. package/src/jobs/query.ts +62 -0
  127. package/src/jobs/render.ts +103 -0
  128. package/src/jobs/runtime.ts +89 -0
  129. package/src/jobs/state.ts +25 -0
  130. package/src/jobs/store.ts +168 -0
  131. package/src/jobs/terminal/keys.ts +292 -0
  132. package/src/jobs/terminal/protocol.ts +37 -0
  133. package/src/jobs/terminal/read.ts +131 -0
  134. package/src/jobs/terminal/render.ts +70 -0
  135. package/src/jobs/terminal/screen.ts +92 -0
  136. package/src/jobs/terminal/session.ts +100 -0
  137. package/src/jobs/terminal/shell.ts +22 -0
  138. package/src/jobs/terminal/snapshot.ts +8 -0
  139. package/src/jobs/terminal/visible-text.ts +53 -0
  140. package/src/jobs/tools.ts +203 -0
  141. package/src/jobs/types.ts +60 -0
  142. package/src/jobs/viewer/component.ts +209 -0
  143. package/src/jobs/viewer/metadata.ts +9 -0
  144. package/src/jobs/viewer.ts +149 -0
  145. package/src/jobs/workspace.ts +31 -0
  146. package/src/runtime/.gitkeep +0 -0
  147. package/src/runtime/binding.ts +26 -0
  148. package/src/runtime/cli-prompt.ts +24 -0
  149. package/src/runtime/clipboard.ts +16 -0
  150. package/src/runtime/config-edit.ts +31 -0
  151. package/src/runtime/config-fields.ts +65 -0
  152. package/src/runtime/config.ts +111 -0
  153. package/src/runtime/errors.ts +11 -0
  154. package/src/runtime/json-store.ts +156 -0
  155. package/src/runtime/notification-render.ts +35 -0
  156. package/src/runtime/notifications.ts +98 -0
  157. package/src/runtime/owner.ts +54 -0
  158. package/src/runtime/read.ts +200 -0
  159. package/src/runtime/renderers.ts +50 -0
  160. package/src/runtime/responses/index.ts +108 -0
  161. package/src/runtime/responses/payload.ts +78 -0
  162. package/src/runtime/settings/index.ts +24 -0
  163. package/src/runtime/settings/view.ts +84 -0
  164. package/src/runtime/suite.ts +192 -0
  165. package/src/runtime/text.ts +6 -0
  166. package/src/runtime/tools.ts +131 -0
  167. package/src/runtime/wait-render.ts +33 -0
  168. package/src/runtime/wait.ts +134 -0
  169. package/src/tasks/commands.ts +41 -0
  170. package/src/tasks/index.ts +305 -0
  171. package/src/tasks/model.ts +152 -0
  172. package/src/tasks/presentation.ts +40 -0
  173. package/src/tasks/query.ts +38 -0
  174. package/src/tasks/render.ts +54 -0
  175. package/src/tasks/schema.ts +25 -0
  176. package/src/tasks/store.ts +164 -0
  177. package/src/tasks/tools.ts +69 -0
  178. package/src/tasks/types.ts +61 -0
  179. package/src/tasks/viewer.ts +68 -0
  180. package/src/ui/.gitkeep +0 -0
  181. package/src/ui/actions.ts +50 -0
  182. package/src/ui/browser-chrome.ts +175 -0
  183. package/src/ui/browser.ts +292 -0
  184. package/src/ui/details.ts +111 -0
  185. package/src/ui/dock/line.ts +14 -0
  186. package/src/ui/dock/rows.ts +78 -0
  187. package/src/ui/dock.ts +224 -0
  188. package/src/ui/format.ts +25 -0
  189. package/src/ui/frame.ts +8 -0
  190. package/src/ui/inline-input.ts +98 -0
  191. package/src/ui/reading.ts +105 -0
  192. package/src/ui/rendering/builtin-command.ts +34 -0
  193. package/src/ui/rendering/command.ts +60 -0
  194. package/src/ui/rendering/read-page.ts +15 -0
  195. package/src/ui/rendering/shell/bash.ts +281 -0
  196. package/src/ui/rendering/shell/index.ts +24 -0
  197. package/src/ui/rendering/shell/powershell.ts +155 -0
  198. package/src/ui/rendering/shell/spans.ts +28 -0
  199. package/src/ui/scroll.ts +111 -0
  200. package/src/ui/select.ts +67 -0
  201. package/src/ui/status.ts +67 -0
  202. package/src/ui/structured-details.ts +41 -0
  203. package/src/ui/terminal.ts +137 -0
  204. package/src/ui/ticker.ts +18 -0
  205. package/src/ui/tool-render.ts +152 -0
  206. package/src/ui/transcript.ts +140 -0
  207. package/src/ui/viewer/agent-information.ts +34 -0
  208. package/src/ui/viewer/editor.ts +18 -0
  209. package/src/ui/viewer/navigation.ts +25 -0
  210. package/themes/oh-my-pi.json +95 -0
  211. package/third-party/UPSTREAM.md +88 -0
  212. package/third-party/licenses/.gitkeep +0 -0
  213. package/third-party/licenses/oh-my-pi.txt +23 -0
  214. package/third-party/licenses/pi-ask-user.txt +21 -0
  215. package/third-party/licenses/pi-background-jobs.txt +21 -0
  216. package/third-party/licenses/pi-goal.txt +21 -0
  217. package/third-party/licenses/pi-interactive-shell.txt +25 -0
  218. package/third-party/licenses/pi-subagents.txt +21 -0
  219. package/third-party/licenses/pi-tasks.txt +21 -0
  220. package/third-party/sources.json +111 -0
@@ -0,0 +1,85 @@
1
+ import { truncateToWidth } from '@earendil-works/pi-tui';
2
+ import { toolRenderers, stateLine, type ToolExpandedRow } from '../ui/tool-render.ts';
3
+ import { readPageFields } from '../ui/rendering/read-page.ts';
4
+ import { agentDisplayName } from './registry.ts';
5
+ import type { ReadPage } from '../runtime/read.ts';
6
+ import type { StopOutcome } from '../runtime/tools.ts';
7
+ import type { JobSummary } from '../jobs/types.ts';
8
+ import type { ScheduledAgent } from './schedules/store.ts';
9
+ import type { agentSummary } from './index.ts';
10
+
11
+ type Summary = ReturnType<typeof agentSummary>;
12
+ type Details = { agent: Summary; backgrounded?: boolean; question?: unknown };
13
+ type Args = { id: string; runId?: string };
14
+ type StartArgs = { type?: string; name?: string; prompt: string; schedule?: string; background?: boolean };
15
+ function agentFields(agent: Summary): ToolExpandedRow[] {
16
+ return [
17
+ { label: 'id', value: agent.id }, { label: 'runId', value: agent.runId },
18
+ { label: 'state', value: agent.state, tone: stateLine(agent.state).tone },
19
+ ...agent.model ? [{ label: 'model', value: agent.model }, { label: 'thinking', value: agent.thinking }] : [],
20
+ ...agent.turns !== undefined ? [{ label: 'turns', value: String(agent.turns) }] : [],
21
+ ...agent.toolUses !== undefined ? [{ label: 'toolUses', value: String(agent.toolUses) }] : [],
22
+ ...agent.taskId ? [{ label: 'taskId', value: agent.taskId }] : [],
23
+ ...agent.taskGeneration ? [{ label: 'taskGeneration', value: agent.taskGeneration }] : [],
24
+ ...agent.activity ? [{ label: 'activity', value: agent.activity }] : [],
25
+ ...agent.usage ? [{ code: JSON.stringify(agent.usage, null, 2), language: 'json' as const, label: 'usage' }] : [],
26
+ ...agent.error ? [{ label: 'error', value: agent.error, tone: 'error' as const }] : [],
27
+ ];
28
+ }
29
+ export const startRenderers = toolRenderers<StartArgs, Details | { schedule: ScheduledAgent }>({
30
+ call: args => args.schedule
31
+ ? { icon: '⏲', tone: 'accent', title: 'Agent schedule', summary: args.schedule }
32
+ : { icon: '⟳', tone: 'accent', title: args.name ?? args.type ?? 'general-purpose',
33
+ summary: truncateToWidth(args.prompt?.split('\n')[0] ?? '', 60), meta: args.name ? [args.type ?? 'general-purpose'] : [] },
34
+ collapsed: (data, args) => 'schedule' in data
35
+ ? { icon: '⏲', tone: 'accent', title: data.schedule.id, summary: data.schedule.request.type, meta: data.schedule.nextRun ? [`next ${new Date(data.schedule.nextRun).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`] : [] }
36
+ : { ...stateLine(data.agent.state), title: data.agent.name,
37
+ meta: [...args.background === false && data.agent.elapsedMs !== undefined ? [`${(data.agent.elapsedMs / 1000).toFixed(1)}s`]
38
+ : [{ text: data.agent.state, tone: stateLine(data.agent.state).tone! }], ...data.backgrounded ? ['continuing in background'] : []] },
39
+ expanded: data => 'agent' in data ? [...agentFields(data.agent),
40
+ { label: 'promptSummary', value: data.agent.promptSummary },
41
+ ...data.agent.resultSummary !== undefined ? [{ label: 'resultSummary', value: data.agent.resultSummary }] : []]
42
+ : [{ code: JSON.stringify(data.schedule, null, 2), language: 'json', label: 'schedule' }],
43
+ });
44
+ export const listRenderers = toolRenderers<{ agentId?: string; state?: string; scope?: string }, { agents: Summary[]; nextCursor?: string }>({
45
+ call: args => ({ icon: '⟳', tone: 'accent', title: 'Agents', summary: args.agentId ? agentDisplayName(args.agentId) : undefined }),
46
+ collapsed: (data, args) => ({ icon: '', title: 'Agents', summary: `${data.agents.length} ${args.state ?? 'active'} (${args.scope ?? 'session'})`, meta: data.nextCursor ? ['more'] : [] }),
47
+ expanded: data => [...data.agents.flatMap(agent => [
48
+ { ...stateLine(agent.state), title: agent.name, meta: [{ text: agent.state, tone: stateLine(agent.state).tone! }, `${agent.id} · ${agent.runId}`] },
49
+ ...agent.error ? [{ label: 'error', value: agent.error, tone: 'error' as const }] : [],
50
+ ]), ...data.nextCursor ? [{ label: 'more', value: 'next page available', tone: 'warning' as const }] : []],
51
+ });
52
+ export const getRenderers = toolRenderers<Args & { detail?: boolean }, Details & { jobs?: JobSummary[]; jobsUnavailable?: string }>({
53
+ call: args => ({ icon: '⟳', tone: 'accent', title: 'Agent', summary: agentDisplayName(args.id, args.runId) }),
54
+ collapsed: data => ({ ...stateLine(data.question ? 'waiting(parent)' : data.agent.state), title: data.agent.name,
55
+ meta: [{ text: data.question ? 'question pending' : data.agent.state, tone: stateLine(data.question ? 'waiting(parent)' : data.agent.state).tone! }] }),
56
+ expanded: ({ agent, question, jobs, jobsUnavailable }, args) => [...agentFields(agent),
57
+ ...question ? [{ code: JSON.stringify(question, null, 2), language: 'json' as const, label: 'question' }] : [],
58
+ ...args.detail ? [
59
+ { label: 'modelSource', value: agent.modelSource }, { label: 'thinkingSource', value: agent.thinkingSource },
60
+ ...agent.contextUsage ? [{ code: JSON.stringify(agent.contextUsage, null, 2), language: 'json' as const, label: 'contextUsage' }] : [],
61
+ ...agent.lastUpdateAt ? [{ label: 'lastUpdateAt', value: agent.lastUpdateAt }] : [],
62
+ ] : [],
63
+ ...jobsUnavailable ? [{ label: 'jobsUnavailable', value: jobsUnavailable, tone: 'warning' as const }] : [],
64
+ ...jobs?.length ? [{ label: 'jobs', value: jobs.map(job => [job.id, job.state, job.cleanup.state, job.cleanup.error].filter(Boolean).join(' · ')).join('\n') }] : []],
65
+ });
66
+ export const readRenderers = toolRenderers<Args & { stream?: string }, Details & ReadPage & { stream: string }>({
67
+ call: args => ({ icon: '⟳', tone: 'accent', title: 'Agent read', summary: agentDisplayName(args.id, args.runId), meta: args.stream ? [args.stream] : [] }),
68
+ collapsed: data => ({ icon: '', title: data.agent.name, summary: `read · ${data.stream} ${data.offset}–${data.nextOffset} / ${data.totalBytes} B` }),
69
+ expanded: data => [...readPageFields(data), data.text], // Transcript and log text are literal, never Markdown or inferred code.
70
+ });
71
+ export const sendRenderers = toolRenderers<Args, Details & { action: string }>({
72
+ call: args => ({ icon: '⟳', tone: 'accent', title: 'Agent send', summary: agentDisplayName(args.id) }),
73
+ collapsed: data => ({ icon: '', title: data.agent.name, summary: data.action }),
74
+ expanded: data => [{ label: 'action', value: data.action }, ...agentFields(data.agent)],
75
+ });
76
+ export const stopRenderers = toolRenderers<Args, StopOutcome & { runId: string; name?: string }>({
77
+ call: args => ({ icon: '⟳', tone: 'accent', title: 'Agent stop', summary: agentDisplayName(args.id, args.runId) }),
78
+ collapsed: (data, args) => ({ ...stateLine(data.state), title: data.name ?? agentDisplayName(args.id, args.runId),
79
+ meta: [{ text: data.state, tone: stateLine(data.state).tone! }, { text: `cleanup ${data.cleanup}`,
80
+ tone: ['pending', 'unconfirmed'].includes(data.cleanup) ? 'warning' : 'dim' },
81
+ ...data.affected.length > 1 ? [`+${data.affected.length - 1} affected`] : []] }),
82
+ expanded: data => [{ label: 'runId', value: data.runId }, { label: 'requested', value: String(data.requested) },
83
+ { label: 'cleanup', value: data.cleanup, tone: ['pending', 'unconfirmed'].includes(data.cleanup) ? 'warning' : 'dim' },
84
+ { code: JSON.stringify(data.affected, null, 2), language: 'json', label: 'affected' }],
85
+ });
@@ -0,0 +1,48 @@
1
+ // Imported/adapted from @tintinweb/pi-subagents 0.23.0 src/context.ts (MIT).
2
+
3
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+
5
+ export function extractText(content: readonly { type: string; text?: string }[]): string {
6
+ return content
7
+ .filter(c => c.type === "text")
8
+ .map(c => c.text ?? "")
9
+ .join("\n");
10
+ }
11
+
12
+ /** Snapshot the parent's current branch for inherit_context, without tool results or thinking. */
13
+ export function buildParentContext(ctx: Pick<ExtensionContext, 'sessionManager'>): string {
14
+ const entries = ctx.sessionManager.getBranch();
15
+ if (entries.length === 0) return "";
16
+
17
+ const parts: string[] = [];
18
+
19
+ for (const entry of entries) {
20
+ if (entry.type === "message") {
21
+ const msg = entry.message;
22
+ if (msg.role === "user") {
23
+ const text = typeof msg.content === "string"
24
+ ? msg.content
25
+ : extractText(msg.content);
26
+ if (text.trim()) parts.push(`[User]: ${text.trim()}`);
27
+ } else if (msg.role === "assistant") {
28
+ const text = extractText(msg.content);
29
+ if (text.trim()) parts.push(`[Assistant]: ${text.trim()}`);
30
+ }
31
+ } else if (entry.type === "compaction") {
32
+ if (entry.summary) {
33
+ parts.push(`[Summary]: ${entry.summary}`);
34
+ }
35
+ }
36
+ }
37
+
38
+ if (parts.length === 0) return "";
39
+
40
+ return `# Parent Conversation Context
41
+ Use this parent conversation as context for the task below.
42
+
43
+ ${parts.join("\n\n")}
44
+
45
+ ---
46
+ # Your Task (below)
47
+ `;
48
+ }
@@ -0,0 +1,86 @@
1
+ // Resource selection adapted from @tintinweb/pi-subagents 0.23.0 src/agent-runner.ts (MIT).
2
+ // Pi resolves paths before its loader runs factories, so excludes and the suite singleton
3
+ // are filtered before execution rather than in the upstream post-load extensionsOverride.
4
+ import { readFileSync } from 'node:fs';
5
+ import { resolve } from 'node:path';
6
+ import { createCodemodeExtension, createMcpExtension, createToolSearchExtension, DefaultPackageManager,
7
+ DefaultResourceLoader, getAgentDir, SettingsManager, type ExtensionFactory, type Skill } from '@earendil-works/pi-coding-agent';
8
+ import { ToolError } from '../../runtime/errors.ts';
9
+ import type { Execution } from '../types.ts';
10
+ import { extensionCanonicalNames, matchesToolPattern, parseExtensionsSpec, parseExtSelectors } from './selectors.ts';
11
+ import { scopeGateExtension, type NestedCallGate } from './scope.ts';
12
+ import { buildMemoryBlock, buildReadOnlyMemoryBlock } from './memory.ts';
13
+ import { inheritableParentPrompt } from './prompts.ts';
14
+
15
+ const builtins = ['read', 'write', 'edit', 'bash', 'grep', 'find', 'ls', 'powershell'];
16
+ const suiteTools = ['task_list', 'task_get', 'task_edit', 'job_start', 'job_list', 'job_get', 'job_read', 'job_write', 'job_stop', 'wait'];
17
+ const nestedTools = ['agent_start', 'agent_list', 'agent_get', 'agent_read', 'agent_send', 'agent_stop', 'wait'];
18
+
19
+ export async function childResources(run: Execution, factory: ExtensionFactory) {
20
+ const { type, record, parent } = run, cwd = run.configCwd, agentDir = getAgentDir();
21
+ const projectTrusted = run.configTrusted;
22
+ const settingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted });
23
+ const extensions = run.isolated ? false : type.extensions ?? true, skills = run.isolated ? false : type.skills ?? true;
24
+ const selectors = parseExtSelectors(run.isolated ? [] : type.tools?.filter(name => name.startsWith('ext:')) ?? []);
25
+ const mcpToolPatterns = type.tools?.filter(name => name.startsWith('mcp__')).map(name => name.slice(5).includes('__') ? name : `${name}__*`);
26
+ const toolNames = type.tools?.filter(name => !name.startsWith('ext:') && !name.startsWith('mcp__')) ?? [...builtins, ...suiteTools];
27
+ const readmitToolNames = new Set(type.tools?.length === 0 ? [] : ['ask_user']);
28
+ if (run.options.structuredOutput) readmitToolNames.add('StructuredOutput');
29
+ if (type.allowedSubagents && !run.isolated && record.ancestors.length + 1 < run.config.agents.maxDepth) for (const name of nestedTools) readmitToolNames.add(name);
30
+ const disallowedSet = new Set(type.excludeTools);
31
+ const effectivelyHas = (name: string) => matchesToolPattern(name, toolNames) && !matchesToolPattern(name, [...disallowedSet]);
32
+ const writableMemory = effectivelyHas('write') || effectivelyHas('edit');
33
+ if (type.memory) for (const name of writableMemory ? ['read', 'write', 'edit'] : ['read']) if (!disallowedSet.has(name)) readmitToolNames.add(name);
34
+
35
+ const builtinFactories = [
36
+ { name: 'codemode', factory: createCodemodeExtension(), builtin: true, replaceable: true },
37
+ { name: 'tool-search', factory: createToolSearchExtension(), builtin: true, replaceable: true },
38
+ { name: 'mcp', factory: createMcpExtension(), builtin: true, replaceable: true },
39
+ ];
40
+ const packages = new DefaultPackageManager({ cwd, agentDir, settingsManager, builtinExtensions: builtinFactories.map(item => item.name) });
41
+ const spec = Array.isArray(extensions) ? parseExtensionsSpec(extensions, cwd) : undefined;
42
+ const resolved = extensions === false ? [] : (await packages.resolve(async () => 'error')).extensions;
43
+ const additional = spec?.paths.length ? (await packages.resolveExtensionSources(spec.paths, { temporary: true })).extensions : [];
44
+ const excluded = new Set(run.isolated ? [] : type.excludeExtensions?.map(name => name.toLowerCase()));
45
+ const disabledBuiltins = process.argv.some(arg => arg === '--no-extensions' || arg === '-ne') ? ['codemode', 'tool-search', 'mcp'] : process.argv.includes('--no-mcp') ? ['mcp'] : [];
46
+ const discovered = [...resolved, ...additional].filter(resource => resource.enabled);
47
+ for (const name of excluded) if (!discovered.some(resource => extensionCanonicalNames(resource.path).includes(name))) {
48
+ throw new ToolError('AGENT_CONFIG', `${type.sourcePath ?? type.name}: excluded extension ${name} is not enabled or available. Remove it from exclude_extensions or enable it in Pi settings.`);
49
+ }
50
+ const loadAll = extensions === true || spec?.wildcard;
51
+ const paths = [...new Set(discovered.filter(resource => {
52
+ const names = extensionCanonicalNames(resource.path);
53
+ if (names.includes('pi-suite') || names.some(name => excluded.has(name))) return false;
54
+ if (resource.path.startsWith('builtin:') && disabledBuiltins.includes(resource.path.slice(8))) return false;
55
+ return loadAll || names.some(name => spec?.names.has(name));
56
+ }).map(resource => resource.path))];
57
+ const availableNames = new Set(paths.flatMap(extensionCanonicalNames));
58
+ for (const name of [...spec?.names ?? [], ...selectors.extNames]) {
59
+ if (!availableNames.has(name) && !excluded.has(name)) throw new ToolError('AGENT_CONFIG', `${type.sourcePath ?? type.name}: extension ${name} is not enabled or available. Enable it in Pi settings or remove it from extensions and ext: tools.`);
60
+ }
61
+ const gate: NestedCallGate = {}, preloaded: Skill[] = [];
62
+ const memory = type.memory ? (writableMemory ? buildMemoryBlock : buildReadOnlyMemoryBlock)(type.name, type.memory, cwd) : '';
63
+ const inherited = type.promptMode === 'append' ? inheritableParentPrompt(parent.ctx.getSystemPrompt(), cwd) : '';
64
+ const prompt = () => [inherited, `<active_agent name="${type.name}"/>`, type.systemPrompt, memory,
65
+ ...preloaded.map(skill => `# Preloaded Skill: ${skill.name}\n${readFileSync(skill.filePath, 'utf8')}`)].filter(Boolean).join('\n\n');
66
+ const loader = new DefaultResourceLoader({ cwd, agentDir, settingsManager, noExtensions: true, additionalExtensionPaths: paths,
67
+ extensionFactories: [...builtinFactories, scopeGateExtension(gate), { name: 'pi-suite-child', hidden: true, factory }],
68
+ noSkills: skills === false, noPromptTemplates: true, noThemes: true, noContextFiles: true,
69
+ skillsOverride: base => {
70
+ if (!Array.isArray(skills)) return base;
71
+ preloaded.splice(0, preloaded.length, ...base.skills.filter(skill => skills.includes(skill.name)));
72
+ for (const name of skills) if (!preloaded.some(skill => skill.name === name)) throw new ToolError('AGENT_CONFIG', `${type.sourcePath ?? type.name}: skill ${name} is not enabled or available. Enable it in Pi settings or remove it from skills.`);
73
+ return { ...base, skills: [] };
74
+ },
75
+ systemPromptOverride: prompt, appendSystemPromptOverride: () => [],
76
+ });
77
+ await loader.reload();
78
+ const errors = [...loader.getExtensions().errors.map(error => `${error.path}: ${error.error}`),
79
+ ...loader.getSkills().diagnostics.filter(item => item.type === 'error').map(item => `${item.path}: ${item.message}`)];
80
+ if (errors.length) throw new ToolError('AGENT_CONFIG', errors.join('; '));
81
+ // Config trust covers the opened project, not an arbitrary RPC target's MCP configuration.
82
+ const sessionSettings = resolve(record.cwd) === resolve(cwd) ? settingsManager
83
+ : Object.assign(SettingsManager.create(cwd, agentDir, { projectTrusted }), { isProjectTrusted: () => false });
84
+ return { loader, settingsManager: sessionSettings, scope: { loader, toolNames, disallowedSet, ...selectors,
85
+ mcpToolPatterns: mcpToolPatterns?.length ? mcpToolPatterns : undefined, readmitToolNames, nestedCallGate: gate } };
86
+ }
@@ -0,0 +1,67 @@
1
+ // Memory prompts imported from @tintinweb/pi-subagents 0.23.0 src/memory.ts (MIT).
2
+ // Directory names are validated at the frontmatter boundary; Pi's filesystem semantics apply.
3
+ import { mkdirSync, readFileSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { getAgentDir } from '@earendil-works/pi-coding-agent';
6
+ import type { MemoryScope } from '../types.ts';
7
+
8
+ function resolveMemoryDir(name: string, scope: MemoryScope, cwd: string): string {
9
+ return join(scope === 'user' ? getAgentDir() : join(cwd, '.pi'), scope === 'local' ? 'agent-memory-local' : 'agent-memory', name);
10
+ }
11
+ function readMemoryIndex(dir: string): string | undefined {
12
+ let content: string;
13
+ try { content = readFileSync(join(dir, 'MEMORY.md'), 'utf8'); }
14
+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return; throw error; }
15
+ const lines = content.split('\n');
16
+ return lines.length > 200 ? lines.slice(0, 200).join('\n') + '\n... (truncated at 200 lines)' : content;
17
+ }
18
+
19
+ export function buildMemoryBlock(agentName: string, scope: MemoryScope, cwd: string): string {
20
+ const memoryDir = resolveMemoryDir(agentName, scope, cwd);
21
+ mkdirSync(memoryDir, { recursive: true });
22
+
23
+ const existingMemory = readMemoryIndex(memoryDir);
24
+
25
+ const header = `# Agent Memory
26
+
27
+ Persistent memory directory (${scope}): ${memoryDir}/`;
28
+
29
+ const memoryContent = existingMemory
30
+ ? `\n\n## Current MEMORY.md\n${existingMemory}`
31
+ : `\n\nCreate ${join(memoryDir, "MEMORY.md")} when you have something to save.`;
32
+
33
+ const instructions = `
34
+
35
+ ## Memory Instructions
36
+ - Only the first 200 lines of MEMORY.md are loaded. Keep it as an index.
37
+ - Save details in separate files in this directory and link to them from MEMORY.md.
38
+ - Each memory file should use this frontmatter format:
39
+ \`\`\`markdown
40
+ ---
41
+ name: <memory name>
42
+ description: <one-line description>
43
+ type: <user|feedback|project|reference>
44
+ ---
45
+ <memory content>
46
+ \`\`\`
47
+ - Check for duplicates before adding a memory. Update or remove outdated entries.`;
48
+
49
+ return header + memoryContent + instructions;
50
+ }
51
+
52
+ /** Missing memory is normal; only the writable variant creates the directory. */
53
+ export function buildReadOnlyMemoryBlock(agentName: string, scope: MemoryScope, cwd: string): string {
54
+ const memoryDir = resolveMemoryDir(agentName, scope, cwd);
55
+ const existingMemory = readMemoryIndex(memoryDir);
56
+
57
+ const header = `# Agent Memory (read-only)
58
+
59
+ Memory directory (${scope}): ${memoryDir}/
60
+ Use existing memories as context. Do not modify them.`;
61
+
62
+ const memoryContent = existingMemory
63
+ ? `\n\n## Current MEMORY.md\n${existingMemory}`
64
+ : `\n\nNo memory is available.`;
65
+
66
+ return header + memoryContent;
67
+ }
@@ -0,0 +1,96 @@
1
+ // Manifest shapes, declared paths and package gates adapted from @tintinweb/pi-subagents
2
+ // 0.23.0 src/package-resources.ts (MIT). Pi owns installed-root resolution; no dependency scan.
3
+ import { readFileSync, readdirSync, realpathSync, statSync } from 'node:fs';
4
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
5
+ import { DefaultPackageManager, getAgentDir, SettingsManager } from '@earendil-works/pi-coding-agent';
6
+ import { ToolError } from '../../runtime/errors.ts';
7
+
8
+ export type PackageGate = boolean | string[];
9
+ export type PackageResourceKind = 'agents' | 'workflows';
10
+ export type PackageResource = { path: string; packageName: string; packageRoot: string };
11
+ const extensions = { agents: '.md', workflows: '.js' };
12
+
13
+ function readManifest(root: string): Record<string, unknown> | undefined {
14
+ try {
15
+ const value: unknown = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
16
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new ToolError('AGENT_CONFIG', `Invalid package manifest: ${join(root, 'package.json')} must contain a JSON object.`);
17
+ return value as Record<string, unknown>;
18
+ } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return; throw error; }
19
+ }
20
+ function declaration(value: unknown): Partial<Record<PackageResourceKind, string[]>> | undefined {
21
+ if (value === undefined) return;
22
+ const object = Array.isArray(value) ? { agents: value } : value;
23
+ if (!object || typeof object !== 'object') throw new ToolError('AGENT_CONFIG', 'pi.subagents in package.json must be an array or an object with agents/workflows arrays.');
24
+ const result: Partial<Record<PackageResourceKind, string[]>> = {};
25
+ for (const kind of ['agents', 'workflows'] as const) {
26
+ const entries = (object as Record<string, unknown>)[kind];
27
+ if (entries === undefined) continue;
28
+ if (!Array.isArray(entries) || entries.some(entry => typeof entry !== 'string')) throw new ToolError('AGENT_CONFIG', `pi.subagents.${kind} must be a string array`);
29
+ result[kind] = entries;
30
+ }
31
+ return result;
32
+ }
33
+ export function readSubagentManifest(manifest: Record<string, unknown>) {
34
+ const pi = manifest.pi as { subagents?: unknown } | undefined;
35
+ return declaration(pi?.subagents ?? manifest['pi-subagents']);
36
+ }
37
+ /** Missing exclusions still compare canonically when an ancestor is a symlink. */
38
+ function realOrSelf(path: string): string {
39
+ try { return realpathSync(path); }
40
+ catch (error) {
41
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
42
+ const parent = dirname(path);
43
+ return parent === path ? path : join(realOrSelf(parent), basename(path));
44
+ }
45
+ }
46
+ function inside(root: string, path: string): boolean {
47
+ const rel = relative(realOrSelf(root), realOrSelf(path));
48
+ return rel !== '' && rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
49
+ }
50
+ export function packageAllowed(source: string, name: string | undefined, gate: PackageGate | undefined): boolean {
51
+ if (gate === false) return false;
52
+ if (gate === undefined || gate === true) return true;
53
+ const candidates = [source, name, name?.startsWith('@') ? name.slice(name.indexOf('/') + 1) : name].map(value => value?.toLowerCase());
54
+ return gate.some(value => candidates.includes(value.trim().toLowerCase()));
55
+ }
56
+
57
+ /** Only installed, explicitly declared resources participate; absence does not trigger install. */
58
+ export function packageResources(cwd: string, kind: PackageResourceKind, trusted: boolean, gate?: PackageGate, agentDir = getAgentDir()): PackageResource[] {
59
+ if (gate === false || Array.isArray(gate) && !gate.length) return [];
60
+ const settingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted: trusted });
61
+ const manager = new DefaultPackageManager({ cwd, agentDir, settingsManager });
62
+ const resources: PackageResource[] = [], seen = new Set<string>();
63
+ for (const pkg of manager.listConfiguredPackages()) {
64
+ if (!pkg.installedPath) continue;
65
+ const root = resolve(pkg.installedPath);
66
+ if (seen.has(root)) continue;
67
+ seen.add(root);
68
+ const manifest = readManifest(root);
69
+ if (!manifest) continue;
70
+ const name = typeof manifest.name === 'string' ? manifest.name : undefined;
71
+ if (!packageAllowed(pkg.source, name, gate)) continue;
72
+ const entries = readSubagentManifest(manifest)?.[kind];
73
+ if (!entries) continue;
74
+ const excluded = entries.filter(entry => entry.startsWith('!')).map(entry => resolve(root, entry.slice(1)));
75
+ for (const path of excluded) if (!inside(root, path)) throw new ToolError('AGENT_CONFIG', `Package exclusion is outside install root: ${path}. Use a path inside the package.`);
76
+ const exclusions = new Set(excluded.map(realOrSelf)), files = new Set<string>();
77
+ for (const entry of entries) {
78
+ if (entry.startsWith('!')) continue;
79
+ const path = resolve(root, entry);
80
+ if (!inside(root, path)) throw new ToolError('AGENT_CONFIG', `Package resource is outside install root: ${path}. Declare a path inside the package.`);
81
+ if (exclusions.has(realOrSelf(path))) continue;
82
+ const stat = statSync(path);
83
+ // Like the upstream agent loader, a declared directory contributes its direct files.
84
+ const candidates = stat.isDirectory() ? readdirSync(path).sort().map(file => join(path, file)) : [path];
85
+ for (const file of candidates) {
86
+ if (!file.endsWith(extensions[kind]) || exclusions.has(realOrSelf(file))) continue;
87
+ if (!inside(root, file)) throw new ToolError('AGENT_CONFIG', `Package resource escapes install root: ${file}. Point it to a file inside the package.`);
88
+ const info = statSync(file);
89
+ if (!info.isFile() || info.size > 1_048_576) throw new ToolError('AGENT_CONFIG', `Package resource must be a regular file of at most 1 MiB: ${file}. Change or remove the declaration.`);
90
+ files.add(file);
91
+ }
92
+ }
93
+ for (const path of files) resources.push({ path, packageName: name ?? pkg.source, packageRoot: root });
94
+ }
95
+ return resources;
96
+ }
@@ -0,0 +1,8 @@
1
+ import { homedir } from 'node:os';
2
+ import { isAbsolute, resolve } from 'node:path';
3
+
4
+ /** Path expansion is shared by history discovery and execution without loading child resources. */
5
+ export function resourcePath(path: string, cwd: string): string {
6
+ const expanded = path === '~' || path.startsWith('~/') || path.startsWith('~\\') ? homedir() + path.slice(1) : path;
7
+ return isAbsolute(expanded) ? expanded : resolve(cwd, expanded);
8
+ }
@@ -0,0 +1,11 @@
1
+ // Imported from @tintinweb/pi-subagents 0.23.0 src/prompts.ts (MIT).
2
+ // Child skills/cwd/extension sections are rendered by Pi; inherit the stable parent prefix.
3
+ export function inheritableParentPrompt(rendered: string, cwd: string): string {
4
+ const cwdAt = rendered.lastIndexOf(`\n\n<cwd>\n${cwd.replace(/\\/g, "/")}\n</cwd>`);
5
+ if (cwdAt < 0) return rendered;
6
+ const head = rendered.slice(0, cwdAt);
7
+ if (!head.endsWith("\n</skills>")) return head;
8
+ const skillsAt = head.lastIndexOf("\n\n<skills>\n");
9
+ return skillsAt < 0 ? head : head.slice(0, skillsAt);
10
+ }
11
+
@@ -0,0 +1,147 @@
1
+ // Imported/adapted from @tintinweb/pi-subagents 0.23.0 src/agent-runner.ts (MIT).
2
+ import type { AgentSession, AgentSessionEvent, DefaultResourceLoader, InlineExtension } from "@earendil-works/pi-coding-agent";
3
+ import { extensionCanonicalNames, isMcpToolName, MCP_BRIDGE_TOOL_NAMES, matchesToolPattern } from "./selectors.ts";
4
+
5
+ export function installExtensionToolScope(
6
+ session: AgentSession,
7
+ ctx: {
8
+ loader: DefaultResourceLoader;
9
+ toolNames: string[];
10
+ disallowedSet: Set<string> | undefined;
11
+ extNames: Set<string>;
12
+ narrowing: Map<string, Set<string>>;
13
+ /** MCP patterns from tools; undefined leaves MCP tools to the ordinary selection rules. */
14
+ mcpToolPatterns: string[] | undefined;
15
+ /** Selected injected tools, including parent questions, nested delegation and memory. */
16
+ readmitToolNames: Set<string>;
17
+ /** Receives the scope check the child's nested-call gate extension applies. */
18
+ nestedCallGate: NestedCallGate;
19
+ },
20
+ ): void {
21
+ const { loader, toolNames, disallowedSet, extNames, narrowing, mcpToolPatterns, readmitToolNames, nestedCallGate } =
22
+ ctx;
23
+ // Factories/paths are fixed for this child; late registrations change their tool maps only.
24
+ // Resolve file/package aliases once, rather than re-read manifests on every tool invocation.
25
+ const aliases = new Map(loader.getExtensions().extensions.map(extension => [extension.path, extensionCanonicalNames(extension.path)]));
26
+
27
+ // Any ext: selector turns extension tools into an allowlist: an unnamed extension still
28
+ // loads and runs its handlers but contributes no tools, and ext:foo/bar narrows foo to bar.
29
+ const inScope = (): Set<string> => {
30
+ const denied = (name: string) => matchesToolPattern(name, [...disallowedSet ?? []]);
31
+ const keep = new Set(session.getAllTools().map(tool => tool.name).filter(name => matchesToolPattern(name, toolNames) && !denied(name)));
32
+ const optInActive = extNames.size > 0;
33
+ for (const extension of loader.getExtensions().extensions) {
34
+ // The shared suite registers its complete tool set; only the run's selected suite tools
35
+ // belong here. It is not an external extension that an opt-in can accidentally widen.
36
+ if (extension.path === '<inline:pi-suite-child>' || extension.path === '<inline:pi-suite-scope>') continue;
37
+ const canons = aliases.get(extension.path)!;
38
+ if (optInActive && !canons.some((c) => extNames.has(c))) continue;
39
+ // First narrowing alias wins: one extension is not narrowed under two different names.
40
+ const narrowed = canons.map((c) => narrowing.get(c)).find(Boolean);
41
+ for (const name of extension.tools.keys()) {
42
+ if (narrowed && !narrowed.has(name)) continue;
43
+ if (denied(name)) continue;
44
+ keep.add(name);
45
+ }
46
+ }
47
+ // Bare `mcp__` entries, as in pi's `--tools`: only matching MCP tools stay, from
48
+ // whichever extension serves them (pi's MCP or an adapter), even one the `ext:`
49
+ // opt-in left out — and so do the bridges that reach them.
50
+ if (mcpToolPatterns) {
51
+ for (const name of keep) {
52
+ if (!isMcpToolName(name)) continue;
53
+ // Resource helpers serve multiple namespaces through a server argument;
54
+ // an explicit helper selection must not be erased by a server-tool filter.
55
+ const selected = name.startsWith('mcp__') ? matchesToolPattern(name, mcpToolPatterns) : matchesToolPattern(name, toolNames);
56
+ if (!selected) keep.delete(name);
57
+ }
58
+ for (const extension of loader.getExtensions().extensions) {
59
+ for (const name of extension.tools.keys()) {
60
+ if (denied(name)) continue;
61
+ if (MCP_BRIDGE_TOOL_NAMES.has(name) || matchesToolPattern(name, mcpToolPatterns)) keep.add(name);
62
+ }
63
+ }
64
+ }
65
+ // Injected tools (parent questions, nested delegation, memory) belong to this agent even
66
+ // when tools: omits them. The caller already applied disallowed_tools to this set.
67
+ for (const name of readmitToolNames) if (!denied(name)) keep.add(name);
68
+ return keep;
69
+ };
70
+
71
+ // Names this agent selects explicitly: its built-ins, injected tools, `ext:foo/bar`
72
+ // narrowings and exact `mcp__` entries. pi activates a named tool even when it is
73
+ // `defaultActive: false`, as `--tools` does.
74
+ const named = new Set([
75
+ ...session.getAllTools().map(tool => tool.name).filter(name => matchesToolPattern(name, toolNames)),
76
+ ...readmitToolNames,
77
+ ...[...narrowing.values()].flatMap((s) => [...s]),
78
+ ...(mcpToolPatterns ?? []).filter((p) => !p.includes("*")),
79
+ ]);
80
+
81
+ // Activate what pi itself would: only tools declared to the model (`direct`/
82
+ // `model-only` exposure), and of those only named ones or ones not opted out
83
+ // with `defaultActive: false`. `codemode`/`deferred` tools (pi's MCP tools by
84
+ // default) stay undeclared until their extension or `tool_search` activates
85
+ // them — so an already-active tool is kept, or turn_end would undo that.
86
+ const renarrow = () => {
87
+ const allowed = inScope();
88
+ const current = session.getActiveToolNames();
89
+ const active = new Set(current);
90
+ const next = session
91
+ .getAllTools()
92
+ .filter(({ name, exposure = "direct" }) => {
93
+ if (!allowed.has(name)) return false;
94
+ if (active.has(name)) return true;
95
+ if (exposure !== "direct" && exposure !== "model-only") return false;
96
+ return named.has(name) || session.getToolDefinition(name)?.defaultActive !== false;
97
+ })
98
+ .map((t) => t.name);
99
+ // setActiveToolsByName unconditionally rebuilds the system prompt, so skip
100
+ // the no-op that steady-state turns would otherwise pay for every turn.
101
+ if (next.length !== current.length || next.some((n, i) => n !== current[i])) {
102
+ session.setActiveToolsByName(next);
103
+ }
104
+ };
105
+
106
+ // Activate what registered during session_start (eager MCP servers); pi would
107
+ // otherwise leave only its four default built-ins active at turn 1.
108
+ renarrow();
109
+
110
+ session.subscribe((event: AgentSessionEvent) => {
111
+ if (event.type === "turn_end") renarrow();
112
+ });
113
+
114
+ nestedCallGate.allows = (name) => inScope().has(name);
115
+
116
+ const priorBeforeToolCall = session.agent.beforeToolCall;
117
+ session.agent.beforeToolCall = async (context, signal) => {
118
+ if (!inScope().has(context.toolCall.name)) {
119
+ return {
120
+ block: true,
121
+ reason: `Tool "${context.toolCall.name}" is not available to this subagent. Use one of your listed tools.`,
122
+ };
123
+ }
124
+ return priorBeforeToolCall?.(context, signal);
125
+ };
126
+ }
127
+
128
+ /** Set once the child's tool scope is installed; until then the gate admits everything. */
129
+ export type NestedCallGate = { allows?: (name: string) => boolean };
130
+
131
+ const SCOPE_GATE_NAME = "pi-suite-scope";
132
+
133
+ /** Pi sends ctx.executeTool calls (including codemode) through tool_call, not agent.beforeToolCall. */
134
+ export function scopeGateExtension(gate: NestedCallGate): InlineExtension {
135
+ return {
136
+ name: SCOPE_GATE_NAME,
137
+ hidden: true,
138
+ factory: (ext) => {
139
+ ext.on("tool_call", (event) =>
140
+ gate.allows?.(event.toolName) === false
141
+ ? { block: true, reason: `Tool "${event.toolName}" is not available to this subagent. Use one of your listed tools.` }
142
+ : undefined,
143
+ );
144
+ },
145
+ };
146
+ }
147
+