@robota-sdk/agent-sdk 3.0.0-beta.5 → 3.0.0-beta.50

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