@townco/agent 0.1.52 → 0.1.53

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 (38) hide show
  1. package/dist/acp-server/adapter.d.ts +2 -0
  2. package/dist/acp-server/adapter.js +28 -3
  3. package/dist/acp-server/cli.d.ts +3 -1
  4. package/dist/acp-server/session-storage.d.ts +2 -0
  5. package/dist/acp-server/session-storage.js +2 -0
  6. package/dist/bin.js +0 -0
  7. package/dist/definition/mcp.d.ts +0 -0
  8. package/dist/definition/mcp.js +0 -0
  9. package/dist/definition/tools/todo.d.ts +49 -0
  10. package/dist/definition/tools/todo.js +80 -0
  11. package/dist/definition/tools/web_search.d.ts +4 -0
  12. package/dist/definition/tools/web_search.js +26 -0
  13. package/dist/dev-agent/index.d.ts +2 -0
  14. package/dist/dev-agent/index.js +18 -0
  15. package/dist/example.d.ts +2 -0
  16. package/dist/example.js +19 -0
  17. package/dist/runner/agent-runner.d.ts +4 -0
  18. package/dist/runner/index.d.ts +3 -1
  19. package/dist/runner/langchain/index.d.ts +0 -1
  20. package/dist/runner/langchain/index.js +88 -27
  21. package/dist/tsconfig.tsbuildinfo +1 -1
  22. package/dist/utils/__tests__/tool-overhead-calculator.test.d.ts +1 -0
  23. package/dist/utils/__tests__/tool-overhead-calculator.test.js +153 -0
  24. package/dist/utils/context-size-calculator.d.ts +9 -4
  25. package/dist/utils/context-size-calculator.js +23 -6
  26. package/dist/utils/tool-overhead-calculator.d.ts +30 -0
  27. package/dist/utils/tool-overhead-calculator.js +54 -0
  28. package/package.json +6 -6
  29. package/dist/check-jaeger.d.ts +0 -5
  30. package/dist/check-jaeger.js +0 -82
  31. package/dist/run-subagents.d.ts +0 -9
  32. package/dist/run-subagents.js +0 -110
  33. package/dist/runner/langchain/custom-stream-types.d.ts +0 -36
  34. package/dist/runner/langchain/custom-stream-types.js +0 -23
  35. package/dist/runner/langchain/tools/bash.d.ts +0 -14
  36. package/dist/runner/langchain/tools/bash.js +0 -135
  37. package/dist/test-telemetry.d.ts +0 -5
  38. package/dist/test-telemetry.js +0 -88
@@ -1,135 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import { once } from "node:events";
3
- import * as path from "node:path";
4
- import { SandboxManager, } from "@anthropic-ai/sandbox-runtime";
5
- import { tool } from "langchain";
6
- import { z } from "zod";
7
- /**
8
- * Lazily initialize Sandbox Runtime with write access limited to workingDirectory.
9
- */
10
- let initialized = false;
11
- async function ensureSandbox(workingDirectory) {
12
- if (initialized)
13
- return;
14
- const cfg = {
15
- network: {
16
- // No outbound network needed for basic bash commands; block by default.
17
- allowedDomains: [],
18
- deniedDomains: [],
19
- },
20
- filesystem: {
21
- // Allow writes only within the configured sandbox directory.
22
- allowWrite: [workingDirectory],
23
- denyWrite: [],
24
- // Optional: harden reads a bit (deny common sensitive dirs)
25
- denyRead: ["~/.ssh", "~/.gnupg", "/etc/ssh"],
26
- },
27
- };
28
- await SandboxManager.initialize(cfg);
29
- initialized = true;
30
- }
31
- /** Run a command string inside the sandbox, returning { stdout, stderr, code, timedOut }. */
32
- async function runSandboxed(cmd, cwd, timeoutMs) {
33
- const wrapped = await SandboxManager.wrapWithSandbox(cmd);
34
- const child = spawn(wrapped, { shell: true, cwd });
35
- const stdout = [];
36
- const stderr = [];
37
- child.stdout?.on("data", (d) => stdout.push(Buffer.from(d)));
38
- child.stderr?.on("data", (d) => stderr.push(Buffer.from(d)));
39
- let timedOut = false;
40
- let timeoutHandle;
41
- // Set up timeout if specified
42
- if (timeoutMs !== undefined && timeoutMs > 0) {
43
- timeoutHandle = setTimeout(() => {
44
- timedOut = true;
45
- child.kill("SIGTERM");
46
- // If process doesn't exit after SIGTERM, force kill after 1 second
47
- setTimeout(() => {
48
- if (!child.killed) {
49
- child.kill("SIGKILL");
50
- }
51
- }, 1000);
52
- }, timeoutMs);
53
- }
54
- const [code] = (await once(child, "exit"));
55
- if (timeoutHandle) {
56
- clearTimeout(timeoutHandle);
57
- }
58
- return {
59
- stdout: Buffer.concat(stdout),
60
- stderr: Buffer.concat(stderr),
61
- code: code ?? 1,
62
- timedOut,
63
- };
64
- }
65
- /** Truncate output if it exceeds the maximum length. */
66
- function truncateOutput(output, maxLength = 30000) {
67
- if (output.length <= maxLength) {
68
- return output;
69
- }
70
- return `${output.slice(0, maxLength)}\n\n... (output truncated, ${output.length - maxLength} characters omitted)`;
71
- }
72
- export function makeBashTool(workingDirectory) {
73
- const resolvedWd = path.resolve(workingDirectory ?? process.cwd());
74
- const bash = tool(async ({ command, timeout, description }) => {
75
- await ensureSandbox(resolvedWd);
76
- // Validate timeout
77
- const DEFAULT_TIMEOUT = 120000; // 2 minutes
78
- const MAX_TIMEOUT = 600000; // 10 minutes
79
- let timeoutMs = timeout ?? DEFAULT_TIMEOUT;
80
- if (timeoutMs > MAX_TIMEOUT) {
81
- throw new Error(`Timeout cannot exceed ${MAX_TIMEOUT}ms (10 minutes), got ${timeoutMs}ms`);
82
- }
83
- if (timeoutMs < 0) {
84
- throw new Error(`Timeout must be positive, got ${timeoutMs}ms`);
85
- }
86
- // Execute the command
87
- const startTime = Date.now();
88
- const { stdout, stderr, code, timedOut } = await runSandboxed(command, resolvedWd, timeoutMs);
89
- const executionTime = Date.now() - startTime;
90
- // Convert buffers to strings
91
- const stdoutStr = stdout.toString("utf8");
92
- const stderrStr = stderr.toString("utf8");
93
- // Truncate outputs if necessary
94
- const truncatedStdout = truncateOutput(stdoutStr);
95
- const truncatedStderr = truncateOutput(stderrStr);
96
- // Build result message
97
- let result = "";
98
- if (timedOut) {
99
- result += `Command timed out after ${timeoutMs}ms\n\n`;
100
- }
101
- if (truncatedStdout) {
102
- result += truncatedStdout;
103
- }
104
- if (truncatedStderr) {
105
- if (result)
106
- result += "\n\n";
107
- result += `STDERR:\n${truncatedStderr}`;
108
- }
109
- if (!truncatedStdout && !truncatedStderr) {
110
- result = "(no output)";
111
- }
112
- // Add exit code info
113
- result += `\n\nExit code: ${code}`;
114
- if (description) {
115
- result += `\nDescription: ${description}`;
116
- }
117
- result += `\nExecution time: ${executionTime}ms`;
118
- return result;
119
- }, {
120
- name: "Bash",
121
- description: 'Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures.\n\nBefore executing the command, please follow these steps:\n\n1. Directory Verification:\n - If the command will create new directories or files, first use `ls` to verify the parent directory exists and is the correct location\n - For example, before running "mkdir foo/bar", first use `ls foo` to check that "foo" exists and is the intended parent directory\n\n2. Command Execution:\n - Always quote file paths that contain spaces with double quotes (e.g., cd "path with spaces/file.txt")\n - Examples of proper quoting:\n - cd "/Users/name/My Documents" (correct)\n - cd /Users/name/My Documents (incorrect - will fail)\n - python "/path/with spaces/script.py" (correct)\n - python /path/with spaces/script.py (incorrect - will fail)\n - After ensuring proper quoting, execute the command.\n - Capture the output of the command.\n\nUsage notes:\n - The command argument is required.\n - You can specify an optional timeout in milliseconds (up to 600000ms / 10 minutes). If not specified, commands will timeout after 120000ms (2 minutes).\n - It is very helpful if you write a clear, concise description of what this command does in 5-10 words.\n - If the output exceeds 30000 characters, output will be truncated before being returned to you.\n - You can use the `run_in_background` parameter to run the command in the background, which allows you to continue working while the command runs. You can monitor the output using the Bash tool as it becomes available. Never use `run_in_background` to run \'sleep\' as it will return immediately. You do not need to use \'&\' at the end of the command when using this parameter.\n - VERY IMPORTANT: You MUST avoid using search commands like `find` and `grep`. Instead use Grep, Glob, or Task to search. You MUST avoid read tools like `cat`, `head`, and `tail`, and use Read to read files.\n - If you _still_ need to run `grep`, STOP. ALWAYS USE ripgrep at `rg` first, which all Claude Code users have pre-installed.\n - When issuing multiple commands, use the \';\' or \'&&\' operator to separate them. DO NOT use newlines (newlines are ok in quoted strings).\n - Try to maintain your current working directory throughout the session by using absolute paths and avoiding usage of `cd`. You may use `cd` if the User explicitly requests it.\n <good-example>\n pytest /foo/bar/tests\n </good-example>\n <bad-example>\n cd /foo/bar && pytest tests\n </bad-example>\n\n# Committing changes with git\n\nWhen the user asks you to create a new git commit, follow these steps carefully:\n\n1. You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. ALWAYS run the following bash commands in parallel, each using the Bash tool:\n - Run a git status command to see all untracked files.\n - Run a git diff command to see both staged and unstaged changes that will be committed.\n - Run a git log command to see recent commit messages, so that you can follow this repository\'s commit message style.\n2. Analyze all staged changes (both previously staged and newly added) and draft a commit message:\n - Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.). Ensure the message accurately reflects the changes and their purpose (i.e. "add" means a wholly new feature, "update" means an enhancement to an existing feature, "fix" means a bug fix, etc.).\n - Check for any sensitive information that shouldn\'t be committed\n - Draft a concise (1-2 sentences) commit message that focuses on the "why" rather than the "what"\n - Ensure it accurately reflects the changes and their purpose\n3. You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. ALWAYS run the following commands in parallel:\n - Add relevant untracked files to the staging area.\n - Create the commit with a message ending with:\n šŸ¤– Generated with [Claude Code](https://claude.ai/code)\n\n Co-Authored-By: Claude <noreply@anthropic.com>\n - Run git status to make sure the commit succeeded.\n4. If the commit fails due to pre-commit hook changes, retry the commit ONCE to include these automated changes. If it fails again, it usually means a pre-commit hook is preventing the commit. If the commit succeeds but you notice that files were modified by the pre-commit hook, you MUST amend your commit to include them.\n\nImportant notes:\n- NEVER update the git config\n- NEVER run additional commands to read or explore code, besides git bash commands\n- NEVER use the TodoWrite or Task tools\n- DO NOT push to the remote repository unless the user explicitly asks you to do so\n- IMPORTANT: Never use git commands with the -i flag (like git rebase -i or git add -i) since they require interactive input which is not supported.\n- If there are no changes to commit (i.e., no untracked files and no modifications), do not create an empty commit\n- In order to ensure good formatting, ALWAYS pass the commit message via a HEREDOC, a la this example:\n<example>\ngit commit -m "$(cat <<\'EOF\'\n Commit message here.\n\n šŸ¤– Generated with [Claude Code](https://claude.ai/code)\n\n Co-Authored-By: Claude <noreply@anthropic.com>\n EOF\n )"\n</example>\n\n# Creating pull requests\nUse the gh command via the Bash tool for ALL GitHub-related tasks including working with issues, pull requests, checks, and releases. If given a Github URL use the gh command to get the information needed.\n\nIMPORTANT: When the user asks you to create a pull request, follow these steps carefully:\n\n1. You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. ALWAYS run the following bash commands in parallel using the Bash tool, in order to understand the current state of the branch since it diverged from the main branch:\n - Run a git status command to see all untracked files\n - Run a git diff command to see both staged and unstaged changes that will be committed\n - Check if the current branch tracks a remote branch and is up to date with the remote, so you know if you need to push to the remote\n - Run a git log command and `git diff [base-branch]...HEAD` to understand the full commit history for the current branch (from the time it diverged from the base branch)\n2. Analyze all changes that will be included in the pull request, making sure to look at all relevant commits (NOT just the latest commit, but ALL commits that will be included in the pull request!!!), and draft a pull request summary\n3. You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. ALWAYS run the following commands in parallel:\n - Create new branch if needed\n - Push to remote with -u flag if needed\n - Create PR using gh pr create with the format below. Use a HEREDOC to pass the body to ensure correct formatting.\n<example>\ngh pr create --title "the pr title" --body "$(cat <<\'EOF\'\n## Summary\n<1-3 bullet points>\n\n## Test plan\n[Checklist of TODOs for testing the pull request...]\n\nšŸ¤– Generated with [Claude Code](https://claude.ai/code)\nEOF\n)"\n</example>\n\nImportant:\n- NEVER update the git config\n- DO NOT use the TodoWrite or Task tools\n- Return the PR URL when you\'re done, so the user can see it\n\n# Other common operations\n- View comments on a Github PR: gh api repos/foo/bar/pulls/123/comments',
122
- schema: z.object({
123
- command: z.string().describe("The command to execute"),
124
- timeout: z
125
- .number()
126
- .optional()
127
- .describe("Optional timeout in milliseconds (max 600000)"),
128
- description: z
129
- .string()
130
- .optional()
131
- .describe("Clear, concise description of what this command does in 5-10 words, in active voice. Examples:\nInput: ls\nOutput: List files in current directory\n\nInput: git status\nOutput: Show working tree status\n\nInput: npm install\nOutput: Install package dependencies\n\nInput: mkdir foo\nOutput: Create directory 'foo'"),
132
- }),
133
- });
134
- return bash;
135
- }
@@ -1,5 +0,0 @@
1
- /**
2
- * Simple test script to verify OpenTelemetry is working
3
- * Run with: ENABLE_TELEMETRY=true DEBUG_TELEMETRY=true bun test-telemetry.ts
4
- */
5
- export {};
@@ -1,88 +0,0 @@
1
- /**
2
- * Simple test script to verify OpenTelemetry is working
3
- * Run with: ENABLE_TELEMETRY=true DEBUG_TELEMETRY=true bun test-telemetry.ts
4
- */
5
- import { makeRunnerFromDefinition } from "./runner/index.js";
6
- import { configureTelemetry } from "./telemetry/index.js";
7
- // Initialize OpenTelemetry
8
- console.log("šŸ”§ Initializing OpenTelemetry...");
9
- const { NodeTracerProvider } = await import("@opentelemetry/sdk-trace-node");
10
- const { BatchSpanProcessor } = await import("@opentelemetry/sdk-trace-base");
11
- const { OTLPTraceExporter } = await import("@opentelemetry/exporter-trace-otlp-grpc");
12
- const { Resource } = await import("@opentelemetry/resources");
13
- const { ATTR_SERVICE_NAME } = await import("@opentelemetry/semantic-conventions");
14
- const serviceName = "test-agent";
15
- const otlpEndpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT ?? "http://localhost:4317";
16
- console.log(`šŸ“” Service: ${serviceName}`);
17
- console.log(`šŸ“” Endpoint: ${otlpEndpoint}`);
18
- const provider = new NodeTracerProvider({
19
- resource: new Resource({
20
- [ATTR_SERVICE_NAME]: serviceName,
21
- }),
22
- });
23
- const exporter = new OTLPTraceExporter({
24
- url: otlpEndpoint,
25
- });
26
- provider.addSpanProcessor(new BatchSpanProcessor(exporter));
27
- provider.register();
28
- configureTelemetry({
29
- enabled: true,
30
- serviceName,
31
- attributes: {
32
- "test.run": "true",
33
- },
34
- });
35
- console.log("āœ… OpenTelemetry initialized\n");
36
- // Create a simple test agent
37
- console.log("šŸ¤– Creating test agent...");
38
- const runner = makeRunnerFromDefinition({
39
- model: "claude-sonnet-4-5-20250929",
40
- systemPrompt: "You are a helpful assistant. Keep responses brief.",
41
- tools: ["get_weather"],
42
- });
43
- console.log("āœ… Agent created\n");
44
- // Run a simple test invocation
45
- console.log("šŸš€ Running test invocation...");
46
- const result = runner.invoke({
47
- prompt: [
48
- {
49
- type: "text",
50
- text: "What's the weather like in San Francisco?",
51
- },
52
- ],
53
- sessionId: "test-session-123",
54
- messageId: "test-msg-1",
55
- });
56
- console.log("šŸ“Ø Processing response...\n");
57
- let tokenCount = 0;
58
- let toolCalls = 0;
59
- for await (const chunk of result) {
60
- if (chunk.sessionUpdate === "tool_call") {
61
- console.log(`šŸ”§ Tool called: ${chunk.title}`);
62
- toolCalls++;
63
- }
64
- else if (chunk.sessionUpdate === "agent_message_chunk") {
65
- if (chunk.content.type === "text") {
66
- process.stdout.write(chunk.content.text);
67
- }
68
- if (chunk._meta &&
69
- "tokenUsage" in chunk._meta &&
70
- chunk._meta.tokenUsage &&
71
- typeof chunk._meta.tokenUsage === "object" &&
72
- "outputTokens" in chunk._meta.tokenUsage) {
73
- tokenCount += chunk._meta.tokenUsage.outputTokens ?? 0;
74
- }
75
- }
76
- }
77
- console.log("\n\nāœ… Test completed!");
78
- console.log(`šŸ“Š Stats: ${toolCalls} tool calls, ~${tokenCount} output tokens`);
79
- // Force flush before exit
80
- console.log("\nā³ Flushing telemetry data...");
81
- await provider.forceFlush();
82
- console.log("āœ… Telemetry flushed!");
83
- console.log("\nšŸŽÆ Check Jaeger UI at: http://localhost:16686");
84
- console.log(` Service: ${serviceName}`);
85
- console.log(` Look for "agent.invoke" spans`);
86
- // Give a moment for final flush
87
- await new Promise((resolve) => setTimeout(resolve, 1000));
88
- process.exit(0);