@townco/agent 0.1.43 → 0.1.45

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.
Files changed (52) hide show
  1. package/dist/acp-server/adapter.d.ts +1 -0
  2. package/dist/acp-server/adapter.js +130 -9
  3. package/dist/acp-server/cli.d.ts +3 -1
  4. package/dist/acp-server/session-storage.d.ts +21 -1
  5. package/dist/acp-server/session-storage.js +19 -1
  6. package/dist/bin.js +0 -0
  7. package/dist/definition/index.d.ts +19 -0
  8. package/dist/definition/index.js +11 -0
  9. package/dist/definition/mcp.js +0 -1
  10. package/dist/definition/tools/todo.d.ts +49 -0
  11. package/dist/definition/tools/todo.js +80 -0
  12. package/dist/definition/tools/web_search.d.ts +4 -0
  13. package/dist/definition/tools/web_search.js +26 -0
  14. package/dist/dev-agent/index.d.ts +2 -0
  15. package/dist/dev-agent/index.js +18 -0
  16. package/dist/example.d.ts +2 -0
  17. package/dist/example.js +19 -0
  18. package/dist/index.js +13 -2
  19. package/dist/runner/agent-runner.d.ts +28 -2
  20. package/dist/runner/agent-runner.js +2 -1
  21. package/dist/runner/hooks/constants.d.ts +9 -0
  22. package/dist/runner/hooks/constants.js +19 -0
  23. package/dist/runner/hooks/executor.d.ts +23 -0
  24. package/dist/runner/hooks/executor.js +163 -0
  25. package/dist/runner/hooks/index.d.ts +5 -0
  26. package/dist/runner/hooks/index.js +5 -0
  27. package/dist/runner/hooks/loader.d.ts +5 -0
  28. package/dist/runner/hooks/loader.js +49 -0
  29. package/dist/runner/hooks/predefined/compaction-tool.d.ts +6 -0
  30. package/dist/runner/hooks/predefined/compaction-tool.js +42 -0
  31. package/dist/runner/hooks/registry.d.ts +14 -0
  32. package/dist/runner/hooks/registry.js +20 -0
  33. package/dist/runner/hooks/types.d.ts +144 -0
  34. package/dist/runner/hooks/types.js +33 -0
  35. package/dist/runner/index.d.ts +3 -1
  36. package/dist/runner/langchain/index.js +16 -10
  37. package/dist/runner/langchain/model-factory.js +3 -1
  38. package/dist/scaffold/claude-scaffold.js +8 -6
  39. package/dist/storage/index.js +3 -1
  40. package/dist/templates/index.d.ts +7 -0
  41. package/dist/templates/index.js +7 -2
  42. package/dist/test-script.js +3 -1
  43. package/dist/tsconfig.tsbuildinfo +1 -1
  44. package/index.ts +14 -2
  45. package/package.json +5 -5
  46. package/templates/index.ts +14 -2
  47. package/dist/acp-server/test-acp-summarize.d.ts +0 -7
  48. package/dist/acp-server/test-acp-summarize.js +0 -127
  49. package/dist/acp-server/test-summarizer.d.ts +0 -7
  50. package/dist/acp-server/test-summarizer.js +0 -170
  51. package/dist/acp-server/tool-summarizer.d.ts +0 -125
  52. package/dist/acp-server/tool-summarizer.js +0 -182
@@ -18,6 +18,7 @@ export declare class AgentAcpAdapter implements acp.Agent {
18
18
  private agent;
19
19
  private storage;
20
20
  private noSession;
21
+ private agentDir;
21
22
  constructor(agent: AgentRunner, connection: acp.AgentSideConnection, agentDir?: string, agentName?: string);
22
23
  initialize(_params: acp.InitializeRequest): Promise<acp.InitializeResponse>;
23
24
  newSession(params: acp.NewSessionRequest): Promise<acp.NewSessionResponse>;
@@ -1,10 +1,71 @@
1
1
  import * as acp from "@agentclientprotocol/sdk";
2
+ import { createLogger } from "@townco/core";
3
+ import { HookExecutor, loadHookCallback } from "../runner/hooks";
2
4
  import { SessionStorage, } from "./session-storage.js";
5
+ const logger = createLogger("adapter");
3
6
  /**
4
7
  * ACP extension key for subagent mode indicator
5
8
  * Following ACP extensibility pattern with namespaced key
6
9
  */
7
10
  export const SUBAGENT_MODE_KEY = "town.com/isSubagent";
11
+ /**
12
+ * Create a context snapshot based on the previous context
13
+ * Preserves full messages from previous context and adds new pointers
14
+ */
15
+ function createContextSnapshot(messageCount, timestamp, previousContext) {
16
+ const messages = [];
17
+ if (previousContext) {
18
+ // Start with all messages from previous context
19
+ messages.push(...previousContext.messages);
20
+ // Find the highest pointer index in previous context
21
+ let maxPointerIndex = -1;
22
+ for (const entry of previousContext.messages) {
23
+ if (entry.type === "pointer" && entry.index > maxPointerIndex) {
24
+ maxPointerIndex = entry.index;
25
+ }
26
+ }
27
+ // Add pointers for any new messages since the previous context
28
+ for (let i = maxPointerIndex + 1; i < messageCount; i++) {
29
+ messages.push({ type: "pointer", index: i });
30
+ }
31
+ }
32
+ else {
33
+ // No previous context, create pointers for all messages
34
+ for (let i = 0; i < messageCount; i++) {
35
+ messages.push({ type: "pointer", index: i });
36
+ }
37
+ }
38
+ return { timestamp, messages };
39
+ }
40
+ /**
41
+ * Resolve context entries to session messages
42
+ * Converts pointers to actual messages and includes full messages
43
+ */
44
+ function resolveContextToMessages(context, allMessages) {
45
+ if (context.length === 0) {
46
+ return [];
47
+ }
48
+ // Use the latest context entry
49
+ const latestContext = context[context.length - 1];
50
+ if (!latestContext) {
51
+ return [];
52
+ }
53
+ const resolved = [];
54
+ for (const entry of latestContext.messages) {
55
+ if (entry.type === "pointer") {
56
+ // Resolve pointer to actual message
57
+ const message = allMessages[entry.index];
58
+ if (message) {
59
+ resolved.push(message);
60
+ }
61
+ }
62
+ else if (entry.type === "full") {
63
+ // Use full message directly
64
+ resolved.push(entry.message);
65
+ }
66
+ }
67
+ return resolved;
68
+ }
8
69
  /** Adapts an Agent to speak the ACP protocol */
9
70
  export class AgentAcpAdapter {
10
71
  connection;
@@ -12,16 +73,18 @@ export class AgentAcpAdapter {
12
73
  agent;
13
74
  storage;
14
75
  noSession;
76
+ agentDir;
15
77
  constructor(agent, connection, agentDir, agentName) {
16
78
  this.connection = connection;
17
79
  this.sessions = new Map();
18
80
  this.agent = agent;
81
+ this.agentDir = agentDir;
19
82
  this.noSession = process.env.TOWN_NO_SESSION === "true";
20
83
  this.storage =
21
84
  agentDir && agentName && !this.noSession
22
85
  ? new SessionStorage(agentDir, agentName)
23
86
  : null;
24
- console.log("[adapter] Initialized with:", {
87
+ logger.info("Initialized with", {
25
88
  agentDir,
26
89
  agentName,
27
90
  noSession: this.noSession,
@@ -42,6 +105,7 @@ export class AgentAcpAdapter {
42
105
  this.sessions.set(sessionId, {
43
106
  pendingPrompt: null,
44
107
  messages: [],
108
+ context: [],
45
109
  requestParams: params,
46
110
  });
47
111
  return {
@@ -60,12 +124,13 @@ export class AgentAcpAdapter {
60
124
  this.sessions.set(params.sessionId, {
61
125
  pendingPrompt: null,
62
126
  messages: storedSession.messages,
127
+ context: storedSession.context,
63
128
  requestParams: { cwd: process.cwd(), mcpServers: [] },
64
129
  });
65
130
  // Replay conversation history to client with ordered content blocks
66
- console.log(`[adapter] Replaying ${storedSession.messages.length} messages for session ${params.sessionId}`);
131
+ logger.info(`Replaying ${storedSession.messages.length} messages for session ${params.sessionId}`);
67
132
  for (const msg of storedSession.messages) {
68
- console.log(`[adapter] Replaying message: ${msg.role} with ${msg.content.length} content blocks`);
133
+ logger.debug(`Replaying message: ${msg.role} with ${msg.content.length} content blocks`);
69
134
  // Iterate through content blocks in order
70
135
  for (const block of msg.content) {
71
136
  if (block.type === "text") {
@@ -150,10 +215,11 @@ export class AgentAcpAdapter {
150
215
  let session = this.sessions.get(params.sessionId);
151
216
  // If session not found (e.g., after server restart), create a new one
152
217
  if (!session) {
153
- console.log(`Session ${params.sessionId} not found, creating new session`);
218
+ logger.info(`Session ${params.sessionId} not found, creating new session`);
154
219
  session = {
155
220
  pendingPrompt: null,
156
221
  messages: [],
222
+ context: [],
157
223
  requestParams: { cwd: process.cwd(), mcpServers: [] },
158
224
  };
159
225
  this.sessions.set(params.sessionId, session);
@@ -167,6 +233,11 @@ export class AgentAcpAdapter {
167
233
  .filter((p) => p.type === "text")
168
234
  .map((p) => p.text)
169
235
  .join("\n");
236
+ logger.info("User message received", {
237
+ sessionId: params.sessionId,
238
+ messagePreview: userMessageText.slice(0, 100),
239
+ noSession: this.noSession,
240
+ });
170
241
  // Only store messages if session persistence is enabled
171
242
  if (!this.noSession) {
172
243
  const userMessage = {
@@ -175,6 +246,12 @@ export class AgentAcpAdapter {
175
246
  timestamp: new Date().toISOString(),
176
247
  };
177
248
  session.messages.push(userMessage);
249
+ // Create context snapshot based on previous context
250
+ const previousContext = session.context.length > 0
251
+ ? session.context[session.context.length - 1]
252
+ : undefined;
253
+ const contextSnapshot = createContextSnapshot(session.messages.length, new Date().toISOString(), previousContext);
254
+ session.context.push(contextSnapshot);
178
255
  }
179
256
  // Build ordered content blocks for the assistant response
180
257
  const contentBlocks = [];
@@ -187,12 +264,48 @@ export class AgentAcpAdapter {
187
264
  }
188
265
  };
189
266
  try {
267
+ // Execute hooks before agent invocation
268
+ const hooks = this.agent.definition.hooks;
269
+ logger.info("Checking hooks", {
270
+ noSession: this.noSession,
271
+ hasHooks: !!hooks,
272
+ hooksLength: hooks?.length ?? 0,
273
+ contextEntries: session.context.length,
274
+ totalMessages: session.messages.length,
275
+ });
276
+ if (!this.noSession && hooks && hooks.length > 0) {
277
+ logger.info("Executing hooks before agent invocation");
278
+ const hookExecutor = new HookExecutor(hooks, this.agent.definition.model, (callbackRef) => loadHookCallback(callbackRef, this.agentDir));
279
+ // Create read-only session view for hooks
280
+ const readonlySession = {
281
+ messages: session.messages,
282
+ context: session.context,
283
+ requestParams: session.requestParams,
284
+ };
285
+ const hookResult = await hookExecutor.executeHooks(readonlySession);
286
+ // Send hook notifications to client
287
+ for (const notification of hookResult.notifications) {
288
+ this.connection.sessionUpdate({
289
+ sessionId: params.sessionId,
290
+ update: notification,
291
+ });
292
+ }
293
+ // Append new context entries returned by hooks
294
+ if (hookResult.newContextEntries.length > 0) {
295
+ logger.info(`Appending ${hookResult.newContextEntries.length} new context entries from hooks`);
296
+ session.context.push(...hookResult.newContextEntries);
297
+ }
298
+ }
299
+ // Resolve context to messages for agent invocation
300
+ const contextMessages = this.noSession
301
+ ? []
302
+ : resolveContextToMessages(session.context, session.messages);
190
303
  const invokeParams = {
191
304
  prompt: params.prompt,
192
305
  sessionId: params.sessionId,
193
306
  messageId,
194
- // Only pass session history if session persistence is enabled
195
- sessionMessages: this.noSession ? [] : session.messages,
307
+ // Pass resolved context messages to agent
308
+ contextMessages,
196
309
  };
197
310
  // Only add sessionMeta if it's defined
198
311
  if (session.requestParams._meta) {
@@ -215,7 +328,7 @@ export class AgentAcpAdapter {
215
328
  msg._meta &&
216
329
  typeof msg._meta === "object" &&
217
330
  "tokenUsage" in msg._meta) {
218
- console.log("DEBUG adapter: sending agent_message_chunk with tokenUsage in _meta:", JSON.stringify(msg._meta.tokenUsage));
331
+ logger.debug("sending agent_message_chunk with tokenUsage in _meta", { tokenUsage: msg._meta.tokenUsage });
219
332
  }
220
333
  }
221
334
  // Handle tool_call - flush pending text and add ToolCallBlock
@@ -299,14 +412,22 @@ export class AgentAcpAdapter {
299
412
  timestamp: new Date().toISOString(),
300
413
  };
301
414
  session.messages.push(assistantMessage);
415
+ // Create context snapshot based on previous context
416
+ const previousContext = session.context.length > 0
417
+ ? session.context[session.context.length - 1]
418
+ : undefined;
419
+ const contextSnapshot = createContextSnapshot(session.messages.length, new Date().toISOString(), previousContext);
420
+ session.context.push(contextSnapshot);
302
421
  }
303
422
  // Save session to disk if storage is configured and session persistence is enabled
304
423
  if (!this.noSession && this.storage) {
305
424
  try {
306
- await this.storage.saveSession(params.sessionId, session.messages);
425
+ await this.storage.saveSession(params.sessionId, session.messages, session.context);
307
426
  }
308
427
  catch (error) {
309
- console.error(`Failed to save session ${params.sessionId}:`, error instanceof Error ? error.message : String(error));
428
+ logger.error(`Failed to save session ${params.sessionId}`, {
429
+ error: error instanceof Error ? error.message : String(error),
430
+ });
310
431
  }
311
432
  }
312
433
  session.pendingPrompt = null;
@@ -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;
@@ -26,6 +26,25 @@ export interface SessionMessage {
26
26
  content: ContentBlock[];
27
27
  timestamp: string;
28
28
  }
29
+ /**
30
+ * Context entry types - for time-based context snapshots
31
+ */
32
+ export interface MessagePointer {
33
+ type: "pointer";
34
+ index: number;
35
+ }
36
+ export interface FullMessageEntry {
37
+ type: "full";
38
+ message: SessionMessage;
39
+ }
40
+ export type ContextMessageEntry = MessagePointer | FullMessageEntry;
41
+ /**
42
+ * Context entry - immutable snapshot of context at a point in time
43
+ */
44
+ export interface ContextEntry {
45
+ timestamp: string;
46
+ messages: ContextMessageEntry[];
47
+ }
29
48
  /**
30
49
  * Session metadata
31
50
  */
@@ -40,6 +59,7 @@ export interface SessionMetadata {
40
59
  export interface StoredSession {
41
60
  sessionId: string;
42
61
  messages: SessionMessage[];
62
+ context: ContextEntry[];
43
63
  metadata: SessionMetadata;
44
64
  }
45
65
  /**
@@ -67,7 +87,7 @@ export declare class SessionStorage {
67
87
  * Save a session to disk
68
88
  * Uses atomic write (write to temp file, then rename)
69
89
  */
70
- saveSession(sessionId: string, messages: SessionMessage[]): Promise<void>;
90
+ saveSession(sessionId: string, messages: SessionMessage[], context: ContextEntry[]): Promise<void>;
71
91
  /**
72
92
  * Load a session from disk
73
93
  */
@@ -40,6 +40,22 @@ const sessionMessageSchema = z.object({
40
40
  content: z.array(contentBlockSchema),
41
41
  timestamp: z.string(),
42
42
  });
43
+ const messagePointerSchema = z.object({
44
+ type: z.literal("pointer"),
45
+ index: z.number(),
46
+ });
47
+ const fullMessageEntrySchema = z.object({
48
+ type: z.literal("full"),
49
+ message: sessionMessageSchema,
50
+ });
51
+ const contextMessageEntrySchema = z.discriminatedUnion("type", [
52
+ messagePointerSchema,
53
+ fullMessageEntrySchema,
54
+ ]);
55
+ const contextEntrySchema = z.object({
56
+ timestamp: z.string(),
57
+ messages: z.array(contextMessageEntrySchema),
58
+ });
43
59
  const sessionMetadataSchema = z.object({
44
60
  createdAt: z.string(),
45
61
  updatedAt: z.string(),
@@ -48,6 +64,7 @@ const sessionMetadataSchema = z.object({
48
64
  const storedSessionSchema = z.object({
49
65
  sessionId: z.string(),
50
66
  messages: z.array(sessionMessageSchema),
67
+ context: z.array(contextEntrySchema),
51
68
  metadata: sessionMetadataSchema,
52
69
  });
53
70
  /**
@@ -84,7 +101,7 @@ export class SessionStorage {
84
101
  * Save a session to disk
85
102
  * Uses atomic write (write to temp file, then rename)
86
103
  */
87
- async saveSession(sessionId, messages) {
104
+ async saveSession(sessionId, messages, context) {
88
105
  this.ensureSessionsDir();
89
106
  const sessionPath = this.getSessionPath(sessionId);
90
107
  const tempPath = `${sessionPath}.tmp`;
@@ -95,6 +112,7 @@ export class SessionStorage {
95
112
  const session = {
96
113
  sessionId,
97
114
  messages,
115
+ context,
98
116
  metadata: {
99
117
  createdAt: existingSession?.metadata.createdAt || now,
100
118
  updatedAt: now,
package/dist/bin.js CHANGED
File without changes
@@ -12,6 +12,16 @@ export declare const McpConfigSchema: z.ZodUnion<readonly [z.ZodObject<{
12
12
  url: z.ZodString;
13
13
  headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
14
14
  }, z.core.$strip>]>;
15
+ /** Hook configuration schema. */
16
+ export declare const HookConfigSchema: z.ZodObject<{
17
+ type: z.ZodEnum<{
18
+ context_size: "context_size";
19
+ }>;
20
+ setting: z.ZodOptional<z.ZodObject<{
21
+ threshold: z.ZodNumber;
22
+ }, z.core.$strip>>;
23
+ callback: z.ZodString;
24
+ }, z.core.$strip>;
15
25
  /** Agent definition schema. */
16
26
  export declare const AgentDefinitionSchema: z.ZodObject<{
17
27
  systemPrompt: z.ZodNullable<z.ZodString>;
@@ -43,4 +53,13 @@ export declare const AgentDefinitionSchema: z.ZodObject<{
43
53
  headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
44
54
  }, z.core.$strip>]>>>;
45
55
  harnessImplementation: z.ZodOptional<z.ZodLiteral<"langchain">>;
56
+ hooks: z.ZodOptional<z.ZodArray<z.ZodObject<{
57
+ type: z.ZodEnum<{
58
+ context_size: "context_size";
59
+ }>;
60
+ setting: z.ZodOptional<z.ZodObject<{
61
+ threshold: z.ZodNumber;
62
+ }, z.core.$strip>>;
63
+ callback: z.ZodString;
64
+ }, z.core.$strip>>>;
46
65
  }, z.core.$strip>;
@@ -52,6 +52,16 @@ const ToolSchema = z.union([
52
52
  FilesystemToolSchema,
53
53
  DirectToolSchema,
54
54
  ]);
55
+ /** Hook configuration schema. */
56
+ export const HookConfigSchema = z.object({
57
+ type: z.enum(["context_size"]),
58
+ setting: z
59
+ .object({
60
+ threshold: z.number().min(0).max(100),
61
+ })
62
+ .optional(),
63
+ callback: z.string(),
64
+ });
55
65
  /** Agent definition schema. */
56
66
  export const AgentDefinitionSchema = z.object({
57
67
  systemPrompt: z.string().nullable(),
@@ -59,4 +69,5 @@ export const AgentDefinitionSchema = z.object({
59
69
  tools: z.array(ToolSchema).optional(),
60
70
  mcps: z.array(McpConfigSchema).optional(),
61
71
  harnessImplementation: z.literal("langchain").optional(),
72
+ hooks: z.array(HookConfigSchema).optional(),
62
73
  });
@@ -1 +0,0 @@
1
- "use strict";
@@ -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
+ }
package/dist/index.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { basename } from "node:path";
2
+ import { createLogger } from "@townco/core";
2
3
  import { makeHttpTransport, makeStdioTransport } from "./acp-server";
3
4
  import { makeSubagentsTool } from "./utils";
5
+ const logger = createLogger("agent-index");
4
6
  const exampleAgent = {
5
7
  model: "claude-sonnet-4-5-20250929",
6
8
  systemPrompt: "You are a helpful assistant.",
@@ -21,6 +23,15 @@ const exampleAgent = {
21
23
  ]),
22
24
  ],
23
25
  mcps: [],
26
+ hooks: [
27
+ {
28
+ type: "context_size",
29
+ setting: {
30
+ threshold: 95,
31
+ },
32
+ callback: "compaction_tool",
33
+ },
34
+ ],
24
35
  };
25
36
  // Parse transport type and flags from command line arguments
26
37
  const args = process.argv.slice(2);
@@ -40,7 +51,7 @@ else if (transport === "stdio") {
40
51
  makeStdioTransport(exampleAgent);
41
52
  }
42
53
  else {
43
- console.error(`Invalid transport: ${transport}`);
44
- console.error("Usage: bun run index.ts [stdio|http] [--no-session]");
54
+ logger.error(`Invalid transport: ${transport}`);
55
+ logger.error("Usage: bun run index.ts [stdio|http] [--no-session]");
45
56
  process.exit(1);
46
57
  }