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

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