@townco/agent 0.1.30 → 0.1.32

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.
@@ -16,9 +16,11 @@ export declare class AgentAcpAdapter implements acp.Agent {
16
16
  private connection;
17
17
  private sessions;
18
18
  private agent;
19
- constructor(agent: AgentRunner, connection: acp.AgentSideConnection);
19
+ private storage;
20
+ constructor(agent: AgentRunner, connection: acp.AgentSideConnection, agentDir?: string, agentName?: string);
20
21
  initialize(_params: acp.InitializeRequest): Promise<acp.InitializeResponse>;
21
22
  newSession(params: acp.NewSessionRequest): Promise<acp.NewSessionResponse>;
23
+ loadSession(params: acp.LoadSessionRequest): Promise<acp.LoadSessionResponse>;
22
24
  authenticate(_params: acp.AuthenticateRequest): Promise<acp.AuthenticateResponse | undefined>;
23
25
  setSessionMode(_params: acp.SetSessionModeRequest): Promise<acp.SetSessionModeResponse>;
24
26
  prompt(params: acp.PromptRequest): Promise<acp.PromptResponse>;
@@ -1,4 +1,5 @@
1
1
  import * as acp from "@agentclientprotocol/sdk";
2
+ import { SessionStorage } from "./session-storage.js";
2
3
  /**
3
4
  * ACP extension key for subagent mode indicator
4
5
  * Following ACP extensibility pattern with namespaced key
@@ -9,16 +10,25 @@ export class AgentAcpAdapter {
9
10
  connection;
10
11
  sessions;
11
12
  agent;
12
- constructor(agent, connection) {
13
+ storage;
14
+ constructor(agent, connection, agentDir, agentName) {
13
15
  this.connection = connection;
14
16
  this.sessions = new Map();
15
17
  this.agent = agent;
18
+ this.storage =
19
+ agentDir && agentName ? new SessionStorage(agentDir, agentName) : null;
20
+ console.log("[adapter] Initialized with:", {
21
+ agentDir,
22
+ agentName,
23
+ hasStorage: this.storage !== null,
24
+ sessionStoragePath: this.storage ? `${agentDir}/.sessions` : null
25
+ });
16
26
  }
17
27
  async initialize(_params) {
18
28
  return {
19
29
  protocolVersion: acp.PROTOCOL_VERSION,
20
30
  agentCapabilities: {
21
- loadSession: false,
31
+ loadSession: this.storage !== null,
22
32
  },
23
33
  };
24
34
  }
@@ -33,6 +43,37 @@ export class AgentAcpAdapter {
33
43
  sessionId,
34
44
  };
35
45
  }
46
+ async loadSession(params) {
47
+ if (!this.storage) {
48
+ throw new Error("Session storage is not configured");
49
+ }
50
+ const storedSession = await this.storage.loadSession(params.sessionId);
51
+ if (!storedSession) {
52
+ throw new Error(`Session ${params.sessionId} not found`);
53
+ }
54
+ // Restore session in active sessions map
55
+ this.sessions.set(params.sessionId, {
56
+ pendingPrompt: null,
57
+ messages: storedSession.messages,
58
+ requestParams: { cwd: process.cwd(), mcpServers: [] },
59
+ });
60
+ // Replay conversation history to client
61
+ console.log(`[adapter] Replaying ${storedSession.messages.length} messages for session ${params.sessionId}`);
62
+ for (const msg of storedSession.messages) {
63
+ console.log(`[adapter] Replaying message: ${msg.role} - ${msg.content.substring(0, 50)}...`);
64
+ this.connection.sessionUpdate({
65
+ sessionId: params.sessionId,
66
+ update: {
67
+ sessionUpdate: msg.role === "user" ? "user_message_chunk" : "agent_message_chunk",
68
+ content: {
69
+ type: "text",
70
+ text: msg.content,
71
+ },
72
+ },
73
+ });
74
+ }
75
+ return {};
76
+ }
36
77
  async authenticate(_params) {
37
78
  // No auth needed - return empty response
38
79
  return {};
@@ -57,25 +98,48 @@ export class AgentAcpAdapter {
57
98
  session.pendingPrompt = new AbortController();
58
99
  // Generate a unique messageId for this assistant response
59
100
  const messageId = Math.random().toString(36).substring(2);
101
+ // Extract and store the user message
102
+ const userMessageContent = params.prompt
103
+ .filter((p) => p.type === "text")
104
+ .map((p) => p.text)
105
+ .join("\n");
106
+ const userMessage = {
107
+ role: "user",
108
+ content: userMessageContent,
109
+ timestamp: new Date().toISOString(),
110
+ };
111
+ session.messages.push(userMessage);
112
+ // Accumulate assistant response content
113
+ let assistantContent = "";
60
114
  try {
61
115
  const invokeParams = {
62
116
  prompt: params.prompt,
63
117
  sessionId: params.sessionId,
64
118
  messageId,
119
+ sessionMessages: session.messages, // Pass session history to agent
65
120
  };
66
121
  // Only add sessionMeta if it's defined
67
122
  if (session.requestParams._meta) {
68
123
  invokeParams.sessionMeta = session.requestParams._meta;
69
124
  }
70
125
  for await (const msg of this.agent.invoke(invokeParams)) {
71
- // Debug: log if this is an agent_message_chunk with tokenUsage in _meta
126
+ // Accumulate assistant content from message chunks
72
127
  if ("sessionUpdate" in msg &&
73
128
  msg.sessionUpdate === "agent_message_chunk") {
129
+ if ("content" in msg &&
130
+ msg.content &&
131
+ typeof msg.content === "object") {
132
+ const content = msg.content;
133
+ if (content.type === "text" && typeof content.text === "string") {
134
+ assistantContent += content.text;
135
+ }
136
+ }
137
+ // Debug: log if this chunk has tokenUsage in _meta
74
138
  if ("_meta" in msg &&
75
139
  msg._meta &&
76
140
  typeof msg._meta === "object" &&
77
141
  "tokenUsage" in msg._meta) {
78
- console.error("DEBUG adapter: sending agent_message_chunk with tokenUsage in _meta:", JSON.stringify(msg._meta.tokenUsage));
142
+ console.log("DEBUG adapter: sending agent_message_chunk with tokenUsage in _meta:", JSON.stringify(msg._meta.tokenUsage));
79
143
  }
80
144
  }
81
145
  // The agent may emit extended types (like tool_output) that aren't in ACP SDK yet
@@ -92,6 +156,24 @@ export class AgentAcpAdapter {
92
156
  }
93
157
  throw err;
94
158
  }
159
+ // Store the complete assistant response in session messages
160
+ if (assistantContent.length > 0) {
161
+ const assistantMessage = {
162
+ role: "assistant",
163
+ content: assistantContent,
164
+ timestamp: new Date().toISOString(),
165
+ };
166
+ session.messages.push(assistantMessage);
167
+ }
168
+ // Save session to disk if storage is configured
169
+ if (this.storage) {
170
+ try {
171
+ await this.storage.saveSession(params.sessionId, session.messages);
172
+ }
173
+ catch (error) {
174
+ console.error(`Failed to save session ${params.sessionId}:`, error instanceof Error ? error.message : String(error));
175
+ }
176
+ }
95
177
  session.pendingPrompt = null;
96
178
  return {
97
179
  stopReason: "end_turn",
@@ -1,3 +1,5 @@
1
1
  import type { AgentDefinition } from "../definition";
2
2
  import { type AgentRunner } from "../runner";
3
- export declare function makeStdioTransport(agent: AgentRunner | AgentDefinition): void;
3
+ export declare function makeStdioTransport(
4
+ agent: AgentRunner | AgentDefinition,
5
+ ): void;
@@ -3,9 +3,13 @@ import * as acp from "@agentclientprotocol/sdk";
3
3
  import { makeRunnerFromDefinition } from "../runner";
4
4
  import { AgentAcpAdapter } from "./adapter";
5
5
  export function makeStdioTransport(agent) {
6
- const agentRunner = "definition" in agent ? agent : makeRunnerFromDefinition(agent);
7
- const input = Writable.toWeb(process.stdout);
8
- const output = Readable.toWeb(process.stdin);
9
- const stream = acp.ndJsonStream(input, output);
10
- new acp.AgentSideConnection((conn) => new AgentAcpAdapter(agentRunner, conn), stream);
6
+ const agentRunner =
7
+ "definition" in agent ? agent : makeRunnerFromDefinition(agent);
8
+ const input = Writable.toWeb(process.stdout);
9
+ const output = Readable.toWeb(process.stdin);
10
+ const stream = acp.ndJsonStream(input, output);
11
+ new acp.AgentSideConnection(
12
+ (conn) => new AgentAcpAdapter(agentRunner, conn),
13
+ stream,
14
+ );
11
15
  }
@@ -1,3 +1,3 @@
1
1
  import type { AgentDefinition } from "../definition";
2
2
  import { type AgentRunner } from "../runner";
3
- export declare function makeHttpTransport(agent: AgentRunner | AgentDefinition): void;
3
+ export declare function makeHttpTransport(agent: AgentRunner | AgentDefinition, agentDir?: string, agentName?: string): void;
@@ -47,12 +47,12 @@ function safeChannelName(prefix, id) {
47
47
  const hash = createHash("sha256").update(id).digest("hex").slice(0, 16);
48
48
  return `${prefix}_${hash}`;
49
49
  }
50
- export function makeHttpTransport(agent) {
50
+ export function makeHttpTransport(agent, agentDir, agentName) {
51
51
  const inbound = new TransformStream();
52
52
  const outbound = new TransformStream();
53
53
  const bridge = acp.ndJsonStream(outbound.writable, inbound.readable);
54
54
  const agentRunner = "definition" in agent ? agent : makeRunnerFromDefinition(agent);
55
- new acp.AgentSideConnection((conn) => new AgentAcpAdapter(agentRunner, conn), bridge);
55
+ new acp.AgentSideConnection((conn) => new AgentAcpAdapter(agentRunner, conn, agentDir, agentName), bridge);
56
56
  const app = new Hono();
57
57
  // Track active SSE streams by sessionId for direct output delivery
58
58
  const sseStreams = new Map();
@@ -330,12 +330,23 @@ export function makeHttpTransport(agent) {
330
330
  details: parseResult.error.issues,
331
331
  }, 400);
332
332
  }
333
- const body = parseResult.data;
333
+ // Use rawBody instead of parseResult.data to preserve all fields
334
+ // The Zod validation above ensures the structure is valid, but we don't
335
+ // want it to strip fields due to union matching issues
336
+ const body = rawBody;
334
337
  // Ensure the request has an id
335
338
  const id = "id" in body ? body.id : null;
336
339
  const isRequest = id != null;
337
340
  const method = "method" in body ? body.method : "notification";
338
341
  logger.debug("POST /rpc - Received request", { method, id, isRequest });
342
+ // Debug log for session/load requests
343
+ if (method === "session/load") {
344
+ logger.debug("POST /rpc - session/load request details", {
345
+ rawBody: JSON.stringify(rawBody),
346
+ parsedBody: JSON.stringify(body),
347
+ params: "params" in body ? body.params : "NO PARAMS",
348
+ });
349
+ }
339
350
  if (isRequest) {
340
351
  // For requests, set up a listener before sending the request
341
352
  const responseChannel = safeChannelName("response", String(id));
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Session message format stored in files
3
+ */
4
+ export interface SessionMessage {
5
+ role: "user" | "assistant";
6
+ content: string;
7
+ timestamp: string;
8
+ }
9
+ /**
10
+ * Session metadata
11
+ */
12
+ export interface SessionMetadata {
13
+ createdAt: string;
14
+ updatedAt: string;
15
+ agentName: string;
16
+ }
17
+ /**
18
+ * Complete session data stored in JSON files
19
+ */
20
+ export interface StoredSession {
21
+ sessionId: string;
22
+ messages: SessionMessage[];
23
+ metadata: SessionMetadata;
24
+ }
25
+ /**
26
+ * File-based session storage
27
+ * Stores sessions in agents/<agent-name>/.sessions/<session_id>.json
28
+ */
29
+ export declare class SessionStorage {
30
+ private sessionsDir;
31
+ private agentName;
32
+ /**
33
+ * Create a new SessionStorage instance
34
+ * @param agentDir - Path to the agent directory (e.g., agents/my-agent)
35
+ * @param agentName - Name of the agent (used in metadata)
36
+ */
37
+ constructor(agentDir: string, agentName: string);
38
+ /**
39
+ * Ensure the .sessions directory exists
40
+ */
41
+ private ensureSessionsDir;
42
+ /**
43
+ * Get the file path for a session
44
+ */
45
+ private getSessionPath;
46
+ /**
47
+ * Save a session to disk
48
+ * Uses atomic write (write to temp file, then rename)
49
+ */
50
+ saveSession(sessionId: string, messages: SessionMessage[]): Promise<void>;
51
+ /**
52
+ * Load a session from disk
53
+ */
54
+ loadSession(sessionId: string): Promise<StoredSession | null>;
55
+ /**
56
+ * Synchronous session loading (for internal use)
57
+ */
58
+ private loadSessionSync;
59
+ /**
60
+ * Check if a session exists
61
+ */
62
+ sessionExists(sessionId: string): boolean;
63
+ /**
64
+ * Delete a session
65
+ */
66
+ deleteSession(sessionId: string): Promise<boolean>;
67
+ /**
68
+ * List all session IDs
69
+ */
70
+ listSessions(): Promise<string[]>;
71
+ }
@@ -0,0 +1,155 @@
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync, } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { z } from "zod";
4
+ /**
5
+ * Zod schema for validating session files
6
+ */
7
+ const sessionMessageSchema = z.object({
8
+ role: z.enum(["user", "assistant"]),
9
+ content: z.string(),
10
+ timestamp: z.string(),
11
+ });
12
+ const sessionMetadataSchema = z.object({
13
+ createdAt: z.string(),
14
+ updatedAt: z.string(),
15
+ agentName: z.string(),
16
+ });
17
+ const storedSessionSchema = z.object({
18
+ sessionId: z.string(),
19
+ messages: z.array(sessionMessageSchema),
20
+ metadata: sessionMetadataSchema,
21
+ });
22
+ /**
23
+ * File-based session storage
24
+ * Stores sessions in agents/<agent-name>/.sessions/<session_id>.json
25
+ */
26
+ export class SessionStorage {
27
+ sessionsDir;
28
+ agentName;
29
+ /**
30
+ * Create a new SessionStorage instance
31
+ * @param agentDir - Path to the agent directory (e.g., agents/my-agent)
32
+ * @param agentName - Name of the agent (used in metadata)
33
+ */
34
+ constructor(agentDir, agentName) {
35
+ this.sessionsDir = join(agentDir, ".sessions");
36
+ this.agentName = agentName;
37
+ }
38
+ /**
39
+ * Ensure the .sessions directory exists
40
+ */
41
+ ensureSessionsDir() {
42
+ if (!existsSync(this.sessionsDir)) {
43
+ mkdirSync(this.sessionsDir, { recursive: true });
44
+ }
45
+ }
46
+ /**
47
+ * Get the file path for a session
48
+ */
49
+ getSessionPath(sessionId) {
50
+ return join(this.sessionsDir, `${sessionId}.json`);
51
+ }
52
+ /**
53
+ * Save a session to disk
54
+ * Uses atomic write (write to temp file, then rename)
55
+ */
56
+ async saveSession(sessionId, messages) {
57
+ this.ensureSessionsDir();
58
+ const sessionPath = this.getSessionPath(sessionId);
59
+ const tempPath = `${sessionPath}.tmp`;
60
+ const now = new Date().toISOString();
61
+ const existingSession = this.sessionExists(sessionId)
62
+ ? this.loadSessionSync(sessionId)
63
+ : null;
64
+ const session = {
65
+ sessionId,
66
+ messages,
67
+ metadata: {
68
+ createdAt: existingSession?.metadata.createdAt || now,
69
+ updatedAt: now,
70
+ agentName: this.agentName,
71
+ },
72
+ };
73
+ try {
74
+ // Write to temp file
75
+ writeFileSync(tempPath, JSON.stringify(session, null, 2), "utf-8");
76
+ // Atomic rename
77
+ if (existsSync(sessionPath)) {
78
+ unlinkSync(sessionPath);
79
+ }
80
+ writeFileSync(sessionPath, readFileSync(tempPath, "utf-8"), "utf-8");
81
+ unlinkSync(tempPath);
82
+ }
83
+ catch (error) {
84
+ // Clean up temp file on error
85
+ if (existsSync(tempPath)) {
86
+ unlinkSync(tempPath);
87
+ }
88
+ throw new Error(`Failed to save session ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
89
+ }
90
+ }
91
+ /**
92
+ * Load a session from disk
93
+ */
94
+ async loadSession(sessionId) {
95
+ return this.loadSessionSync(sessionId);
96
+ }
97
+ /**
98
+ * Synchronous session loading (for internal use)
99
+ */
100
+ loadSessionSync(sessionId) {
101
+ const sessionPath = this.getSessionPath(sessionId);
102
+ if (!existsSync(sessionPath)) {
103
+ return null;
104
+ }
105
+ try {
106
+ const content = readFileSync(sessionPath, "utf-8");
107
+ const parsed = JSON.parse(content);
108
+ // Validate with zod
109
+ const validated = storedSessionSchema.parse(parsed);
110
+ return validated;
111
+ }
112
+ catch (error) {
113
+ throw new Error(`Failed to load session ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
114
+ }
115
+ }
116
+ /**
117
+ * Check if a session exists
118
+ */
119
+ sessionExists(sessionId) {
120
+ return existsSync(this.getSessionPath(sessionId));
121
+ }
122
+ /**
123
+ * Delete a session
124
+ */
125
+ async deleteSession(sessionId) {
126
+ const sessionPath = this.getSessionPath(sessionId);
127
+ if (!existsSync(sessionPath)) {
128
+ return false;
129
+ }
130
+ try {
131
+ unlinkSync(sessionPath);
132
+ return true;
133
+ }
134
+ catch (error) {
135
+ throw new Error(`Failed to delete session ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
136
+ }
137
+ }
138
+ /**
139
+ * List all session IDs
140
+ */
141
+ async listSessions() {
142
+ if (!existsSync(this.sessionsDir)) {
143
+ return [];
144
+ }
145
+ try {
146
+ const files = readdirSync(this.sessionsDir);
147
+ return files
148
+ .filter((file) => file.endsWith(".json") && !file.endsWith(".tmp"))
149
+ .map((file) => file.replace(".json", ""));
150
+ }
151
+ catch (error) {
152
+ throw new Error(`Failed to list sessions: ${error instanceof Error ? error.message : String(error)}`);
153
+ }
154
+ }
155
+ }
package/dist/bin.js CHANGED
File without changes
File without changes
File without changes
@@ -0,0 +1,49 @@
1
+ import { z } from "zod";
2
+ export declare const todoItemSchema: z.ZodObject<
3
+ {
4
+ content: z.ZodString;
5
+ status: z.ZodEnum<{
6
+ pending: "pending";
7
+ in_progress: "in_progress";
8
+ completed: "completed";
9
+ }>;
10
+ activeForm: z.ZodString;
11
+ },
12
+ z.core.$strip
13
+ >;
14
+ export declare const todoWrite: import("langchain").DynamicStructuredTool<
15
+ z.ZodObject<
16
+ {
17
+ todos: z.ZodArray<
18
+ z.ZodObject<
19
+ {
20
+ content: z.ZodString;
21
+ status: z.ZodEnum<{
22
+ pending: "pending";
23
+ in_progress: "in_progress";
24
+ completed: "completed";
25
+ }>;
26
+ activeForm: z.ZodString;
27
+ },
28
+ z.core.$strip
29
+ >
30
+ >;
31
+ },
32
+ z.core.$strip
33
+ >,
34
+ {
35
+ todos: {
36
+ content: string;
37
+ status: "pending" | "in_progress" | "completed";
38
+ activeForm: string;
39
+ }[];
40
+ },
41
+ {
42
+ todos: {
43
+ content: string;
44
+ status: "pending" | "in_progress" | "completed";
45
+ activeForm: string;
46
+ }[];
47
+ },
48
+ string
49
+ >;
@@ -0,0 +1,80 @@
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(
9
+ ({ todos }) => {
10
+ // Simple implementation that confirms the todos were written
11
+ return `Successfully updated todo list with ${todos.length} items`;
12
+ },
13
+ {
14
+ name: "todo_write",
15
+ 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.
16
+ It also helps the user understand the progress of the task and overall progress of their requests.
17
+
18
+ ## When to Use This Tool
19
+ Use this tool proactively in these scenarios:
20
+
21
+ 1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
22
+ 2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
23
+ 3. User explicitly requests todo list - When the user directly asks you to use the todo list
24
+ 4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
25
+ 5. After receiving new instructions - Immediately capture user requirements as todos
26
+ 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
27
+ 7. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation
28
+
29
+ ## When NOT to Use This Tool
30
+
31
+ Skip using this tool when:
32
+ 1. There is only a single, straightforward task
33
+ 2. The task is trivial and tracking it provides no organizational benefit
34
+ 3. The task can be completed in less than 3 trivial steps
35
+ 4. The task is purely conversational or informational
36
+
37
+ 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.
38
+
39
+ ## Task States and Management
40
+
41
+ 1. **Task States**: Use these states to track progress:
42
+ - pending: Task not yet started
43
+ - in_progress: Currently working on (limit to ONE task at a time)
44
+ - completed: Task finished successfully
45
+
46
+ **IMPORTANT**: Task descriptions must have two forms:
47
+ - content: The imperative form describing what needs to be done (e.g., "Run tests", "Build the project")
48
+ - activeForm: The present continuous form shown during execution (e.g., "Running tests", "Building the project")
49
+
50
+ 2. **Task Management**:
51
+ - Update task status in real-time as you work
52
+ - Mark tasks complete IMMEDIATELY after finishing (don't batch completions)
53
+ - Exactly ONE task must be in_progress at any time (not less, not more)
54
+ - Complete current tasks before starting new ones
55
+ - Remove tasks that are no longer relevant from the list entirely
56
+
57
+ 3. **Task Completion Requirements**:
58
+ - ONLY mark a task as completed when you have FULLY accomplished it
59
+ - If you encounter errors, blockers, or cannot finish, keep the task as in_progress
60
+ - When blocked, create a new task describing what needs to be resolved
61
+ - Never mark a task as completed if:
62
+ - Tests are failing
63
+ - Implementation is partial
64
+ - You encountered unresolved errors
65
+ - You couldn't find necessary files or dependencies
66
+
67
+ 4. **Task Breakdown**:
68
+ - Create specific, actionable items
69
+ - Break complex tasks into smaller, manageable steps
70
+ - Use clear, descriptive task names
71
+ - Always provide both forms:
72
+ - content: "Fix authentication bug"
73
+ - activeForm: "Fixing authentication bug"
74
+
75
+ When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.`,
76
+ schema: z.object({
77
+ todos: z.array(todoItemSchema),
78
+ }),
79
+ },
80
+ );
@@ -0,0 +1,4 @@
1
+ import { ExaSearchResults } from "@langchain/exa";
2
+ export declare function makeWebSearchTool(): ExaSearchResults<{
3
+ text: true;
4
+ }>;
@@ -0,0 +1,26 @@
1
+ import { ExaSearchResults } from "@langchain/exa";
2
+ import Exa from "exa-js";
3
+
4
+ let _webSearchInstance = null;
5
+ export function makeWebSearchTool() {
6
+ if (_webSearchInstance) {
7
+ return _webSearchInstance;
8
+ }
9
+ const apiKey = process.env.EXA_API_KEY;
10
+ if (!apiKey) {
11
+ throw new Error(
12
+ "EXA_API_KEY environment variable is required to use the web_search tool. " +
13
+ "Please set it to your Exa API key from https://exa.ai",
14
+ );
15
+ }
16
+ const client = new Exa(apiKey);
17
+ _webSearchInstance = new ExaSearchResults({
18
+ client,
19
+ searchArgs: {
20
+ numResults: 5,
21
+ type: "auto",
22
+ text: true,
23
+ },
24
+ });
25
+ return _webSearchInstance;
26
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env bun
2
+ export {};
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env bun
2
+ import { readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { makeHttpTransport, makeStdioTransport } from "../acp-server/index";
5
+ // Load agent definition from JSON file
6
+ const configPath = join(import.meta.dir, "agent.json");
7
+ const agent = JSON.parse(readFileSync(configPath, "utf-8"));
8
+ const transport = process.argv[2] || "stdio";
9
+ if (transport === "http") {
10
+ makeHttpTransport(agent);
11
+ }
12
+ else if (transport === "stdio") {
13
+ makeStdioTransport(agent);
14
+ }
15
+ else {
16
+ console.error(`Invalid transport: ${transport}`);
17
+ process.exit(1);
18
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env bun
2
+ export {};
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env bun
2
+ import { makeHttpTransport, makeStdioTransport } from "./acp-server/index.js";
3
+
4
+ const exampleAgent = {
5
+ model: "claude-sonnet-4-5-20250929",
6
+ systemPrompt: "You are a helpful assistant.",
7
+ tools: ["todo_write", "get_weather", "web_search"],
8
+ };
9
+ // Parse transport type from command line argument
10
+ const transport = process.argv[2] || "stdio";
11
+ if (transport === "http") {
12
+ makeHttpTransport(exampleAgent);
13
+ } else if (transport === "stdio") {
14
+ makeStdioTransport(exampleAgent);
15
+ } else {
16
+ console.error(`Invalid transport: ${transport}`);
17
+ console.error("Usage: bun run example.ts [stdio|http]");
18
+ process.exit(1);
19
+ }