@townco/agent 0.1.47 → 0.1.49

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.
@@ -17,15 +17,25 @@ function createContextSnapshot(messageCount, timestamp, previousContext) {
17
17
  if (previousContext) {
18
18
  // Start with all messages from previous context
19
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;
20
+ // Determine the starting index for new pointers
21
+ let startPointerIndex;
22
+ if (previousContext.compactedUpTo !== undefined) {
23
+ // If previous context was a compaction, start adding pointers
24
+ // for messages after the compaction boundary
25
+ startPointerIndex = previousContext.compactedUpTo + 1;
26
+ }
27
+ else {
28
+ // Find the highest pointer index in previous context
29
+ let maxPointerIndex = -1;
30
+ for (const entry of previousContext.messages) {
31
+ if (entry.type === "pointer" && entry.index > maxPointerIndex) {
32
+ maxPointerIndex = entry.index;
33
+ }
25
34
  }
35
+ startPointerIndex = maxPointerIndex + 1;
26
36
  }
27
37
  // Add pointers for any new messages since the previous context
28
- for (let i = maxPointerIndex + 1; i < messageCount; i++) {
38
+ for (let i = startPointerIndex; i < messageCount; i++) {
29
39
  messages.push({ type: "pointer", index: i });
30
40
  }
31
41
  }
@@ -294,6 +304,18 @@ export class AgentAcpAdapter {
294
304
  if (hookResult.newContextEntries.length > 0) {
295
305
  logger.info(`Appending ${hookResult.newContextEntries.length} new context entries from hooks`);
296
306
  session.context.push(...hookResult.newContextEntries);
307
+ // Save session immediately after hooks to persist compacted context
308
+ if (this.storage) {
309
+ try {
310
+ await this.storage.saveSession(params.sessionId, session.messages, session.context);
311
+ logger.info("Session saved after hook execution with new context entries");
312
+ }
313
+ catch (error) {
314
+ logger.error(`Failed to save session ${params.sessionId} after hook execution`, {
315
+ error: error instanceof Error ? error.message : String(error),
316
+ });
317
+ }
318
+ }
297
319
  }
298
320
  }
299
321
  // Resolve context to messages for agent invocation
@@ -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;
@@ -44,6 +44,12 @@ export type ContextMessageEntry = MessagePointer | FullMessageEntry;
44
44
  export interface ContextEntry {
45
45
  timestamp: string;
46
46
  messages: ContextMessageEntry[];
47
+ /**
48
+ * When set, indicates this context entry represents a compaction
49
+ * and all messages up to and including this index have been
50
+ * compacted into the full message(s) in this entry
51
+ */
52
+ compactedUpTo?: number | undefined;
47
53
  }
48
54
  /**
49
55
  * Session metadata
@@ -55,6 +55,7 @@ const contextMessageEntrySchema = z.discriminatedUnion("type", [
55
55
  const contextEntrySchema = z.object({
56
56
  timestamp: z.string(),
57
57
  messages: z.array(contextMessageEntrySchema),
58
+ compactedUpTo: z.number().optional(),
58
59
  });
59
60
  const sessionMetadataSchema = z.object({
60
61
  createdAt: z.string(),
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
+ }
@@ -1,6 +1,6 @@
1
1
  import { type HookCallback } from "../types";
2
2
  /**
3
- * Placeholder compaction tool for testing hooks
4
- * Logs the context and returns null (no new context entry)
3
+ * Compaction tool that uses an LLM to summarize conversation history
4
+ * when context size reaches the configured threshold
5
5
  */
6
6
  export declare const compactionTool: HookCallback;
@@ -1,9 +1,11 @@
1
+ import { ChatAnthropic } from "@langchain/anthropic";
2
+ import { HumanMessage, SystemMessage } from "@langchain/core/messages";
1
3
  import { createLogger } from "@townco/core";
2
4
  import { createContextEntry, createFullMessageEntry, } from "../types";
3
5
  const logger = createLogger("compaction-tool");
4
6
  /**
5
- * Placeholder compaction tool for testing hooks
6
- * Logs the context and returns null (no new context entry)
7
+ * Compaction tool that uses an LLM to summarize conversation history
8
+ * when context size reaches the configured threshold
7
9
  */
8
10
  export const compactionTool = async (ctx) => {
9
11
  logger.info("Compaction tool triggered", {
@@ -14,29 +16,105 @@ export const compactionTool = async (ctx) => {
14
16
  totalMessages: ctx.session.messages.length,
15
17
  model: ctx.model,
16
18
  });
17
- // TODO: Implement actual compaction logic
18
- // Example: Create a new context entry with a summary message
19
- // const summaryEntry = createFullMessageEntry(
20
- // "assistant",
21
- // "Summary of previous conversation: ..."
22
- // );
23
- //
24
- // const newContextEntry = createContextEntry([summaryEntry]);
25
- //
26
- // return {
27
- // newContextEntry,
28
- // metadata: {
29
- // action: "compacted",
30
- // messagesRemoved: ctx.session.messages.length - 1,
31
- // tokensSaved: 1000,
32
- // },
33
- // };
34
- // For now, just return null (no new context entry)
35
- return {
36
- newContextEntry: null,
37
- metadata: {
38
- action: "placeholder",
39
- message: "Compaction tool called but no action taken (placeholder)",
40
- },
41
- };
19
+ try {
20
+ // Create the LLM client using the same model as the agent
21
+ const model = new ChatAnthropic({
22
+ model: ctx.model,
23
+ temperature: 0,
24
+ });
25
+ // Build the conversation history to compact
26
+ const messagesToCompact = ctx.session.messages;
27
+ // Convert session messages to text for context
28
+ const conversationText = messagesToCompact
29
+ .map((msg) => {
30
+ const textContent = msg.content
31
+ .filter((block) => block.type === "text")
32
+ .map((block) => block.text)
33
+ .join("\n");
34
+ return `${msg.role.toUpperCase()}:\n${textContent}`;
35
+ })
36
+ .join("\n\n---\n\n");
37
+ // Create system prompt for compaction
38
+ const systemPrompt = new SystemMessage("You are a helpful AI assistant tasked with summarizing conversations.");
39
+ // Create detailed compaction instructions with a generic, domain-agnostic approach
40
+ const userPrompt = `Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
41
+ This summary should be thorough in capturing important details, decisions, and context that would be essential for continuing the conversation/task without losing important information.
42
+
43
+ Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
44
+
45
+ 1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
46
+ - The user's explicit requests and intents
47
+ - Your approach to addressing the user's requests
48
+ - Key decisions and important concepts discussed
49
+ - Specific details that are important to remember
50
+ - Challenges encountered and how they were addressed
51
+ - Pay special attention to specific user feedback, especially if the user told you to do something differently
52
+ 2. Double-check for accuracy and completeness, addressing each required element thoroughly
53
+
54
+ Your summary should include the following sections:
55
+
56
+ 1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
57
+ 2. Key Topics and Concepts: List all important topics, concepts, and themes discussed in the conversation
58
+ 3. Important Details and Information: Document specific details, information, or content that was shared, examined, or created. Pay special attention to the most recent messages and include important details where applicable
59
+ 4. Challenges and Solutions: List any challenges, issues, or obstacles that came up and how they were addressed. Pay special attention to specific user feedback, especially if the user asked for a different approach
60
+ 5. Problem Solving: Document problems solved and any ongoing work or troubleshooting efforts
61
+ 6. All User Messages: List ALL user messages (excluding tool results). These are critical for understanding the user's feedback and changing intent
62
+ 7. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on
63
+ 8. Current Work: Describe in detail precisely what was being worked on immediately before this summary, paying special attention to the most recent messages from both user and assistant
64
+ 9. Optional Next Step: List the next step related to the most recent work. IMPORTANT: ensure this step is DIRECTLY in line with the user's most recent explicit requests and the task you were working on. If the last task was concluded, only list next steps if they are explicitly in line with the user's request. Do not start on tangential requests or old requests that were already completed without confirming with the user first.
65
+ If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.
66
+
67
+ Here's the conversation to summarize:
68
+
69
+ ${conversationText}
70
+
71
+ Please provide your summary based on the conversation above, following this structure and ensuring precision and thoroughness in your response.`;
72
+ const userMessage = new HumanMessage(userPrompt);
73
+ // Invoke the LLM
74
+ logger.info("Invoking LLM for compaction summary");
75
+ const response = await model.invoke([systemPrompt, userMessage]);
76
+ // Extract the summary text from the response
77
+ const summaryText = typeof response.content === "string"
78
+ ? response.content
79
+ : Array.isArray(response.content)
80
+ ? response.content
81
+ .filter((block) => typeof block === "object" &&
82
+ block !== null &&
83
+ "text" in block)
84
+ .map((block) => block.text)
85
+ .join("\n")
86
+ : "Failed to extract summary";
87
+ logger.info("Generated compaction summary", {
88
+ originalMessages: messagesToCompact.length,
89
+ summaryLength: summaryText.length,
90
+ estimatedTokensSaved: Math.round(ctx.currentTokens * 0.7),
91
+ });
92
+ // Create a new context entry with the summary
93
+ const summaryEntry = createFullMessageEntry("user", `This session is being continued from a previous conversation that ran out of context. The conversation is summarized below:\n${summaryText}`);
94
+ // Set compactedUpTo to indicate all messages have been compacted into the summary
95
+ const lastMessageIndex = messagesToCompact.length - 1;
96
+ const newContextEntry = createContextEntry([summaryEntry], undefined, lastMessageIndex);
97
+ return {
98
+ newContextEntry,
99
+ metadata: {
100
+ action: "compacted",
101
+ messagesRemoved: messagesToCompact.length - 1,
102
+ tokensSaved: Math.round(ctx.currentTokens * 0.7),
103
+ summaryGenerated: true,
104
+ },
105
+ };
106
+ }
107
+ catch (error) {
108
+ logger.error("Compaction tool error", {
109
+ error: error instanceof Error ? error.message : String(error),
110
+ stack: error instanceof Error ? error.stack : undefined,
111
+ });
112
+ return {
113
+ newContextEntry: null,
114
+ metadata: {
115
+ action: "failed",
116
+ error: error instanceof Error ? error.message : String(error),
117
+ },
118
+ };
119
+ }
42
120
  };
@@ -106,7 +106,7 @@ export declare function createContextEntry(messages: Array<{
106
106
  } | {
107
107
  type: "full";
108
108
  message: SessionMessage;
109
- }>, timestamp?: string): ContextEntry;
109
+ }>, timestamp?: string, compactedUpTo?: number): ContextEntry;
110
110
  /**
111
111
  * Helper function to create a full message entry for context
112
112
  * Use this when hooks need to inject new messages into context
@@ -2,11 +2,15 @@
2
2
  * Helper function to create a new context entry
3
3
  * Use this when hooks want to create a new context snapshot
4
4
  */
5
- export function createContextEntry(messages, timestamp) {
6
- return {
5
+ export function createContextEntry(messages, timestamp, compactedUpTo) {
6
+ const entry = {
7
7
  timestamp: timestamp || new Date().toISOString(),
8
8
  messages,
9
9
  };
10
+ if (compactedUpTo !== undefined) {
11
+ entry.compactedUpTo = compactedUpTo;
12
+ }
13
+ return entry;
10
14
  }
11
15
  /**
12
16
  * Helper function to create a full message entry for context
@@ -1,4 +1,6 @@
1
1
  import type { AgentDefinition } from "../definition";
2
2
  import { type AgentRunner } from "./agent-runner";
3
3
  export type { AgentRunner };
4
- export declare const makeRunnerFromDefinition: (definition: AgentDefinition) => AgentRunner;
4
+ export declare const makeRunnerFromDefinition: (
5
+ definition: AgentDefinition,
6
+ ) => AgentRunner;