@townco/cli 0.1.13 → 0.1.14

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,9 +1,8 @@
1
1
  interface CreateCommandProps {
2
- name?: string;
3
- model?: string;
4
- tools?: readonly string[];
5
- systemPrompt?: string;
6
- overwrite?: boolean;
2
+ name?: string;
3
+ model?: string;
4
+ tools?: readonly string[];
5
+ systemPrompt?: string;
6
+ overwrite?: boolean;
7
7
  }
8
8
  export declare function createCommand(props: CreateCommandProps): Promise<void>;
9
- export {};
@@ -131,20 +131,10 @@ function CreateApp({ name: initialName, model: initialModel, tools: initialTools
131
131
  if (result.success) {
132
132
  setScaffoldStatus("done");
133
133
  setAgentPath(result.path);
134
- // Output in the same format as 'town list'
135
- const modelLabel = model.replace("claude-", "");
136
- console.log(`\n\x1b[1mAgent created successfully!\x1b[0m\n`);
137
- console.log(` \x1b[32m●\x1b[0m \x1b[1m${name}\x1b[0m`);
138
- console.log(` \x1b[2mModel: ${modelLabel}\x1b[0m`);
139
- if (agentDef.tools && agentDef.tools.length > 0) {
140
- console.log(` \x1b[2mTools: ${agentDef.tools.join(", ")}\x1b[0m`);
141
- }
142
- console.log(` \x1b[2mPath: ${result.path}\x1b[0m`);
143
- console.log();
144
- console.log(`\x1b[2mRun an agent with: town run ${agentDef.name}\x1b[0m`);
145
- console.log(`\x1b[2mTUI mode (default), --gui for web interface, --http for API server\x1b[0m`);
146
- // Exit immediately
147
- process.exit(0);
134
+ // Exit after showing the done message
135
+ setTimeout(() => {
136
+ process.exit(0);
137
+ }, 100);
148
138
  }
149
139
  else {
150
140
  setScaffoldStatus("error");
@@ -297,13 +287,14 @@ function CreateApp({ name: initialName, model: initialModel, tools: initialTools
297
287
  // Done stage
298
288
  if (stage === "done") {
299
289
  if (scaffoldStatus === "scaffolding") {
300
- return (_jsx(Box, { flexDirection: "column", children: _jsx(Text, { children: "\u23F3 Creating agent package..." }) }));
290
+ return (_jsx(Box, { flexDirection: "column", children: _jsxs(Text, { children: ["\u23F3 Creating agent ", agentDef.name, "..."] }) }));
301
291
  }
302
292
  if (scaffoldStatus === "error") {
303
293
  return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { color: "red", children: "\u2717 Error creating agent package" }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { children: scaffoldError }) })] }));
304
294
  }
305
295
  if (scaffoldStatus === "done") {
306
- return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { color: "green", children: "\u2713 Agent package created successfully!" }), _jsx(Box, { marginTop: 1, children: _jsxs(Text, { dimColor: true, children: ["Path: ", agentPath] }) }), _jsx(Box, { marginTop: 1, children: _jsxs(Text, { dimColor: true, children: ["You can run the agent with:", " ", _jsxs(Text, { bold: true, color: "cyan", children: ["town run ", agentDef.name] })] }) })] }));
296
+ const modelLabel = agentDef.model?.replace("claude-", "") || "";
297
+ return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { bold: true, children: "Agent created successfully!" }), _jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsxs(Text, { children: [_jsx(Text, { color: "green", children: "\u25CF" }), " ", _jsx(Text, { bold: true, children: agentDef.name })] }), _jsxs(Text, { dimColor: true, children: [" Model: ", modelLabel] }), agentDef.tools && agentDef.tools.length > 0 && (_jsxs(Text, { dimColor: true, children: [" Tools: ", agentDef.tools.join(", ")] })), _jsxs(Text, { dimColor: true, children: [" Path: ", agentPath] })] }), _jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsxs(Text, { dimColor: true, children: ["Run an agent with: town run ", agentDef.name] }), _jsx(Text, { dimColor: true, children: "TUI mode (default), --gui for web interface, --http for API server" })] })] }));
307
298
  }
308
299
  }
309
300
  return null;
@@ -1,9 +1,14 @@
1
1
  interface MCPAddProps {
2
- name?: string;
3
- url?: string;
4
- command?: string;
5
- args?: readonly string[];
2
+ name?: string;
3
+ url?: string;
4
+ command?: string;
5
+ args?: readonly string[];
6
6
  }
7
- declare function MCPAddApp({ name: initialName, url: initialUrl, command: initialCommand, args: initialArgs, }: MCPAddProps): import("react/jsx-runtime").JSX.Element | null;
7
+ declare function MCPAddApp({
8
+ name: initialName,
9
+ url: initialUrl,
10
+ command: initialCommand,
11
+ args: initialArgs,
12
+ }: MCPAddProps): import("react/jsx-runtime").JSX.Element | null;
8
13
  export default MCPAddApp;
9
14
  export declare function runMCPAdd(props?: MCPAddProps): Promise<void>;
@@ -1,61 +1,188 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
1
  import { Box, render, Text, useApp, useInput } from "ink";
3
2
  import { useEffect, useState } from "react";
3
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
4
4
  import { listMCPConfigs } from "../lib/mcp-storage";
5
+
5
6
  // ============================================================================
6
7
  // Main Component
7
8
  // ============================================================================
8
9
  function MCPListApp() {
9
- const [result, setResult] = useState(null);
10
- const [loading, setLoading] = useState(true);
11
- const { exit } = useApp();
12
- useEffect(() => {
13
- function loadConfigs() {
14
- try {
15
- const configs = listMCPConfigs();
16
- setResult({ configs });
17
- }
18
- catch (error) {
19
- const errorMsg = error instanceof Error ? error.message : String(error);
20
- setResult({ configs: [], error: errorMsg });
21
- }
22
- finally {
23
- setLoading(false);
24
- }
25
- }
26
- loadConfigs();
27
- }, []);
28
- // Exit on any key press when not loading
29
- useInput((_input, key) => {
30
- if (!loading) {
31
- if (key.return || key.escape || _input === "q") {
32
- exit();
33
- }
34
- }
35
- });
36
- if (loading) {
37
- return (_jsx(Box, { children: _jsx(Text, { children: "Loading MCP servers..." }) }));
38
- }
39
- if (result?.error) {
40
- return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Box, { marginBottom: 1, children: _jsx(Text, { bold: true, color: "red", children: "\u274C Error loading MCP servers" }) }), _jsx(Box, { marginBottom: 1, children: _jsx(Text, { children: result.error }) }), _jsx(Box, { children: _jsx(Text, { dimColor: true, children: "Press Enter or Q to exit" }) })] }));
41
- }
42
- if (!result || result.configs.length === 0) {
43
- return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Box, { marginBottom: 1, children: _jsx(Text, { bold: true, children: "No MCP servers configured" }) }), _jsx(Box, { marginBottom: 1, children: _jsx(Text, { dimColor: true, children: "Add one with: town mcp add" }) }), _jsx(Box, { children: _jsx(Text, { dimColor: true, children: "Press Enter or Q to exit" }) })] }));
44
- }
45
- return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Box, { marginBottom: 1, children: _jsxs(Text, { bold: true, children: ["Configured MCP Servers (", result.configs.length, ")"] }) }), result.configs.map((config, index) => (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsx(Box, { children: _jsxs(Text, { bold: true, color: "cyan", children: [index + 1, ". ", config.name] }) }), _jsx(Box, { paddingLeft: 3, children: config.transport === "http" ? (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { children: ["Transport: ", _jsx(Text, { color: "green", children: "HTTP" })] }), _jsxs(Text, { children: ["URL: ", config.url] })] })) : (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { children: ["Transport: ", _jsx(Text, { color: "blue", children: "stdio" })] }), _jsxs(Text, { children: ["Command: ", config.command] }), config.args && config.args.length > 0 && (_jsxs(Text, { children: ["Args: ", config.args.join(" ")] }))] })) })] }, config.name))), _jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "Use `town mcp remove` to remove a server or `town mcp add` to add one" }) }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "Press Enter or Q to exit" }) })] }));
10
+ const [result, setResult] = useState(null);
11
+ const [loading, setLoading] = useState(true);
12
+ const { exit } = useApp();
13
+ useEffect(() => {
14
+ function loadConfigs() {
15
+ try {
16
+ const configs = listMCPConfigs();
17
+ setResult({ configs });
18
+ } catch (error) {
19
+ const errorMsg = error instanceof Error ? error.message : String(error);
20
+ setResult({ configs: [], error: errorMsg });
21
+ } finally {
22
+ setLoading(false);
23
+ }
24
+ }
25
+ loadConfigs();
26
+ }, []);
27
+ // Exit on any key press when not loading
28
+ useInput((_input, key) => {
29
+ if (!loading) {
30
+ if (key.return || key.escape || _input === "q") {
31
+ exit();
32
+ }
33
+ }
34
+ });
35
+ if (loading) {
36
+ return _jsx(Box, {
37
+ children: _jsx(Text, { children: "Loading MCP servers..." }),
38
+ });
39
+ }
40
+ if (result?.error) {
41
+ return _jsxs(Box, {
42
+ flexDirection: "column",
43
+ children: [
44
+ _jsx(Box, {
45
+ marginBottom: 1,
46
+ children: _jsx(Text, {
47
+ bold: true,
48
+ color: "red",
49
+ children: "\u274C Error loading MCP servers",
50
+ }),
51
+ }),
52
+ _jsx(Box, {
53
+ marginBottom: 1,
54
+ children: _jsx(Text, { children: result.error }),
55
+ }),
56
+ _jsx(Box, {
57
+ children: _jsx(Text, {
58
+ dimColor: true,
59
+ children: "Press Enter or Q to exit",
60
+ }),
61
+ }),
62
+ ],
63
+ });
64
+ }
65
+ if (!result || result.configs.length === 0) {
66
+ return _jsxs(Box, {
67
+ flexDirection: "column",
68
+ children: [
69
+ _jsx(Box, {
70
+ marginBottom: 1,
71
+ children: _jsx(Text, {
72
+ bold: true,
73
+ children: "No MCP servers configured",
74
+ }),
75
+ }),
76
+ _jsx(Box, {
77
+ marginBottom: 1,
78
+ children: _jsx(Text, {
79
+ dimColor: true,
80
+ children: "Add one with: town mcp add",
81
+ }),
82
+ }),
83
+ _jsx(Box, {
84
+ children: _jsx(Text, {
85
+ dimColor: true,
86
+ children: "Press Enter or Q to exit",
87
+ }),
88
+ }),
89
+ ],
90
+ });
91
+ }
92
+ return _jsxs(Box, {
93
+ flexDirection: "column",
94
+ children: [
95
+ _jsx(Box, {
96
+ marginBottom: 1,
97
+ children: _jsxs(Text, {
98
+ bold: true,
99
+ children: ["Configured MCP Servers (", result.configs.length, ")"],
100
+ }),
101
+ }),
102
+ result.configs.map((config, index) =>
103
+ _jsxs(
104
+ Box,
105
+ {
106
+ flexDirection: "column",
107
+ marginBottom: 1,
108
+ children: [
109
+ _jsx(Box, {
110
+ children: _jsxs(Text, {
111
+ bold: true,
112
+ color: "cyan",
113
+ children: [index + 1, ". ", config.name],
114
+ }),
115
+ }),
116
+ _jsx(Box, {
117
+ paddingLeft: 3,
118
+ children:
119
+ config.transport === "http"
120
+ ? _jsxs(Box, {
121
+ flexDirection: "column",
122
+ children: [
123
+ _jsxs(Text, {
124
+ children: [
125
+ "Transport: ",
126
+ _jsx(Text, { color: "green", children: "HTTP" }),
127
+ ],
128
+ }),
129
+ _jsxs(Text, { children: ["URL: ", config.url] }),
130
+ ],
131
+ })
132
+ : _jsxs(Box, {
133
+ flexDirection: "column",
134
+ children: [
135
+ _jsxs(Text, {
136
+ children: [
137
+ "Transport: ",
138
+ _jsx(Text, { color: "blue", children: "stdio" }),
139
+ ],
140
+ }),
141
+ _jsxs(Text, {
142
+ children: ["Command: ", config.command],
143
+ }),
144
+ config.args &&
145
+ config.args.length > 0 &&
146
+ _jsxs(Text, {
147
+ children: ["Args: ", config.args.join(" ")],
148
+ }),
149
+ ],
150
+ }),
151
+ }),
152
+ ],
153
+ },
154
+ config.name,
155
+ ),
156
+ ),
157
+ _jsx(Box, {
158
+ marginTop: 1,
159
+ children: _jsx(Text, {
160
+ dimColor: true,
161
+ children:
162
+ "Use `town mcp remove` to remove a server or `town mcp add` to add one",
163
+ }),
164
+ }),
165
+ _jsx(Box, {
166
+ marginTop: 1,
167
+ children: _jsx(Text, {
168
+ dimColor: true,
169
+ children: "Press Enter or Q to exit",
170
+ }),
171
+ }),
172
+ ],
173
+ });
46
174
  }
47
175
  // ============================================================================
48
176
  // Export and Runner
49
177
  // ============================================================================
50
178
  export default MCPListApp;
51
179
  export async function runMCPList() {
52
- const { waitUntilExit, clear } = render(_jsx(MCPListApp, {}));
53
- try {
54
- await waitUntilExit();
55
- }
56
- finally {
57
- clear();
58
- // Ensure cursor is visible
59
- process.stdout.write("\x1B[?25h");
60
- }
180
+ const { waitUntilExit, clear } = render(_jsx(MCPListApp, {}));
181
+ try {
182
+ await waitUntilExit();
183
+ } finally {
184
+ clear();
185
+ // Ensure cursor is visible
186
+ process.stdout.write("\x1B[?25h");
187
+ }
61
188
  }
@@ -1,10 +1,42 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
1
2
  import { spawn } from "node:child_process";
2
3
  import { existsSync } from "node:fs";
3
4
  import { readFile } from "node:fs/promises";
4
5
  import { homedir } from "node:os";
5
6
  import { join } from "node:path";
6
7
  import { agentExists, getAgentPath } from "@townco/agent/storage";
8
+ import { render } from "ink";
7
9
  import open from "open";
10
+ import { useCallback, useMemo, useRef, useState } from "react";
11
+ import { TabbedOutput } from "../components/TabbedOutput.js";
12
+ import { findAvailablePort } from "../lib/port-utils.js";
13
+ function GuiRunner({ agentProcess, guiProcess, agentPort, onExit, }) {
14
+ const [guiPort, setGuiPort] = useState(5173);
15
+ const browserOpenedRef = useRef(false);
16
+ const handlePortDetected = useCallback((processIndex, port) => {
17
+ // Process index 1 is the GUI process
18
+ if (processIndex === 1) {
19
+ setGuiPort(port);
20
+ // Open browser once we know the actual port
21
+ if (!browserOpenedRef.current) {
22
+ browserOpenedRef.current = true;
23
+ const guiUrl = `http://localhost:${port}`;
24
+ open(guiUrl).catch((error) => {
25
+ // Silently fail - user can open manually
26
+ console.warn(`Could not automatically open browser: ${error.message}`);
27
+ });
28
+ }
29
+ }
30
+ }, []);
31
+ // Memoize processes array based only on actual process objects and initial ports
32
+ // Don't include guiPort as dependency to prevent re-creating array when port is detected
33
+ // TabbedOutput will update the displayed port internally via onPortDetected callback
34
+ const processes = useMemo(() => [
35
+ { name: "Agent", process: agentProcess, port: agentPort },
36
+ { name: "GUI", process: guiProcess, port: guiPort },
37
+ ], [agentProcess, guiProcess, agentPort, guiPort]);
38
+ return (_jsx(TabbedOutput, { processes: processes, onExit: onExit, onPortDetected: handlePortDetected }));
39
+ }
8
40
  async function loadEnvVars() {
9
41
  const envPath = join(homedir(), ".config", "town", ".env");
10
42
  const envVars = {};
@@ -42,7 +74,7 @@ export async function runCommand(options) {
42
74
  }
43
75
  const agentPath = getAgentPath(name);
44
76
  const binPath = join(agentPath, "bin.ts");
45
- // If GUI or HTTP-only mode, run differently
77
+ // If GUI mode, run with tabbed interface
46
78
  if (gui) {
47
79
  const guiPath = join(agentPath, "gui");
48
80
  // Check if GUI exists
@@ -56,72 +88,58 @@ export async function runCommand(options) {
56
88
  console.log(`Recreate the agent with "town create" to include the GUI.`);
57
89
  process.exit(1);
58
90
  }
91
+ // Find an available port for the agent
92
+ const availablePort = await findAvailablePort(port);
93
+ if (availablePort !== port) {
94
+ console.log(`Port ${port} is in use, using port ${availablePort} instead`);
95
+ }
59
96
  console.log(`Starting agent "${name}" with GUI...`);
60
- console.log(`Starting agent HTTP server on port ${port}...`);
61
- console.log(`Starting GUI development server...\n`);
62
- // Start the agent in HTTP mode first
97
+ console.log(`Agent HTTP server will run on port ${availablePort}`);
98
+ console.log(`GUI dev server will run on port 5173\n`);
99
+ // Set stdin to raw mode for Ink
100
+ if (process.stdin.isTTY) {
101
+ process.stdin.setRawMode(true);
102
+ }
103
+ // Start the agent in HTTP mode
63
104
  const agentProcess = spawn("bun", [binPath, "http"], {
64
105
  cwd: agentPath,
65
- stdio: "pipe",
106
+ stdio: ["ignore", "pipe", "pipe"], // Pipe stdout/stderr for capture
66
107
  env: {
67
108
  ...process.env,
68
109
  ...configEnvVars,
69
110
  NODE_ENV: process.env.NODE_ENV || "production",
70
- PORT: port.toString(),
111
+ PORT: availablePort.toString(),
71
112
  },
72
113
  });
73
- agentProcess.on("error", (error) => {
74
- console.error(`Failed to start agent: ${error.message}`);
75
- process.exit(1);
114
+ // Start the GUI dev server
115
+ const guiProcess = spawn("bun", ["run", "dev"], {
116
+ cwd: guiPath,
117
+ stdio: ["ignore", "pipe", "pipe"], // Pipe stdout/stderr for capture
118
+ env: {
119
+ ...process.env,
120
+ ...configEnvVars,
121
+ VITE_AGENT_URL: `http://localhost:${availablePort}`,
122
+ },
76
123
  });
77
- // Wait a bit for agent to start, then start the GUI
78
- setTimeout(() => {
79
- // Start the GUI dev server
80
- const guiProcess = spawn("bun", ["run", "dev"], {
81
- cwd: guiPath,
82
- stdio: "inherit",
83
- env: {
84
- ...process.env,
85
- ...configEnvVars,
86
- VITE_AGENT_URL: `http://localhost:${port}`,
87
- },
88
- });
89
- guiProcess.on("error", (error) => {
90
- console.error(`Failed to start GUI: ${error.message}`);
91
- agentProcess.kill();
92
- process.exit(1);
93
- });
94
- guiProcess.on("close", (code) => {
124
+ // Render the tabbed UI with dynamic port detection
125
+ const { waitUntilExit } = render(_jsx(GuiRunner, { agentProcess: agentProcess, guiProcess: guiProcess, agentPort: availablePort, onExit: () => {
95
126
  agentProcess.kill();
96
- if (code !== 0 && code !== null) {
97
- console.error(`GUI exited with code ${code}`);
98
- process.exit(code);
99
- }
100
- });
101
- // Open browser after GUI server has time to start (default Vite port is 5173)
102
- setTimeout(() => {
103
- const guiUrl = "http://localhost:5173";
104
- console.log(`Opening browser at ${guiUrl}...`);
105
- open(guiUrl).catch((error) => {
106
- console.warn(`Could not automatically open browser: ${error.message}`);
107
- console.log(`Please manually open: ${guiUrl}`);
108
- });
109
- }, 2000);
110
- }, 1000);
111
- agentProcess.on("close", (code) => {
112
- if (code !== 0 && code !== null) {
113
- console.error(`Agent exited with code ${code}`);
114
- process.exit(code);
115
- }
116
- });
117
- return;
127
+ guiProcess.kill();
128
+ } }));
129
+ await waitUntilExit();
130
+ process.exit(0);
118
131
  }
119
132
  else if (http) {
120
- console.log(`Starting agent "${name}" in HTTP mode on port ${port}...`);
133
+ // Find an available port for the agent
134
+ const availablePort = await findAvailablePort(port);
135
+ if (availablePort !== port) {
136
+ console.log(`Port ${port} is in use, using port ${availablePort} instead\n`);
137
+ }
138
+ console.log(`Starting agent "${name}" in HTTP mode on port ${availablePort}...`);
121
139
  console.log(`\nEndpoints:`);
122
- console.log(` http://localhost:${port}/health - Health check`);
123
- console.log(` http://localhost:${port}/rpc - RPC endpoint`);
124
- console.log(` http://localhost:${port}/events - SSE event stream\n`);
140
+ console.log(` http://localhost:${availablePort}/health - Health check`);
141
+ console.log(` http://localhost:${availablePort}/rpc - RPC endpoint`);
142
+ console.log(` http://localhost:${availablePort}/events - SSE event stream\n`);
125
143
  // Run the agent in HTTP mode
126
144
  const agentProcess = spawn("bun", [binPath, "http"], {
127
145
  cwd: agentPath,
@@ -130,7 +148,7 @@ export async function runCommand(options) {
130
148
  ...process.env,
131
149
  ...configEnvVars,
132
150
  NODE_ENV: process.env.NODE_ENV || "production",
133
- PORT: port.toString(),
151
+ PORT: availablePort.toString(),
134
152
  },
135
153
  });
136
154
  agentProcess.on("error", (error) => {
@@ -0,0 +1,7 @@
1
+ export interface ProcessPaneProps {
2
+ title: string;
3
+ output: string[];
4
+ port: number | undefined;
5
+ status: "starting" | "running" | "stopped" | "error";
6
+ }
7
+ export declare function ProcessPane({ title, output, port, status }: ProcessPaneProps): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,17 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Box, Text } from "ink";
3
+ import { useMemo } from "react";
4
+ export function ProcessPane({ title, output, port, status }) {
5
+ // Keep only last 50 lines to prevent memory issues
6
+ const displayOutput = useMemo(() => {
7
+ return output.slice(-50);
8
+ }, [output]);
9
+ const statusColor = status === "running"
10
+ ? "green"
11
+ : status === "error"
12
+ ? "red"
13
+ : status === "starting"
14
+ ? "yellow"
15
+ : "gray";
16
+ return (_jsxs(Box, { flexDirection: "column", height: "100%", children: [_jsxs(Box, { borderStyle: "single", paddingX: 1, marginBottom: 1, flexShrink: 0, children: [_jsx(Text, { color: "cyan", bold: true, children: title }), port && _jsxs(Text, { color: "gray", children: [" - http://localhost:", port] }), _jsx(Text, { children: " " }), _jsx(Text, { color: statusColor, children: "\u25CF" }), _jsxs(Text, { children: [" ", status] })] }), _jsx(Box, { flexDirection: "column", flexGrow: 1, minHeight: 0, paddingX: 1, children: displayOutput.length === 0 ? (_jsx(Text, { color: "gray", children: "Waiting for output..." })) : (displayOutput.map((line, idx) => (_jsx(Text, { children: line }, `${idx}-${line.slice(0, 20)}`)))) }), _jsx(Box, { borderStyle: "single", borderColor: "gray", paddingX: 1, flexShrink: 0, children: _jsxs(Text, { color: "gray", children: ["Lines: ", output.length, " | Displaying last ", displayOutput.length] }) })] }));
17
+ }
@@ -0,0 +1,5 @@
1
+ export interface StatusLineProps {
2
+ activeTab: number;
3
+ tabs: string[];
4
+ }
5
+ export declare function StatusLine({ activeTab, tabs }: StatusLineProps): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,5 @@
1
+ import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
2
+ import { Box, Text } from "ink";
3
+ export function StatusLine({ activeTab, tabs }) {
4
+ return (_jsxs(Box, { borderStyle: "single", borderColor: "blue", paddingX: 1, children: [tabs.map((tab, idx) => (_jsxs(Text, { children: [_jsxs(Text, { color: activeTab === idx ? "green" : "gray", children: [idx + 1, ". ", tab] }), idx < tabs.length - 1 && _jsx(Text, { color: "gray", children: " | " })] }, tab))), _jsx(Text, { color: "gray", children: " | " }), _jsx(Text, { color: "yellow", children: "tab" }), _jsx(Text, { color: "gray", children: ", " }), _jsx(Text, { color: "yellow", children: "\u2190\u2192" }), _jsx(Text, { color: "gray", children: " or " }), _jsxs(Text, { color: "yellow", children: ["1-", tabs.length] }), _jsx(Text, { color: "gray", children: " to switch" })] }));
5
+ }
@@ -0,0 +1,12 @@
1
+ import type { ChildProcess } from "node:child_process";
2
+ export interface ProcessInfo {
3
+ name: string;
4
+ process: ChildProcess;
5
+ port?: number;
6
+ }
7
+ export interface TabbedOutputProps {
8
+ processes: ProcessInfo[];
9
+ onExit: () => void;
10
+ onPortDetected?: (processIndex: number, port: number) => void;
11
+ }
12
+ export declare function TabbedOutput({ processes, onExit, onPortDetected, }: TabbedOutputProps): import("react/jsx-runtime").JSX.Element | null;
@@ -0,0 +1,136 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Box, useApp, useInput } from "ink";
3
+ import { useEffect, useRef, useState } from "react";
4
+ import { ProcessPane } from "./ProcessPane.js";
5
+ import { StatusLine } from "./StatusLine.js";
6
+ export function TabbedOutput({ processes, onExit, onPortDetected, }) {
7
+ const { exit } = useApp();
8
+ const [activeTab, setActiveTab] = useState(0);
9
+ const [outputs, setOutputs] = useState(processes.map(() => []));
10
+ const [statuses, setStatuses] = useState(processes.map(() => "starting"));
11
+ const [ports, setPorts] = useState(processes.map((p) => p.port));
12
+ const portDetectedRef = useRef(new Set());
13
+ // Handle keyboard input
14
+ useInput((input, key) => {
15
+ if (key.ctrl && input === "c") {
16
+ // Cleanup and exit
17
+ onExit();
18
+ exit();
19
+ return;
20
+ }
21
+ // Tab key to toggle between tabs
22
+ if (key.tab) {
23
+ setActiveTab((activeTab + 1) % processes.length);
24
+ return;
25
+ }
26
+ if (key.leftArrow && activeTab > 0) {
27
+ setActiveTab(activeTab - 1);
28
+ }
29
+ else if (key.rightArrow && activeTab < processes.length - 1) {
30
+ setActiveTab(activeTab + 1);
31
+ }
32
+ // Number keys to jump to tabs
33
+ const num = Number.parseInt(input, 10);
34
+ if (!Number.isNaN(num) && num >= 1 && num <= processes.length) {
35
+ setActiveTab(num - 1);
36
+ }
37
+ });
38
+ // Set up process output listeners
39
+ useEffect(() => {
40
+ processes.forEach((processInfo, idx) => {
41
+ const { process } = processInfo;
42
+ // Mark as running when we see first output
43
+ const markAsRunning = () => {
44
+ setStatuses((prev) => {
45
+ const newStatuses = [...prev];
46
+ if (newStatuses[idx] === "starting") {
47
+ newStatuses[idx] = "running";
48
+ }
49
+ return newStatuses;
50
+ });
51
+ };
52
+ // Capture stdout
53
+ process.stdout?.on("data", (data) => {
54
+ const output = data.toString();
55
+ const lines = output.split("\n").filter(Boolean);
56
+ setOutputs((prev) => {
57
+ const newOutputs = [...prev];
58
+ newOutputs[idx] = [...(newOutputs[idx] || []), ...lines];
59
+ return newOutputs;
60
+ });
61
+ markAsRunning();
62
+ // Check for Vite port in output and notify if callback provided
63
+ if (onPortDetected && !portDetectedRef.current.has(idx)) {
64
+ const portMatch = output.match(/Local:\s+http:\/\/localhost:(\d+)/);
65
+ if (portMatch?.[1]) {
66
+ const detectedPort = Number.parseInt(portMatch[1], 10);
67
+ portDetectedRef.current.add(idx);
68
+ // Update our internal ports state
69
+ setPorts((prev) => {
70
+ const newPorts = [...prev];
71
+ newPorts[idx] = detectedPort;
72
+ return newPorts;
73
+ });
74
+ onPortDetected(idx, detectedPort);
75
+ }
76
+ }
77
+ });
78
+ // Capture stderr
79
+ process.stderr?.on("data", (data) => {
80
+ const text = data.toString();
81
+ const lines = text.split("\n").filter(Boolean);
82
+ const errorLines = lines.map((line) => `[ERROR] ${line}`);
83
+ setOutputs((prev) => {
84
+ const newOutputs = [...prev];
85
+ newOutputs[idx] = [...(newOutputs[idx] || []), ...errorLines];
86
+ return newOutputs;
87
+ });
88
+ markAsRunning();
89
+ });
90
+ // Handle process exit
91
+ process.on("close", (code) => {
92
+ setStatuses((prev) => {
93
+ const newStatuses = [...prev];
94
+ newStatuses[idx] = code === 0 ? "stopped" : "error";
95
+ return newStatuses;
96
+ });
97
+ if (code !== 0 && code !== null) {
98
+ setOutputs((prev) => {
99
+ const newOutputs = [...prev];
100
+ newOutputs[idx] = [
101
+ ...(newOutputs[idx] || []),
102
+ `\n[Process exited with code ${code}]`,
103
+ ];
104
+ return newOutputs;
105
+ });
106
+ }
107
+ });
108
+ process.on("error", (error) => {
109
+ setStatuses((prev) => {
110
+ const newStatuses = [...prev];
111
+ newStatuses[idx] = "error";
112
+ return newStatuses;
113
+ });
114
+ setOutputs((prev) => {
115
+ const newOutputs = [...prev];
116
+ newOutputs[idx] = [
117
+ ...(newOutputs[idx] || []),
118
+ `\n[Process error: ${error.message}]`,
119
+ ];
120
+ return newOutputs;
121
+ });
122
+ });
123
+ });
124
+ // Cleanup function
125
+ return () => {
126
+ processes.forEach(({ process }) => {
127
+ process.kill();
128
+ });
129
+ };
130
+ }, [processes, onPortDetected]);
131
+ const currentProcess = processes[activeTab];
132
+ if (!currentProcess) {
133
+ return null;
134
+ }
135
+ return (_jsxs(Box, { flexDirection: "column", height: "100%", children: [_jsx(StatusLine, { activeTab: activeTab, tabs: processes.map((p) => p.name) }), _jsx(ProcessPane, { title: currentProcess.name, output: outputs[activeTab] || [], port: ports[activeTab], status: statuses[activeTab] || "starting" })] }));
136
+ }
package/dist/index.js CHANGED
File without changes
@@ -1,9 +1,9 @@
1
1
  export type MCPConfig = {
2
- name: string;
3
- transport: "stdio" | "http";
4
- command?: string;
5
- args?: string[];
6
- url?: string;
2
+ name: string;
3
+ transport: "stdio" | "http";
4
+ command?: string;
5
+ args?: string[];
6
+ url?: string;
7
7
  };
8
8
  /**
9
9
  * Save an MCP config to the store
@@ -1,6 +1,7 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
+
4
5
  // ============================================================================
5
6
  // Constants
6
7
  // ============================================================================
@@ -13,38 +14,40 @@ const MCPS_FILE = join(TOWN_CONFIG_DIR, "mcps.json");
13
14
  * Ensure the config directory exists
14
15
  */
15
16
  function ensureConfigDir() {
16
- if (!existsSync(TOWN_CONFIG_DIR)) {
17
- mkdirSync(TOWN_CONFIG_DIR, { recursive: true });
18
- }
17
+ if (!existsSync(TOWN_CONFIG_DIR)) {
18
+ mkdirSync(TOWN_CONFIG_DIR, { recursive: true });
19
+ }
19
20
  }
20
21
  /**
21
22
  * Load all MCP configs from the JSON file
22
23
  */
23
24
  function loadStore() {
24
- ensureConfigDir();
25
- if (!existsSync(MCPS_FILE)) {
26
- return {};
27
- }
28
- try {
29
- const content = readFileSync(MCPS_FILE, "utf-8");
30
- return JSON.parse(content);
31
- }
32
- catch (error) {
33
- throw new Error(`Failed to load MCP configs: ${error instanceof Error ? error.message : String(error)}`);
34
- }
25
+ ensureConfigDir();
26
+ if (!existsSync(MCPS_FILE)) {
27
+ return {};
28
+ }
29
+ try {
30
+ const content = readFileSync(MCPS_FILE, "utf-8");
31
+ return JSON.parse(content);
32
+ } catch (error) {
33
+ throw new Error(
34
+ `Failed to load MCP configs: ${error instanceof Error ? error.message : String(error)}`,
35
+ );
36
+ }
35
37
  }
36
38
  /**
37
39
  * Save all MCP configs to the JSON file
38
40
  */
39
41
  function saveStore(store) {
40
- ensureConfigDir();
41
- try {
42
- const content = JSON.stringify(store, null, 2);
43
- writeFileSync(MCPS_FILE, content, "utf-8");
44
- }
45
- catch (error) {
46
- throw new Error(`Failed to save MCP configs: ${error instanceof Error ? error.message : String(error)}`);
47
- }
42
+ ensureConfigDir();
43
+ try {
44
+ const content = JSON.stringify(store, null, 2);
45
+ writeFileSync(MCPS_FILE, content, "utf-8");
46
+ } catch (error) {
47
+ throw new Error(
48
+ `Failed to save MCP configs: ${error instanceof Error ? error.message : String(error)}`,
49
+ );
50
+ }
48
51
  }
49
52
  // ============================================================================
50
53
  // Public API
@@ -53,55 +56,54 @@ function saveStore(store) {
53
56
  * Save an MCP config to the store
54
57
  */
55
58
  export function saveMCPConfig(config) {
56
- const store = loadStore();
57
- store[config.name] = config;
58
- saveStore(store);
59
+ const store = loadStore();
60
+ store[config.name] = config;
61
+ saveStore(store);
59
62
  }
60
63
  /**
61
64
  * Load an MCP config by name
62
65
  */
63
66
  export function loadMCPConfig(name) {
64
- const store = loadStore();
65
- return store[name] || null;
67
+ const store = loadStore();
68
+ return store[name] || null;
66
69
  }
67
70
  /**
68
71
  * Delete an MCP config by name
69
72
  */
70
73
  export function deleteMCPConfig(name) {
71
- const store = loadStore();
72
- if (store[name]) {
73
- delete store[name];
74
- saveStore(store);
75
- return true;
76
- }
77
- return false;
74
+ const store = loadStore();
75
+ if (store[name]) {
76
+ delete store[name];
77
+ saveStore(store);
78
+ return true;
79
+ }
80
+ return false;
78
81
  }
79
82
  /**
80
83
  * List all MCP configs
81
84
  */
82
85
  export function listMCPConfigs() {
83
- const store = loadStore();
84
- return Object.values(store).sort((a, b) => a.name.localeCompare(b.name));
86
+ const store = loadStore();
87
+ return Object.values(store).sort((a, b) => a.name.localeCompare(b.name));
85
88
  }
86
89
  /**
87
90
  * Check if an MCP config exists
88
91
  */
89
92
  export function mcpConfigExists(name) {
90
- const store = loadStore();
91
- return name in store;
93
+ const store = loadStore();
94
+ return name in store;
92
95
  }
93
96
  /**
94
97
  * Get a summary of an MCP config for display
95
98
  */
96
99
  export function getMCPSummary(config) {
97
- if (config.transport === "http") {
98
- return `HTTP: ${config.url}`;
99
- }
100
- else {
101
- const parts = [`Stdio: ${config.command}`];
102
- if (config.args && config.args.length > 0) {
103
- parts.push(`[${config.args.join(" ")}]`);
104
- }
105
- return parts.join(" ");
106
- }
100
+ if (config.transport === "http") {
101
+ return `HTTP: ${config.url}`;
102
+ } else {
103
+ const parts = [`Stdio: ${config.command}`];
104
+ if (config.args && config.args.length > 0) {
105
+ parts.push(`[${config.args.join(" ")}]`);
106
+ }
107
+ return parts.join(" ");
108
+ }
107
109
  }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Check if a port is available
3
+ */
4
+ export declare function isPortAvailable(port: number): Promise<boolean>;
5
+ /**
6
+ * Find the next available port starting from the given port
7
+ */
8
+ export declare function findAvailablePort(startPort: number, maxAttempts?: number): Promise<number>;
@@ -0,0 +1,35 @@
1
+ import { createServer } from "node:net";
2
+ /**
3
+ * Check if a port is available
4
+ */
5
+ export async function isPortAvailable(port) {
6
+ return new Promise((resolve) => {
7
+ const server = createServer();
8
+ server.once("error", (err) => {
9
+ if (err.code === "EADDRINUSE") {
10
+ resolve(false);
11
+ }
12
+ else {
13
+ resolve(false);
14
+ }
15
+ });
16
+ server.once("listening", () => {
17
+ server.close();
18
+ resolve(true);
19
+ });
20
+ server.listen(port);
21
+ });
22
+ }
23
+ /**
24
+ * Find the next available port starting from the given port
25
+ */
26
+ export async function findAvailablePort(startPort, maxAttempts = 10) {
27
+ for (let i = 0; i < maxAttempts; i++) {
28
+ const port = startPort + i;
29
+ const available = await isPortAvailable(port);
30
+ if (available) {
31
+ return port;
32
+ }
33
+ }
34
+ throw new Error(`Could not find an available port between ${startPort} and ${startPort + maxAttempts - 1}`);
35
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@townco/cli",
3
- "version": "0.1.13",
3
+ "version": "0.1.14",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "town": "./dist/index.js"
@@ -19,16 +19,16 @@
19
19
  "build": "tsc"
20
20
  },
21
21
  "devDependencies": {
22
- "@townco/tsconfig": "0.1.5",
22
+ "@townco/tsconfig": "0.1.6",
23
23
  "@types/bun": "^1.3.1",
24
24
  "@types/react": "^19.2.2"
25
25
  },
26
26
  "dependencies": {
27
27
  "@optique/core": "^0.6.2",
28
28
  "@optique/run": "^0.6.2",
29
- "@townco/agent": "0.1.13",
30
- "@townco/secret": "0.1.8",
31
- "@townco/ui": "0.1.8",
29
+ "@townco/agent": "0.1.14",
30
+ "@townco/secret": "0.1.9",
31
+ "@townco/ui": "0.1.9",
32
32
  "@types/inquirer": "^9.0.9",
33
33
  "ink": "^6.4.0",
34
34
  "ink-text-input": "^6.0.0",