@robota-sdk/agent-sdk 3.0.0-beta.4 → 3.0.0-beta.43

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.
@@ -30,31 +30,53 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ AgentExecutor: () => AgentExecutor,
34
+ BUILT_IN_AGENTS: () => BUILT_IN_AGENTS,
35
+ BuiltinCommandSource: () => BuiltinCommandSource,
36
+ BundlePluginInstaller: () => BundlePluginInstaller,
37
+ BundlePluginLoader: () => BundlePluginLoader,
38
+ CommandRegistry: () => CommandRegistry,
33
39
  DEFAULT_TOOL_DESCRIPTIONS: () => DEFAULT_TOOL_DESCRIPTIONS,
34
- FileSessionLogger: () => import_agent_sessions3.FileSessionLogger,
35
- Session: () => import_agent_sessions2.Session,
36
- SessionStore: () => import_agent_sessions4.SessionStore,
37
- SilentSessionLogger: () => import_agent_sessions3.SilentSessionLogger,
40
+ FileSessionLogger: () => import_agent_sessions6.FileSessionLogger,
41
+ InteractiveSession: () => InteractiveSession,
42
+ MarketplaceClient: () => MarketplaceClient,
43
+ PluginSettingsStore: () => PluginSettingsStore,
44
+ PromptExecutor: () => PromptExecutor,
45
+ Session: () => import_agent_sessions5.Session,
46
+ SessionStore: () => import_agent_sessions7.SessionStore,
47
+ SilentSessionLogger: () => import_agent_sessions6.SilentSessionLogger,
48
+ SkillCommandSource: () => SkillCommandSource,
49
+ SystemCommandExecutor: () => SystemCommandExecutor,
38
50
  TRUST_TO_MODE: () => import_agent_core.TRUST_TO_MODE,
39
- agentTool: () => agentTool,
51
+ assembleSubagentPrompt: () => assembleSubagentPrompt,
40
52
  bashTool: () => import_agent_tools3.bashTool,
41
53
  buildSystemPrompt: () => buildSystemPrompt,
54
+ createAgentTool: () => createAgentTool,
42
55
  createDefaultTools: () => createDefaultTools,
43
56
  createProvider: () => createProvider,
44
57
  createSession: () => createSession,
58
+ createSubagentLogger: () => createSubagentLogger,
59
+ createSubagentSession: () => createSubagentSession,
60
+ createSystemCommands: () => createSystemCommands,
45
61
  detectProject: () => detectProject,
46
62
  editTool: () => import_agent_tools6.editTool,
47
- evaluatePermission: () => import_agent_core2.evaluatePermission,
63
+ evaluatePermission: () => import_agent_core4.evaluatePermission,
64
+ getBuiltInAgent: () => getBuiltInAgent,
65
+ getForkWorkerSuffix: () => getForkWorkerSuffix,
66
+ getSubagentSuffix: () => getSubagentSuffix,
48
67
  globTool: () => import_agent_tools7.globTool,
49
68
  grepTool: () => import_agent_tools8.grepTool,
50
69
  loadConfig: () => loadConfig,
51
70
  loadContext: () => loadContext,
71
+ parseFrontmatter: () => parseFrontmatter2,
52
72
  projectPaths: () => projectPaths,
53
73
  promptForApproval: () => promptForApproval,
54
74
  query: () => query,
55
75
  readTool: () => import_agent_tools4.readTool,
56
- runHooks: () => import_agent_core3.runHooks,
57
- setAgentToolDeps: () => setAgentToolDeps,
76
+ resolveSubagentLogDir: () => resolveSubagentLogDir,
77
+ retrieveAgentToolDeps: () => retrieveAgentToolDeps,
78
+ runHooks: () => import_agent_core5.runHooks,
79
+ storeAgentToolDeps: () => storeAgentToolDeps,
58
80
  userPaths: () => userPaths,
59
81
  writeTool: () => import_agent_tools5.writeTool
60
82
  });
@@ -63,8 +85,115 @@ module.exports = __toCommonJS(index_exports);
63
85
  // src/types.ts
64
86
  var import_agent_core = require("@robota-sdk/agent-core");
65
87
 
88
+ // src/hooks/prompt-executor.ts
89
+ function extractJson(raw) {
90
+ const codeBlockMatch = /```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/.exec(raw);
91
+ if (codeBlockMatch) {
92
+ return codeBlockMatch[1].trim();
93
+ }
94
+ return raw.trim();
95
+ }
96
+ var PromptExecutor = class {
97
+ type = "prompt";
98
+ providerFactory;
99
+ defaultModel;
100
+ constructor(options) {
101
+ this.providerFactory = options.providerFactory;
102
+ this.defaultModel = options.defaultModel;
103
+ }
104
+ async execute(definition, input) {
105
+ const promptDef = definition;
106
+ const model = promptDef.model ?? this.defaultModel;
107
+ try {
108
+ const provider = this.providerFactory(model);
109
+ const prompt = `${promptDef.prompt}
110
+
111
+ Context:
112
+ ${JSON.stringify(input)}
113
+
114
+ Respond with JSON: { "ok": boolean, "reason"?: string }`;
115
+ const rawResponse = await provider.complete(prompt);
116
+ const jsonStr = extractJson(rawResponse);
117
+ let parsed;
118
+ try {
119
+ parsed = JSON.parse(jsonStr);
120
+ } catch {
121
+ return {
122
+ exitCode: 1,
123
+ stdout: "",
124
+ stderr: `Failed to parse AI response as JSON: ${rawResponse}`
125
+ };
126
+ }
127
+ if (parsed.ok) {
128
+ return { exitCode: 0, stdout: JSON.stringify(parsed), stderr: "" };
129
+ }
130
+ return {
131
+ exitCode: 2,
132
+ stdout: "",
133
+ stderr: parsed.reason ?? "Blocked by prompt hook"
134
+ };
135
+ } catch (err) {
136
+ const message = err instanceof Error ? err.message : String(err);
137
+ return { exitCode: 1, stdout: "", stderr: message };
138
+ }
139
+ }
140
+ };
141
+
142
+ // src/hooks/agent-executor.ts
143
+ var DEFAULT_MAX_TURNS = 50;
144
+ var DEFAULT_TIMEOUT_SECONDS = 60;
145
+ function extractJson2(raw) {
146
+ const codeBlockMatch = /```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/.exec(raw);
147
+ if (codeBlockMatch) {
148
+ return codeBlockMatch[1].trim();
149
+ }
150
+ return raw.trim();
151
+ }
152
+ var AgentExecutor = class {
153
+ type = "agent";
154
+ sessionFactory;
155
+ constructor(options) {
156
+ this.sessionFactory = options.sessionFactory;
157
+ }
158
+ async execute(definition, input) {
159
+ const agentDef = definition;
160
+ const maxTurns = agentDef.maxTurns ?? DEFAULT_MAX_TURNS;
161
+ const timeout = agentDef.timeout ?? DEFAULT_TIMEOUT_SECONDS;
162
+ try {
163
+ const session = this.sessionFactory({ maxTurns, timeout });
164
+ const prompt = `Hook input:
165
+ ${JSON.stringify(input)}
166
+
167
+ Respond with JSON: { "ok": boolean, "reason"?: string }`;
168
+ const rawResponse = await session.run(prompt);
169
+ const jsonStr = extractJson2(rawResponse);
170
+ let parsed;
171
+ try {
172
+ parsed = JSON.parse(jsonStr);
173
+ } catch {
174
+ return {
175
+ exitCode: 1,
176
+ stdout: "",
177
+ stderr: `Failed to parse agent response as JSON: ${rawResponse}`
178
+ };
179
+ }
180
+ if (parsed.ok) {
181
+ return { exitCode: 0, stdout: JSON.stringify(parsed), stderr: "" };
182
+ }
183
+ return {
184
+ exitCode: 2,
185
+ stdout: "",
186
+ stderr: parsed.reason ?? "Blocked by agent hook"
187
+ };
188
+ } catch (err) {
189
+ const message = err instanceof Error ? err.message : String(err);
190
+ return { exitCode: 1, stdout: "", stderr: message };
191
+ }
192
+ }
193
+ };
194
+
66
195
  // src/assembly/create-session.ts
67
- var import_agent_sessions = require("@robota-sdk/agent-sessions");
196
+ var import_agent_sessions2 = require("@robota-sdk/agent-sessions");
68
197
 
69
198
  // src/context/system-prompt-builder.ts
70
199
  var TRUST_LEVEL_DESCRIPTIONS = {
@@ -95,17 +224,38 @@ function buildToolsSection(descriptions) {
95
224
  const lines = ["## Available Tools", ...descriptions.map((d) => `- ${d}`)];
96
225
  return lines.join("\n");
97
226
  }
227
+ function buildSkillsSection(skills) {
228
+ const invocable = skills.filter((s) => s.disableModelInvocation !== true);
229
+ if (invocable.length === 0) {
230
+ return "";
231
+ }
232
+ const lines = [
233
+ "## Skills",
234
+ "The following skills are available:",
235
+ "",
236
+ ...invocable.map((s) => `- ${s.name}: ${s.description}`)
237
+ ];
238
+ return lines.join("\n");
239
+ }
98
240
  function buildSystemPrompt(params) {
99
- const { agentsMd, claudeMd, toolDescriptions, trustLevel, projectInfo } = params;
241
+ const { agentsMd, claudeMd, toolDescriptions, trustLevel, projectInfo, cwd, language } = params;
100
242
  const sections = [];
101
- sections.push(
102
- [
103
- "## Role",
104
- "You are an AI coding assistant with access to tools that let you read and modify code.",
105
- "You help developers understand, write, and improve their codebase.",
106
- "Always be precise, follow existing code conventions, and prefer minimal changes."
107
- ].join("\n")
108
- );
243
+ const roleLines = [
244
+ "## Role",
245
+ "You are an AI coding assistant with access to tools that let you read and modify code.",
246
+ "You help developers understand, write, and improve their codebase.",
247
+ "Always be precise, follow existing code conventions, and prefer minimal changes."
248
+ ];
249
+ if (language) {
250
+ roleLines.push(
251
+ `Always respond in ${language}. Use ${language} for all explanations and communications.`
252
+ );
253
+ }
254
+ sections.push(roleLines.join("\n"));
255
+ if (cwd) {
256
+ sections.push(`## Working Directory
257
+ \`${cwd}\``);
258
+ }
109
259
  sections.push(buildProjectSection(projectInfo));
110
260
  sections.push(
111
261
  [
@@ -131,6 +281,12 @@ function buildSystemPrompt(params) {
131
281
  if (toolsSection.length > 0) {
132
282
  sections.push(toolsSection);
133
283
  }
284
+ if (params.skills !== void 0 && params.skills.length > 0) {
285
+ const skillsSection = buildSkillsSection(params.skills);
286
+ if (skillsSection.length > 0) {
287
+ sections.push(skillsSection);
288
+ }
289
+ }
134
290
  return sections.join("\n\n");
135
291
  }
136
292
 
@@ -170,25 +326,407 @@ function createProvider(config) {
170
326
  return new import_agent_provider_anthropic.AnthropicProvider({ apiKey });
171
327
  }
172
328
 
329
+ // src/tools/agent-tool.ts
330
+ var import_zod = require("zod");
331
+ var import_agent_tools2 = require("@robota-sdk/agent-tools");
332
+
333
+ // src/agents/built-in-agents.ts
334
+ var GENERAL_PURPOSE_SYSTEM_PROMPT = `You are a general-purpose task execution agent. You have access to all tools available in the parent session and can perform any task delegated to you.
335
+
336
+ Your role is to complete the assigned task thoroughly and accurately. Follow these guidelines:
337
+
338
+ - Execute the task as described in the prompt. Do not expand scope beyond what is requested.
339
+ - Use the most appropriate tools for each step. Prefer precise tools (Read, Grep, Glob) over broad ones (Bash) when possible.
340
+ - Report your findings clearly and concisely when the task is complete.
341
+ - If a task cannot be completed, explain why and what information is missing.
342
+ - Maintain the same code quality standards as the parent session (strict types, no fallbacks, proper error handling).`;
343
+ var EXPLORE_SYSTEM_PROMPT = `You are a codebase exploration and analysis agent. Your purpose is to search, read, and understand code without making any modifications.
344
+
345
+ You operate in read-only mode. You must NEVER attempt to write or edit files. Your tools are restricted to read-only operations: reading files, searching with grep and glob, and running non-destructive bash commands.
346
+
347
+ Your role is to answer questions about the codebase by:
348
+
349
+ - Searching for relevant files, symbols, and patterns using Glob and Grep.
350
+ - Reading source files, configuration, and documentation to understand structure and behavior.
351
+ - Tracing code paths across modules to understand how components interact.
352
+ - Summarizing findings in a clear, structured format with file paths and line references.
353
+ - Identifying architectural patterns, dependencies, and potential issues.
354
+
355
+ When exploring, prefer targeted searches over broad scans. Start with the most likely locations and narrow down. Always include absolute file paths in your responses so the caller can navigate directly to relevant code.`;
356
+ var PLAN_SYSTEM_PROMPT = `You are a planning, research, and architecture agent. Your purpose is to analyze requirements, research approaches, and produce structured plans without making any code modifications.
357
+
358
+ You operate in read-only mode. You must NEVER attempt to write or edit files. Your tools are restricted to read-only operations.
359
+
360
+ Your role is to:
361
+
362
+ - Analyze the current codebase state relevant to the task by reading specs, source code, and tests.
363
+ - Research implementation approaches by examining existing patterns and architectural conventions in the repository.
364
+ - Identify affected files, modules, and interfaces that a proposed change would touch.
365
+ - Assess risks, dependencies, and potential breaking changes.
366
+ - Produce a structured implementation plan with clear steps, file lists, and ordering.
367
+ - Consider edge cases, error handling, and test coverage requirements.
368
+
369
+ Output your plan in a structured format with numbered steps. For each step, specify which files are involved and what changes are needed. Flag any decisions that require human judgment or clarification.`;
370
+ var BUILT_IN_AGENTS = [
371
+ {
372
+ name: "general-purpose",
373
+ description: "General-purpose task execution agent with full tool access.",
374
+ systemPrompt: GENERAL_PURPOSE_SYSTEM_PROMPT
375
+ },
376
+ {
377
+ name: "Explore",
378
+ description: "Read-only codebase exploration and analysis agent.",
379
+ systemPrompt: EXPLORE_SYSTEM_PROMPT,
380
+ model: "claude-haiku-4-5",
381
+ disallowedTools: ["Write", "Edit"]
382
+ },
383
+ {
384
+ name: "Plan",
385
+ description: "Read-only planning, research, and architecture agent.",
386
+ systemPrompt: PLAN_SYSTEM_PROMPT,
387
+ disallowedTools: ["Write", "Edit"]
388
+ }
389
+ ];
390
+ function getBuiltInAgent(name) {
391
+ return BUILT_IN_AGENTS.find((agent) => agent.name === name);
392
+ }
393
+
394
+ // src/assembly/create-subagent-session.ts
395
+ var import_agent_sessions = require("@robota-sdk/agent-sessions");
396
+
397
+ // src/assembly/subagent-prompts.ts
398
+ function getSubagentSuffix() {
399
+ return `When you complete the task, respond with a concise report covering what was done and any key findings \u2014 the caller will relay this to the user, so it only needs the essentials.
400
+
401
+ In your final response, share file paths (always absolute, never relative) that are relevant to the task. Include code snippets only when the exact text is load-bearing \u2014 do not recap code you merely read.
402
+
403
+ Do not use emojis.`;
404
+ }
405
+ function getForkWorkerSuffix() {
406
+ return `You are a worker subagent executing a specific task. Do NOT spawn sub-agents; execute directly. Keep your report under 500 words. Use this structure:
407
+ - Scope: What was requested
408
+ - Result: What was done
409
+ - Key files: Relevant file paths (absolute)
410
+ - Files changed: List of modifications
411
+ - Issues: Any problems encountered`;
412
+ }
413
+ function assembleSubagentPrompt(options) {
414
+ const parts = [options.agentBody];
415
+ if (options.claudeMd) {
416
+ parts.push(options.claudeMd);
417
+ }
418
+ if (options.agentsMd) {
419
+ parts.push(options.agentsMd);
420
+ }
421
+ const suffix = options.isForkWorker ? getForkWorkerSuffix() : getSubagentSuffix();
422
+ parts.push(suffix);
423
+ return parts.join("\n\n");
424
+ }
425
+
426
+ // src/assembly/create-subagent-session.ts
427
+ var MODEL_SHORTCUTS = {
428
+ sonnet: "claude-sonnet-4-6",
429
+ haiku: "claude-haiku-4-5",
430
+ opus: "claude-opus-4-6"
431
+ };
432
+ function resolveModelId(shortName, _parentModel) {
433
+ return MODEL_SHORTCUTS[shortName] ?? shortName;
434
+ }
435
+ function filterTools(parentTools, agentDefinition) {
436
+ let tools = [...parentTools];
437
+ if (agentDefinition.disallowedTools) {
438
+ const denySet = new Set(agentDefinition.disallowedTools);
439
+ tools = tools.filter((t) => !denySet.has(t.getName()));
440
+ }
441
+ if (agentDefinition.tools) {
442
+ const allowSet = new Set(agentDefinition.tools);
443
+ tools = tools.filter((t) => allowSet.has(t.getName()));
444
+ }
445
+ tools = tools.filter((t) => t.getName() !== "Agent");
446
+ return tools;
447
+ }
448
+ function createSubagentSession(options) {
449
+ const { agentDefinition, parentConfig, parentContext, parentTools, terminal } = options;
450
+ const tools = filterTools(parentTools, agentDefinition);
451
+ const model = agentDefinition.model ? resolveModelId(agentDefinition.model, parentConfig.provider.model) : parentConfig.provider.model;
452
+ const systemMessage = assembleSubagentPrompt({
453
+ agentBody: agentDefinition.systemPrompt,
454
+ claudeMd: parentContext.claudeMd,
455
+ agentsMd: parentContext.agentsMd,
456
+ isForkWorker: options.isForkWorker ?? false
457
+ });
458
+ const provider = createProvider(parentConfig);
459
+ return new import_agent_sessions.Session({
460
+ tools,
461
+ provider,
462
+ systemMessage,
463
+ terminal,
464
+ model,
465
+ maxTurns: agentDefinition.maxTurns,
466
+ permissions: parentConfig.permissions,
467
+ permissionMode: options.permissionMode,
468
+ defaultTrustLevel: parentConfig.defaultTrustLevel,
469
+ permissionHandler: options.permissionHandler,
470
+ hooks: options.hooks,
471
+ hookTypeExecutors: options.hookTypeExecutors,
472
+ onTextDelta: options.onTextDelta,
473
+ onToolExecution: options.onToolExecution
474
+ });
475
+ }
476
+
477
+ // src/tools/agent-tool.ts
478
+ function asZodSchema(schema) {
479
+ return schema;
480
+ }
481
+ var AgentSchema = import_zod.z.object({
482
+ prompt: import_zod.z.string().describe("The task for the subagent to perform"),
483
+ subagent_type: import_zod.z.string().optional().describe('Agent type: "general-purpose", "Explore", "Plan", or a custom agent name'),
484
+ model: import_zod.z.string().optional().describe("Optional model override")
485
+ });
486
+ var sessionDepsStore = /* @__PURE__ */ new WeakMap();
487
+ function storeAgentToolDeps(key, deps) {
488
+ sessionDepsStore.set(key, deps);
489
+ }
490
+ function retrieveAgentToolDeps(key) {
491
+ return sessionDepsStore.get(key);
492
+ }
493
+ function resolveAgentDefinition(agentType, customRegistry) {
494
+ const builtIn = getBuiltInAgent(agentType);
495
+ if (builtIn) return builtIn;
496
+ if (customRegistry) return customRegistry(agentType);
497
+ return void 0;
498
+ }
499
+ function generateAgentId() {
500
+ return `agent_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
501
+ }
502
+ function createAgentTool(deps) {
503
+ async function runAgent(args) {
504
+ const agentType = args.subagent_type ?? "general-purpose";
505
+ const agentDef = resolveAgentDefinition(agentType, deps.customAgentRegistry);
506
+ if (!agentDef) {
507
+ return JSON.stringify({
508
+ success: false,
509
+ output: "",
510
+ error: `Unknown agent type: ${agentType}`
511
+ });
512
+ }
513
+ const effectiveDef = args.model ? { ...agentDef, model: args.model } : agentDef;
514
+ const session = createSubagentSession({
515
+ agentDefinition: effectiveDef,
516
+ parentConfig: deps.config,
517
+ parentContext: deps.context,
518
+ parentTools: deps.tools,
519
+ terminal: deps.terminal,
520
+ permissionMode: deps.permissionMode,
521
+ permissionHandler: deps.permissionHandler,
522
+ hooks: deps.hooks,
523
+ hookTypeExecutors: deps.hookTypeExecutors,
524
+ onTextDelta: deps.onTextDelta,
525
+ onToolExecution: deps.onToolExecution
526
+ });
527
+ const agentId = generateAgentId();
528
+ try {
529
+ const response = await session.run(args.prompt);
530
+ return JSON.stringify({
531
+ success: true,
532
+ output: response,
533
+ agentId
534
+ });
535
+ } catch (err) {
536
+ const message = err instanceof Error ? err.message : String(err);
537
+ return JSON.stringify({
538
+ success: false,
539
+ output: "",
540
+ error: `Sub-agent error: ${message}`,
541
+ agentId
542
+ });
543
+ }
544
+ }
545
+ return (0, import_agent_tools2.createZodFunctionTool)(
546
+ "Agent",
547
+ "Launch a subagent to handle a task in an isolated context. The subagent gets its own context window and returns a result when done. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.",
548
+ asZodSchema(AgentSchema),
549
+ async (params) => {
550
+ return runAgent(params);
551
+ }
552
+ );
553
+ }
554
+
555
+ // src/agents/agent-definition-loader.ts
556
+ var import_node_fs = require("fs");
557
+ var import_node_path = require("path");
558
+ var import_node_os = require("os");
559
+ var LIST_KEYS = /* @__PURE__ */ new Set(["tools", "disallowedTools"]);
560
+ var NUMBER_KEYS = /* @__PURE__ */ new Set(["maxTurns"]);
561
+ function parseFrontmatter(content) {
562
+ const lines = content.split("\n");
563
+ if (lines[0]?.trim() !== "---") {
564
+ return { frontmatter: null, body: content };
565
+ }
566
+ let endIndex = -1;
567
+ for (let i = 1; i < lines.length; i++) {
568
+ if (lines[i]?.trim() === "---") {
569
+ endIndex = i;
570
+ break;
571
+ }
572
+ }
573
+ if (endIndex === -1) {
574
+ return { frontmatter: null, body: content };
575
+ }
576
+ const result = {};
577
+ for (let i = 1; i < endIndex; i++) {
578
+ const line = lines[i];
579
+ const match = line.match(/^([a-zA-Z][a-zA-Z0-9]*(?:[A-Z][a-z]*)*):\s*(.+)/);
580
+ if (!match) continue;
581
+ const key = match[1];
582
+ const rawValue = match[2].trim();
583
+ if (LIST_KEYS.has(key)) {
584
+ result[key] = rawValue.split(",").map((s) => s.trim());
585
+ } else if (NUMBER_KEYS.has(key)) {
586
+ result[key] = parseInt(rawValue, 10);
587
+ } else {
588
+ result[key] = rawValue;
589
+ }
590
+ }
591
+ const body = lines.slice(endIndex + 1).join("\n").trim();
592
+ return {
593
+ frontmatter: Object.keys(result).length > 0 ? result : null,
594
+ body
595
+ };
596
+ }
597
+ function scanAgentsDir(dir) {
598
+ if (!(0, import_node_fs.existsSync)(dir)) return [];
599
+ const agents = [];
600
+ let entries;
601
+ try {
602
+ entries = (0, import_node_fs.readdirSync)(dir, { withFileTypes: true });
603
+ } catch {
604
+ return [];
605
+ }
606
+ for (const entry of entries) {
607
+ if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
608
+ const filePath = (0, import_node_path.join)(dir, entry.name);
609
+ const content = (0, import_node_fs.readFileSync)(filePath, "utf-8");
610
+ const { frontmatter, body } = parseFrontmatter(content);
611
+ const fallbackName = (0, import_node_path.basename)(entry.name, ".md");
612
+ const agent = {
613
+ name: frontmatter?.name ?? fallbackName,
614
+ description: frontmatter?.description ?? "",
615
+ systemPrompt: body
616
+ };
617
+ if (frontmatter?.model !== void 0) agent.model = frontmatter.model;
618
+ if (frontmatter?.maxTurns !== void 0) agent.maxTurns = frontmatter.maxTurns;
619
+ if (frontmatter?.tools !== void 0) agent.tools = frontmatter.tools;
620
+ if (frontmatter?.disallowedTools !== void 0)
621
+ agent.disallowedTools = frontmatter.disallowedTools;
622
+ agents.push(agent);
623
+ }
624
+ return agents;
625
+ }
626
+ var AgentDefinitionLoader = class {
627
+ cwd;
628
+ home;
629
+ constructor(cwd, home) {
630
+ this.cwd = cwd;
631
+ this.home = home ?? (0, import_node_os.homedir)();
632
+ }
633
+ /** Load all agent definitions, merged with built-in agents. Custom overrides built-in on name collision. */
634
+ loadAll() {
635
+ const sources = [
636
+ scanAgentsDir((0, import_node_path.join)(this.cwd, ".claude", "agents")),
637
+ scanAgentsDir((0, import_node_path.join)(this.home, ".robota", "agents"))
638
+ ];
639
+ const seen = /* @__PURE__ */ new Set();
640
+ const customAgents = [];
641
+ for (const agents of sources) {
642
+ for (const agent of agents) {
643
+ if (!seen.has(agent.name)) {
644
+ seen.add(agent.name);
645
+ customAgents.push(agent);
646
+ }
647
+ }
648
+ }
649
+ const result = [...customAgents];
650
+ for (const builtIn of BUILT_IN_AGENTS) {
651
+ if (!seen.has(builtIn.name)) {
652
+ result.push(builtIn);
653
+ }
654
+ }
655
+ return result;
656
+ }
657
+ /** Get a specific agent by name (custom or built-in). */
658
+ getAgent(name) {
659
+ return this.loadAll().find((agent) => agent.name === name);
660
+ }
661
+ };
662
+
173
663
  // src/assembly/create-session.ts
174
664
  function createSession(options) {
175
665
  const provider = options.provider ?? createProvider(options.config);
176
666
  const defaultTools = createDefaultTools();
177
667
  const tools = [...defaultTools, ...options.additionalTools ?? []];
668
+ const agentLoader = new AgentDefinitionLoader(process.cwd());
669
+ const hookTypeExecutors = [];
670
+ if (options.providerFactory) {
671
+ hookTypeExecutors.push(
672
+ new PromptExecutor({
673
+ providerFactory: options.providerFactory,
674
+ defaultModel: options.config.provider.model
675
+ })
676
+ );
677
+ }
678
+ if (options.sessionFactory) {
679
+ hookTypeExecutors.push(
680
+ new AgentExecutor({
681
+ sessionFactory: options.sessionFactory
682
+ })
683
+ );
684
+ }
685
+ if (options.additionalHookExecutors) {
686
+ hookTypeExecutors.push(...options.additionalHookExecutors);
687
+ }
688
+ const agentToolDeps = {
689
+ config: options.config,
690
+ context: options.context,
691
+ tools,
692
+ terminal: options.terminal,
693
+ permissionMode: options.permissionMode,
694
+ permissionHandler: options.permissionHandler,
695
+ hooks: options.config.hooks,
696
+ hookTypeExecutors: hookTypeExecutors.length > 0 ? hookTypeExecutors : void 0,
697
+ onTextDelta: options.onTextDelta,
698
+ onToolExecution: options.onToolExecution,
699
+ customAgentRegistry: (name) => agentLoader.getAgent(name)
700
+ };
701
+ tools.push(createAgentTool(agentToolDeps));
178
702
  const buildPrompt = options.systemPromptBuilder ?? buildSystemPrompt;
179
703
  const systemMessage = buildPrompt({
180
704
  agentsMd: options.context.agentsMd,
181
705
  claudeMd: options.context.claudeMd,
182
706
  toolDescriptions: options.toolDescriptions ?? DEFAULT_TOOL_DESCRIPTIONS,
183
707
  trustLevel: options.config.defaultTrustLevel,
184
- projectInfo: options.projectInfo ?? { type: "unknown", language: "unknown" }
708
+ projectInfo: options.projectInfo ?? { type: "unknown", language: "unknown" },
709
+ cwd: process.cwd(),
710
+ language: options.config.language
185
711
  });
186
- return new import_agent_sessions.Session({
712
+ const defaultAllow = [
713
+ "Read(.agents/**)",
714
+ "Read(.claude/**)",
715
+ "Read(.robota/**)",
716
+ "Glob(.agents/**)",
717
+ "Glob(.claude/**)",
718
+ "Glob(.robota/**)"
719
+ ];
720
+ const mergedPermissions = {
721
+ allow: [...defaultAllow, ...options.config.permissions.allow ?? []],
722
+ deny: options.config.permissions.deny ?? []
723
+ };
724
+ const session = new import_agent_sessions2.Session({
187
725
  tools,
188
726
  provider,
189
727
  systemMessage,
190
728
  terminal: options.terminal,
191
- permissions: options.config.permissions,
729
+ permissions: mergedPermissions,
192
730
  hooks: options.config.hooks,
193
731
  permissionMode: options.permissionMode,
194
732
  defaultTrustLevel: options.config.defaultTrustLevel,
@@ -197,57 +735,119 @@ function createSession(options) {
197
735
  sessionStore: options.sessionStore,
198
736
  permissionHandler: options.permissionHandler,
199
737
  onTextDelta: options.onTextDelta,
738
+ onToolExecution: options.onToolExecution,
200
739
  promptForApproval: options.promptForApproval,
201
740
  onCompact: options.onCompact,
202
741
  compactInstructions: options.compactInstructions ?? options.context.compactInstructions,
203
- sessionLogger: options.sessionLogger
742
+ sessionLogger: options.sessionLogger,
743
+ hookTypeExecutors: hookTypeExecutors.length > 0 ? hookTypeExecutors : void 0
204
744
  });
745
+ storeAgentToolDeps(session, agentToolDeps);
746
+ return session;
205
747
  }
206
748
 
207
- // src/index.ts
208
- var import_agent_sessions2 = require("@robota-sdk/agent-sessions");
749
+ // src/assembly/subagent-logger.ts
750
+ var import_node_fs2 = require("fs");
751
+ var import_node_path2 = require("path");
209
752
  var import_agent_sessions3 = require("@robota-sdk/agent-sessions");
210
- var import_agent_sessions4 = require("@robota-sdk/agent-sessions");
753
+ function createSubagentLogger(parentSessionId, _agentId, baseLogsDir) {
754
+ const subagentDir = (0, import_node_path2.join)(baseLogsDir, parentSessionId, "subagents");
755
+ (0, import_node_fs2.mkdirSync)(subagentDir, { recursive: true });
756
+ return new import_agent_sessions3.FileSessionLogger(subagentDir);
757
+ }
758
+ function resolveSubagentLogDir(parentSessionId, baseLogsDir) {
759
+ return (0, import_node_path2.join)(baseLogsDir, parentSessionId, "subagents");
760
+ }
761
+
762
+ // src/index.ts
763
+ var import_agent_sessions5 = require("@robota-sdk/agent-sessions");
764
+ var import_agent_sessions6 = require("@robota-sdk/agent-sessions");
765
+ var import_agent_sessions7 = require("@robota-sdk/agent-sessions");
211
766
 
212
767
  // src/config/config-loader.ts
213
768
  var import_fs = require("fs");
214
769
  var import_path = require("path");
215
770
 
216
771
  // src/config/config-types.ts
217
- var import_zod = require("zod");
218
- var ProviderSchema = import_zod.z.object({
219
- name: import_zod.z.string().optional(),
220
- model: import_zod.z.string().optional(),
221
- apiKey: import_zod.z.string().optional()
772
+ var import_zod2 = require("zod");
773
+ var ProviderSchema = import_zod2.z.object({
774
+ name: import_zod2.z.string().optional(),
775
+ model: import_zod2.z.string().optional(),
776
+ apiKey: import_zod2.z.string().optional()
222
777
  });
223
- var PermissionsSchema = import_zod.z.object({
778
+ var PermissionsSchema = import_zod2.z.object({
224
779
  /** Patterns that are always approved without prompting */
225
- allow: import_zod.z.array(import_zod.z.string()).optional(),
780
+ allow: import_zod2.z.array(import_zod2.z.string()).optional(),
226
781
  /** Patterns that are always denied */
227
- deny: import_zod.z.array(import_zod.z.string()).optional()
782
+ deny: import_zod2.z.array(import_zod2.z.string()).optional()
783
+ });
784
+ var EnvSchema = import_zod2.z.record(import_zod2.z.string()).optional();
785
+ var CommandHookDefinitionSchema = import_zod2.z.object({
786
+ type: import_zod2.z.literal("command"),
787
+ command: import_zod2.z.string(),
788
+ timeout: import_zod2.z.number().optional()
789
+ });
790
+ var HttpHookDefinitionSchema = import_zod2.z.object({
791
+ type: import_zod2.z.literal("http"),
792
+ url: import_zod2.z.string(),
793
+ headers: import_zod2.z.record(import_zod2.z.string()).optional(),
794
+ timeout: import_zod2.z.number().optional()
228
795
  });
229
- var EnvSchema = import_zod.z.record(import_zod.z.string()).optional();
230
- var HookDefinitionSchema = import_zod.z.object({
231
- type: import_zod.z.literal("command"),
232
- command: import_zod.z.string()
796
+ var PromptHookDefinitionSchema = import_zod2.z.object({
797
+ type: import_zod2.z.literal("prompt"),
798
+ prompt: import_zod2.z.string(),
799
+ model: import_zod2.z.string().optional()
233
800
  });
234
- var HookGroupSchema = import_zod.z.object({
235
- matcher: import_zod.z.string(),
236
- hooks: import_zod.z.array(HookDefinitionSchema)
801
+ var AgentHookDefinitionSchema = import_zod2.z.object({
802
+ type: import_zod2.z.literal("agent"),
803
+ agent: import_zod2.z.string(),
804
+ maxTurns: import_zod2.z.number().optional(),
805
+ timeout: import_zod2.z.number().optional()
237
806
  });
238
- var HooksSchema = import_zod.z.object({
239
- PreToolUse: import_zod.z.array(HookGroupSchema).optional(),
240
- PostToolUse: import_zod.z.array(HookGroupSchema).optional(),
241
- SessionStart: import_zod.z.array(HookGroupSchema).optional(),
242
- Stop: import_zod.z.array(HookGroupSchema).optional()
807
+ var HookDefinitionSchema = import_zod2.z.discriminatedUnion("type", [
808
+ CommandHookDefinitionSchema,
809
+ HttpHookDefinitionSchema,
810
+ PromptHookDefinitionSchema,
811
+ AgentHookDefinitionSchema
812
+ ]);
813
+ var HookGroupSchema = import_zod2.z.object({
814
+ matcher: import_zod2.z.string(),
815
+ hooks: import_zod2.z.array(HookDefinitionSchema)
816
+ });
817
+ var HooksSchema = import_zod2.z.object({
818
+ PreToolUse: import_zod2.z.array(HookGroupSchema).optional(),
819
+ PostToolUse: import_zod2.z.array(HookGroupSchema).optional(),
820
+ SessionStart: import_zod2.z.array(HookGroupSchema).optional(),
821
+ Stop: import_zod2.z.array(HookGroupSchema).optional(),
822
+ PreCompact: import_zod2.z.array(HookGroupSchema).optional(),
823
+ PostCompact: import_zod2.z.array(HookGroupSchema).optional(),
824
+ UserPromptSubmit: import_zod2.z.array(HookGroupSchema).optional(),
825
+ Notification: import_zod2.z.array(HookGroupSchema).optional()
243
826
  }).optional();
244
- var SettingsSchema = import_zod.z.object({
827
+ var EnabledPluginsSchema = import_zod2.z.record(import_zod2.z.boolean()).optional();
828
+ var MarketplaceSourceSchema = import_zod2.z.object({
829
+ source: import_zod2.z.object({
830
+ type: import_zod2.z.enum(["github", "git", "local", "url"]),
831
+ repo: import_zod2.z.string().optional(),
832
+ url: import_zod2.z.string().optional(),
833
+ path: import_zod2.z.string().optional(),
834
+ ref: import_zod2.z.string().optional()
835
+ })
836
+ });
837
+ var ExtraKnownMarketplacesSchema = import_zod2.z.record(MarketplaceSourceSchema).optional();
838
+ var SettingsSchema = import_zod2.z.object({
245
839
  /** Trust level used when no --permission-mode flag is given */
246
- defaultTrustLevel: import_zod.z.enum(["safe", "moderate", "full"]).optional(),
840
+ defaultTrustLevel: import_zod2.z.enum(["safe", "moderate", "full"]).optional(),
841
+ /** Response language (e.g., "ko", "en", "ja"). Injected into system prompt. */
842
+ language: import_zod2.z.string().optional(),
247
843
  provider: ProviderSchema.optional(),
248
844
  permissions: PermissionsSchema.optional(),
249
845
  env: EnvSchema,
250
- hooks: HooksSchema
846
+ hooks: HooksSchema,
847
+ /** Plugin enablement map: plugin name -> enabled/disabled */
848
+ enabledPlugins: EnabledPluginsSchema,
849
+ /** Extra marketplace URLs for BundlePlugin discovery */
850
+ extraKnownMarketplaces: ExtraKnownMarketplacesSchema
251
851
  });
252
852
 
253
853
  // src/config/config-loader.ts
@@ -271,8 +871,15 @@ function readJsonFile(filePath) {
271
871
  if (!(0, import_fs.existsSync)(filePath)) {
272
872
  return void 0;
273
873
  }
274
- const raw = (0, import_fs.readFileSync)(filePath, "utf-8");
275
- return JSON.parse(raw);
874
+ const raw = (0, import_fs.readFileSync)(filePath, "utf-8").trim();
875
+ if (raw.length === 0) {
876
+ return void 0;
877
+ }
878
+ try {
879
+ return JSON.parse(raw);
880
+ } catch {
881
+ return void 0;
882
+ }
276
883
  }
277
884
  function resolveEnvRef(value) {
278
885
  const ENV_PREFIX = "$ENV:";
@@ -307,13 +914,16 @@ function mergeSettings(layers) {
307
914
  env: {
308
915
  ...merged.env ?? {},
309
916
  ...layer.env ?? {}
310
- }
917
+ },
918
+ enabledPlugins: merged.enabledPlugins !== void 0 || layer.enabledPlugins !== void 0 ? { ...merged.enabledPlugins ?? {}, ...layer.enabledPlugins ?? {} } : void 0,
919
+ extraKnownMarketplaces: layer.extraKnownMarketplaces ?? merged.extraKnownMarketplaces
311
920
  };
312
921
  }, {});
313
922
  }
314
923
  function toResolvedConfig(merged) {
315
924
  return {
316
925
  defaultTrustLevel: merged.defaultTrustLevel ?? DEFAULTS.defaultTrustLevel,
926
+ language: merged.language,
317
927
  provider: {
318
928
  name: merged.provider?.name ?? DEFAULTS.provider.name,
319
929
  model: merged.provider?.model ?? DEFAULTS.provider.model,
@@ -324,25 +934,39 @@ function toResolvedConfig(merged) {
324
934
  deny: merged.permissions?.deny ?? DEFAULTS.permissions.deny
325
935
  },
326
936
  env: merged.env ?? DEFAULTS.env,
327
- hooks: merged.hooks ?? void 0
937
+ hooks: merged.hooks ?? void 0,
938
+ enabledPlugins: merged.enabledPlugins ?? void 0,
939
+ extraKnownMarketplaces: merged.extraKnownMarketplaces ?? void 0
328
940
  };
329
941
  }
942
+ function getSettingsPaths(cwd) {
943
+ const home = getHomeDir();
944
+ return [
945
+ (0, import_path.join)(home, ".robota", "settings.json"),
946
+ // 1. user (lowest)
947
+ (0, import_path.join)(cwd, ".robota", "settings.json"),
948
+ // 2. project
949
+ (0, import_path.join)(cwd, ".robota", "settings.local.json"),
950
+ // 3. project-local
951
+ (0, import_path.join)(cwd, ".claude", "settings.json"),
952
+ // 4. project, Claude Code compat
953
+ (0, import_path.join)(cwd, ".claude", "settings.local.json")
954
+ // 5. project-local (highest)
955
+ ];
956
+ }
330
957
  async function loadConfig(cwd) {
331
- const userSettingsPath = (0, import_path.join)(getHomeDir(), ".robota", "settings.json");
332
- const projectSettingsPath = (0, import_path.join)(cwd, ".robota", "settings.json");
333
- const localSettingsPath = (0, import_path.join)(cwd, ".robota", "settings.local.json");
334
- const rawLayers = [
335
- readJsonFile(userSettingsPath),
336
- readJsonFile(projectSettingsPath),
337
- readJsonFile(localSettingsPath)
338
- ].filter((v) => v !== void 0);
339
- const parsedLayers = rawLayers.map((raw, index) => {
958
+ const allPaths = getSettingsPaths(cwd);
959
+ const rawEntries = [];
960
+ for (const filePath of allPaths) {
961
+ const raw = readJsonFile(filePath);
962
+ if (raw !== void 0) {
963
+ rawEntries.push({ raw, path: filePath });
964
+ }
965
+ }
966
+ const parsedLayers = rawEntries.map(({ raw, path }) => {
340
967
  const result = SettingsSchema.safeParse(raw);
341
968
  if (!result.success) {
342
- const paths = [userSettingsPath, projectSettingsPath, localSettingsPath].filter(
343
- (_, i) => rawLayers[i] !== void 0
344
- );
345
- throw new Error(`Invalid settings in ${paths[index] ?? "unknown"}: ${result.error.message}`);
969
+ throw new Error(`Invalid settings in ${path}: ${result.error.message}`);
346
970
  }
347
971
  return resolveEnvRefs(result.data);
348
972
  });
@@ -533,100 +1157,1520 @@ async function query(prompt, options) {
533
1157
  }
534
1158
 
535
1159
  // src/index.ts
536
- var import_agent_core2 = require("@robota-sdk/agent-core");
537
- var import_agent_core3 = require("@robota-sdk/agent-core");
1160
+ var import_agent_core4 = require("@robota-sdk/agent-core");
1161
+ var import_agent_core5 = require("@robota-sdk/agent-core");
538
1162
 
539
1163
  // src/paths.ts
540
- var import_node_path = require("path");
541
- var import_node_os = require("os");
1164
+ var import_node_path3 = require("path");
1165
+ var import_node_os2 = require("os");
542
1166
  function projectPaths(cwd) {
543
- const base = (0, import_node_path.join)(cwd, ".robota");
1167
+ const base = (0, import_node_path3.join)(cwd, ".robota");
544
1168
  return {
545
- settings: (0, import_node_path.join)(base, "settings.json"),
546
- settingsLocal: (0, import_node_path.join)(base, "settings.local.json"),
547
- logs: (0, import_node_path.join)(base, "logs"),
548
- sessions: (0, import_node_path.join)(base, "sessions")
1169
+ settings: (0, import_node_path3.join)(base, "settings.json"),
1170
+ settingsLocal: (0, import_node_path3.join)(base, "settings.local.json"),
1171
+ logs: (0, import_node_path3.join)(base, "logs"),
1172
+ sessions: (0, import_node_path3.join)(base, "sessions")
549
1173
  };
550
1174
  }
551
1175
  function userPaths() {
552
- const base = (0, import_node_path.join)((0, import_node_os.homedir)(), ".robota");
1176
+ const base = (0, import_node_path3.join)((0, import_node_os2.homedir)(), ".robota");
553
1177
  return {
554
- settings: (0, import_node_path.join)(base, "settings.json"),
555
- sessions: (0, import_node_path.join)(base, "sessions")
1178
+ settings: (0, import_node_path3.join)(base, "settings.json"),
1179
+ sessions: (0, import_node_path3.join)(base, "sessions")
556
1180
  };
557
1181
  }
558
1182
 
559
- // src/tools/agent-tool.ts
560
- var import_zod2 = require("zod");
561
- var import_agent_tools2 = require("@robota-sdk/agent-tools");
562
- function asZodSchema(schema) {
563
- return schema;
1183
+ // src/plugins/plugin-settings-store.ts
1184
+ var import_node_fs3 = require("fs");
1185
+ var import_node_path4 = require("path");
1186
+ var PluginSettingsStore = class {
1187
+ settingsPath;
1188
+ constructor(settingsPath) {
1189
+ this.settingsPath = settingsPath;
1190
+ }
1191
+ /** Read the full settings file from disk. */
1192
+ readAll() {
1193
+ if (!(0, import_node_fs3.existsSync)(this.settingsPath)) {
1194
+ return {};
1195
+ }
1196
+ try {
1197
+ const raw = (0, import_node_fs3.readFileSync)(this.settingsPath, "utf-8");
1198
+ const data = JSON.parse(raw);
1199
+ if (typeof data === "object" && data !== null) {
1200
+ return data;
1201
+ }
1202
+ return {};
1203
+ } catch {
1204
+ return {};
1205
+ }
1206
+ }
1207
+ /** Write the full settings file to disk. */
1208
+ writeAll(settings) {
1209
+ const dir = (0, import_node_path4.dirname)(this.settingsPath);
1210
+ if (!(0, import_node_fs3.existsSync)(dir)) {
1211
+ (0, import_node_fs3.mkdirSync)(dir, { recursive: true });
1212
+ }
1213
+ (0, import_node_fs3.writeFileSync)(this.settingsPath, JSON.stringify(settings, null, 2), "utf-8");
1214
+ }
1215
+ // --- enabledPlugins ---
1216
+ /** Get the enabledPlugins map. */
1217
+ getEnabledPlugins() {
1218
+ const settings = this.readAll();
1219
+ const ep = settings.enabledPlugins;
1220
+ if (typeof ep === "object" && ep !== null) {
1221
+ return ep;
1222
+ }
1223
+ return {};
1224
+ }
1225
+ /** Set a single plugin's enabled state. */
1226
+ setPluginEnabled(pluginId, enabled) {
1227
+ const settings = this.readAll();
1228
+ const ep = this.getEnabledPluginsFrom(settings);
1229
+ ep[pluginId] = enabled;
1230
+ settings.enabledPlugins = ep;
1231
+ this.writeAll(settings);
1232
+ }
1233
+ /** Remove a plugin from enabledPlugins. */
1234
+ removePluginEntry(pluginId) {
1235
+ const settings = this.readAll();
1236
+ const ep = this.getEnabledPluginsFrom(settings);
1237
+ delete ep[pluginId];
1238
+ settings.enabledPlugins = ep;
1239
+ this.writeAll(settings);
1240
+ }
1241
+ // --- extraKnownMarketplaces ---
1242
+ /** Get all persisted marketplace sources. */
1243
+ getMarketplaceSources() {
1244
+ const settings = this.readAll();
1245
+ const extra = settings.extraKnownMarketplaces;
1246
+ if (typeof extra === "object" && extra !== null) {
1247
+ return extra;
1248
+ }
1249
+ return {};
1250
+ }
1251
+ /** Add or update a marketplace source. */
1252
+ setMarketplaceSource(name, source) {
1253
+ const settings = this.readAll();
1254
+ const extra = this.getMarketplaceSourcesFrom(settings);
1255
+ extra[name] = { source };
1256
+ settings.extraKnownMarketplaces = extra;
1257
+ this.writeAll(settings);
1258
+ }
1259
+ /** Remove a marketplace source. */
1260
+ removeMarketplaceSource(name) {
1261
+ const settings = this.readAll();
1262
+ const extra = this.getMarketplaceSourcesFrom(settings);
1263
+ delete extra[name];
1264
+ settings.extraKnownMarketplaces = extra;
1265
+ this.writeAll(settings);
1266
+ }
1267
+ // --- helpers ---
1268
+ getEnabledPluginsFrom(settings) {
1269
+ const ep = settings.enabledPlugins;
1270
+ if (typeof ep === "object" && ep !== null) {
1271
+ return ep;
1272
+ }
1273
+ return {};
1274
+ }
1275
+ getMarketplaceSourcesFrom(settings) {
1276
+ const extra = settings.extraKnownMarketplaces;
1277
+ if (typeof extra === "object" && extra !== null) {
1278
+ return extra;
1279
+ }
1280
+ return {};
1281
+ }
1282
+ };
1283
+
1284
+ // src/plugins/bundle-plugin-loader.ts
1285
+ var import_node_fs4 = require("fs");
1286
+ var import_node_path5 = require("path");
1287
+ function parseSkillFrontmatter(raw) {
1288
+ const trimmed = raw.trimStart();
1289
+ if (!trimmed.startsWith("---")) {
1290
+ return { metadata: {}, content: raw };
1291
+ }
1292
+ const endIndex = trimmed.indexOf("---", 3);
1293
+ if (endIndex === -1) {
1294
+ return { metadata: {}, content: raw };
1295
+ }
1296
+ const frontmatterBlock = trimmed.slice(3, endIndex).trim();
1297
+ const content = trimmed.slice(endIndex + 3).trimStart();
1298
+ const metadata = {};
1299
+ for (const line of frontmatterBlock.split("\n")) {
1300
+ const colonIndex = line.indexOf(":");
1301
+ if (colonIndex === -1) continue;
1302
+ const key = line.slice(0, colonIndex).trim();
1303
+ let value = line.slice(colonIndex + 1).trim();
1304
+ if (typeof value === "string" && value.startsWith("[") && value.endsWith("]")) {
1305
+ const inner = value.slice(1, -1);
1306
+ value = inner.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
1307
+ }
1308
+ if (key) {
1309
+ metadata[key] = value;
1310
+ }
1311
+ }
1312
+ return { metadata, content };
564
1313
  }
565
- var AgentSchema = import_zod2.z.object({
566
- prompt: import_zod2.z.string().describe("Task description for the sub-agent"),
567
- description: import_zod2.z.string().optional().describe("Short description of what the sub-agent will do (3-5 words)")
568
- });
569
- var agentToolDeps;
570
- function setAgentToolDeps(deps) {
571
- agentToolDeps = deps;
572
- }
573
- async function runAgent(args) {
574
- if (!agentToolDeps) {
575
- const result = {
576
- success: false,
577
- output: "",
578
- error: "Agent tool not initialized \u2014 missing dependencies"
1314
+ function validateManifest(data) {
1315
+ if (typeof data !== "object" || data === null) return null;
1316
+ const obj = data;
1317
+ if (typeof obj.name !== "string") return null;
1318
+ if (typeof obj.version !== "string") return null;
1319
+ if (typeof obj.description !== "string") return null;
1320
+ const features = typeof obj.features === "object" && obj.features !== null ? obj.features : {};
1321
+ return {
1322
+ name: obj.name,
1323
+ version: obj.version,
1324
+ description: obj.description,
1325
+ features: {
1326
+ commands: features.commands === true ? true : void 0,
1327
+ agents: features.agents === true ? true : void 0,
1328
+ skills: features.skills === true ? true : void 0,
1329
+ hooks: features.hooks === true ? true : void 0,
1330
+ mcp: features.mcp === true ? true : void 0
1331
+ }
1332
+ };
1333
+ }
1334
+ function getSortedSubdirs(dirPath) {
1335
+ if (!(0, import_node_fs4.existsSync)(dirPath)) return [];
1336
+ try {
1337
+ const entries = (0, import_node_fs4.readdirSync)(dirPath, { withFileTypes: true });
1338
+ return entries.filter((e) => e.isDirectory()).map((e) => e.name).sort();
1339
+ } catch {
1340
+ return [];
1341
+ }
1342
+ }
1343
+ var BundlePluginLoader = class {
1344
+ pluginsDir;
1345
+ enabledPlugins;
1346
+ constructor(pluginsDir, enabledPlugins) {
1347
+ this.pluginsDir = pluginsDir;
1348
+ this.enabledPlugins = enabledPlugins ?? {};
1349
+ }
1350
+ /** Load all discovered and enabled bundle plugins (sync). */
1351
+ loadPluginsSync() {
1352
+ return this.discoverAndLoad();
1353
+ }
1354
+ /** Load all discovered and enabled bundle plugins (async wrapper). */
1355
+ async loadAll() {
1356
+ return this.discoverAndLoad();
1357
+ }
1358
+ /**
1359
+ * Discover and load plugins from the cache directory.
1360
+ *
1361
+ * Directory structure: `<pluginsDir>/cache/<marketplace>/<plugin>/<version>/`
1362
+ * For each marketplace/plugin pair, the latest version (lexicographically last) is loaded.
1363
+ */
1364
+ discoverAndLoad() {
1365
+ const cacheDir = (0, import_node_path5.join)(this.pluginsDir, "cache");
1366
+ if (!(0, import_node_fs4.existsSync)(cacheDir)) {
1367
+ return [];
1368
+ }
1369
+ const results = [];
1370
+ const marketplaces = getSortedSubdirs(cacheDir);
1371
+ for (const marketplace of marketplaces) {
1372
+ const marketplaceDir = (0, import_node_path5.join)(cacheDir, marketplace);
1373
+ const plugins = getSortedSubdirs(marketplaceDir);
1374
+ for (const pluginName of plugins) {
1375
+ const pluginDir = (0, import_node_path5.join)(marketplaceDir, pluginName);
1376
+ const versions = getSortedSubdirs(pluginDir);
1377
+ if (versions.length === 0) continue;
1378
+ const latestVersion = versions[versions.length - 1];
1379
+ const versionDir = (0, import_node_path5.join)(pluginDir, latestVersion);
1380
+ const manifestPath = (0, import_node_path5.join)(versionDir, ".claude-plugin", "plugin.json");
1381
+ if (!(0, import_node_fs4.existsSync)(manifestPath)) continue;
1382
+ const manifest = this.readManifest(manifestPath);
1383
+ if (!manifest) continue;
1384
+ const pluginId = `${manifest.name}@${marketplace}`;
1385
+ if (this.isDisabled(pluginId, manifest.name)) continue;
1386
+ const loaded = this.loadPlugin(versionDir, manifest);
1387
+ results.push(loaded);
1388
+ }
1389
+ }
1390
+ return results;
1391
+ }
1392
+ /** Read and validate a plugin.json manifest. Returns null on failure. */
1393
+ readManifest(path) {
1394
+ try {
1395
+ const raw = (0, import_node_fs4.readFileSync)(path, "utf-8");
1396
+ const data = JSON.parse(raw);
1397
+ return validateManifest(data);
1398
+ } catch {
1399
+ return null;
1400
+ }
1401
+ }
1402
+ /**
1403
+ * Check if a plugin is explicitly disabled.
1404
+ * Checks both `name@marketplace` and `name` keys.
1405
+ * Plugins not listed in enabledPlugins are enabled by default.
1406
+ */
1407
+ isDisabled(pluginId, pluginName) {
1408
+ if (pluginId in this.enabledPlugins) {
1409
+ return this.enabledPlugins[pluginId] === false;
1410
+ }
1411
+ if (pluginName in this.enabledPlugins) {
1412
+ return this.enabledPlugins[pluginName] === false;
1413
+ }
1414
+ return false;
1415
+ }
1416
+ /** Load a single plugin's skills, hooks, agents, and MCP config. */
1417
+ loadPlugin(pluginDir, manifest) {
1418
+ return {
1419
+ manifest,
1420
+ skills: this.loadSkills(pluginDir, manifest.name),
1421
+ commands: this.loadCommands(pluginDir, manifest.name),
1422
+ hooks: this.loadHooks(pluginDir),
1423
+ mcpConfig: this.loadMcpConfig(pluginDir),
1424
+ agents: this.loadAgents(pluginDir),
1425
+ pluginDir
579
1426
  };
580
- return JSON.stringify(result);
581
1427
  }
582
- const noopTerminal = {
583
- write: () => {
584
- },
585
- writeLine: () => {
1428
+ /** Load skills from the plugin's skills/ directory. */
1429
+ loadSkills(pluginDir, pluginName) {
1430
+ const skillsDir = (0, import_node_path5.join)(pluginDir, "skills");
1431
+ if (!(0, import_node_fs4.existsSync)(skillsDir)) return [];
1432
+ const entries = (0, import_node_fs4.readdirSync)(skillsDir, { withFileTypes: true });
1433
+ const skills = [];
1434
+ for (const entry of entries) {
1435
+ if (!entry.isDirectory()) continue;
1436
+ const skillFile = (0, import_node_path5.join)(skillsDir, entry.name, "SKILL.md");
1437
+ if (!(0, import_node_fs4.existsSync)(skillFile)) continue;
1438
+ const raw = (0, import_node_fs4.readFileSync)(skillFile, "utf-8");
1439
+ const { metadata, content } = parseSkillFrontmatter(raw);
1440
+ const description = typeof metadata.description === "string" ? metadata.description : "";
1441
+ const skill = {
1442
+ name: entry.name,
1443
+ description,
1444
+ skillContent: content,
1445
+ ...metadata
1446
+ };
1447
+ skills.push(skill);
1448
+ }
1449
+ return skills;
1450
+ }
1451
+ /** Load commands from the plugin's commands/ directory (flat .md files). */
1452
+ loadCommands(pluginDir, pluginName) {
1453
+ const commandsDir = (0, import_node_path5.join)(pluginDir, "commands");
1454
+ if (!(0, import_node_fs4.existsSync)(commandsDir)) return [];
1455
+ const entries = (0, import_node_fs4.readdirSync)(commandsDir, { withFileTypes: true });
1456
+ const commands = [];
1457
+ for (const entry of entries) {
1458
+ if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
1459
+ const raw = (0, import_node_fs4.readFileSync)((0, import_node_path5.join)(commandsDir, entry.name), "utf-8");
1460
+ const { metadata, content } = parseSkillFrontmatter(raw);
1461
+ const name = typeof metadata.name === "string" ? metadata.name : entry.name.replace(/\.md$/, "");
1462
+ const description = typeof metadata.description === "string" ? metadata.description : "";
1463
+ commands.push({
1464
+ ...metadata,
1465
+ name: `${pluginName}:${name}`,
1466
+ description,
1467
+ skillContent: content
1468
+ });
1469
+ }
1470
+ return commands;
1471
+ }
1472
+ /** Load hooks from hooks/hooks.json if present. */
1473
+ loadHooks(pluginDir) {
1474
+ const hooksPath = (0, import_node_path5.join)(pluginDir, "hooks", "hooks.json");
1475
+ if (!(0, import_node_fs4.existsSync)(hooksPath)) return {};
1476
+ try {
1477
+ const raw = (0, import_node_fs4.readFileSync)(hooksPath, "utf-8");
1478
+ const data = JSON.parse(raw);
1479
+ if (typeof data === "object" && data !== null) {
1480
+ return data;
1481
+ }
1482
+ return {};
1483
+ } catch {
1484
+ return {};
1485
+ }
1486
+ }
1487
+ /** Load MCP server configuration if present. Checks `.mcp.json` at plugin root first. */
1488
+ loadMcpConfig(pluginDir) {
1489
+ const primaryPath = (0, import_node_path5.join)(pluginDir, ".mcp.json");
1490
+ const fallbackPath = (0, import_node_path5.join)(pluginDir, ".claude-plugin", "mcp.json");
1491
+ const mcpPath = (0, import_node_fs4.existsSync)(primaryPath) ? primaryPath : fallbackPath;
1492
+ if (!(0, import_node_fs4.existsSync)(mcpPath)) return void 0;
1493
+ try {
1494
+ const raw = (0, import_node_fs4.readFileSync)(mcpPath, "utf-8");
1495
+ return JSON.parse(raw);
1496
+ } catch {
1497
+ return void 0;
1498
+ }
1499
+ }
1500
+ /** Load agent definitions from agents/ directory if present. */
1501
+ loadAgents(pluginDir) {
1502
+ const agentsDir = (0, import_node_path5.join)(pluginDir, "agents");
1503
+ if (!(0, import_node_fs4.existsSync)(agentsDir)) return [];
1504
+ try {
1505
+ const entries = (0, import_node_fs4.readdirSync)(agentsDir, { withFileTypes: true });
1506
+ return entries.filter((e) => e.isDirectory() || e.name.endsWith(".md")).map((e) => e.name.replace(/\.md$/, ""));
1507
+ } catch {
1508
+ return [];
1509
+ }
1510
+ }
1511
+ };
1512
+
1513
+ // src/plugins/bundle-plugin-installer.ts
1514
+ var import_node_child_process = require("child_process");
1515
+ var import_node_fs5 = require("fs");
1516
+ var import_node_path6 = require("path");
1517
+ var GIT_CLONE_TIMEOUT_MS = 6e4;
1518
+ var BundlePluginInstaller = class {
1519
+ pluginsDir;
1520
+ cacheDir;
1521
+ registryPath;
1522
+ settingsStore;
1523
+ marketplaceClient;
1524
+ exec;
1525
+ constructor(options) {
1526
+ this.pluginsDir = options.pluginsDir;
1527
+ this.cacheDir = (0, import_node_path6.join)(this.pluginsDir, "cache");
1528
+ this.registryPath = (0, import_node_path6.join)(this.pluginsDir, "installed_plugins.json");
1529
+ this.settingsStore = options.settingsStore;
1530
+ this.marketplaceClient = options.marketplaceClient;
1531
+ this.exec = options.exec ?? this.defaultExec;
1532
+ }
1533
+ /**
1534
+ * Install a plugin from a marketplace.
1535
+ *
1536
+ * 1. Read marketplace manifest to find the plugin entry.
1537
+ * 2. Resolve source (relative path, github, or url).
1538
+ * 3. Copy/clone to `cache/<marketplace>/<plugin>/<version>/`.
1539
+ * 4. Record in `installed_plugins.json`.
1540
+ */
1541
+ async install(pluginName, marketplaceName) {
1542
+ const manifest = this.marketplaceClient.fetchManifest(marketplaceName);
1543
+ const entry = manifest.plugins.find((p) => p.name === pluginName);
1544
+ if (!entry) {
1545
+ throw new Error(`Plugin "${pluginName}" not found in marketplace "${marketplaceName}"`);
1546
+ }
1547
+ const version = this.resolveVersion(entry, marketplaceName);
1548
+ const targetDir = (0, import_node_path6.join)(this.cacheDir, marketplaceName, pluginName, version);
1549
+ if ((0, import_node_fs5.existsSync)(targetDir)) {
1550
+ throw new Error(
1551
+ `Plugin "${pluginName}" version "${version}" is already installed from "${marketplaceName}"`
1552
+ );
1553
+ }
1554
+ this.resolveAndInstall(entry.source, marketplaceName, pluginName, targetDir);
1555
+ const pluginId = `${pluginName}@${marketplaceName}`;
1556
+ const registry = this.readRegistry();
1557
+ registry[pluginId] = {
1558
+ pluginName,
1559
+ marketplace: marketplaceName,
1560
+ version,
1561
+ installPath: targetDir,
1562
+ installedAt: (/* @__PURE__ */ new Date()).toISOString()
1563
+ };
1564
+ this.writeRegistry(registry);
1565
+ }
1566
+ /**
1567
+ * Uninstall a plugin.
1568
+ * Removes from cache and from installed_plugins.json.
1569
+ */
1570
+ async uninstall(pluginId) {
1571
+ const registry = this.readRegistry();
1572
+ const record = registry[pluginId];
1573
+ if (!record) {
1574
+ throw new Error(`Plugin "${pluginId}" is not installed`);
1575
+ }
1576
+ if ((0, import_node_fs5.existsSync)(record.installPath)) {
1577
+ (0, import_node_fs5.rmSync)(record.installPath, { recursive: true, force: true });
1578
+ }
1579
+ delete registry[pluginId];
1580
+ this.writeRegistry(registry);
1581
+ this.settingsStore.removePluginEntry(pluginId);
1582
+ }
1583
+ /** Enable a plugin by setting its enabledPlugins entry to true. */
1584
+ async enable(pluginId) {
1585
+ this.settingsStore.setPluginEnabled(pluginId, true);
1586
+ }
1587
+ /** Disable a plugin by setting its enabledPlugins entry to false. */
1588
+ async disable(pluginId) {
1589
+ this.settingsStore.setPluginEnabled(pluginId, false);
1590
+ }
1591
+ /** Get all installed plugins. */
1592
+ getInstalledPlugins() {
1593
+ return this.readRegistry();
1594
+ }
1595
+ /** Get plugins installed from a specific marketplace. */
1596
+ getPluginsByMarketplace(marketplaceName) {
1597
+ const registry = this.readRegistry();
1598
+ return Object.values(registry).filter((r) => r.marketplace === marketplaceName);
1599
+ }
1600
+ // --- Private helpers ---
1601
+ /** Resolve the version for a plugin entry. */
1602
+ resolveVersion(entry, marketplaceName) {
1603
+ const entryWithVersion = entry;
1604
+ if (typeof entryWithVersion.version === "string" && entryWithVersion.version) {
1605
+ return entryWithVersion.version;
1606
+ }
1607
+ return this.marketplaceClient.getMarketplaceSha(marketplaceName);
1608
+ }
1609
+ /**
1610
+ * Normalize source object — Claude Code manifests use `source` key instead of `type`.
1611
+ * e.g., { source: "url", url: "..." } → { type: "url", url: "..." }
1612
+ */
1613
+ normalizeSource(source) {
1614
+ if (typeof source === "string") return source;
1615
+ const obj = source;
1616
+ if (!obj.type && typeof obj.source === "string") {
1617
+ return { ...obj, type: obj.source };
1618
+ }
1619
+ return source;
1620
+ }
1621
+ /** Resolve the source and install the plugin. */
1622
+ resolveAndInstall(rawSource, marketplaceName, pluginName, targetDir) {
1623
+ (0, import_node_fs5.mkdirSync)(targetDir, { recursive: true });
1624
+ const source = this.normalizeSource(rawSource);
1625
+ try {
1626
+ if (typeof source === "string") {
1627
+ const marketplaceDir = this.marketplaceClient.getMarketplaceDir(marketplaceName);
1628
+ const sourcePath = (0, import_node_path6.join)(marketplaceDir, source);
1629
+ if (!(0, import_node_fs5.existsSync)(sourcePath)) {
1630
+ throw new Error(
1631
+ `Plugin source path "${source}" not found in marketplace "${marketplaceName}"`
1632
+ );
1633
+ }
1634
+ (0, import_node_fs5.cpSync)(sourcePath, targetDir, { recursive: true });
1635
+ } else if (source.type === "github") {
1636
+ const repoUrl = `https://github.com/${source.repo}.git`;
1637
+ this.cloneToDir(repoUrl, targetDir, pluginName);
1638
+ } else if (source.type === "url" && typeof source.url === "string" && source.url.endsWith(".git")) {
1639
+ this.cloneToDir(source.url, targetDir, pluginName);
1640
+ } else if (source.type === "url") {
1641
+ throw new Error(`URL source "${source.url}" is not a git repository (must end with .git)`);
1642
+ } else {
1643
+ throw new Error(`Unknown source type: ${JSON.stringify(source)}`);
1644
+ }
1645
+ } catch (err) {
1646
+ if ((0, import_node_fs5.existsSync)(targetDir)) {
1647
+ (0, import_node_fs5.rmSync)(targetDir, { recursive: true, force: true });
1648
+ }
1649
+ throw err;
1650
+ }
1651
+ }
1652
+ /** Clone a git repository to the target directory. */
1653
+ cloneToDir(repoUrl, targetDir, pluginName) {
1654
+ (0, import_node_fs5.rmSync)(targetDir, { recursive: true, force: true });
1655
+ const command = `git clone --depth 1 ${repoUrl} ${targetDir}`;
1656
+ try {
1657
+ this.exec(command, { timeout: GIT_CLONE_TIMEOUT_MS, stdio: "pipe" });
1658
+ } catch (error) {
1659
+ const message = error instanceof Error ? error.message : String(error);
1660
+ throw new Error(`Failed to clone plugin "${pluginName}": ${message}`);
1661
+ }
1662
+ }
1663
+ /** Read the installed_plugins.json registry. */
1664
+ readRegistry() {
1665
+ if (!(0, import_node_fs5.existsSync)(this.registryPath)) {
1666
+ return {};
1667
+ }
1668
+ try {
1669
+ const raw = (0, import_node_fs5.readFileSync)(this.registryPath, "utf-8");
1670
+ const data = JSON.parse(raw);
1671
+ if (typeof data === "object" && data !== null) {
1672
+ return data;
1673
+ }
1674
+ return {};
1675
+ } catch {
1676
+ return {};
1677
+ }
1678
+ }
1679
+ /** Write the installed_plugins.json registry. */
1680
+ writeRegistry(registry) {
1681
+ const dir = (0, import_node_path6.dirname)(this.registryPath);
1682
+ if (!(0, import_node_fs5.existsSync)(dir)) {
1683
+ (0, import_node_fs5.mkdirSync)(dir, { recursive: true });
1684
+ }
1685
+ (0, import_node_fs5.writeFileSync)(this.registryPath, JSON.stringify(registry, null, 2), "utf-8");
1686
+ }
1687
+ /** Default exec implementation using child_process. */
1688
+ defaultExec(command, options) {
1689
+ return (0, import_node_child_process.execSync)(command, { timeout: options.timeout, stdio: "pipe" });
1690
+ }
1691
+ };
1692
+
1693
+ // src/plugins/marketplace-client.ts
1694
+ var import_node_child_process2 = require("child_process");
1695
+ var import_node_fs6 = require("fs");
1696
+ var import_node_path7 = require("path");
1697
+ var GIT_TIMEOUT_MS = 6e4;
1698
+ var MarketplaceClient = class {
1699
+ pluginsDir;
1700
+ exec;
1701
+ marketplacesDir;
1702
+ registryPath;
1703
+ constructor(options) {
1704
+ this.pluginsDir = options.pluginsDir;
1705
+ this.exec = options.exec ?? this.defaultExec;
1706
+ this.marketplacesDir = (0, import_node_path7.join)(this.pluginsDir, "marketplaces");
1707
+ this.registryPath = (0, import_node_path7.join)(this.pluginsDir, "known_marketplaces.json");
1708
+ }
1709
+ /**
1710
+ * Add a marketplace by cloning its repository.
1711
+ *
1712
+ * 1. Parse source: `owner/repo` string becomes a GitHub source.
1713
+ * 2. Shallow git clone (`--depth 1`) to `marketplaces/<name>/`.
1714
+ * 3. Read `.claude-plugin/marketplace.json` for the `name` field.
1715
+ * 4. Register in `known_marketplaces.json`.
1716
+ *
1717
+ * Returns the registered marketplace name from the manifest.
1718
+ */
1719
+ addMarketplace(source) {
1720
+ const tempName = "temp-" + Date.now().toString(36);
1721
+ const tempDir = (0, import_node_path7.join)(this.marketplacesDir, tempName);
1722
+ (0, import_node_fs6.mkdirSync)(this.marketplacesDir, { recursive: true });
1723
+ if (source.type === "local") {
1724
+ if (!(0, import_node_fs6.existsSync)(source.path)) {
1725
+ throw new Error(`Local marketplace path does not exist: ${source.path}`);
1726
+ }
1727
+ (0, import_node_fs6.cpSync)(source.path, tempDir, { recursive: true });
1728
+ } else {
1729
+ const cloneUrl = this.resolveCloneUrl(source);
1730
+ const command = `git clone --depth 1 ${cloneUrl} ${tempDir}`;
1731
+ try {
1732
+ this.exec(command, { timeout: GIT_TIMEOUT_MS, stdio: "pipe" });
1733
+ } catch (error) {
1734
+ const message = error instanceof Error ? error.message : String(error);
1735
+ throw new Error(`Failed to clone marketplace: ${message}`);
1736
+ }
1737
+ }
1738
+ const manifestPath = (0, import_node_path7.join)(tempDir, ".claude-plugin", "marketplace.json");
1739
+ if (!(0, import_node_fs6.existsSync)(manifestPath)) {
1740
+ (0, import_node_fs6.rmSync)(tempDir, { recursive: true, force: true });
1741
+ throw new Error(
1742
+ source.type === "local" ? "Local directory does not contain .claude-plugin/marketplace.json" : "Cloned repository does not contain .claude-plugin/marketplace.json"
1743
+ );
1744
+ }
1745
+ const manifest = this.readManifestFromPath(manifestPath);
1746
+ const name = manifest.name;
1747
+ if (!name) {
1748
+ (0, import_node_fs6.rmSync)(tempDir, { recursive: true, force: true });
1749
+ throw new Error('Marketplace manifest does not contain a "name" field');
1750
+ }
1751
+ const registry = this.readRegistry();
1752
+ if (registry[name]) {
1753
+ (0, import_node_fs6.rmSync)(tempDir, { recursive: true, force: true });
1754
+ throw new Error(`Marketplace "${name}" already exists`);
1755
+ }
1756
+ const finalDir = (0, import_node_path7.join)(this.marketplacesDir, name);
1757
+ (0, import_node_fs6.renameSync)(tempDir, finalDir);
1758
+ registry[name] = {
1759
+ source,
1760
+ installLocation: finalDir,
1761
+ lastUpdated: (/* @__PURE__ */ new Date()).toISOString()
1762
+ };
1763
+ this.writeRegistry(registry);
1764
+ return name;
1765
+ }
1766
+ /**
1767
+ * Remove a marketplace.
1768
+ * Uninstalls all plugins from that marketplace, then deletes the clone directory
1769
+ * and removes from the registry.
1770
+ */
1771
+ removeMarketplace(name) {
1772
+ const registry = this.readRegistry();
1773
+ const entry = registry[name];
1774
+ if (!entry) {
1775
+ throw new Error(`Marketplace "${name}" not found`);
1776
+ }
1777
+ this.removeInstalledPluginsForMarketplace(name);
1778
+ if ((0, import_node_fs6.existsSync)(entry.installLocation)) {
1779
+ (0, import_node_fs6.rmSync)(entry.installLocation, { recursive: true, force: true });
1780
+ }
1781
+ delete registry[name];
1782
+ this.writeRegistry(registry);
1783
+ }
1784
+ /**
1785
+ * Update a marketplace by running git pull on its clone.
1786
+ * The manifest is re-read from disk on demand (via fetchManifest), so the
1787
+ * updated manifest is automatically available after pull.
1788
+ *
1789
+ * TODO: After pull, detect version changes in installed plugins and offer
1790
+ * to update them (re-install at new version).
1791
+ */
1792
+ updateMarketplace(name) {
1793
+ const registry = this.readRegistry();
1794
+ const entry = registry[name];
1795
+ if (!entry) {
1796
+ throw new Error(`Marketplace "${name}" not found`);
1797
+ }
1798
+ if (!(0, import_node_fs6.existsSync)(entry.installLocation)) {
1799
+ throw new Error(`Marketplace directory for "${name}" does not exist`);
1800
+ }
1801
+ if (entry.source.type === "local") {
1802
+ const localSource = entry.source;
1803
+ if (!(0, import_node_fs6.existsSync)(localSource.path)) {
1804
+ throw new Error(`Local marketplace path does not exist: ${localSource.path}`);
1805
+ }
1806
+ (0, import_node_fs6.rmSync)(entry.installLocation, { recursive: true, force: true });
1807
+ (0, import_node_fs6.cpSync)(localSource.path, entry.installLocation, { recursive: true });
1808
+ } else {
1809
+ const command = `git -C ${entry.installLocation} pull`;
1810
+ try {
1811
+ this.exec(command, { timeout: GIT_TIMEOUT_MS, stdio: "pipe" });
1812
+ } catch (error) {
1813
+ const message = error instanceof Error ? error.message : String(error);
1814
+ throw new Error(`Failed to update marketplace "${name}": ${message}`);
1815
+ }
1816
+ }
1817
+ entry.lastUpdated = (/* @__PURE__ */ new Date()).toISOString();
1818
+ this.writeRegistry(registry);
1819
+ }
1820
+ /** List all registered marketplaces. */
1821
+ listMarketplaces() {
1822
+ const registry = this.readRegistry();
1823
+ return Object.entries(registry).map(([name, entry]) => ({
1824
+ name,
1825
+ source: entry.source,
1826
+ lastUpdated: entry.lastUpdated
1827
+ }));
1828
+ }
1829
+ /**
1830
+ * Read the marketplace manifest from a registered marketplace's clone.
1831
+ */
1832
+ fetchManifest(marketplaceName) {
1833
+ const registry = this.readRegistry();
1834
+ const entry = registry[marketplaceName];
1835
+ if (!entry) {
1836
+ throw new Error(`Marketplace "${marketplaceName}" not found`);
1837
+ }
1838
+ const manifestPath = (0, import_node_path7.join)(entry.installLocation, ".claude-plugin", "marketplace.json");
1839
+ if (!(0, import_node_fs6.existsSync)(manifestPath)) {
1840
+ throw new Error(
1841
+ `Marketplace "${marketplaceName}" does not contain .claude-plugin/marketplace.json`
1842
+ );
1843
+ }
1844
+ return this.readManifestFromPath(manifestPath);
1845
+ }
1846
+ /** Get the clone directory path for a registered marketplace. */
1847
+ getMarketplaceDir(name) {
1848
+ const registry = this.readRegistry();
1849
+ const entry = registry[name];
1850
+ if (!entry) {
1851
+ throw new Error(`Marketplace "${name}" not found`);
1852
+ }
1853
+ return entry.installLocation;
1854
+ }
1855
+ /**
1856
+ * Get the current git SHA (first 12 chars) for a marketplace clone.
1857
+ * Used as a version identifier when plugins lack explicit versions.
1858
+ */
1859
+ getMarketplaceSha(name) {
1860
+ const dir = this.getMarketplaceDir(name);
1861
+ try {
1862
+ const result = this.exec(`git -C ${dir} rev-parse HEAD`, {
1863
+ timeout: GIT_TIMEOUT_MS,
1864
+ stdio: "pipe"
1865
+ });
1866
+ return result.toString().trim().slice(0, 12);
1867
+ } catch {
1868
+ return "unknown";
1869
+ }
1870
+ }
1871
+ /** List all available plugins across all marketplaces. */
1872
+ listAvailablePlugins() {
1873
+ const results = [];
1874
+ const marketplaces = this.listMarketplaces();
1875
+ for (const { name } of marketplaces) {
1876
+ try {
1877
+ const manifest = this.fetchManifest(name);
1878
+ for (const plugin of manifest.plugins) {
1879
+ results.push({ ...plugin, marketplace: name });
1880
+ }
1881
+ } catch {
1882
+ }
1883
+ }
1884
+ return results;
1885
+ }
1886
+ // --- Private helpers ---
1887
+ /** Resolve a marketplace source to a git clone URL. */
1888
+ resolveCloneUrl(source) {
1889
+ switch (source.type) {
1890
+ case "github":
1891
+ return `https://github.com/${source.repo}.git`;
1892
+ case "git":
1893
+ return source.url;
1894
+ case "local":
1895
+ throw new Error("Local source type does not use git cloning");
1896
+ case "url":
1897
+ throw new Error("URL marketplace source is not yet supported");
1898
+ }
1899
+ }
1900
+ /**
1901
+ * Remove all installed plugins that belong to a given marketplace.
1902
+ * Reads installed_plugins.json, deletes cache directories for matching plugins,
1903
+ * and updates the registry.
1904
+ */
1905
+ removeInstalledPluginsForMarketplace(marketplaceName) {
1906
+ const installedPath = (0, import_node_path7.join)(this.pluginsDir, "installed_plugins.json");
1907
+ if (!(0, import_node_fs6.existsSync)(installedPath)) return;
1908
+ let registry;
1909
+ try {
1910
+ const raw = (0, import_node_fs6.readFileSync)(installedPath, "utf-8");
1911
+ const data = JSON.parse(raw);
1912
+ if (typeof data !== "object" || data === null) return;
1913
+ registry = data;
1914
+ } catch {
1915
+ return;
1916
+ }
1917
+ let changed = false;
1918
+ for (const [pluginId, record] of Object.entries(registry)) {
1919
+ if (record.marketplace === marketplaceName) {
1920
+ if (record.installPath && (0, import_node_fs6.existsSync)(record.installPath)) {
1921
+ (0, import_node_fs6.rmSync)(record.installPath, { recursive: true, force: true });
1922
+ }
1923
+ delete registry[pluginId];
1924
+ changed = true;
1925
+ }
1926
+ }
1927
+ if (changed) {
1928
+ const dir = (0, import_node_path7.dirname)(installedPath);
1929
+ if (!(0, import_node_fs6.existsSync)(dir)) {
1930
+ (0, import_node_fs6.mkdirSync)(dir, { recursive: true });
1931
+ }
1932
+ (0, import_node_fs6.writeFileSync)(installedPath, JSON.stringify(registry, null, 2), "utf-8");
1933
+ }
1934
+ }
1935
+ /** Read and parse a marketplace.json from a file path. */
1936
+ readManifestFromPath(path) {
1937
+ const raw = (0, import_node_fs6.readFileSync)(path, "utf-8");
1938
+ const data = JSON.parse(raw);
1939
+ if (typeof data !== "object" || data === null) {
1940
+ throw new Error("Invalid marketplace manifest: not an object");
1941
+ }
1942
+ const obj = data;
1943
+ if (typeof obj.name !== "string") {
1944
+ throw new Error('Invalid marketplace manifest: missing "name" field');
1945
+ }
1946
+ return data;
1947
+ }
1948
+ /** Read the known_marketplaces.json registry. */
1949
+ readRegistry() {
1950
+ if (!(0, import_node_fs6.existsSync)(this.registryPath)) {
1951
+ return {};
1952
+ }
1953
+ try {
1954
+ const raw = (0, import_node_fs6.readFileSync)(this.registryPath, "utf-8");
1955
+ const data = JSON.parse(raw);
1956
+ if (typeof data === "object" && data !== null) {
1957
+ return data;
1958
+ }
1959
+ return {};
1960
+ } catch {
1961
+ return {};
1962
+ }
1963
+ }
1964
+ /** Write the known_marketplaces.json registry. */
1965
+ writeRegistry(registry) {
1966
+ const dir = (0, import_node_path7.dirname)(this.registryPath);
1967
+ if (!(0, import_node_fs6.existsSync)(dir)) {
1968
+ (0, import_node_fs6.mkdirSync)(dir, { recursive: true });
1969
+ }
1970
+ (0, import_node_fs6.writeFileSync)(this.registryPath, JSON.stringify(registry, null, 2), "utf-8");
1971
+ }
1972
+ /** Default exec implementation using child_process. */
1973
+ defaultExec(command, options) {
1974
+ return (0, import_node_child_process2.execSync)(command, { timeout: options.timeout, stdio: "pipe" });
1975
+ }
1976
+ };
1977
+
1978
+ // src/commands/command-registry.ts
1979
+ var CommandRegistry = class {
1980
+ sources = [];
1981
+ addSource(source) {
1982
+ this.sources.push(source);
1983
+ }
1984
+ /** Get all commands, optionally filtered by prefix */
1985
+ getCommands(filter) {
1986
+ const all = [];
1987
+ for (const source of this.sources) {
1988
+ all.push(...source.getCommands());
1989
+ }
1990
+ if (!filter) return all;
1991
+ const lower = filter.toLowerCase();
1992
+ return all.filter((cmd) => cmd.name.toLowerCase().startsWith(lower));
1993
+ }
1994
+ /** Resolve a short name to its fully qualified plugin:name form */
1995
+ resolveQualifiedName(shortName) {
1996
+ const matches = this.getCommands().filter(
1997
+ (c) => c.source === "plugin" && c.name.includes(":") && c.name.endsWith(`:${shortName}`)
1998
+ );
1999
+ if (matches.length !== 1) return null;
2000
+ return matches[0].name;
2001
+ }
2002
+ /** Get subcommands for a specific command */
2003
+ getSubcommands(commandName) {
2004
+ const lower = commandName.toLowerCase();
2005
+ for (const source of this.sources) {
2006
+ for (const cmd of source.getCommands()) {
2007
+ if (cmd.name.toLowerCase() === lower && cmd.subcommands) {
2008
+ return cmd.subcommands;
2009
+ }
2010
+ }
2011
+ }
2012
+ return [];
2013
+ }
2014
+ };
2015
+
2016
+ // src/commands/builtin-source.ts
2017
+ var import_agent_core2 = require("@robota-sdk/agent-core");
2018
+ function buildModelSubcommands() {
2019
+ const seen = /* @__PURE__ */ new Set();
2020
+ const commands = [];
2021
+ for (const model of Object.values(import_agent_core2.CLAUDE_MODELS)) {
2022
+ if (seen.has(model.name)) continue;
2023
+ seen.add(model.name);
2024
+ commands.push({
2025
+ name: model.id,
2026
+ description: `${model.name} (${(0, import_agent_core2.formatTokenCount)(model.contextWindow).toUpperCase()})`,
2027
+ source: "builtin"
2028
+ });
2029
+ }
2030
+ return commands;
2031
+ }
2032
+ function createBuiltinCommands() {
2033
+ return [
2034
+ { name: "help", description: "Show available commands", source: "builtin" },
2035
+ { name: "clear", description: "Clear conversation history", source: "builtin" },
2036
+ {
2037
+ name: "mode",
2038
+ description: "Permission mode",
2039
+ source: "builtin",
2040
+ subcommands: [
2041
+ { name: "plan", description: "Plan only, no execution", source: "builtin" },
2042
+ { name: "default", description: "Ask before risky actions", source: "builtin" },
2043
+ { name: "acceptEdits", description: "Auto-approve file edits", source: "builtin" },
2044
+ { name: "bypassPermissions", description: "Skip all permission checks", source: "builtin" }
2045
+ ]
586
2046
  },
587
- writeMarkdown: () => {
2047
+ {
2048
+ name: "model",
2049
+ description: "Select AI model",
2050
+ source: "builtin",
2051
+ subcommands: buildModelSubcommands()
588
2052
  },
589
- writeError: () => {
2053
+ {
2054
+ name: "language",
2055
+ description: "Set response language",
2056
+ source: "builtin",
2057
+ subcommands: [
2058
+ { name: "ko", description: "Korean", source: "builtin" },
2059
+ { name: "en", description: "English", source: "builtin" },
2060
+ { name: "ja", description: "Japanese", source: "builtin" },
2061
+ { name: "zh", description: "Chinese", source: "builtin" }
2062
+ ]
590
2063
  },
591
- prompt: () => Promise.resolve(""),
592
- select: () => Promise.resolve(0),
593
- spinner: () => ({ stop: () => {
594
- }, update: () => {
595
- } })
2064
+ { name: "compact", description: "Compress context window", source: "builtin" },
2065
+ { name: "cost", description: "Show session info", source: "builtin" },
2066
+ { name: "context", description: "Context window info", source: "builtin" },
2067
+ { name: "permissions", description: "Permission rules", source: "builtin" },
2068
+ { name: "plugin", description: "Manage plugins", source: "builtin" },
2069
+ { name: "reload-plugins", description: "Reload all plugin resources", source: "builtin" },
2070
+ { name: "reset", description: "Delete settings and exit", source: "builtin" },
2071
+ { name: "exit", description: "Exit CLI", source: "builtin" }
2072
+ ];
2073
+ }
2074
+ var BuiltinCommandSource = class {
2075
+ name = "builtin";
2076
+ commands;
2077
+ constructor() {
2078
+ this.commands = createBuiltinCommands();
2079
+ }
2080
+ getCommands() {
2081
+ return this.commands;
2082
+ }
2083
+ };
2084
+
2085
+ // src/commands/skill-source.ts
2086
+ var import_node_fs7 = require("fs");
2087
+ var import_node_path8 = require("path");
2088
+ var import_node_os3 = require("os");
2089
+ var BOOLEAN_KEYS = /* @__PURE__ */ new Set(["disable-model-invocation", "user-invocable"]);
2090
+ var LIST_KEYS2 = /* @__PURE__ */ new Set(["allowed-tools"]);
2091
+ function kebabToCamel(key) {
2092
+ return key.replace(/-([a-z])/g, (_match, letter) => letter.toUpperCase());
2093
+ }
2094
+ function parseFrontmatter2(content) {
2095
+ const lines = content.split("\n");
2096
+ if (lines[0]?.trim() !== "---") return null;
2097
+ const result = {};
2098
+ for (let i = 1; i < lines.length; i++) {
2099
+ const line = lines[i];
2100
+ if (line.trim() === "---") break;
2101
+ const match = line.match(/^([a-z][a-z0-9-]*):\s*(.+)/);
2102
+ if (!match) continue;
2103
+ const key = match[1];
2104
+ const rawValue = match[2].trim();
2105
+ const camelKey = kebabToCamel(key);
2106
+ if (BOOLEAN_KEYS.has(key)) {
2107
+ result[camelKey] = rawValue === "true";
2108
+ } else if (LIST_KEYS2.has(key)) {
2109
+ result[camelKey] = rawValue.split(",").map((s) => s.trim());
2110
+ } else {
2111
+ result[camelKey] = rawValue;
2112
+ }
2113
+ }
2114
+ return Object.keys(result).length > 0 ? result : null;
2115
+ }
2116
+ function buildCommand(frontmatter, content, fallbackName) {
2117
+ const cmd = {
2118
+ name: frontmatter?.name ?? fallbackName,
2119
+ description: frontmatter?.description ?? `Skill: ${fallbackName}`,
2120
+ source: "skill",
2121
+ skillContent: content
596
2122
  };
597
- const subSession = createSession({
598
- config: agentToolDeps.config,
599
- context: agentToolDeps.context,
600
- projectInfo: agentToolDeps.projectInfo,
601
- terminal: noopTerminal,
602
- // Sub-agents bypass permissions they inherit parent's trust
603
- permissionMode: "bypassPermissions"
604
- });
605
- try {
606
- const response = await subSession.run(args.prompt);
607
- const result = {
608
- success: true,
609
- output: response
2123
+ if (frontmatter?.argumentHint !== void 0) cmd.argumentHint = frontmatter.argumentHint;
2124
+ if (frontmatter?.disableModelInvocation !== void 0)
2125
+ cmd.disableModelInvocation = frontmatter.disableModelInvocation;
2126
+ if (frontmatter?.userInvocable !== void 0) cmd.userInvocable = frontmatter.userInvocable;
2127
+ if (frontmatter?.allowedTools !== void 0) cmd.allowedTools = frontmatter.allowedTools;
2128
+ if (frontmatter?.model !== void 0) cmd.model = frontmatter.model;
2129
+ if (frontmatter?.effort !== void 0) cmd.effort = frontmatter.effort;
2130
+ if (frontmatter?.context !== void 0) cmd.context = frontmatter.context;
2131
+ if (frontmatter?.agent !== void 0) cmd.agent = frontmatter.agent;
2132
+ return cmd;
2133
+ }
2134
+ function scanSkillsDir(skillsDir) {
2135
+ if (!(0, import_node_fs7.existsSync)(skillsDir)) return [];
2136
+ const commands = [];
2137
+ const entries = (0, import_node_fs7.readdirSync)(skillsDir, { withFileTypes: true });
2138
+ for (const entry of entries) {
2139
+ if (!entry.isDirectory()) continue;
2140
+ const skillFile = (0, import_node_path8.join)(skillsDir, entry.name, "SKILL.md");
2141
+ if (!(0, import_node_fs7.existsSync)(skillFile)) continue;
2142
+ const content = (0, import_node_fs7.readFileSync)(skillFile, "utf-8");
2143
+ const frontmatter = parseFrontmatter2(content);
2144
+ commands.push(buildCommand(frontmatter, content, entry.name));
2145
+ }
2146
+ return commands;
2147
+ }
2148
+ function scanCommandsDir(commandsDir) {
2149
+ if (!(0, import_node_fs7.existsSync)(commandsDir)) return [];
2150
+ const commands = [];
2151
+ const entries = (0, import_node_fs7.readdirSync)(commandsDir, { withFileTypes: true });
2152
+ for (const entry of entries) {
2153
+ if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
2154
+ const filePath = (0, import_node_path8.join)(commandsDir, entry.name);
2155
+ const content = (0, import_node_fs7.readFileSync)(filePath, "utf-8");
2156
+ const frontmatter = parseFrontmatter2(content);
2157
+ const fallbackName = (0, import_node_path8.basename)(entry.name, ".md");
2158
+ commands.push(buildCommand(frontmatter, content, fallbackName));
2159
+ }
2160
+ return commands;
2161
+ }
2162
+ var SkillCommandSource = class {
2163
+ name = "skill";
2164
+ cwd;
2165
+ home;
2166
+ cachedCommands = null;
2167
+ constructor(cwd, home) {
2168
+ this.cwd = cwd;
2169
+ this.home = home ?? (0, import_node_os3.homedir)();
2170
+ }
2171
+ getCommands() {
2172
+ if (this.cachedCommands) return this.cachedCommands;
2173
+ const sources = [
2174
+ scanSkillsDir((0, import_node_path8.join)(this.cwd, ".claude", "skills")),
2175
+ scanCommandsDir((0, import_node_path8.join)(this.cwd, ".claude", "commands")),
2176
+ scanSkillsDir((0, import_node_path8.join)(this.home, ".robota", "skills")),
2177
+ scanSkillsDir((0, import_node_path8.join)(this.cwd, ".agents", "skills"))
2178
+ ];
2179
+ const seen = /* @__PURE__ */ new Set();
2180
+ const merged = [];
2181
+ for (const commands of sources) {
2182
+ for (const cmd of commands) {
2183
+ if (!seen.has(cmd.name)) {
2184
+ seen.add(cmd.name);
2185
+ merged.push(cmd);
2186
+ }
2187
+ }
2188
+ }
2189
+ this.cachedCommands = merged;
2190
+ return this.cachedCommands;
2191
+ }
2192
+ getModelInvocableSkills() {
2193
+ return this.getCommands().filter((cmd) => cmd.disableModelInvocation !== true);
2194
+ }
2195
+ getUserInvocableSkills() {
2196
+ return this.getCommands().filter((cmd) => cmd.userInvocable !== false);
2197
+ }
2198
+ };
2199
+
2200
+ // src/commands/system-command.ts
2201
+ var VALID_MODES = ["plan", "default", "acceptEdits", "bypassPermissions"];
2202
+ function createSystemCommands() {
2203
+ return [
2204
+ {
2205
+ name: "help",
2206
+ description: "Show available commands",
2207
+ execute: (_session, _args) => ({
2208
+ message: [
2209
+ "Available commands:",
2210
+ " help \u2014 Show this help",
2211
+ " clear \u2014 Clear conversation",
2212
+ " compact [instr] \u2014 Compact context (optional focus instructions)",
2213
+ " mode [m] \u2014 Show/change permission mode",
2214
+ " model <id> \u2014 Change AI model",
2215
+ " language <code> \u2014 Set response language (ko, en, ja, zh)",
2216
+ " cost \u2014 Show session info",
2217
+ " context \u2014 Context window info",
2218
+ " permissions \u2014 Permission rules",
2219
+ " reset \u2014 Delete settings and exit"
2220
+ ].join("\n"),
2221
+ success: true
2222
+ })
2223
+ },
2224
+ {
2225
+ name: "clear",
2226
+ description: "Clear conversation history",
2227
+ execute: (session, _args) => {
2228
+ const underlying = session.getSession();
2229
+ underlying.clearHistory();
2230
+ return { message: "Conversation cleared.", success: true };
2231
+ }
2232
+ },
2233
+ {
2234
+ name: "compact",
2235
+ description: "Compress context window",
2236
+ execute: async (session, args) => {
2237
+ const underlying = session.getSession();
2238
+ const instructions = args.trim() || void 0;
2239
+ const before = underlying.getContextState().usedPercentage;
2240
+ await underlying.compact(instructions);
2241
+ const after = underlying.getContextState().usedPercentage;
2242
+ return {
2243
+ message: `Context compacted: ${Math.round(before)}% -> ${Math.round(after)}%`,
2244
+ success: true,
2245
+ data: { before, after }
2246
+ };
2247
+ }
2248
+ },
2249
+ {
2250
+ name: "mode",
2251
+ description: "Show/change permission mode",
2252
+ execute: (session, args) => {
2253
+ const underlying = session.getSession();
2254
+ const arg = args.trim().split(/\s+/)[0];
2255
+ if (!arg) {
2256
+ return {
2257
+ message: `Current mode: ${underlying.getPermissionMode()}`,
2258
+ success: true,
2259
+ data: { mode: underlying.getPermissionMode() }
2260
+ };
2261
+ }
2262
+ if (VALID_MODES.includes(arg)) {
2263
+ underlying.setPermissionMode(arg);
2264
+ return {
2265
+ message: `Permission mode set to: ${arg}`,
2266
+ success: true,
2267
+ data: { mode: arg }
2268
+ };
2269
+ }
2270
+ return {
2271
+ message: `Invalid mode. Valid: ${VALID_MODES.join(" | ")}`,
2272
+ success: false
2273
+ };
2274
+ }
2275
+ },
2276
+ {
2277
+ name: "model",
2278
+ description: "Change AI model",
2279
+ execute: (_session, args) => {
2280
+ const modelId = args.trim().split(/\s+/)[0];
2281
+ if (!modelId) {
2282
+ return { message: "Usage: model <model-id>", success: false };
2283
+ }
2284
+ return {
2285
+ message: `Model change requested: ${modelId}`,
2286
+ success: true,
2287
+ data: { modelId }
2288
+ };
2289
+ }
2290
+ },
2291
+ {
2292
+ name: "language",
2293
+ description: "Set response language",
2294
+ execute: (_session, args) => {
2295
+ const lang = args.trim().split(/\s+/)[0];
2296
+ if (!lang) {
2297
+ return { message: "Usage: language <code> (e.g., ko, en, ja, zh)", success: false };
2298
+ }
2299
+ return {
2300
+ message: `Language set to "${lang}".`,
2301
+ success: true,
2302
+ data: { language: lang }
2303
+ };
2304
+ }
2305
+ },
2306
+ {
2307
+ name: "cost",
2308
+ description: "Show session info",
2309
+ execute: (session, _args) => {
2310
+ const underlying = session.getSession();
2311
+ const sessionId = underlying.getSessionId();
2312
+ const messageCount = underlying.getMessageCount();
2313
+ return {
2314
+ message: `Session: ${sessionId}
2315
+ Messages: ${messageCount}`,
2316
+ success: true,
2317
+ data: { sessionId, messageCount }
2318
+ };
2319
+ }
2320
+ },
2321
+ {
2322
+ name: "context",
2323
+ description: "Context window info",
2324
+ execute: (session, _args) => {
2325
+ const ctx = session.getContextState();
2326
+ return {
2327
+ message: `Context: ${ctx.usedTokens.toLocaleString()} / ${ctx.maxTokens.toLocaleString()} tokens (${Math.round(ctx.usedPercentage)}%)`,
2328
+ success: true,
2329
+ data: {
2330
+ usedTokens: ctx.usedTokens,
2331
+ maxTokens: ctx.maxTokens,
2332
+ percentage: ctx.usedPercentage
2333
+ }
2334
+ };
2335
+ }
2336
+ },
2337
+ {
2338
+ name: "permissions",
2339
+ description: "Show permission rules",
2340
+ execute: (session, _args) => {
2341
+ const underlying = session.getSession();
2342
+ const mode = underlying.getPermissionMode();
2343
+ const sessionAllowed = underlying.getSessionAllowedTools();
2344
+ const lines = [`Permission mode: ${mode}`];
2345
+ if (sessionAllowed.length > 0) {
2346
+ lines.push(`Session-approved tools: ${sessionAllowed.join(", ")}`);
2347
+ } else {
2348
+ lines.push("No session-approved tools.");
2349
+ }
2350
+ return {
2351
+ message: lines.join("\n"),
2352
+ success: true,
2353
+ data: { mode, sessionAllowed }
2354
+ };
2355
+ }
2356
+ },
2357
+ {
2358
+ name: "reset",
2359
+ description: "Delete settings",
2360
+ execute: (_session, _args) => {
2361
+ return {
2362
+ message: "Reset requested.",
2363
+ success: true,
2364
+ data: { resetRequested: true }
2365
+ };
2366
+ }
2367
+ }
2368
+ ];
2369
+ }
2370
+ var SystemCommandExecutor = class {
2371
+ commands;
2372
+ constructor(commands) {
2373
+ this.commands = /* @__PURE__ */ new Map();
2374
+ for (const cmd of commands ?? createSystemCommands()) {
2375
+ this.commands.set(cmd.name, cmd);
2376
+ }
2377
+ }
2378
+ /** Register an additional command. */
2379
+ register(command) {
2380
+ this.commands.set(command.name, command);
2381
+ }
2382
+ /** Execute a command by name. Returns null if command not found. */
2383
+ async execute(name, session, args) {
2384
+ const cmd = this.commands.get(name);
2385
+ if (!cmd) return null;
2386
+ return await cmd.execute(session, args);
2387
+ }
2388
+ /** List all registered commands. */
2389
+ listCommands() {
2390
+ return [...this.commands.values()];
2391
+ }
2392
+ /** Check if a command exists. */
2393
+ hasCommand(name) {
2394
+ return this.commands.has(name);
2395
+ }
2396
+ };
2397
+
2398
+ // src/interactive/interactive-session.ts
2399
+ var import_agent_sessions4 = require("@robota-sdk/agent-sessions");
2400
+ var import_agent_core3 = require("@robota-sdk/agent-core");
2401
+ var TOOL_ARG_DISPLAY_MAX = 80;
2402
+ var TAIL_KEEP = 30;
2403
+ var MAX_COMPLETED_TOOLS = 50;
2404
+ var STREAMING_FLUSH_INTERVAL_MS = 16;
2405
+ var InteractiveSession = class {
2406
+ session;
2407
+ listeners = /* @__PURE__ */ new Map();
2408
+ // Streaming state
2409
+ streamingText = "";
2410
+ flushTimer = null;
2411
+ // Tool state
2412
+ activeTools = [];
2413
+ // Execution state
2414
+ executing = false;
2415
+ pendingPrompt = null;
2416
+ pendingDisplayInput;
2417
+ pendingRawInput;
2418
+ // Display messages (what clients render — not the raw session history)
2419
+ messages = [];
2420
+ constructor(options) {
2421
+ if (options.session) {
2422
+ this.session = options.session;
2423
+ } else {
2424
+ const cwd = options.cwd ?? process.cwd();
2425
+ const paths = projectPaths(cwd);
2426
+ this.session = createSession({
2427
+ config: options.config,
2428
+ context: options.context,
2429
+ projectInfo: options.projectInfo,
2430
+ sessionStore: options.sessionStore,
2431
+ permissionMode: options.permissionMode,
2432
+ maxTurns: options.maxTurns,
2433
+ terminal: NOOP_TERMINAL,
2434
+ sessionLogger: new import_agent_sessions4.FileSessionLogger(paths.logs),
2435
+ permissionHandler: options.permissionHandler,
2436
+ onTextDelta: (delta) => this.handleTextDelta(delta),
2437
+ onToolExecution: (event) => this.handleToolExecution(event)
2438
+ });
2439
+ }
2440
+ }
2441
+ // ── Event system ──────────────────────────────────────────────
2442
+ on(event, handler) {
2443
+ if (!this.listeners.has(event)) {
2444
+ this.listeners.set(event, /* @__PURE__ */ new Set());
2445
+ }
2446
+ this.listeners.get(event).add(handler);
2447
+ }
2448
+ off(event, handler) {
2449
+ this.listeners.get(event)?.delete(handler);
2450
+ }
2451
+ emit(event, ...args) {
2452
+ const handlers = this.listeners.get(event);
2453
+ if (handlers) {
2454
+ for (const handler of handlers) {
2455
+ handler(...args);
2456
+ }
2457
+ }
2458
+ }
2459
+ // ── Public API ────────────────────────────────────────────────
2460
+ /** Submit a prompt. Queues if already executing (max 1 queued).
2461
+ * displayInput overrides what appears as the user message (e.g., "/audit" instead of full skill prompt).
2462
+ * rawInput is passed to Session.run() for hook matching (e.g., "/rulebased-harness:audit"). */
2463
+ async submit(input, displayInput, rawInput) {
2464
+ if (this.executing) {
2465
+ this.pendingPrompt = input;
2466
+ this.pendingDisplayInput = displayInput;
2467
+ this.pendingRawInput = rawInput;
2468
+ return;
2469
+ }
2470
+ await this.executePrompt(input, displayInput, rawInput);
2471
+ }
2472
+ /** Abort current execution and clear queue. */
2473
+ abort() {
2474
+ this.pendingPrompt = null;
2475
+ this.session.abort();
2476
+ }
2477
+ /** Cancel queued prompt without aborting current execution. */
2478
+ cancelQueue() {
2479
+ this.pendingPrompt = null;
2480
+ }
2481
+ isExecuting() {
2482
+ return this.executing;
2483
+ }
2484
+ getPendingPrompt() {
2485
+ return this.pendingPrompt;
2486
+ }
2487
+ getMessages() {
2488
+ return this.messages;
2489
+ }
2490
+ getStreamingText() {
2491
+ return this.streamingText;
2492
+ }
2493
+ getActiveTools() {
2494
+ return this.activeTools;
2495
+ }
2496
+ getContextState() {
2497
+ return this.session.getContextState();
2498
+ }
2499
+ getSession() {
2500
+ return this.session;
2501
+ }
2502
+ // ── Execution ─────────────────────────────────────────────────
2503
+ async executePrompt(input, displayInput, rawInput) {
2504
+ this.executing = true;
2505
+ this.clearStreaming();
2506
+ this.emit("thinking", true);
2507
+ this.messages.push((0, import_agent_core3.createUserMessage)(displayInput ?? input));
2508
+ const historyBefore = this.session.getHistory().length;
2509
+ try {
2510
+ const response = await this.session.run(input, rawInput);
2511
+ this.flushStreaming();
2512
+ this.clearStreaming();
2513
+ const result = this.buildResult(response || "(empty response)", historyBefore);
2514
+ this.messages.push((0, import_agent_core3.createAssistantMessage)(result.response));
2515
+ this.emit("complete", result);
2516
+ this.emit("context_update", this.getContextState());
2517
+ } catch (err) {
2518
+ this.flushStreaming();
2519
+ this.clearStreaming();
2520
+ if (isAbortError(err)) {
2521
+ const result = this.buildInterruptedResult(historyBefore);
2522
+ if (result.response) {
2523
+ this.messages.push((0, import_agent_core3.createAssistantMessage)(result.response));
2524
+ }
2525
+ this.messages.push((0, import_agent_core3.createSystemMessage)("Interrupted by user."));
2526
+ this.emit("interrupted", result);
2527
+ } else {
2528
+ const errMsg = err instanceof Error ? err.message : String(err);
2529
+ this.messages.push((0, import_agent_core3.createSystemMessage)(`Error: ${errMsg}`));
2530
+ this.emit("error", err instanceof Error ? err : new Error(errMsg));
2531
+ }
2532
+ } finally {
2533
+ this.executing = false;
2534
+ this.emit("thinking", false);
2535
+ if (this.pendingPrompt) {
2536
+ const queued = this.pendingPrompt;
2537
+ const queuedDisplay = this.pendingDisplayInput;
2538
+ const queuedRaw = this.pendingRawInput;
2539
+ this.pendingPrompt = null;
2540
+ this.pendingDisplayInput = void 0;
2541
+ this.pendingRawInput = void 0;
2542
+ setTimeout(() => this.executePrompt(queued, queuedDisplay, queuedRaw), 0);
2543
+ }
2544
+ }
2545
+ }
2546
+ // ── Streaming callbacks ───────────────────────────────────────
2547
+ handleTextDelta(delta) {
2548
+ this.streamingText += delta;
2549
+ this.emit("text_delta", delta);
2550
+ if (!this.flushTimer) {
2551
+ this.flushTimer = setTimeout(() => {
2552
+ this.flushTimer = null;
2553
+ }, STREAMING_FLUSH_INTERVAL_MS);
2554
+ }
2555
+ }
2556
+ handleToolExecution(event) {
2557
+ if (event.type === "start") {
2558
+ const firstArg = extractFirstArg(event.toolArgs);
2559
+ const state = {
2560
+ toolName: event.toolName,
2561
+ firstArg,
2562
+ isRunning: true
2563
+ };
2564
+ this.activeTools.push(state);
2565
+ this.emit("tool_start", state);
2566
+ } else {
2567
+ const result = event.denied ? "denied" : event.success === false ? "error" : "success";
2568
+ const idx = this.activeTools.findIndex((t) => t.toolName === event.toolName && t.isRunning);
2569
+ if (idx !== -1) {
2570
+ const finished = {
2571
+ ...this.activeTools[idx],
2572
+ isRunning: false,
2573
+ result
2574
+ };
2575
+ this.activeTools[idx] = finished;
2576
+ this.trimCompletedTools();
2577
+ this.emit("tool_end", finished);
2578
+ }
2579
+ }
2580
+ }
2581
+ // ── Helpers ───────────────────────────────────────────────────
2582
+ clearStreaming() {
2583
+ this.streamingText = "";
2584
+ this.activeTools = [];
2585
+ if (this.flushTimer) {
2586
+ clearTimeout(this.flushTimer);
2587
+ this.flushTimer = null;
2588
+ }
2589
+ }
2590
+ flushStreaming() {
2591
+ if (this.flushTimer) {
2592
+ clearTimeout(this.flushTimer);
2593
+ this.flushTimer = null;
2594
+ }
2595
+ }
2596
+ buildResult(response, historyBefore) {
2597
+ const toolSummaries = this.extractToolSummaries(historyBefore);
2598
+ return {
2599
+ response,
2600
+ messages: this.messages,
2601
+ toolSummaries,
2602
+ contextState: this.getContextState()
610
2603
  };
611
- return JSON.stringify(result);
612
- } catch (err) {
613
- const message = err instanceof Error ? err.message : String(err);
614
- const result = {
615
- success: false,
616
- output: "",
617
- error: `Sub-agent error: ${message}`
2604
+ }
2605
+ buildInterruptedResult(historyBefore) {
2606
+ const history = this.session.getHistory();
2607
+ const toolSummaries = this.extractToolSummaries(historyBefore);
2608
+ const parts = [];
2609
+ for (let i = historyBefore; i < history.length; i++) {
2610
+ const msg = history[i];
2611
+ if (msg?.role === "assistant" && msg.content) {
2612
+ parts.push(msg.content);
2613
+ }
2614
+ }
2615
+ return {
2616
+ response: parts.join("\n\n"),
2617
+ messages: this.messages,
2618
+ toolSummaries,
2619
+ contextState: this.getContextState()
618
2620
  };
619
- return JSON.stringify(result);
620
2621
  }
621
- }
622
- var agentTool = (0, import_agent_tools2.createZodFunctionTool)(
623
- "Agent",
624
- "Spawn a sub-agent with isolated context to handle a task. The sub-agent has its own conversation history and can use all tools.",
625
- asZodSchema(AgentSchema),
626
- async (params) => {
627
- return runAgent(params);
2622
+ extractToolSummaries(historyBefore) {
2623
+ const history = this.session.getHistory();
2624
+ const summaries = [];
2625
+ for (let i = historyBefore; i < history.length; i++) {
2626
+ const msg = history[i];
2627
+ if (msg?.role === "assistant" && msg.toolCalls) {
2628
+ for (const tc of msg.toolCalls) {
2629
+ summaries.push({ name: tc.function.name, args: tc.function.arguments });
2630
+ }
2631
+ }
2632
+ }
2633
+ return summaries;
628
2634
  }
629
- );
2635
+ trimCompletedTools() {
2636
+ const completed = this.activeTools.filter((t) => !t.isRunning);
2637
+ if (completed.length > MAX_COMPLETED_TOOLS) {
2638
+ const excess = completed.length - MAX_COMPLETED_TOOLS;
2639
+ let removed = 0;
2640
+ this.activeTools = this.activeTools.filter((t) => {
2641
+ if (!t.isRunning && removed < excess) {
2642
+ removed++;
2643
+ return false;
2644
+ }
2645
+ return true;
2646
+ });
2647
+ }
2648
+ }
2649
+ };
2650
+ function isAbortError(err) {
2651
+ return err instanceof DOMException && err.name === "AbortError" || err instanceof Error && (err.message.includes("aborted") || err.message.includes("abort"));
2652
+ }
2653
+ function extractFirstArg(toolArgs) {
2654
+ if (!toolArgs) return "";
2655
+ const firstVal = Object.values(toolArgs)[0];
2656
+ const raw = typeof firstVal === "string" ? firstVal : JSON.stringify(firstVal ?? "");
2657
+ return raw.length > TOOL_ARG_DISPLAY_MAX ? raw.slice(0, TOOL_ARG_DISPLAY_MAX - TAIL_KEEP - 3) + "..." + raw.slice(-TAIL_KEEP) : raw;
2658
+ }
2659
+ var NOOP_TERMINAL = {
2660
+ write: () => {
2661
+ },
2662
+ writeLine: () => {
2663
+ },
2664
+ writeMarkdown: () => {
2665
+ },
2666
+ writeError: () => {
2667
+ },
2668
+ prompt: () => Promise.resolve(""),
2669
+ select: () => Promise.resolve(0),
2670
+ spinner: () => ({ stop: () => {
2671
+ }, update: () => {
2672
+ } })
2673
+ };
630
2674
 
631
2675
  // src/index.ts
632
2676
  var import_agent_tools3 = require("@robota-sdk/agent-tools");
@@ -637,31 +2681,53 @@ var import_agent_tools7 = require("@robota-sdk/agent-tools");
637
2681
  var import_agent_tools8 = require("@robota-sdk/agent-tools");
638
2682
  // Annotate the CommonJS export names for ESM import in node:
639
2683
  0 && (module.exports = {
2684
+ AgentExecutor,
2685
+ BUILT_IN_AGENTS,
2686
+ BuiltinCommandSource,
2687
+ BundlePluginInstaller,
2688
+ BundlePluginLoader,
2689
+ CommandRegistry,
640
2690
  DEFAULT_TOOL_DESCRIPTIONS,
641
2691
  FileSessionLogger,
2692
+ InteractiveSession,
2693
+ MarketplaceClient,
2694
+ PluginSettingsStore,
2695
+ PromptExecutor,
642
2696
  Session,
643
2697
  SessionStore,
644
2698
  SilentSessionLogger,
2699
+ SkillCommandSource,
2700
+ SystemCommandExecutor,
645
2701
  TRUST_TO_MODE,
646
- agentTool,
2702
+ assembleSubagentPrompt,
647
2703
  bashTool,
648
2704
  buildSystemPrompt,
2705
+ createAgentTool,
649
2706
  createDefaultTools,
650
2707
  createProvider,
651
2708
  createSession,
2709
+ createSubagentLogger,
2710
+ createSubagentSession,
2711
+ createSystemCommands,
652
2712
  detectProject,
653
2713
  editTool,
654
2714
  evaluatePermission,
2715
+ getBuiltInAgent,
2716
+ getForkWorkerSuffix,
2717
+ getSubagentSuffix,
655
2718
  globTool,
656
2719
  grepTool,
657
2720
  loadConfig,
658
2721
  loadContext,
2722
+ parseFrontmatter,
659
2723
  projectPaths,
660
2724
  promptForApproval,
661
2725
  query,
662
2726
  readTool,
2727
+ resolveSubagentLogDir,
2728
+ retrieveAgentToolDeps,
663
2729
  runHooks,
664
- setAgentToolDeps,
2730
+ storeAgentToolDeps,
665
2731
  userPaths,
666
2732
  writeTool
667
2733
  });