triagent 0.1.0-alpha1 → 0.1.0-alpha10

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.
package/README.md CHANGED
@@ -5,7 +5,17 @@ AI-powered Kubernetes debugging agent with terminal UI.
5
5
  ## Installation
6
6
 
7
7
  ```bash
8
- bun install triagent
8
+ # bun
9
+ bun install -g triagent
10
+
11
+ # npm
12
+ npm install -g triagent
13
+
14
+ # yarn
15
+ yarn global add triagent
16
+
17
+ # pnpm
18
+ pnpm add -g triagent
9
19
  ```
10
20
 
11
21
  ## Usage
@@ -20,14 +30,62 @@ triagent --webhook-only
20
30
 
21
31
  ## Configuration
22
32
 
23
- Set the following environment variables:
33
+ Configuration can be set via CLI commands or environment variables. CLI config takes precedence over environment variables.
34
+
35
+ ### CLI Config
24
36
 
25
37
  ```bash
26
- ANTHROPIC_API_KEY=your-api-key
27
- # or
28
- OPENAI_API_KEY=your-api-key
29
- # or
30
- GOOGLE_GENERATIVE_AI_API_KEY=your-api-key
38
+ # Set configuration values
39
+ triagent config set <key> <value>
40
+
41
+ # Get a configuration value
42
+ triagent config get <key>
43
+
44
+ # List all configuration values
45
+ triagent config list
46
+
47
+ # Show config file path
48
+ triagent config path
49
+ ```
50
+
51
+ ### Config Keys
52
+
53
+ | Key | Description | Default |
54
+ |-----|-------------|---------|
55
+ | `aiProvider` | AI provider (`openai`, `anthropic`, `google`) | `anthropic` |
56
+ | `aiModel` | Model ID (e.g., `gpt-4o`, `claude-sonnet-4-20250514`) | Provider default |
57
+ | `apiKey` | API key for the provider | - |
58
+ | `baseUrl` | Custom API base URL (for proxies or local models) | - |
59
+ | `webhookPort` | Webhook server port | `3000` |
60
+ | `codebasePath` | Path to codebase | `./` |
61
+ | `kubeConfigPath` | Kubernetes config path | `~/.kube` |
62
+
63
+ ### Environment Variables
64
+
65
+ | Variable | Description |
66
+ |----------|-------------|
67
+ | `AI_PROVIDER` | AI provider (`openai`, `anthropic`, `google`) |
68
+ | `AI_MODEL` | Model ID |
69
+ | `AI_BASE_URL` | Custom API base URL |
70
+ | `OPENAI_API_KEY` | OpenAI API key |
71
+ | `ANTHROPIC_API_KEY` | Anthropic API key |
72
+ | `GOOGLE_GENERATIVE_AI_API_KEY` | Google AI API key |
73
+ | `WEBHOOK_PORT` | Webhook server port |
74
+ | `CODEBASE_PATH` | Path to codebase |
75
+ | `KUBE_CONFIG_PATH` | Kubernetes config path |
76
+
77
+ ### Examples
78
+
79
+ ```bash
80
+ # Configure with Anthropic (default)
81
+ triagent config set apiKey sk-ant-...
82
+
83
+ # Configure with OpenAI
84
+ triagent config set aiProvider openai
85
+ triagent config set apiKey sk-proj-...
86
+
87
+ # Use a custom API endpoint (e.g., proxy or local model)
88
+ triagent config set baseUrl https://your-proxy.example.com/v1
31
89
  ```
32
90
 
33
91
  ## Development
package/bunfig.toml CHANGED
@@ -1 +1,5 @@
1
1
  preload = ["@opentui/solid/preload"]
2
+
3
+ [jsx]
4
+ runtime = "automatic"
5
+ importSource = "@opentui/solid"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "triagent",
3
- "version": "0.1.0-alpha1",
3
+ "version": "0.1.0-alpha10",
4
4
  "description": "AI-powered Kubernetes debugging agent with terminal UI",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
@@ -46,12 +46,15 @@
46
46
  "@opentui/core": "^0.1.72",
47
47
  "@opentui/solid": "^0.1.72",
48
48
  "hono": "^4.6.0",
49
- "solid-js": "^1.9.10",
49
+ "opentui-spinner": "^0.0.6",
50
+ "solid-js": "1.9.9",
51
+ "triagent": "^0.1.0-alpha1",
50
52
  "zod": "^3.24.0"
51
53
  },
52
54
  "devDependencies": {
53
- "typescript": "^5.7.0",
55
+ "@types/babel__core": "^7.20.5",
54
56
  "@types/node": "^22.0.0",
55
- "bun-types": "^1.2.0"
57
+ "bun-types": "^1.2.0",
58
+ "typescript": "^5.7.0"
56
59
  }
57
60
  }
package/src/cli/config.ts CHANGED
@@ -7,6 +7,7 @@ export interface StoredConfig {
7
7
  aiProvider?: AIProvider;
8
8
  aiModel?: string;
9
9
  apiKey?: string;
10
+ baseUrl?: string;
10
11
  webhookPort?: number;
11
12
  codebasePath?: string;
12
13
  kubeConfigPath?: string;
package/src/config.ts CHANGED
@@ -10,6 +10,7 @@ const ConfigSchema = z.object({
10
10
  aiProvider: AIProviderSchema,
11
11
  aiModel: z.string().min(1),
12
12
  apiKey: z.string().min(1),
13
+ baseUrl: z.string().url().optional(),
13
14
  webhookPort: z.number().int().positive().default(3000),
14
15
  codebasePath: z.string().min(1).default("./"),
15
16
  kubeConfigPath: z.string().min(1).default("~/.kube"),
@@ -47,6 +48,7 @@ export async function loadConfig(): Promise<Config> {
47
48
  aiProvider: provider,
48
49
  aiModel: process.env.AI_MODEL || stored.aiModel || getDefaultModel(provider),
49
50
  apiKey: getApiKey(provider, stored),
51
+ baseUrl: process.env.AI_BASE_URL || stored.baseUrl || undefined,
50
52
  webhookPort: parseInt(process.env.WEBHOOK_PORT || String(stored.webhookPort || 3000), 10),
51
53
  codebasePath: expandPath(process.env.CODEBASE_PATH || stored.codebasePath || "./"),
52
54
  kubeConfigPath: expandPath(process.env.KUBE_CONFIG_PATH || stored.kubeConfigPath || "~/.kube"),
package/src/index.ts CHANGED
@@ -1,8 +1,10 @@
1
1
  #!/usr/bin/env bun
2
+ // Load solid JSX plugin before any TSX imports
3
+ import "@opentui/solid/preload";
4
+
2
5
  import { loadConfig } from "./config.js";
3
6
  import { initSandboxFromConfig } from "./sandbox/bashlet.js";
4
7
  import { createMastraInstance, buildIncidentPrompt, getDebuggerAgent } from "./mastra/index.js";
5
- import { runTUI } from "./tui/app.jsx";
6
8
  import { startWebhookServer } from "./server/webhook.js";
7
9
  import {
8
10
  loadStoredConfig,
@@ -84,6 +86,7 @@ CONFIG KEYS:
84
86
  aiProvider - AI provider (openai, anthropic, google)
85
87
  aiModel - Model ID (e.g., gpt-4o, claude-sonnet-4-20250514)
86
88
  apiKey - API key for the provider
89
+ baseUrl - Custom API base URL (for proxies or local models)
87
90
  webhookPort - Webhook server port (default: 3000)
88
91
  codebasePath - Path to codebase (default: ./)
89
92
  kubeConfigPath - Kubernetes config path (default: ~/.kube)
@@ -109,6 +112,7 @@ MODES:
109
112
  ENVIRONMENT VARIABLES:
110
113
  AI_PROVIDER - AI provider (openai, anthropic, google)
111
114
  AI_MODEL - Model ID (e.g., gpt-4o, claude-3-5-sonnet)
115
+ AI_BASE_URL - Custom API base URL (for proxies or local models)
112
116
  OPENAI_API_KEY - OpenAI API key
113
117
  ANTHROPIC_API_KEY - Anthropic API key
114
118
  GOOGLE_GENERATIVE_AI_API_KEY - Google AI API key
@@ -152,7 +156,12 @@ async function runDirectIncident(description: string): Promise<void> {
152
156
  if (toolCalls && toolCalls.length > 0) {
153
157
  const toolCall = toolCalls[0];
154
158
  const toolName = "toolName" in toolCall ? toolCall.toolName : "tool";
155
- console.log(`\n[Tool: ${toolName}]\n`);
159
+ const args = "args" in toolCall ? toolCall.args : {};
160
+ console.log(`\n[Tool: ${toolName}]`);
161
+ if (args && typeof args === "object" && "command" in args) {
162
+ console.log(`$ ${args.command}`);
163
+ }
164
+ console.log();
156
165
  }
157
166
  },
158
167
  });
@@ -174,6 +183,7 @@ async function handleConfigCommand(args: CliArgs): Promise<void> {
174
183
  "aiProvider",
175
184
  "aiModel",
176
185
  "apiKey",
186
+ "baseUrl",
177
187
  "webhookPort",
178
188
  "codebasePath",
179
189
  "kubeConfigPath",
@@ -289,6 +299,8 @@ async function main(): Promise<void> {
289
299
  } else {
290
300
  // Interactive TUI mode
291
301
  console.log("Starting Triagent TUI...\n");
302
+ // Dynamic import to ensure solid plugin is loaded first
303
+ const { runTUI } = await import("./tui/app.jsx");
292
304
  const tui = await runTUI();
293
305
 
294
306
  // Handle graceful shutdown
@@ -1,6 +1,6 @@
1
1
  import { Agent } from "@mastra/core/agent";
2
2
  import { z } from "zod";
3
- import { kubectlTool } from "../tools/kubectl.js";
3
+ import { cliTool } from "../tools/cli.js";
4
4
  import { gitTool } from "../tools/git.js";
5
5
  import { filesystemTool } from "../tools/filesystem.js";
6
6
  import type { Config } from "../../config.js";
@@ -9,12 +9,14 @@ const DEBUGGER_INSTRUCTIONS = `You are an expert Kubernetes debugging agent name
9
9
 
10
10
  ## Your Capabilities
11
11
 
12
- 1. **Kubernetes Inspection** (kubectl tool):
13
- - Get resource status (pods, deployments, services, configmaps)
14
- - Describe resources for detailed information
15
- - Fetch container logs
16
- - Check resource usage (top)
17
- - Review cluster events
12
+ 1. **CLI Access** (cli tool):
13
+ - Run any shell command including kubectl, grep, awk, jq, curl, etc.
14
+ - Pipe commands together for powerful filtering and processing
15
+ - Examples:
16
+ - \`kubectl get pods -A | grep inventory\`
17
+ - \`kubectl logs deploy/myapp --tail 100 | grep -i error\`
18
+ - \`kubectl get pods -o json | jq '.items[].metadata.name'\`
19
+ - \`kubectl describe pod mypod | grep -A10 Events\`
18
20
 
19
21
  2. **Code Analysis** (filesystem tool):
20
22
  - Read source code files
@@ -27,6 +29,39 @@ const DEBUGGER_INSTRUCTIONS = `You are an expert Kubernetes debugging agent name
27
29
  - Show specific commit details
28
30
  - Blame files to find who changed what
29
31
 
32
+ ## Resource Discovery Strategy
33
+
34
+ When asked to find resources for a service (e.g., "inventory service"), DO NOT simply try one label like \`app=inventory\` and give up if not found. Instead, use a systematic discovery approach:
35
+
36
+ 1. **Search by partial name match using grep**:
37
+ - \`kubectl get pods -A | grep -i inventory\`
38
+ - \`kubectl get deploy,svc -A | grep -i inventory\`
39
+ - This finds resources with "inventory" anywhere in the name (e.g., \`inventory-api\`, \`svc-inventory\`)
40
+
41
+ 2. **If grep returns no results, list all resources to browse**:
42
+ - \`kubectl get pods,deploy,svc -A\` to see everything
43
+ - \`kubectl get pods -n <namespace>\` if namespace is known
44
+
45
+ 3. **Try common label patterns**:
46
+ - \`kubectl get pods -A -l app=inventory\`
47
+ - \`kubectl get pods -A -l app.kubernetes.io/name=inventory\`
48
+ - \`kubectl get pods -A -l component=inventory\`
49
+
50
+ 4. **Follow the resource chain**:
51
+ - Found a Service? \`kubectl describe svc <name> | grep Selector\` then find pods with that selector
52
+ - Found a Deployment? \`kubectl get pods -l app=<deployment-name>\`
53
+ - Use \`kubectl get endpoints <svc-name>\` to see which pods back a service
54
+
55
+ 5. **Check events for context**:
56
+ - \`kubectl get events -A --sort-by='.lastTimestamp' | grep -i inventory\`
57
+ - \`kubectl get events -A --sort-by='.lastTimestamp' | head -20\` for recent cluster activity
58
+
59
+ 6. **When you find a potential match**:
60
+ - \`kubectl describe <resource> <name>\` to confirm it's the right one
61
+ - Check related resources (pods for a deployment, endpoints for a service)
62
+
63
+ Always report what you searched for and what you found, even if it's not an exact match. The user can confirm if you found the right resource.
64
+
30
65
  ## Investigation Process
31
66
 
32
67
  When given an incident, follow this systematic approach:
@@ -36,26 +71,32 @@ When given an incident, follow this systematic approach:
36
71
  - What symptoms are being observed
37
72
  - When the issue started (if known)
38
73
 
39
- 2. **Check Cluster State**:
40
- - Get pod status for affected services
41
- - Check for recent events
74
+ 2. **Discover Relevant Resources**:
75
+ - Use the Resource Discovery Strategy above to find the affected resources
76
+ - Don't assume exact names or labels - search broadly first
77
+ - Follow the resource chain (Service → Deployment → Pods → Containers)
78
+
79
+ 3. **Check Cluster State**:
80
+ - Get pod status for discovered resources
81
+ - Check for recent events related to those resources
42
82
  - Look at resource usage
43
83
 
44
- 3. **Analyze Logs**:
45
- - Fetch logs from affected pods
84
+ 4. **Analyze Logs**:
85
+ - Fetch logs from affected pods (use \`--tail 100\` to get recent logs)
46
86
  - Look for errors, exceptions, or unusual patterns
87
+ - If multiple containers, check each one
47
88
 
48
- 4. **Investigate Recent Changes**:
89
+ 5. **Investigate Recent Changes**:
49
90
  - Check git log for recent commits
50
91
  - Review diffs of suspicious changes
51
92
  - Correlate timing with when issues started
52
93
 
53
- 5. **Examine Code**:
94
+ 6. **Examine Code**:
54
95
  - Read relevant configuration files
55
96
  - Check application code if needed
56
97
  - Look for misconfigurations
57
98
 
58
- 6. **Synthesize Findings**:
99
+ 7. **Synthesize Findings**:
59
100
  - Identify the root cause
60
101
  - List affected resources
61
102
  - Provide actionable recommendations
@@ -122,16 +163,21 @@ export const InvestigationResultSchema = z.object({
122
163
  export type InvestigationResult = z.infer<typeof InvestigationResultSchema>;
123
164
 
124
165
  export function createDebuggerAgent(config: Config) {
125
- // Construct model string based on provider
126
- const modelString = `${config.aiProvider}/${config.aiModel}`;
166
+ // Construct model config with API key and optional base URL
167
+ const modelId = `${config.aiProvider}/${config.aiModel}` as const;
168
+ const modelConfig = {
169
+ id: modelId,
170
+ apiKey: config.apiKey,
171
+ ...(config.baseUrl && { url: config.baseUrl }),
172
+ };
127
173
 
128
174
  return new Agent({
129
175
  id: "kubernetes-debugger",
130
176
  name: "Kubernetes Debugger",
131
177
  instructions: DEBUGGER_INSTRUCTIONS,
132
- model: modelString as any, // Mastra handles model routing
178
+ model: modelConfig as any, // Mastra handles model routing
133
179
  tools: {
134
- kubectl: kubectlTool,
180
+ cli: cliTool,
135
181
  git: gitTool,
136
182
  filesystem: filesystemTool,
137
183
  },
@@ -0,0 +1,65 @@
1
+ import { createTool } from "@mastra/core/tools";
2
+ import { z } from "zod";
3
+ import { execCommand } from "../../sandbox/bashlet.js";
4
+
5
+ interface CliOutput {
6
+ success: boolean;
7
+ output: string;
8
+ error?: string;
9
+ }
10
+
11
+ function filterSensitiveData(output: string): string {
12
+ // Redact potential secrets, tokens, and passwords
13
+ return output
14
+ .replace(
15
+ /(password|secret|token|key|credential)[\s:=]+["']?[^\s"'\n]+["']?/gi,
16
+ "$1: [REDACTED]"
17
+ )
18
+ .replace(/Bearer\s+[^\s]+/gi, "Bearer [REDACTED]")
19
+ .replace(/-----BEGIN[^-]+-----[\s\S]*?-----END[^-]+-----/g, "[REDACTED CERTIFICATE/KEY]");
20
+ }
21
+
22
+ export const cliTool = createTool({
23
+ id: "cli",
24
+ description: `Execute shell commands in the sandbox environment.
25
+ Use this to run any CLI commands including kubectl, grep, awk, jq, curl, etc.
26
+ Supports pipes and command chaining.
27
+
28
+ Examples:
29
+ - List all pods: kubectl get pods -A
30
+ - Find pods by name: kubectl get pods -A | grep inventory
31
+ - Get logs with filtering: kubectl logs deployment/myapp -n prod --tail 100 | grep -i error
32
+ - Check resource usage: kubectl top pods -n default
33
+ - Describe and search: kubectl describe pod mypod | grep -A5 "Events"
34
+ - JSON processing: kubectl get pods -o json | jq '.items[].metadata.name'`,
35
+
36
+ inputSchema: z.object({
37
+ command: z.string().describe("The shell command to execute"),
38
+ }),
39
+
40
+ execute: async ({ command }): Promise<CliOutput> => {
41
+ try {
42
+ const result = await execCommand(command);
43
+
44
+ if (result.exitCode !== 0) {
45
+ return {
46
+ success: false,
47
+ output: result.stdout ? filterSensitiveData(result.stdout) : "",
48
+ error: result.stderr || `Command failed with exit code ${result.exitCode}`,
49
+ };
50
+ }
51
+
52
+ return {
53
+ success: true,
54
+ output: filterSensitiveData(result.stdout),
55
+ error: result.stderr ? filterSensitiveData(result.stderr) : undefined,
56
+ };
57
+ } catch (error) {
58
+ return {
59
+ success: false,
60
+ output: "",
61
+ error: error instanceof Error ? error.message : String(error),
62
+ };
63
+ }
64
+ },
65
+ });
@@ -149,7 +149,11 @@ async function runInvestigation(id: string): Promise<void> {
149
149
  if (toolCalls && toolCalls.length > 0) {
150
150
  const toolCall = toolCalls[0];
151
151
  const toolName = "toolName" in toolCall ? toolCall.toolName : "tool";
152
+ const args = "args" in toolCall ? toolCall.args : {};
152
153
  console.log(`[Investigation ${id}] Tool: ${toolName}`);
154
+ if (args && typeof args === "object" && "command" in args) {
155
+ console.log(`[Investigation ${id}] $ ${args.command}`);
156
+ }
153
157
  }
154
158
  },
155
159
  });
package/src/tui/app.tsx CHANGED
@@ -1,6 +1,8 @@
1
+ /* @jsxImportSource @opentui/solid */
1
2
  import { render } from "@opentui/solid";
2
3
  import { createSignal, For, Show, onMount } from "solid-js";
3
4
  import { createTextAttributes } from "@opentui/core";
5
+ import "opentui-spinner/solid";
4
6
  import { getDebuggerAgent, buildIncidentPrompt } from "../mastra/index.js";
5
7
  import type { IncidentInput } from "../mastra/agents/debugger.js";
6
8
 
@@ -10,6 +12,25 @@ interface Message {
10
12
  content: string;
11
13
  timestamp: Date;
12
14
  toolName?: string;
15
+ command?: string;
16
+ }
17
+
18
+ // Conversation history for multi-turn debugging
19
+ interface ConversationMessage {
20
+ role: "user" | "assistant";
21
+ content: string;
22
+ }
23
+
24
+ function formatHistoryAsPrompt(history: ConversationMessage[], newMessage: string): string {
25
+ if (history.length === 0) {
26
+ return newMessage;
27
+ }
28
+
29
+ const historyText = history
30
+ .map((msg) => `${msg.role === "user" ? "User" : "Assistant"}: ${msg.content}`)
31
+ .join("\n\n");
32
+
33
+ return `Previous conversation:\n${historyText}\n\nUser: ${newMessage}`;
13
34
  }
14
35
 
15
36
  type AppStatus = "idle" | "investigating" | "complete" | "error";
@@ -17,8 +38,55 @@ type AppStatus = "idle" | "investigating" | "complete" | "error";
17
38
  const ATTR_DIM = createTextAttributes({ dim: true });
18
39
  const ATTR_BOLD = createTextAttributes({ bold: true });
19
40
 
41
+ function buildDisplayCommand(toolName: string, args: unknown): string | undefined {
42
+ if (!args || typeof args !== "object") return undefined;
43
+
44
+ const a = args as Record<string, unknown>;
45
+
46
+ switch (toolName) {
47
+ case "cli":
48
+ // CLI tool has direct command
49
+ return "command" in a ? String(a.command) : undefined;
50
+
51
+ case "git": {
52
+ // Build git command: git <command> [args...] [path]
53
+ if (!("command" in a)) return undefined;
54
+ const parts = ["git", String(a.command)];
55
+ if ("args" in a && Array.isArray(a.args)) {
56
+ parts.push(...a.args.map(String));
57
+ }
58
+ if ("path" in a && a.path) {
59
+ parts.push(String(a.path));
60
+ }
61
+ return parts.join(" ");
62
+ }
63
+
64
+ case "filesystem": {
65
+ // Build filesystem display: <operation> <path> [pattern]
66
+ if (!("operation" in a)) return undefined;
67
+ const op = String(a.operation);
68
+ const path = "path" in a ? String(a.path) : "";
69
+ if (op === "search" && "pattern" in a) {
70
+ return `grep "${a.pattern}" ${path}`;
71
+ }
72
+ if (op === "read") {
73
+ return `cat ${path}`;
74
+ }
75
+ if (op === "list") {
76
+ return `ls ${path}`;
77
+ }
78
+ return `${op} ${path}`;
79
+ }
80
+
81
+ default:
82
+ // Fallback: try to use command if it exists
83
+ return "command" in a ? String(a.command) : undefined;
84
+ }
85
+ }
86
+
20
87
  function App() {
21
88
  const [messages, setMessages] = createSignal<Message[]>([]);
89
+ const [conversationHistory, setConversationHistory] = createSignal<ConversationMessage[]>([]);
22
90
  const [status, setStatus] = createSignal<AppStatus>("idle");
23
91
  const [currentTool, setCurrentTool] = createSignal<string | null>(null);
24
92
  const [inputValue, setInputValue] = createSignal("");
@@ -40,29 +108,50 @@ function App() {
40
108
  setError(null);
41
109
  setCurrentTool(null);
42
110
 
111
+ // Add user message to UI
43
112
  addMessage({
44
113
  role: "user",
45
114
  content: incident.description,
46
115
  });
47
116
 
117
+ // Build prompt: use full incident prompt for first message, include history for follow-ups
118
+ const isFirstMessage = conversationHistory().length === 0;
119
+ const userContent = isFirstMessage
120
+ ? buildIncidentPrompt(incident)
121
+ : incident.description;
122
+
123
+ // Format prompt with conversation history
124
+ const prompt = formatHistoryAsPrompt(conversationHistory(), userContent);
125
+
126
+ // Add user message to conversation history
127
+ setConversationHistory((prev) => [
128
+ ...prev,
129
+ { role: "user", content: userContent },
130
+ ]);
131
+
48
132
  try {
49
133
  const agent = getDebuggerAgent();
50
- const prompt = buildIncidentPrompt(incident);
51
134
 
52
135
  let assistantContent = "";
53
136
 
137
+ // Send the formatted prompt to the agent
54
138
  const stream = await agent.stream(prompt, {
55
139
  maxSteps: 20,
56
140
  onStepFinish: ({ toolCalls }) => {
57
141
  if (toolCalls && toolCalls.length > 0) {
58
- const toolCall = toolCalls[0];
59
- const toolName =
60
- "toolName" in toolCall ? String(toolCall.toolName) : "tool";
142
+ const toolCall = toolCalls[0] as { toolName?: string; args?: unknown };
143
+ const toolName = toolCall.toolName ?? "tool";
144
+ const args = toolCall.args ?? {};
145
+
146
+ // Build display command based on tool type
147
+ const command = buildDisplayCommand(toolName, args);
148
+
61
149
  setCurrentTool(toolName);
62
150
  addMessage({
63
151
  role: "tool",
64
- content: `Executing ${toolName}...`,
152
+ content: command ? `$ ${command}` : `Executing ${toolName}...`,
65
153
  toolName,
154
+ command,
66
155
  });
67
156
  }
68
157
  },
@@ -72,11 +161,18 @@ function App() {
72
161
  assistantContent += chunk;
73
162
  }
74
163
 
164
+ // Add assistant response to UI
75
165
  addMessage({
76
166
  role: "assistant",
77
167
  content: assistantContent,
78
168
  });
79
169
 
170
+ // Add assistant response to conversation history
171
+ setConversationHistory((prev) => [
172
+ ...prev,
173
+ { role: "assistant", content: assistantContent },
174
+ ]);
175
+
80
176
  setStatus("complete");
81
177
  setCurrentTool(null);
82
178
  } catch (err) {
@@ -185,7 +281,13 @@ function App() {
185
281
  </box>
186
282
  </Show>
187
283
  <Show when={msg.role === "tool"}>
188
- <box flexDirection="row" gap={1}>
284
+ <box flexDirection="row" gap={1} alignItems="center">
285
+ <Show
286
+ when={status() === "investigating" && msg.id === messages().filter(m => m.role === "tool").at(-1)?.id}
287
+ fallback={<text fg="green">✓</text>}
288
+ >
289
+ <spinner name="dots" color="blue" />
290
+ </Show>
189
291
  <text fg="blue" attributes={ATTR_DIM}>
190
292
  [{msg.toolName}]
191
293
  </text>
@@ -1,107 +0,0 @@
1
- import { createTool } from "@mastra/core/tools";
2
- import { z } from "zod";
3
- import { execCommand } from "../../sandbox/bashlet.js";
4
-
5
- const ALLOWED_COMMANDS = ["get", "describe", "logs", "top", "events"] as const;
6
-
7
- const KubectlInputSchema = z.object({
8
- command: z.enum(ALLOWED_COMMANDS).describe("The kubectl command to run"),
9
- resource: z
10
- .string()
11
- .optional()
12
- .describe(
13
- "Resource type (e.g., pods, deployments, services, configmaps, secrets)"
14
- ),
15
- name: z.string().optional().describe("Specific resource name"),
16
- namespace: z
17
- .string()
18
- .optional()
19
- .describe("Kubernetes namespace (defaults to current context namespace)"),
20
- flags: z
21
- .array(z.string())
22
- .optional()
23
- .describe(
24
- "Additional flags (e.g., ['-o', 'yaml'], ['--tail', '100'], ['-l', 'app=myapp'])"
25
- ),
26
- });
27
-
28
- // Output type (no schema validation to allow error returns)
29
- interface KubectlOutput {
30
- success: boolean;
31
- output: string;
32
- error?: string;
33
- }
34
-
35
- function filterSensitiveData(output: string): string {
36
- // Redact potential secrets, tokens, and passwords
37
- return output
38
- .replace(
39
- /(password|secret|token|key|credential)[\s:=]+["']?[^\s"'\n]+["']?/gi,
40
- "$1: [REDACTED]"
41
- )
42
- .replace(/Bearer\s+[^\s]+/gi, "Bearer [REDACTED]")
43
- .replace(/-----BEGIN[^-]+-----[\s\S]*?-----END[^-]+-----/g, "[REDACTED CERTIFICATE/KEY]");
44
- }
45
-
46
- export const kubectlTool = createTool({
47
- id: "kubectl",
48
- description: `Execute kubectl commands to inspect Kubernetes resources.
49
- Available commands: ${ALLOWED_COMMANDS.join(", ")}.
50
- Use this to get information about pods, deployments, services, logs, and cluster events.
51
- Examples:
52
- - Get all pods: { command: "get", resource: "pods", flags: ["-A"] }
53
- - Get pod logs: { command: "logs", name: "my-pod", namespace: "default", flags: ["--tail", "100"] }
54
- - Describe deployment: { command: "describe", resource: "deployment", name: "my-app" }
55
- - Get events: { command: "events", namespace: "production", flags: ["--sort-by", ".lastTimestamp"] }`,
56
-
57
- inputSchema: KubectlInputSchema,
58
-
59
- execute: async (inputData): Promise<KubectlOutput> => {
60
- const { command, resource, name, namespace, flags } = inputData;
61
-
62
- // Build kubectl command
63
- const parts = ["kubectl", command];
64
-
65
- if (resource) {
66
- parts.push(resource);
67
- }
68
-
69
- if (name) {
70
- parts.push(name);
71
- }
72
-
73
- if (namespace) {
74
- parts.push("-n", namespace);
75
- }
76
-
77
- if (flags && flags.length > 0) {
78
- parts.push(...flags);
79
- }
80
-
81
- const fullCommand = parts.join(" ");
82
-
83
- try {
84
- const result = await execCommand(fullCommand);
85
-
86
- if (result.exitCode !== 0) {
87
- return {
88
- success: false,
89
- output: "",
90
- error: result.stderr || `Command failed with exit code ${result.exitCode}`,
91
- };
92
- }
93
-
94
- return {
95
- success: true,
96
- output: filterSensitiveData(result.stdout),
97
- error: result.stderr ? filterSensitiveData(result.stderr) : undefined,
98
- };
99
- } catch (error) {
100
- return {
101
- success: false,
102
- output: "",
103
- error: error instanceof Error ? error.message : String(error),
104
- };
105
- }
106
- },
107
- });