@townco/agent 0.1.0
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 +15 -0
- package/dist/acp-server/adapter.d.ts +15 -0
- package/dist/acp-server/adapter.js +76 -0
- package/dist/acp-server/cli.d.ts +3 -0
- package/dist/acp-server/cli.js +11 -0
- package/dist/acp-server/http.d.ts +3 -0
- package/dist/acp-server/http.js +178 -0
- package/dist/acp-server/index.d.ts +2 -0
- package/dist/acp-server/index.js +2 -0
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +3 -0
- package/dist/definition/index.d.ts +30 -0
- package/dist/definition/index.js +33 -0
- package/dist/definition/mcp.d.ts +0 -0
- package/dist/definition/mcp.js +1 -0
- package/dist/definition/tools/todo.d.ts +33 -0
- package/dist/definition/tools/todo.js +77 -0
- package/dist/definition/tools/web_search.d.ts +4 -0
- package/dist/definition/tools/web_search.js +23 -0
- package/dist/example.d.ts +2 -0
- package/dist/example.js +20 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +20 -0
- package/dist/runner/agent-runner.d.ts +24 -0
- package/dist/runner/agent-runner.js +9 -0
- package/dist/runner/index.d.ts +4 -0
- package/dist/runner/index.js +18 -0
- package/dist/runner/langchain/index.d.ts +15 -0
- package/dist/runner/langchain/index.js +227 -0
- package/dist/runner/langchain/tools/todo.d.ts +33 -0
- package/dist/runner/langchain/tools/todo.js +77 -0
- package/dist/runner/langchain/tools/web_search.d.ts +4 -0
- package/dist/runner/langchain/tools/web_search.js +23 -0
- package/dist/runner/tools.d.ts +3 -0
- package/dist/runner/tools.js +6 -0
- package/dist/scaffold/bundle.d.ts +4 -0
- package/dist/scaffold/bundle.js +28 -0
- package/dist/scaffold/copy-gui.d.ts +4 -0
- package/dist/scaffold/copy-gui.js +210 -0
- package/dist/scaffold/index.d.ts +16 -0
- package/dist/scaffold/index.js +98 -0
- package/dist/storage/index.d.ts +24 -0
- package/dist/storage/index.js +58 -0
- package/dist/templates/index.d.ts +17 -0
- package/dist/templates/index.js +173 -0
- package/dist/test-script.d.ts +1 -0
- package/dist/test-script.js +17 -0
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/package.json +72 -0
- package/templates/index.ts +203 -0
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { PromptResponse, SessionNotification } from "@agentclientprotocol/sdk";
|
|
2
|
+
import { type DynamicStructuredTool, type Tool } from "langchain";
|
|
3
|
+
import type { AgentRunner, CreateAgentRunnerParams, InvokeRequest } from "../agent-runner";
|
|
4
|
+
import type { ToolType } from "../tools";
|
|
5
|
+
type LangchainTool = DynamicStructuredTool | Tool;
|
|
6
|
+
/** Lazily-loaded langchain tools */
|
|
7
|
+
type LazyLangchainTool = MakeLazy<LangchainTool>;
|
|
8
|
+
type MakeLazy<T> = T extends LangchainTool ? () => T : never;
|
|
9
|
+
export declare const TOOL_REGISTRY: Record<ToolType, LangchainTool | LazyLangchainTool>;
|
|
10
|
+
export declare class LangchainAgent implements AgentRunner {
|
|
11
|
+
definition: CreateAgentRunnerParams;
|
|
12
|
+
constructor(params: CreateAgentRunnerParams);
|
|
13
|
+
invoke(req: InvokeRequest): AsyncGenerator<SessionNotification["update"], PromptResponse, undefined>;
|
|
14
|
+
}
|
|
15
|
+
export {};
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
import { MultiServerMCPClient } from "@langchain/mcp-adapters";
|
|
2
|
+
import { AIMessageChunk, createAgent, ToolMessage, tool, } from "langchain";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { todoItemSchema, todoWrite } from "./tools/todo";
|
|
5
|
+
import { makeWebSearchTool } from "./tools/web_search";
|
|
6
|
+
const getWeather = tool(({ city }) => `It's always sunny in ${city}!`, {
|
|
7
|
+
name: "get_weather",
|
|
8
|
+
description: "Get the weather for a given city",
|
|
9
|
+
schema: z.object({
|
|
10
|
+
city: z.string(),
|
|
11
|
+
}),
|
|
12
|
+
});
|
|
13
|
+
export const TOOL_REGISTRY = {
|
|
14
|
+
todo_write: todoWrite,
|
|
15
|
+
get_weather: getWeather,
|
|
16
|
+
web_search: makeWebSearchTool,
|
|
17
|
+
};
|
|
18
|
+
export class LangchainAgent {
|
|
19
|
+
definition;
|
|
20
|
+
constructor(params) {
|
|
21
|
+
this.definition = params;
|
|
22
|
+
}
|
|
23
|
+
async *invoke(req) {
|
|
24
|
+
// Track todo_write tool call IDs to suppress their tool_call notifications
|
|
25
|
+
const todoWriteToolCallIds = new Set();
|
|
26
|
+
const enabledTools = (this.definition.tools ?? []).map((name) => {
|
|
27
|
+
const tool = TOOL_REGISTRY[name];
|
|
28
|
+
if (typeof tool === "function") {
|
|
29
|
+
return tool();
|
|
30
|
+
}
|
|
31
|
+
return tool;
|
|
32
|
+
});
|
|
33
|
+
if ((this.definition.mcps?.length ?? 0) > 0) {
|
|
34
|
+
enabledTools.push(...(await makeMcpToolsClient(this.definition.mcps).getTools()));
|
|
35
|
+
}
|
|
36
|
+
const agentConfig = {
|
|
37
|
+
model: this.definition.model,
|
|
38
|
+
tools: enabledTools,
|
|
39
|
+
};
|
|
40
|
+
if (this.definition.systemPrompt) {
|
|
41
|
+
agentConfig.systemPrompt = this.definition.systemPrompt;
|
|
42
|
+
}
|
|
43
|
+
const agent = createAgent(agentConfig);
|
|
44
|
+
const stream = agent.stream({
|
|
45
|
+
messages: req.prompt
|
|
46
|
+
.filter((promptMsg) => promptMsg.type === "text")
|
|
47
|
+
.map((promptMsg) => ({
|
|
48
|
+
type: "human",
|
|
49
|
+
content: promptMsg.text,
|
|
50
|
+
})),
|
|
51
|
+
}, {
|
|
52
|
+
streamMode: ["updates", "messages"],
|
|
53
|
+
});
|
|
54
|
+
for await (const [streamMode, chunk] of await stream) {
|
|
55
|
+
if (streamMode === "updates") {
|
|
56
|
+
const updatesChunk = modelRequestSchema.safeParse(chunk);
|
|
57
|
+
if (!updatesChunk.success) {
|
|
58
|
+
// Other kinds of updates are either handled in the 'messages'
|
|
59
|
+
// streamMode (tool calls), or we don't care about them so far (not
|
|
60
|
+
// known yet).
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
const updatesMessages = updatesChunk.data.model_request.messages;
|
|
64
|
+
if (!updatesMessages.every((m) => m instanceof AIMessageChunk)) {
|
|
65
|
+
throw new Error(`Unhandled updates message chunk types: ${JSON.stringify(updatesMessages)}`);
|
|
66
|
+
}
|
|
67
|
+
for (const msg of updatesMessages) {
|
|
68
|
+
for (const toolCall of msg.tool_calls ?? []) {
|
|
69
|
+
if (toolCall.id == null) {
|
|
70
|
+
throw new Error(`Tool call is missing id: ${JSON.stringify(toolCall)}`);
|
|
71
|
+
}
|
|
72
|
+
// If this is a todo_write tool call, yield an agent-plan update
|
|
73
|
+
if (toolCall.name === "todo_write" && toolCall.args?.todos) {
|
|
74
|
+
const entries = toolCall.args.todos.flatMap((todo) => {
|
|
75
|
+
const validation = todoItemSchema.safeParse(todo);
|
|
76
|
+
if (!validation.success) {
|
|
77
|
+
// Invalid todo - filter it out
|
|
78
|
+
return [];
|
|
79
|
+
}
|
|
80
|
+
return [
|
|
81
|
+
{
|
|
82
|
+
content: validation.data.content,
|
|
83
|
+
status: validation.data.status,
|
|
84
|
+
priority: "medium",
|
|
85
|
+
},
|
|
86
|
+
];
|
|
87
|
+
});
|
|
88
|
+
yield {
|
|
89
|
+
sessionUpdate: "plan",
|
|
90
|
+
entries: entries,
|
|
91
|
+
};
|
|
92
|
+
// Track this tool call ID to suppress tool_call notifications
|
|
93
|
+
todoWriteToolCallIds.add(toolCall.id);
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
yield {
|
|
97
|
+
sessionUpdate: "tool_call",
|
|
98
|
+
toolCallId: toolCall.id,
|
|
99
|
+
title: toolCall.name,
|
|
100
|
+
kind: "other",
|
|
101
|
+
status: "pending",
|
|
102
|
+
rawInput: toolCall.args,
|
|
103
|
+
};
|
|
104
|
+
yield {
|
|
105
|
+
sessionUpdate: "tool_call_update",
|
|
106
|
+
toolCallId: toolCall.id,
|
|
107
|
+
status: "in_progress",
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
else if (streamMode === "messages") {
|
|
113
|
+
const aiMessage = chunk[0];
|
|
114
|
+
if (aiMessage instanceof AIMessageChunk) {
|
|
115
|
+
if (typeof aiMessage.content === "string") {
|
|
116
|
+
yield {
|
|
117
|
+
sessionUpdate: "agent_message_chunk",
|
|
118
|
+
content: {
|
|
119
|
+
type: "text",
|
|
120
|
+
text: aiMessage.content,
|
|
121
|
+
},
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
else if (Array.isArray(aiMessage.content)) {
|
|
125
|
+
for (const part of aiMessage.content) {
|
|
126
|
+
if (part.type === "text" && typeof part.text === "string") {
|
|
127
|
+
yield {
|
|
128
|
+
sessionUpdate: "agent_message_chunk",
|
|
129
|
+
content: {
|
|
130
|
+
type: "text",
|
|
131
|
+
text: part.text,
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
else if (part.type === "tool_use") {
|
|
136
|
+
// We don't care about tool use chunks -- do nothing
|
|
137
|
+
}
|
|
138
|
+
else if (part.type === "input_json_delta") {
|
|
139
|
+
// We don't care about tool use input delta chunks -- do nothing
|
|
140
|
+
}
|
|
141
|
+
else {
|
|
142
|
+
throw new Error(`Unhandled AIMessageChunk content block type: ${part.type}\n${JSON.stringify(part)}`);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
else {
|
|
147
|
+
throw new Error(`Unhandled AIMessageChunk content type: ${typeof aiMessage.content}`);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
else if (aiMessage instanceof ToolMessage) {
|
|
151
|
+
if (typeof aiMessage.content === "string") {
|
|
152
|
+
if (todoWriteToolCallIds.has(aiMessage.tool_call_id)) {
|
|
153
|
+
// Skip tool_call_update for todo_write tools
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
yield {
|
|
157
|
+
sessionUpdate: "tool_call_update",
|
|
158
|
+
toolCallId: aiMessage.tool_call_id,
|
|
159
|
+
status: "completed",
|
|
160
|
+
content: [
|
|
161
|
+
{
|
|
162
|
+
type: "content",
|
|
163
|
+
content: {
|
|
164
|
+
type: "text",
|
|
165
|
+
text: aiMessage.content,
|
|
166
|
+
},
|
|
167
|
+
},
|
|
168
|
+
],
|
|
169
|
+
rawOutput: { content: aiMessage.content },
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
else {
|
|
173
|
+
throw new Error(`Unhandled ToolMessage content type: ${typeof aiMessage.content}`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
else {
|
|
177
|
+
throw new Error(`Unhandled message chunk type: ${JSON.stringify(aiMessage)}`);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
else {
|
|
181
|
+
throw new Error(`Unhandled stream mode: ${streamMode}`);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return {
|
|
185
|
+
stopReason: "end_turn",
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
const modelRequestSchema = z.object({
|
|
190
|
+
model_request: z.object({
|
|
191
|
+
messages: z.array(z.any()),
|
|
192
|
+
}),
|
|
193
|
+
});
|
|
194
|
+
const makeMcpToolsClient = (mcpConfigs) => {
|
|
195
|
+
const mcpServers = mcpConfigs?.map((config) => {
|
|
196
|
+
if (config.transport === "http") {
|
|
197
|
+
return [
|
|
198
|
+
config.name,
|
|
199
|
+
{
|
|
200
|
+
url: config.url,
|
|
201
|
+
},
|
|
202
|
+
];
|
|
203
|
+
}
|
|
204
|
+
return [
|
|
205
|
+
config.name,
|
|
206
|
+
{
|
|
207
|
+
transport: "stdio",
|
|
208
|
+
command: config.command,
|
|
209
|
+
args: config.args,
|
|
210
|
+
},
|
|
211
|
+
];
|
|
212
|
+
});
|
|
213
|
+
const client = new MultiServerMCPClient({
|
|
214
|
+
// Global tool configuration options
|
|
215
|
+
// Whether to throw on errors if a tool fails to load (optional, default: true)
|
|
216
|
+
throwOnLoadError: true,
|
|
217
|
+
// Whether to prefix tool names with the server name (optional, default: false)
|
|
218
|
+
prefixToolNameWithServerName: false,
|
|
219
|
+
// Optional additional prefix for tool names (optional, default: "")
|
|
220
|
+
additionalToolNamePrefix: "",
|
|
221
|
+
// Use standardized content block format in tool outputs
|
|
222
|
+
useStandardContentBlocks: true,
|
|
223
|
+
// Server configuration
|
|
224
|
+
mcpServers: Object.fromEntries(mcpServers ?? []),
|
|
225
|
+
});
|
|
226
|
+
return client;
|
|
227
|
+
};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
export declare const todoItemSchema: z.ZodObject<{
|
|
3
|
+
content: z.ZodString;
|
|
4
|
+
status: z.ZodEnum<{
|
|
5
|
+
pending: "pending";
|
|
6
|
+
in_progress: "in_progress";
|
|
7
|
+
completed: "completed";
|
|
8
|
+
}>;
|
|
9
|
+
activeForm: z.ZodString;
|
|
10
|
+
}, z.core.$strip>;
|
|
11
|
+
export declare const todoWrite: import("langchain").DynamicStructuredTool<z.ZodObject<{
|
|
12
|
+
todos: z.ZodArray<z.ZodObject<{
|
|
13
|
+
content: z.ZodString;
|
|
14
|
+
status: z.ZodEnum<{
|
|
15
|
+
pending: "pending";
|
|
16
|
+
in_progress: "in_progress";
|
|
17
|
+
completed: "completed";
|
|
18
|
+
}>;
|
|
19
|
+
activeForm: z.ZodString;
|
|
20
|
+
}, z.core.$strip>>;
|
|
21
|
+
}, z.core.$strip>, {
|
|
22
|
+
todos: {
|
|
23
|
+
content: string;
|
|
24
|
+
status: "pending" | "in_progress" | "completed";
|
|
25
|
+
activeForm: string;
|
|
26
|
+
}[];
|
|
27
|
+
}, {
|
|
28
|
+
todos: {
|
|
29
|
+
content: string;
|
|
30
|
+
status: "pending" | "in_progress" | "completed";
|
|
31
|
+
activeForm: string;
|
|
32
|
+
}[];
|
|
33
|
+
}, string>;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { tool } from "langchain";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
export const todoItemSchema = z.object({
|
|
4
|
+
content: z.string().min(1),
|
|
5
|
+
status: z.enum(["pending", "in_progress", "completed"]),
|
|
6
|
+
activeForm: z.string().min(1),
|
|
7
|
+
});
|
|
8
|
+
export const todoWrite = tool(({ todos }) => {
|
|
9
|
+
// Simple implementation that confirms the todos were written
|
|
10
|
+
return `Successfully updated todo list with ${todos.length} items`;
|
|
11
|
+
}, {
|
|
12
|
+
name: "todo_write",
|
|
13
|
+
description: `Use this tool to create and manage a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
|
|
14
|
+
It also helps the user understand the progress of the task and overall progress of their requests.
|
|
15
|
+
|
|
16
|
+
## When to Use This Tool
|
|
17
|
+
Use this tool proactively in these scenarios:
|
|
18
|
+
|
|
19
|
+
1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
|
|
20
|
+
2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
|
|
21
|
+
3. User explicitly requests todo list - When the user directly asks you to use the todo list
|
|
22
|
+
4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
|
|
23
|
+
5. After receiving new instructions - Immediately capture user requirements as todos
|
|
24
|
+
6. When you start working on a task - Mark it as in_progress BEFORE beginning work. Ideally you should only have one todo as in_progress at a time
|
|
25
|
+
7. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation
|
|
26
|
+
|
|
27
|
+
## When NOT to Use This Tool
|
|
28
|
+
|
|
29
|
+
Skip using this tool when:
|
|
30
|
+
1. There is only a single, straightforward task
|
|
31
|
+
2. The task is trivial and tracking it provides no organizational benefit
|
|
32
|
+
3. The task can be completed in less than 3 trivial steps
|
|
33
|
+
4. The task is purely conversational or informational
|
|
34
|
+
|
|
35
|
+
NOTE that you should not use this tool if there is only one trivial task to do. In this case you are better off just doing the task directly.
|
|
36
|
+
|
|
37
|
+
## Task States and Management
|
|
38
|
+
|
|
39
|
+
1. **Task States**: Use these states to track progress:
|
|
40
|
+
- pending: Task not yet started
|
|
41
|
+
- in_progress: Currently working on (limit to ONE task at a time)
|
|
42
|
+
- completed: Task finished successfully
|
|
43
|
+
|
|
44
|
+
**IMPORTANT**: Task descriptions must have two forms:
|
|
45
|
+
- content: The imperative form describing what needs to be done (e.g., "Run tests", "Build the project")
|
|
46
|
+
- activeForm: The present continuous form shown during execution (e.g., "Running tests", "Building the project")
|
|
47
|
+
|
|
48
|
+
2. **Task Management**:
|
|
49
|
+
- Update task status in real-time as you work
|
|
50
|
+
- Mark tasks complete IMMEDIATELY after finishing (don't batch completions)
|
|
51
|
+
- Exactly ONE task must be in_progress at any time (not less, not more)
|
|
52
|
+
- Complete current tasks before starting new ones
|
|
53
|
+
- Remove tasks that are no longer relevant from the list entirely
|
|
54
|
+
|
|
55
|
+
3. **Task Completion Requirements**:
|
|
56
|
+
- ONLY mark a task as completed when you have FULLY accomplished it
|
|
57
|
+
- If you encounter errors, blockers, or cannot finish, keep the task as in_progress
|
|
58
|
+
- When blocked, create a new task describing what needs to be resolved
|
|
59
|
+
- Never mark a task as completed if:
|
|
60
|
+
- Tests are failing
|
|
61
|
+
- Implementation is partial
|
|
62
|
+
- You encountered unresolved errors
|
|
63
|
+
- You couldn't find necessary files or dependencies
|
|
64
|
+
|
|
65
|
+
4. **Task Breakdown**:
|
|
66
|
+
- Create specific, actionable items
|
|
67
|
+
- Break complex tasks into smaller, manageable steps
|
|
68
|
+
- Use clear, descriptive task names
|
|
69
|
+
- Always provide both forms:
|
|
70
|
+
- content: "Fix authentication bug"
|
|
71
|
+
- activeForm: "Fixing authentication bug"
|
|
72
|
+
|
|
73
|
+
When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.`,
|
|
74
|
+
schema: z.object({
|
|
75
|
+
todos: z.array(todoItemSchema),
|
|
76
|
+
}),
|
|
77
|
+
});
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { ExaSearchResults } from "@langchain/exa";
|
|
2
|
+
import Exa from "exa-js";
|
|
3
|
+
let _webSearchInstance = null;
|
|
4
|
+
export function makeWebSearchTool() {
|
|
5
|
+
if (_webSearchInstance) {
|
|
6
|
+
return _webSearchInstance;
|
|
7
|
+
}
|
|
8
|
+
const apiKey = process.env.EXA_API_KEY;
|
|
9
|
+
if (!apiKey) {
|
|
10
|
+
throw new Error("EXA_API_KEY environment variable is required to use the web_search tool. " +
|
|
11
|
+
"Please set it to your Exa API key from https://exa.ai");
|
|
12
|
+
}
|
|
13
|
+
const client = new Exa(apiKey);
|
|
14
|
+
_webSearchInstance = new ExaSearchResults({
|
|
15
|
+
client,
|
|
16
|
+
searchArgs: {
|
|
17
|
+
numResults: 5,
|
|
18
|
+
type: "auto",
|
|
19
|
+
text: true,
|
|
20
|
+
},
|
|
21
|
+
});
|
|
22
|
+
return _webSearchInstance;
|
|
23
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { cp, mkdir } from "node:fs/promises";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
/**
|
|
5
|
+
* Get the source packages/agent directory
|
|
6
|
+
*/
|
|
7
|
+
function getAgentPackageDir() {
|
|
8
|
+
const currentFile = fileURLToPath(import.meta.url);
|
|
9
|
+
// scaffold/bundle.ts -> scaffold -> packages/agent
|
|
10
|
+
return join(dirname(currentFile), "..");
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Copy necessary files from @townco/agent to the agent directory
|
|
14
|
+
*/
|
|
15
|
+
export async function bundleAgentDependencies(agentPath) {
|
|
16
|
+
const sourceDir = getAgentPackageDir();
|
|
17
|
+
// Create lib directory in the agent
|
|
18
|
+
const libDir = join(agentPath, "lib");
|
|
19
|
+
await mkdir(libDir, { recursive: true });
|
|
20
|
+
// Directories to copy
|
|
21
|
+
const dirsToCopy = ["acp-server", "definition", "runner"];
|
|
22
|
+
for (const dir of dirsToCopy) {
|
|
23
|
+
const sourceSubDir = join(sourceDir, dir);
|
|
24
|
+
const targetSubDir = join(libDir, dir);
|
|
25
|
+
// Copy the directory recursively
|
|
26
|
+
await cp(sourceSubDir, targetSubDir, { recursive: true });
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import { cp, mkdir, writeFile } from "node:fs/promises";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
/**
|
|
5
|
+
* Get the source apps/gui directory
|
|
6
|
+
*/
|
|
7
|
+
function getGuiSourceDir() {
|
|
8
|
+
const currentFile = fileURLToPath(import.meta.url);
|
|
9
|
+
// When running from compiled dist:
|
|
10
|
+
// dist/scaffold/copy-gui.js -> dist/scaffold -> dist -> packages/agent -> packages -> root -> apps/gui
|
|
11
|
+
return join(dirname(currentFile), "..", "..", "..", "..", "apps", "gui");
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Get the source packages/ui directory
|
|
15
|
+
*/
|
|
16
|
+
function getUiSourceDir() {
|
|
17
|
+
const currentFile = fileURLToPath(import.meta.url);
|
|
18
|
+
// When running from compiled dist:
|
|
19
|
+
// dist/scaffold/copy-gui.js -> dist/scaffold -> dist -> packages/agent -> packages -> ui
|
|
20
|
+
return join(dirname(currentFile), "..", "..", "..", "ui");
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Copy GUI app to the agent directory
|
|
24
|
+
*/
|
|
25
|
+
export async function copyGuiApp(agentPath) {
|
|
26
|
+
const sourceDir = getGuiSourceDir();
|
|
27
|
+
const guiDir = join(agentPath, "gui");
|
|
28
|
+
// Create gui directory
|
|
29
|
+
await mkdir(guiDir, { recursive: true });
|
|
30
|
+
// Copy everything except node_modules and dist (exclude tsconfig.json as we'll generate it)
|
|
31
|
+
const itemsToCopy = ["src", "index.html", "postcss.config.js"];
|
|
32
|
+
for (const item of itemsToCopy) {
|
|
33
|
+
const sourcePath = join(sourceDir, item);
|
|
34
|
+
const targetPath = join(guiDir, item);
|
|
35
|
+
try {
|
|
36
|
+
await cp(sourcePath, targetPath, { recursive: true });
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
// Item might not exist, that's okay
|
|
40
|
+
console.warn(`Warning: Could not copy ${item}:`, error);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
// Create a standalone tsconfig.json for the GUI (can't extend from workspace tsconfig)
|
|
44
|
+
const guiTsConfig = {
|
|
45
|
+
compilerOptions: {
|
|
46
|
+
allowArbitraryExtensions: true,
|
|
47
|
+
allowUnreachableCode: false,
|
|
48
|
+
allowUnusedLabels: false,
|
|
49
|
+
declaration: true,
|
|
50
|
+
emitDecoratorMetadata: true,
|
|
51
|
+
esModuleInterop: true,
|
|
52
|
+
exactOptionalPropertyTypes: true,
|
|
53
|
+
experimentalDecorators: true,
|
|
54
|
+
jsx: "react-jsx",
|
|
55
|
+
lib: ["DOM", "ESNext"],
|
|
56
|
+
module: "ESNext",
|
|
57
|
+
moduleResolution: "bundler",
|
|
58
|
+
noFallthroughCasesInSwitch: true,
|
|
59
|
+
noImplicitAny: true,
|
|
60
|
+
noImplicitOverride: true,
|
|
61
|
+
noImplicitReturns: true,
|
|
62
|
+
noUncheckedIndexedAccess: true,
|
|
63
|
+
noUncheckedSideEffectImports: true,
|
|
64
|
+
noUnusedLocals: false,
|
|
65
|
+
noUnusedParameters: true,
|
|
66
|
+
resolveJsonModule: true,
|
|
67
|
+
skipLibCheck: true,
|
|
68
|
+
strict: true,
|
|
69
|
+
stripInternal: true,
|
|
70
|
+
target: "ESNext",
|
|
71
|
+
verbatimModuleSyntax: true,
|
|
72
|
+
outDir: "./dist",
|
|
73
|
+
rootDir: "./src",
|
|
74
|
+
},
|
|
75
|
+
include: ["src/**/*"],
|
|
76
|
+
exclude: ["node_modules", "dist"],
|
|
77
|
+
};
|
|
78
|
+
await writeFile(join(guiDir, "tsconfig.json"), JSON.stringify(guiTsConfig, null, 2));
|
|
79
|
+
// Create a custom vite.config.ts with path aliases
|
|
80
|
+
const viteConfig = `import { defineConfig } from "vite";
|
|
81
|
+
import react from "@vitejs/plugin-react";
|
|
82
|
+
import { resolve } from "path";
|
|
83
|
+
|
|
84
|
+
export default defineConfig({
|
|
85
|
+
plugins: [react()],
|
|
86
|
+
resolve: {
|
|
87
|
+
alias: {
|
|
88
|
+
"@townco/ui": resolve(__dirname, "./ui/src"),
|
|
89
|
+
// Exclude Node.js-only modules from browser bundle
|
|
90
|
+
"node:child_process": resolve(__dirname, "./polyfills/child_process.js"),
|
|
91
|
+
"node:stream": resolve(__dirname, "./polyfills/stream.js"),
|
|
92
|
+
},
|
|
93
|
+
},
|
|
94
|
+
optimizeDeps: {
|
|
95
|
+
exclude: ["node:child_process", "node:stream"],
|
|
96
|
+
},
|
|
97
|
+
});
|
|
98
|
+
`;
|
|
99
|
+
await writeFile(join(guiDir, "vite.config.ts"), viteConfig);
|
|
100
|
+
// Create polyfills directory with stub modules for Node.js-only imports
|
|
101
|
+
const polyfillsDir = join(guiDir, "polyfills");
|
|
102
|
+
await mkdir(polyfillsDir, { recursive: true });
|
|
103
|
+
// Provide stub exports for child_process module
|
|
104
|
+
const childProcessPolyfill = `// Polyfill for node:child_process (browser-incompatible)
|
|
105
|
+
export const spawn = () => {
|
|
106
|
+
throw new Error('child_process.spawn is not available in the browser');
|
|
107
|
+
};
|
|
108
|
+
export class ChildProcess {}
|
|
109
|
+
export default { spawn, ChildProcess };
|
|
110
|
+
`;
|
|
111
|
+
await writeFile(join(polyfillsDir, "child_process.js"), childProcessPolyfill);
|
|
112
|
+
// Provide stub exports for stream module
|
|
113
|
+
const streamPolyfill = `// Polyfill for node:stream (browser-incompatible)
|
|
114
|
+
export class Readable {
|
|
115
|
+
constructor() {
|
|
116
|
+
throw new Error('stream.Readable is not available in the browser');
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
export class Writable {
|
|
120
|
+
constructor() {
|
|
121
|
+
throw new Error('stream.Writable is not available in the browser');
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
export class Duplex {
|
|
125
|
+
constructor() {
|
|
126
|
+
throw new Error('stream.Duplex is not available in the browser');
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
export class Transform {
|
|
130
|
+
constructor() {
|
|
131
|
+
throw new Error('stream.Transform is not available in the browser');
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
export default { Readable, Writable, Duplex, Transform };
|
|
135
|
+
`;
|
|
136
|
+
await writeFile(join(polyfillsDir, "stream.js"), streamPolyfill);
|
|
137
|
+
// Generate a custom package.json for the GUI
|
|
138
|
+
const packageJson = {
|
|
139
|
+
name: "agent-gui",
|
|
140
|
+
version: "0.0.1",
|
|
141
|
+
type: "module",
|
|
142
|
+
private: true,
|
|
143
|
+
scripts: {
|
|
144
|
+
dev: "vite",
|
|
145
|
+
build: "vite build",
|
|
146
|
+
preview: "vite preview",
|
|
147
|
+
},
|
|
148
|
+
dependencies: {
|
|
149
|
+
"@agentclientprotocol/sdk": "^0.5.1",
|
|
150
|
+
"@radix-ui/react-dialog": "^1.1.15",
|
|
151
|
+
"@radix-ui/react-label": "^2.1.8",
|
|
152
|
+
"@radix-ui/react-select": "^2.2.6",
|
|
153
|
+
"@radix-ui/react-slot": "^1.2.4",
|
|
154
|
+
"@radix-ui/react-tabs": "^1.1.13",
|
|
155
|
+
"class-variance-authority": "^0.7.1",
|
|
156
|
+
clsx: "^2.1.1",
|
|
157
|
+
"lucide-react": "^0.552.0",
|
|
158
|
+
react: "^19.2.0",
|
|
159
|
+
"react-dom": "^19.2.0",
|
|
160
|
+
"react-markdown": "^10.1.0",
|
|
161
|
+
"remark-gfm": "^4.0.1",
|
|
162
|
+
"tailwind-merge": "^3.3.1",
|
|
163
|
+
zod: "^4.1.12",
|
|
164
|
+
zustand: "^5.0.8",
|
|
165
|
+
},
|
|
166
|
+
devDependencies: {
|
|
167
|
+
"@tailwindcss/postcss": "^4.1.17",
|
|
168
|
+
"@types/react": "^19.2.2",
|
|
169
|
+
"@types/react-dom": "^19.2.2",
|
|
170
|
+
"@vitejs/plugin-react": "^5.1.0",
|
|
171
|
+
autoprefixer: "^10.4.21",
|
|
172
|
+
postcss: "^8.5.6",
|
|
173
|
+
tailwindcss: "^4.1.17",
|
|
174
|
+
typescript: "^5.9.3",
|
|
175
|
+
vite: "^7.2.1",
|
|
176
|
+
},
|
|
177
|
+
};
|
|
178
|
+
await writeFile(join(guiDir, "package.json"), JSON.stringify(packageJson, null, 2));
|
|
179
|
+
// Copy UI package components and styles
|
|
180
|
+
const uiSourceDir = getUiSourceDir();
|
|
181
|
+
const uiTargetDir = join(guiDir, "ui");
|
|
182
|
+
await mkdir(uiTargetDir, { recursive: true });
|
|
183
|
+
// Copy the entire UI src directory (which includes styles)
|
|
184
|
+
const sourcePath = join(uiSourceDir, "src");
|
|
185
|
+
const targetPath = join(uiTargetDir, "src");
|
|
186
|
+
try {
|
|
187
|
+
await cp(sourcePath, targetPath, { recursive: true });
|
|
188
|
+
}
|
|
189
|
+
catch (error) {
|
|
190
|
+
console.warn(`Warning: Could not copy UI src:`, error);
|
|
191
|
+
}
|
|
192
|
+
// Create a tsconfig for the ui directory
|
|
193
|
+
const uiTsConfig = {
|
|
194
|
+
compilerOptions: {
|
|
195
|
+
target: "ESNext",
|
|
196
|
+
module: "ESNext",
|
|
197
|
+
jsx: "react-jsx",
|
|
198
|
+
moduleResolution: "bundler",
|
|
199
|
+
lib: ["ESNext", "DOM", "DOM.Iterable"],
|
|
200
|
+
strict: true,
|
|
201
|
+
esModuleInterop: true,
|
|
202
|
+
skipLibCheck: true,
|
|
203
|
+
forceConsistentCasingInFileNames: true,
|
|
204
|
+
resolveJsonModule: true,
|
|
205
|
+
allowSyntheticDefaultImports: true,
|
|
206
|
+
},
|
|
207
|
+
include: ["**/*.ts", "**/*.tsx"],
|
|
208
|
+
};
|
|
209
|
+
await writeFile(join(uiTargetDir, "tsconfig.json"), JSON.stringify(uiTsConfig, null, 2));
|
|
210
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { AgentDefinition } from "../definition";
|
|
2
|
+
export interface ScaffoldOptions {
|
|
3
|
+
name: string;
|
|
4
|
+
definition: AgentDefinition;
|
|
5
|
+
overwrite?: boolean;
|
|
6
|
+
includeGui?: boolean;
|
|
7
|
+
}
|
|
8
|
+
export interface ScaffoldResult {
|
|
9
|
+
success: boolean;
|
|
10
|
+
path: string;
|
|
11
|
+
error?: string;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Scaffold a new agent package
|
|
15
|
+
*/
|
|
16
|
+
export declare function scaffoldAgent(options: ScaffoldOptions): Promise<ScaffoldResult>;
|