@falkenslab/agent-kit 0.18.0 → 0.19.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 (96) hide show
  1. package/assets/extension-launcher.mjs +24 -0
  2. package/dist/chat/chatController.d.ts +264 -0
  3. package/dist/chat/chatController.js +510 -0
  4. package/dist/chat/extensions.d.ts +14 -0
  5. package/dist/chat/extensions.js +41 -0
  6. package/dist/chat/history.d.ts +17 -0
  7. package/dist/chat/history.js +39 -0
  8. package/dist/{tui → chat}/runs.d.ts +8 -1
  9. package/dist/{tui → chat}/runs.js +1 -1
  10. package/dist/core/agentSpec.d.ts +30 -16
  11. package/dist/core/extensions.d.ts +119 -0
  12. package/dist/core/extensions.js +97 -0
  13. package/dist/core/externalExtensions.d.ts +131 -0
  14. package/dist/core/externalExtensions.js +340 -0
  15. package/dist/core/hooks/planGate.d.ts +2 -0
  16. package/dist/core/hooks/planGate.js +1 -10
  17. package/dist/core/hooks/stepGate.d.ts +1 -1
  18. package/dist/core/hooks/stepGate.js +3 -3
  19. package/dist/core/messages/de.js +11 -32
  20. package/dist/core/messages/en.d.ts +13 -16
  21. package/dist/core/messages/en.js +11 -32
  22. package/dist/core/messages/es.js +11 -32
  23. package/dist/core/messages/fr.js +11 -32
  24. package/dist/core/messages/index.d.ts +6 -0
  25. package/dist/core/messages/index.js +12 -1
  26. package/dist/core/packaged.d.ts +10 -0
  27. package/dist/core/packaged.js +38 -0
  28. package/dist/core/pluginAgents.d.ts +20 -0
  29. package/dist/core/pluginAgents.js +76 -0
  30. package/dist/core/runner.js +16 -9
  31. package/dist/core/session.d.ts +30 -5
  32. package/dist/core/session.js +143 -94
  33. package/dist/core/sessionFacts.d.ts +80 -0
  34. package/dist/core/sessionFacts.js +48 -0
  35. package/dist/core/toolLabels.d.ts +24 -6
  36. package/dist/core/toolLabels.js +24 -39
  37. package/dist/extensions/awareness/index.d.ts +13 -0
  38. package/dist/extensions/awareness/index.js +39 -0
  39. package/dist/extensions/awareness/labels.d.ts +3 -0
  40. package/dist/extensions/awareness/labels.js +12 -0
  41. package/dist/extensions/awareness/tools.d.ts +5 -0
  42. package/dist/extensions/awareness/tools.js +54 -0
  43. package/dist/extensions/knowledge/index.d.ts +8 -0
  44. package/dist/extensions/knowledge/index.js +35 -0
  45. package/dist/{core → extensions/knowledge}/knowledgeStore.d.ts +1 -0
  46. package/dist/extensions/knowledge/labels.d.ts +3 -0
  47. package/dist/extensions/knowledge/labels.js +119 -0
  48. package/dist/{core/knowledge.d.ts → extensions/knowledge/prompt.d.ts} +1 -1
  49. package/dist/{core/knowledge.js → extensions/knowledge/prompt.js} +7 -4
  50. package/dist/{core/tools/knowledgeTools.d.ts → extensions/knowledge/tools.d.ts} +1 -1
  51. package/dist/{core/tools/knowledgeTools.js → extensions/knowledge/tools.js} +2 -2
  52. package/dist/extensions/memory/index.d.ts +12 -0
  53. package/dist/extensions/memory/index.js +56 -0
  54. package/dist/extensions/memory/labels.d.ts +3 -0
  55. package/dist/extensions/memory/labels.js +58 -0
  56. package/dist/extensions/memory/memoryStore.d.ts +53 -0
  57. package/dist/extensions/memory/memoryStore.js +88 -0
  58. package/dist/extensions/memory/tools.d.ts +9 -0
  59. package/dist/extensions/memory/tools.js +82 -0
  60. package/dist/extensions/sources/index.d.ts +9 -0
  61. package/dist/extensions/sources/index.js +40 -0
  62. package/dist/extensions/sources/labels.d.ts +3 -0
  63. package/dist/extensions/sources/labels.js +82 -0
  64. package/dist/{core/tools/saveToSources.d.ts → extensions/sources/tools.d.ts} +1 -1
  65. package/dist/{core/tools/saveToSources.js → extensions/sources/tools.js} +5 -5
  66. package/dist/index.d.ts +14 -9
  67. package/dist/index.js +11 -7
  68. package/dist/tui/chatTui.d.ts +11 -20
  69. package/dist/tui/chatTui.js +75 -230
  70. package/dist/tui/extensionCommand.d.ts +21 -0
  71. package/dist/tui/extensionCommand.js +133 -0
  72. package/dist/tui/ink/runChatInk.d.ts +4 -3
  73. package/dist/tui/ink/runChatInk.js +101 -217
  74. package/extensions/awareness/.claude-plugin/plugin.json +10 -0
  75. package/{assets/agent-help → extensions/awareness/skills/help}/SKILL.md +4 -3
  76. package/{assets/knowledge-plugin → extensions/knowledge}/.claude-plugin/plugin.json +7 -1
  77. package/extensions/memory/.claude-plugin/plugin.json +10 -0
  78. package/extensions/memory/commands/forget.md +8 -0
  79. package/extensions/memory/commands/list.md +5 -0
  80. package/extensions/sources/.claude-plugin/plugin.json +10 -0
  81. package/package.json +3 -2
  82. package/dist/core/agentHelp.d.ts +0 -30
  83. package/dist/core/agentHelp.js +0 -55
  84. /package/dist/{core → extensions/knowledge}/fileKnowledgeStore.d.ts +0 -0
  85. /package/dist/{core → extensions/knowledge}/fileKnowledgeStore.js +0 -0
  86. /package/dist/{core → extensions/knowledge}/knowledgeStore.js +0 -0
  87. /package/dist/{core → extensions/sources}/extractText.d.ts +0 -0
  88. /package/dist/{core → extensions/sources}/extractText.js +0 -0
  89. /package/dist/{core → extensions/sources}/sources.d.ts +0 -0
  90. /package/dist/{core → extensions/sources}/sources.js +0 -0
  91. /package/{assets/knowledge-plugin → extensions/knowledge}/commands/ingest.md +0 -0
  92. /package/{assets/knowledge-plugin → extensions/knowledge}/commands/lint.md +0 -0
  93. /package/{assets/knowledge-plugin → extensions/knowledge}/commands/query.md +0 -0
  94. /package/{assets/knowledge-plugin → extensions/knowledge}/skills/knowledge-ingest/SKILL.md +0 -0
  95. /package/{assets/knowledge-plugin → extensions/knowledge}/skills/knowledge-lint/SKILL.md +0 -0
  96. /package/{assets/knowledge-plugin → extensions/knowledge}/skills/knowledge-query/SKILL.md +0 -0
@@ -10,18 +10,19 @@ import { createFileScopeGate } from "./hooks/fileScopeGate.js";
10
10
  import { createPlanGate } from "./hooks/planGate.js";
11
11
  import { createHumanApprovalServer } from "./tools/humanApproval.js";
12
12
  import { createManualLoginServer } from "./tools/manualLogin.js";
13
- import { createSaveToSourcesServer, sourcesPromptSection } from "./tools/saveToSources.js";
14
13
  import { createTimeServer } from "./tools/time.js";
15
14
  import { TODO_TOOL } from "./todos.js";
16
15
  import { createModeControl } from "./modeControl.js";
17
- import { createFileKnowledgeStore } from "./fileKnowledgeStore.js";
18
- import { createKnowledgeServer } from "./tools/knowledgeTools.js";
16
+ import { extensionsPromptSection, resolveExtensions, skillsMissingCapabilities } from "./extensions.js";
19
17
  import { allowAnyMcpTool } from "./mcpPermissions.js";
20
- import { knowledgePluginRoot, knowledgePromptSection } from "./knowledge.js";
21
- import { AGENT_HELP_SKILL, identityPromptSection, writeAgentHelpPlugin } from "./agentHelp.js";
18
+ import { pluginAgents } from "./pluginAgents.js";
19
+ import { outsideArchive, unpackedClaudeExecutable } from "./packaged.js";
20
+ import { listInstalled, loadExternalExtensions } from "./externalExtensions.js";
22
21
  import { replyLanguageInstruction } from "./language.js";
23
22
  import { chooseLanguage } from "./messages/index.js";
24
23
  import { createRunStore } from "./runs.js";
24
+ import { createSessionView, registerSessionView } from "./sessionFacts.js";
25
+ import { agentKitVersion } from "./version.js";
25
26
  /**
26
27
  * Builds the `options` object passed to the Agent SDK's `query()` — everything about
27
28
  * *how* the agent runs a session (system prompt, tools, MCP servers, hooks), independent
@@ -29,9 +30,10 @@ import { createRunStore } from "./runs.js";
29
30
  * one-shot run or an `AsyncIterable` for a multi-turn chat).
30
31
  *
31
32
  * Everything actually *about the domain* (which system prompt, which MCP servers besides
32
- * the generic human-in-the-loop/knowledge ones below, which plugin roots, which
33
- * subagents) is behind `spec` (see agentSpec.ts) — this function only knows the generic
34
- * fields on `BaseSessionConfig`.
33
+ * the generic human-in-the-loop ones below, which plugin roots, which subagents) is behind
34
+ * `spec` (see agentSpec.ts), and the kit's optional parts (the knowledge base, the sources
35
+ * folder) are extensions whose contributions this function puts together (extensions.ts,
36
+ * ADR-025): it names none of them.
35
37
  *
36
38
  * The per-mode behavioral differences (whether the approval/manual-intervention tools
37
39
  * exist, whether the interactive step gate or the plan gate decides) all fall out of
@@ -57,60 +59,71 @@ export async function buildSessionOptions(config, runDir, spec, options = {}) {
57
59
  // domain's own opt-in signal (see its doc comment in agentSpec.ts), not a generic
58
60
  // boolean this kit could infer on its own.
59
61
  const manualInterventionTexts = mode !== "autonomous" ? spec.manualInterventionTexts : undefined;
60
- // The file tools exist as soon as the project has a place for the agent's notes
61
- // (`knowledgeDir`) or for original files (`sourcesDir`) — there is no separate "context"
62
- // folder: material the user provides is just more of `sourcesDir`.
63
- const includeFileTools = Boolean(config.knowledgeDir || config.sourcesDir);
64
- // The built-in knowledge base (rules in the system prompt + its skills/commands as a plugin) needs
65
- // somewhere to keep the wiki, so it follows `knowledgeDir`; `spec.knowledgeBase: false` opts out.
66
- const includeKnowledgeBase = Boolean(config.knowledgeDir) && spec.knowledgeBase !== false;
67
- // The agent reaches it only through the `knowledge_*` tools, over a store, never with the file
68
- // tools (ADR-024). Without it (`knowledgeBase: false`), `knowledgeDir` is a folder of the
69
- // agent's own notes, kept with the file tools under its own rules.
70
- const notesDir = includeKnowledgeBase ? undefined : config.knowledgeDir;
62
+ // What the enabled extensions bring (ADR-025): their tools, prompt sections, plugins and
63
+ // folders, put together here.
64
+ // `session()` reads the view built below, once the options are: an extension's tools call it later.
65
+ const late = {};
66
+ const extensionContext = {
67
+ config,
68
+ spec,
69
+ runDir,
70
+ mode,
71
+ interactive: mode !== "autonomous",
72
+ session: () => (late.view ? late.view.facts() : Promise.reject(new Error("The session isn't built yet: call session() from a tool, not from contribute()."))),
73
+ };
74
+ // The installed ones (#37), the project's over the agent's: those that can't load are off with
75
+ // why, and so is one named like an extension the spec enables.
76
+ const extensionDirs = config.extensionDirs ?? {};
77
+ const external = await loadExternalExtensions(extensionDirs);
78
+ const enabledNames = new Set((spec.extensions ?? []).map((entry) => (typeof entry === "string" ? entry : entry.name)));
79
+ const resolved = resolveExtensions([...(spec.extensions ?? []), ...external.extensions.filter((extension) => !enabledNames.has(extension.name))], extensionContext);
80
+ resolved.inactive.push(...external.off, ...external.extensions.filter((extension) => enabledNames.has(extension.name)).map((extension) => ({ name: extension.name, reason: "has the name of one this agent already has" })));
81
+ const externalPlugins = new Set(resolved.active.filter(({ extension }) => extension.external).map(({ extension }) => path.resolve(extension.plugin)));
82
+ const added = await Promise.all(resolved.active.map(({ extension }) => extension.contribute(extensionContext)));
83
+ const extensionPlugins = resolved.active.map(({ extension }) => extension.plugin);
84
+ const fromExtensions = (pick) => added.flatMap((contribution) => pick(contribution) ?? []);
85
+ const knowledgeStore = added.map((contribution) => contribution.api?.knowledgeStore).find(Boolean);
86
+ // An extension may claim `knowledgeDir` as reached only through its tools (the knowledge base,
87
+ // ADR-024); otherwise it's a folder of the agent's own notes, kept with the file tools under
88
+ // its own rules.
89
+ const claimed = (dir) => fromExtensions((contribution) => contribution.toolOnlyDirs).some((only) => path.resolve(only.dir) === path.resolve(dir));
90
+ const notesDir = config.knowledgeDir && !claimed(config.knowledgeDir) ? config.knowledgeDir : undefined;
71
91
  const extraDirs = config.extraWritableDirs ?? [];
72
92
  const readableExtras = config.extraReadableDirs ?? [];
73
- // With the knowledge base, the file tools are only for the originals (reading) and the extra
74
- // folders; without either, none.
75
- const fileTools = !includeFileTools
76
- ? []
77
- : !includeKnowledgeBase
78
- ? ["Read", "Write", "Edit", "Glob", "Grep"]
79
- : [...(config.sourcesDir || extraDirs.length || readableExtras.length ? ["Read", "Glob", "Grep"] : []), ...(extraDirs.length ? ["Write", "Edit"] : [])];
93
+ // The file tools the session needs: all five for the notes and the extra writable folders,
94
+ // the reading ones for the extra readable folders, and whatever the extensions ask for (the
95
+ // sources' reading ones); without any of them, none.
96
+ const wantedFileTools = new Set([
97
+ ...(notesDir || extraDirs.length ? FILE_TOOLS : []),
98
+ ...(readableExtras.length ? ["Read", "Glob", "Grep"] : []),
99
+ ...fromExtensions((contribution) => contribution.fileTools),
100
+ ]);
101
+ const fileTools = FILE_TOOLS.filter((tool) => wantedFileTools.has(tool));
80
102
  // Where Write/Edit may act and Grep may search (see hooks/fileScopeGate.ts): the
81
103
  // project's own folders, never the whole cwd — which would include whatever else the
82
- // project directory holds (the user's config...). `sourcesDir` is searchable but
83
- // deliberately NOT writable: originals stay as obtained, and the only way to add to it is
84
- // the `save_to_sources` tool (which never overwrites).
104
+ // project directory holds (the user's config...). An extension's folders (the sources) are
105
+ // searchable but deliberately NOT writable: the only way to add to them is its tools.
106
+ const readOnlyDirs = fromExtensions((contribution) => contribution.readOnlyDirs);
107
+ const toolOnlyDirs = fromExtensions((contribution) => contribution.toolOnlyDirs);
85
108
  const writableDirs = [notesDir, ...extraDirs].filter((d) => Boolean(d));
86
- const searchableDirs = [notesDir, config.sourcesDir, ...extraDirs, ...readableExtras].filter((d) => Boolean(d));
87
- const readOnlyDirs = config.sourcesDir ? [config.sourcesDir] : [];
109
+ const searchableDirs = [notesDir, ...readOnlyDirs, ...extraDirs, ...readableExtras].filter((d) => Boolean(d));
88
110
  // Skills/commands/plugins are a separate concern from the file tools: an agent that
89
111
  // wants a plugin-provided skill/command but has no notes or sources folder shouldn't have
90
112
  // to invent one just to get `cwd`/`skills: "all"`/`plugins` wired up. Gated on either
91
113
  // signal, not on `pluginRoots` alone, so an agent with file tools keeps getting the SDK's
92
114
  // own project-level `.claude/skills`/`.claude/commands` discovery.
93
- // With an identity, the agent-help skill (agentHelp.ts): written into the run's folder, since
94
- // it carries this session's facts and the agent's own guide.
95
- const helpPlugin = spec.identity
96
- ? await writeAgentHelpPlugin(path.join(runDir, "agent-help"), {
97
- mode,
98
- switchable: modeControl.switchable,
99
- knowledgeBase: includeKnowledgeBase,
100
- ...(config.sourcesDir ? { sourcesFolder: `${path.relative(config.projectDir, config.sourcesDir).split(path.sep).join("/")}/` } : {}),
101
- }, spec.helpGuide)
102
- : undefined;
103
- const pluginRoots = [
104
- ...spec.pluginRoots(config),
105
- ...(includeKnowledgeBase ? [knowledgePluginRoot()] : []),
106
- ...(helpPlugin ? [helpPlugin] : []),
107
- ];
108
- const knowledgeStore = includeKnowledgeBase && config.knowledgeDir
109
- ? (spec.knowledgeStore?.(config) ?? createFileKnowledgeStore(config.knowledgeDir, { pageTypes: spec.knowledgePageTypes }))
110
- : undefined;
111
- const includeSkillsAndPlugins = includeFileTools || pluginRoots.length > 0;
112
- // "plugins": the skills of the plugins loaded, named as the SDK names them.
113
- const offeredSkills = spec.skills === "plugins" ? await pluginSkills(pluginRoots) : spec.skills;
115
+ // Outside the archive when the agent runs packaged (Electron's app.asar): the CLI reads them (#42).
116
+ const pluginRoots = [...spec.pluginRoots(config), ...extensionPlugins].map(outsideArchive);
117
+ const includeSkillsAndPlugins = fileTools.length > 0 || pluginRoots.length > 0;
118
+ // "plugins": the skills of the plugins loaded, named as the SDK names them. A skill that
119
+ // `requires` a capability no active extension provides is left out; since the SDK's
120
+ // `skillOverrides` doesn't reach plugin skills (confirmed empirically), leaving one out takes
121
+ // a list: the plugins' skills and the project's, without it.
122
+ const missingCapabilities = await skillsMissingCapabilities(pluginRoots, resolved.capabilities);
123
+ const requested = spec.skills === "plugins" ? await pluginSkills(pluginRoots) : spec.skills;
124
+ const offeredSkills = missingCapabilities.length && (requested === undefined || requested === "all")
125
+ ? [...(await pluginSkills(pluginRoots)), ...((spec.settingSources ?? ["project"]).includes("project") ? await projectSkills(config.projectDir) : [])]
126
+ : requested;
114
127
  const skillTools = includeSkillsAndPlugins ? ["Skill"] : [];
115
128
  // Whatever opt-in subagents `spec` wants for this config, or undefined if none apply.
116
129
  // Subagents need the Agent tool (to delegate to them), and Bash when one of them uses it
@@ -121,39 +134,45 @@ export async function buildSessionOptions(config, runDir, spec, options = {}) {
121
134
  // anything not already present here — which is why the hook, not just omitting "Bash"
122
135
  // from this list, is what actually confines it to subagent use).
123
136
  const subagents = spec.buildSubagents(config);
137
+ // The plugins' subagents too (agents/*.md, the agent's and its extensions'), registered as the
138
+ // spec's are: allowed to be spawned, counted in the Agent and Bash decision, and given the
139
+ // reply line (pluginAgents.ts; ADR-025).
140
+ // An installed extension's get no Bash (ADR-025): one without `tools` gets none.
141
+ const fromPlugins = {
142
+ ...(await pluginAgents(pluginRoots.filter((root) => !externalPlugins.has(path.resolve(root))))),
143
+ ...Object.fromEntries(Object.entries(await pluginAgents([...externalPlugins])).map(([name, agent]) => [name, { ...agent, tools: (agent.tools ?? []).filter((tool) => tool !== "Bash") }])),
144
+ };
145
+ const allAgents = { ...fromPlugins, ...(subagents?.agents ?? {}) };
124
146
  // Each subagent gets the reply line too: its prompt doesn't include the main one's.
125
- const subagentDefinitions = subagents
126
- ? Object.fromEntries(Object.entries(subagents.agents).map(([name, agent]) => [name, { ...agent, prompt: withReplyLine(agent.prompt) }]))
147
+ const subagentDefinitions = Object.keys(allAgents).length
148
+ ? Object.fromEntries(Object.entries(allAgents).map(([name, agent]) => [name, { ...agent, prompt: withReplyLine(agent.prompt) }]))
127
149
  : undefined;
128
- const includeSubagentTools = subagents !== undefined;
150
+ const includeSubagentTools = subagentDefinitions !== undefined;
129
151
  // Bash only when a subagent can use it: one that lists it, or one without `tools`, which
130
152
  // inherits every session tool. Its definition costs about 1.9k input tokens on every call
131
153
  // (measured), and the main agent can't use it anyway.
132
154
  const subagentTools = includeSubagentTools
133
- ? ["Agent", ...(Object.values(subagents.agents).some((agent) => !agent.tools || agent.tools.includes("Bash")) ? ["Bash"] : [])]
155
+ ? ["Agent", ...(Object.values(allAgents).some((agent) => !agent.tools || agent.tools.includes("Bash")) ? ["Bash"] : [])]
134
156
  : [];
135
157
  // The exact set of subagent_type values the Agent tool may spawn in this session — see
136
158
  // createSubagentTypeGate() below for why this can't just be "whatever's in `agents`
137
159
  // below": the SDK's own built-in "general-purpose" type is spawnable regardless of that
138
160
  // map, and inherits the full session tools (Bash included) rather than the narrow list
139
161
  // each declared subagent actually declares.
140
- const allowedSubagentTypes = subagents?.allowedSubagentTypes ?? [];
162
+ const allowedSubagentTypes = [...new Set([...(subagents?.allowedSubagentTypes ?? []), ...Object.keys(fromPlugins)])];
141
163
  const transcriptPath = path.join(runDir, "transcript.jsonl");
142
164
  const transcriptLogger = createTranscriptLogger(transcriptPath, config.secrets ?? []);
143
- // The person's preferences, by title, for the knowledge base's section (#33).
144
- const preferences = knowledgeStore
145
- ? (await knowledgeStore.list()).filter((page) => page.type === "preference" && page.status === "active").map(({ id, title }) => ({ id, title }))
146
- : [];
147
165
  const promptSections = [
148
166
  spec.buildSystemPrompt(config),
149
- ...(spec.identity ? [identityPromptSection(spec.identity)] : []),
150
- // The sources' own section, with or without a knowledge base (#30).
151
- ...(config.sourcesDir ? [sourcesPromptSection(config.projectDir, config.sourcesDir)] : []),
152
- ...(includeKnowledgeBase && config.knowledgeDir
153
- ? [knowledgePromptSection({ withSources: Boolean(config.sourcesDir), pageTypes: knowledgeStore?.types(), preferences })]
154
- : []),
167
+ // What's on and what isn't, then the extensions' own sections.
168
+ ...(resolved.active.length || resolved.inactive.length ? [extensionsPromptSection(resolved)] : []),
169
+ // The extensions' own sections, in their order (the sources' before the knowledge base's).
170
+ ...fromExtensions((contribution) => (contribution.promptSection ? [contribution.promptSection] : [])),
155
171
  ];
172
+ // Packaged, the SDK would look for its CLI binary inside the archive, and hang (#42).
173
+ const claudeExecutable = unpackedClaudeExecutable();
156
174
  const sdkOptions = {
175
+ ...(claudeExecutable ? { pathToClaudeCodeExecutable: claudeExecutable } : {}),
157
176
  systemPrompt: withReplyLine(promptSections.join("\n\n")),
158
177
  // Not the SDK's default (every source): "user" hands the agent the runner's own Claude
159
178
  // Code configuration, and its `language` setting outranked the agent's prompt.
@@ -173,6 +192,9 @@ export async function buildSessionOptions(config, runDir, spec, options = {}) {
173
192
  autoMemoryEnabled: false,
174
193
  includeGitInstructions: false,
175
194
  disableClaudeAiConnectors: true,
195
+ // An installed extension's plugin may carry hooks: none run (ADR-025). The kit's own,
196
+ // passed in `hooks`, still do (confirmed empirically).
197
+ ...(externalPlugins.size ? { disableAllHooks: true } : {}),
176
198
  },
177
199
  // No built-in tools except, if applicable, Read/Write/Edit/Glob/Grep scoped to the
178
200
  // project's own folders (fileScopeGate below), and WebFetch/WebSearch
@@ -214,9 +236,9 @@ export async function buildSessionOptions(config, runDir, spec, options = {}) {
214
236
  additionalDirectories: searchableDirs,
215
237
  // "skills" acts as a name whitelist, not an addition: "all" enables both the
216
238
  // SDK's own official skills (pdf/docx), the project's own custom ones, and the
217
- // plugin-provided built-ins below. A spec's own list gets the knowledge base's
218
- // skills and agent-help added, so it only names its own.
219
- skills: skillList(offeredSkills, includeKnowledgeBase, Boolean(helpPlugin)),
239
+ // plugin-provided built-ins below. A spec's own list gets the extensions' skills
240
+ // added, so it only names its own.
241
+ skills: skillList(offeredSkills, await pluginSkills(extensionPlugins), missingCapabilities),
220
242
  plugins: pluginRoots.map((pluginPath) => ({ type: "local", path: pluginPath, skipMcpDiscovery: true })),
221
243
  }
222
244
  : {}),
@@ -227,29 +249,15 @@ export async function buildSessionOptions(config, runDir, spec, options = {}) {
227
249
  ...spec.buildMcpServers(config, runDir),
228
250
  ...(includeApprovalTool ? { approvals: createHumanApprovalServer(runDir, spec.humanApprovalTexts, { modeControl }) } : {}),
229
251
  ...(manualInterventionTexts ? { manualLogin: createManualLoginServer(runDir, manualInterventionTexts) } : {}),
230
- // The sources folder's tools (tools/saveToSources.ts); asking a person (request_file,
231
- // retire_source) only where there is one.
232
- ...(config.sourcesDir
233
- ? {
234
- sourceFiles: createSaveToSourcesServer(runDir, config.sourcesDir, spec.saveToSourcesDescription, {
235
- projectDir: config.projectDir,
236
- interactive: mode !== "autonomous",
237
- }),
238
- }
239
- : {}),
240
- // The knowledge base's own tools, over its store (tools/knowledgeTools.ts, ADR-024).
241
- ...(knowledgeStore
242
- ? {
243
- knowledge: createKnowledgeServer(knowledgeStore, { runDir, interactive: mode !== "autonomous" }),
244
- }
245
- : {}),
252
+ // The extensions' tools (the knowledge base's, the sources').
253
+ ...Object.assign({}, ...added.map((contribution) => contribution.mcpServers ?? {})),
246
254
  // The date and date arithmetic, in every session and mode: only reads (tools/time.ts).
247
255
  time: createTimeServer(config.timeZone),
248
256
  },
249
257
  hooks: {
250
258
  PreToolUse: [
251
259
  { hooks: [transcriptLogger.preToolUse] },
252
- ...(includeFileTools
260
+ ...(fileTools.length || toolOnlyDirs.length
253
261
  ? [{ hooks: [createFileScopeGate({
254
262
  projectDir: config.projectDir,
255
263
  writableDirs,
@@ -264,13 +272,13 @@ export async function buildSessionOptions(config, runDir, spec, options = {}) {
264
272
  readableDirs: searchableDirs,
265
273
  alsoReadable: [runDir, ...pluginRoots, ...((spec.settingSources ?? ["project"]).includes("project") ? [path.join(config.projectDir, ".claude")] : [])],
266
274
  toolResultsRoot: claudeProjectDir(config.projectDir),
267
- ...(includeKnowledgeBase && config.knowledgeDir ? { toolOnlyDirs: [{ dir: config.knowledgeDir, instead: "the knowledge_* tools" }] } : {}),
275
+ toolOnlyDirs,
268
276
  }),
269
277
  ] }]
270
278
  : []),
271
279
  // Registered wherever the approval tool is, and asking only while the current mode is
272
280
  // "interactive": a guided session can switch to interactive and back (ModeControl).
273
- ...(includeApprovalTool ? [{ hooks: [createStepGate(runDir, () => modeControl.mode === "interactive")] }] : []),
281
+ ...(includeApprovalTool ? [{ hooks: [createStepGate(runDir, () => modeControl.mode === "interactive", fromExtensions((contribution) => contribution.selfAskingTools))] }] : []),
274
282
  // Likewise for "plan", which any non-autonomous session can switch into: the agent
275
283
  // only reads and plans while it's on (hooks/planGate.ts).
276
284
  ...(includeApprovalTool
@@ -279,6 +287,7 @@ export async function buildSessionOptions(config, runDir, spec, options = {}) {
279
287
  hooks: [
280
288
  createPlanGate({
281
289
  projectDir: config.projectDir,
290
+ readOnlyTools: fromExtensions((contribution) => contribution.readOnlyTools),
282
291
  ...(spec.planMode?.isPlanFile ? { isPlanFile: (filePath) => spec.planMode.isPlanFile(filePath, config) } : {}),
283
292
  ...(spec.planMode?.isReadOnlyTool ? { isReadOnlyTool: spec.planMode.isReadOnlyTool } : {}),
284
293
  }, () => modeControl.mode === "plan"),
@@ -297,7 +306,42 @@ export async function buildSessionOptions(config, runDir, spec, options = {}) {
297
306
  PostToolUse: [{ hooks: [transcriptLogger.postToolUse] }],
298
307
  },
299
308
  };
300
- return { options: sdkOptions, transcriptLogger, transcriptPath, modeControl, language, ...(knowledgeStore ? { knowledgeStore } : {}) };
309
+ // The extensions' own hooks (the memory hears the person's messages), after the kit's.
310
+ for (const contribution of added) {
311
+ for (const [event, matchers] of Object.entries(contribution.hooks ?? {})) {
312
+ sdkOptions.hooks[event] = [...(sdkOptions.hooks[event] ?? []), ...matchers];
313
+ }
314
+ }
315
+ const toolLabels = Object.assign({}, ...added.map((contribution) => contribution.toolLabels ?? {}));
316
+ const extensions = {
317
+ dirs: extensionDirs,
318
+ installed: await listInstalled(extensionDirs),
319
+ active: resolved.active.map(({ extension }) => extension.name),
320
+ about: Object.fromEntries(resolved.active.map(({ extension, manifest }) => [extension.name, { description: manifest.description, provides: manifest.provides }])),
321
+ inactive: resolved.inactive,
322
+ };
323
+ // What the session is, for the extensions that ask (sessionFacts.ts, #43).
324
+ late.view = createSessionView({
325
+ ...(spec.identity ? { identity: spec.identity } : {}),
326
+ kitVersion: agentKitVersion(),
327
+ language,
328
+ extensions: {
329
+ active: resolved.active.map(({ extension, manifest }, index) => ({
330
+ name: extension.name,
331
+ description: manifest.description,
332
+ provides: manifest.provides,
333
+ servers: Object.keys(added[index]?.mcpServers ?? {}),
334
+ help: added[index]?.helpLines ?? [],
335
+ })),
336
+ inactive: resolved.inactive,
337
+ },
338
+ subagents: Object.entries(allAgents).map(([name, agent]) => ({ name, description: agent.description })),
339
+ skills: sdkOptions.skills === "all" ? await pluginSkills(pluginRoots) : [...(sdkOptions.skills ?? [])],
340
+ runDir,
341
+ }, modeControl);
342
+ registerSessionView(sdkOptions, late.view);
343
+ const apis = Object.fromEntries(resolved.active.flatMap(({ extension }, index) => (added[index]?.api ? [[extension.name, added[index].api]] : [])));
344
+ return { options: sdkOptions, transcriptLogger, transcriptPath, modeControl, language, toolLabels, extensions, apis, ...(knowledgeStore ? { knowledgeStore } : {}) };
301
345
  }
302
346
  export { createModeControl, togglePlanMode } from "./modeControl.js";
303
347
  /** The Claude Code configuration folder the SDK's CLI uses: `CLAUDE_CONFIG_DIR`, or `~/.claude`. */
@@ -312,8 +356,8 @@ function claudeConfigDir() {
312
356
  export function claudeProjectDir(projectDir) {
313
357
  return path.join(claudeConfigDir(), "projects", path.resolve(projectDir).replace(/[^a-zA-Z0-9]/g, "-"));
314
358
  }
315
- /** The knowledge plugin's skills, as the SDK names a plugin's skills ("plugin:skill"). */
316
- const KNOWLEDGE_SKILLS = ["knowledge-ingest", "knowledge-query", "knowledge-lint"].map((skill) => `knowledge:${skill}`);
359
+ /** The built-in file tools, in the order the session lists them. */
360
+ const FILE_TOOLS = ["Read", "Write", "Edit", "Glob", "Grep"];
317
361
  /**
318
362
  * The skills of the plugins in `roots`, as the SDK names them: `<plugin>:<folder>`, the
319
363
  * plugin's name from its `.claude-plugin/plugin.json` and the skill's folder under `skills/`,
@@ -340,10 +384,15 @@ export async function pluginSkills(roots) {
340
384
  }
341
385
  return names;
342
386
  }
343
- function skillList(skills, knowledgeBase, agentHelp) {
387
+ function skillList(skills, added, leftOut) {
344
388
  if (skills === undefined || skills === "all")
345
389
  return "all";
346
- return [...new Set([...skills, ...(knowledgeBase ? KNOWLEDGE_SKILLS : []), ...(agentHelp ? [AGENT_HELP_SKILL] : [])])];
390
+ return [...new Set([...skills, ...added])].filter((skill) => !leftOut.includes(skill));
391
+ }
392
+ /** The project's own skills (`<projectDir>/.claude/skills/<name>/SKILL.md`), by name. */
393
+ async function projectSkills(projectDir) {
394
+ const folders = await readdir(path.join(projectDir, ".claude", "skills"), { withFileTypes: true }).catch(() => []);
395
+ return folders.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
347
396
  }
348
397
  /**
349
398
  * User message queue backed by a single long-lived generator, for any multi-turn
@@ -0,0 +1,80 @@
1
+ import type { Options, SlashCommand } from "@anthropic-ai/claude-agent-sdk";
2
+ import type { AgentIdentity, Mode } from "./agentSpec.js";
3
+ import type { Language } from "./language.js";
4
+ import type { ModeControl } from "./modeControl.js";
5
+ import type { ContextUsage } from "./runner.js";
6
+ /**
7
+ * What a session is, at the moment it's asked (`ExtensionContext.session()`, #43): the core's
8
+ * facts, read-only, never another extension's data. The mode follows Shift+Tab and plan mode;
9
+ * the tools, skills, commands and context come from the running session once it has started.
10
+ */
11
+ export interface SessionFacts {
12
+ /** Who the agent is (`AgentSpec.identity`). */
13
+ identity?: AgentIdentity;
14
+ /** The agent-kit version it runs on. */
15
+ kitVersion: string;
16
+ /** The kit's language for this session. */
17
+ language: Language;
18
+ /** The mode now, and the ones the person can switch to (Shift+Tab). */
19
+ mode: Mode;
20
+ switchableModes: Mode[];
21
+ /** The extensions running (with their tools and what they say about themselves here), and the ones off, with why. */
22
+ extensions: {
23
+ active: {
24
+ name: string;
25
+ description: string;
26
+ provides: string[];
27
+ tools: string[];
28
+ help: string[];
29
+ }[];
30
+ inactive: {
31
+ name: string;
32
+ reason: string;
33
+ }[];
34
+ };
35
+ /** The subagents it can delegate to. */
36
+ subagents: {
37
+ name: string;
38
+ description: string;
39
+ }[];
40
+ /** Every tool of the session, as the model names it (empty until the session has started). */
41
+ tools: string[];
42
+ /** The skills offered (the running session's list once started; until then, the ones asked for). */
43
+ skills: string[];
44
+ /** The slash commands the person can type, with what each does (empty until the session has started). */
45
+ commands: {
46
+ name: string;
47
+ description: string;
48
+ argumentHint: string;
49
+ }[];
50
+ /** How full the context window is, when the session can tell. */
51
+ context?: ContextUsage;
52
+ /** This run's folder. */
53
+ runDir: string;
54
+ }
55
+ /** What the running session tells the view: `runQuery()` attaches it on its own. */
56
+ export interface SessionLive {
57
+ tools?: string[];
58
+ skills?: string[];
59
+ supportedCommands?: () => Promise<SlashCommand[]>;
60
+ contextUsage?: () => Promise<ContextUsage | null>;
61
+ }
62
+ /** The facts known when the options are built: everything but the mode and what only the running session knows. */
63
+ export type StaticSessionFacts = Omit<SessionFacts, "mode" | "switchableModes" | "tools" | "commands" | "context" | "extensions"> & {
64
+ extensions: {
65
+ active: (Omit<SessionFacts["extensions"]["active"][number], "tools"> & {
66
+ servers: string[];
67
+ })[];
68
+ inactive: SessionFacts["extensions"]["inactive"];
69
+ };
70
+ };
71
+ export interface SessionView {
72
+ facts(): Promise<SessionFacts>;
73
+ attach(live: SessionLive): void;
74
+ }
75
+ /** The view of a session: its static facts, the mode read from `modeControl` on every call, and what the running session attaches. */
76
+ export declare function createSessionView(base: StaticSessionFacts, modeControl: ModeControl): SessionView;
77
+ /** Ties a view to the options `buildSessionOptions()` returns. */
78
+ export declare function registerSessionView(options: Options, view: SessionView): void;
79
+ /** The view tied to these options (or a spread copy of them), if `buildSessionOptions()` built them. */
80
+ export declare function sessionViewOf(options: Options): SessionView | undefined;
@@ -0,0 +1,48 @@
1
+ // A live call made from inside a tool, mid-turn: never let it hold the tool up.
2
+ const LIVE_TIMEOUT_MS = 3000;
3
+ const within = (promise, fallback) => Promise.race([promise.catch(() => fallback), new Promise((resolve) => setTimeout(() => resolve(fallback), LIVE_TIMEOUT_MS).unref())]);
4
+ /** The view of a session: its static facts, the mode read from `modeControl` on every call, and what the running session attaches. */
5
+ export function createSessionView(base, modeControl) {
6
+ let live = {};
7
+ return {
8
+ attach(more) {
9
+ live = { ...live, ...more };
10
+ },
11
+ async facts() {
12
+ const tools = live.tools ?? [];
13
+ const [commands, context] = await Promise.all([
14
+ live.supportedCommands ? within(live.supportedCommands(), []) : Promise.resolve([]),
15
+ live.contextUsage ? within(live.contextUsage(), null) : Promise.resolve(null),
16
+ ]);
17
+ return {
18
+ ...base,
19
+ mode: modeControl.mode,
20
+ switchableModes: [...modeControl.switchable],
21
+ extensions: {
22
+ active: base.extensions.active.map(({ servers, ...extension }) => ({
23
+ ...extension,
24
+ // The running session's names when it has started; until then, each server's wildcard.
25
+ tools: tools.length ? tools.filter((tool) => servers.some((server) => tool.startsWith(`mcp__${server}__`))) : servers.map((server) => `mcp__${server}__*`),
26
+ })),
27
+ inactive: base.extensions.inactive,
28
+ },
29
+ tools,
30
+ skills: live.skills ?? base.skills,
31
+ commands: commands.map(({ name, description, argumentHint }) => ({ name, description, argumentHint })),
32
+ ...(context ? { context } : {}),
33
+ };
34
+ },
35
+ };
36
+ }
37
+ // The view rides on the options under a symbol, for runQuery() to attach the running session to
38
+ // without the host passing anything: a spread (`{ ...options, more }`) keeps it, the SDK ignores
39
+ // it, and options built some other way just leave the live facts out.
40
+ const SESSION_VIEW = Symbol.for("agent-kit.sessionView");
41
+ /** Ties a view to the options `buildSessionOptions()` returns. */
42
+ export function registerSessionView(options, view) {
43
+ Object.defineProperty(options, SESSION_VIEW, { value: view, enumerable: true });
44
+ }
45
+ /** The view tied to these options (or a spread copy of them), if `buildSessionOptions()` built them. */
46
+ export function sessionViewOf(options) {
47
+ return options[SESSION_VIEW];
48
+ }
@@ -1,12 +1,13 @@
1
+ import { type ToolPhrase } from "./messages/index.js";
1
2
  /**
2
3
  * Turns a raw tool name + input into a short, readable console description, instead of
3
4
  * the tool's technical name (e.g. "mcp__playwright__browser_click"). Covers the tools
4
5
  * this kit itself provides (Read/Write/Edit/Glob/Grep/Bash/Agent/WebFetch/WebSearch/Skill,
5
- * plus its own human-approval/manual-intervention/save-to-sources MCP tools)
6
- * generically; a
7
- * concrete agent supplies a `describe` callback for its own domain-specific tools (e.g.
8
- * Playwright's browser_* cases) via `createFriendlyToolLabel()`. The kit's own labels are in
9
- * the current language (see messages/).
6
+ * plus its own human-approval/manual-intervention/clock MCP tools) generically; an extension
7
+ * brings its tools' labels with its contribution (`ToolLabels`, ADR-025), and a concrete agent
8
+ * supplies a `describe` callback for its own domain-specific tools (e.g. Playwright's
9
+ * browser_* cases) via `createFriendlyToolLabel()`. The kit's own labels are in the current
10
+ * language (see messages/).
10
11
  */
11
12
  /** Cuts `text` to `max` characters, with "…" at the end. */
12
13
  export declare function truncate(text: string, max?: number): string;
@@ -15,13 +16,30 @@ export declare function truncate(text: string, max?: number): string;
15
16
  * the tail off long freeform text), a path's most useful part, the file name, is at the end.
16
17
  */
17
18
  export declare function truncatePath(text: string, max?: number): string;
19
+ /** How the chat shows one tool: an extension's, by its full name (`ExtensionContribution.toolLabels`). */
20
+ export interface ToolLabel {
21
+ /** Its line in the chat, from its input, in the kit's language: "Reading concept/llm-wiki". */
22
+ label(input: Record<string, unknown>): string;
23
+ /** How it counts in a folded group's summary, `[one, many]` with `{n}`: `["read {n} page", "read {n} pages"]`. */
24
+ phrase?: ToolPhrase;
25
+ }
26
+ /** Tools' labels by full name (`mcp__<server>__<tool>`): what the extensions of a session bring. */
27
+ export type ToolLabels = Readonly<Record<string, ToolLabel>>;
28
+ /**
29
+ * A `formatAction` that shows the tools in `labels()` with their label, and any other with
30
+ * `formatAction` (the kit's by default). `labels` is read on every call, so it can follow the
31
+ * session in use (`/resume` opens another).
32
+ */
33
+ export declare function withToolLabels(labels: () => ToolLabels | undefined, formatAction?: (toolName: string, toolInput: unknown) => string): (toolName: string, toolInput: unknown) => string;
34
+ /** A `toolPhrase` that counts the tools in `labels()` with their phrase, and any other with `toolPhrase`. */
35
+ export declare function withToolPhrases(labels: () => ToolLabels | undefined, toolPhrase?: (toolName: string) => ToolPhrase | undefined): (toolName: string) => ToolPhrase | undefined;
18
36
  /** An agent's labels for its own tools: the tool's short name and input, to a label, or `undefined` for the kit's default. */
19
37
  export type ToolDescriber = (shortName: string, input: Record<string, unknown>) => string | undefined;
20
38
  /**
21
39
  * Builds a `friendlyToolLabel(toolName, toolInput)` — `describe` lets the host agent
22
40
  * layer its own domain-specific cases (e.g. Playwright's browser_* tools) on top of this
23
41
  * kit's generic ones; `extraLocalServers` names any *additional* MCP server (beyond this
24
- * kit's own "approvals"/"manualLogin"/"sourceFiles"/"time") whose tools should be unwrapped
42
+ * kit's own "approvals"/"manualLogin"/"time") whose tools should be unwrapped
25
43
  * without a "[server] " prefix, e.g. "playwright".
26
44
  */
27
45
  export declare function createFriendlyToolLabel(options?: {