@townco/agent 0.1.51 → 0.1.52

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.
@@ -1,5 +1,3 @@
1
1
  import type { AgentDefinition } from "../definition";
2
2
  import { type AgentRunner } from "../runner";
3
- export declare function makeStdioTransport(
4
- agent: AgentRunner | AgentDefinition,
5
- ): void;
3
+ export declare function makeStdioTransport(agent: AgentRunner | AgentDefinition): void;
@@ -1,2 +1,7 @@
1
+ import { initializeOpenTelemetryFromEnv } from "../telemetry/setup.js";
2
+ // Initialize OpenTelemetry when this module is imported (if enabled)
3
+ if (process.env.ENABLE_TELEMETRY === "true") {
4
+ initializeOpenTelemetryFromEnv();
5
+ }
1
6
  export { makeStdioTransport } from "./cli";
2
7
  export { makeHttpTransport } from "./http";
package/dist/bin.js CHANGED
File without changes
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Quick script to verify Jaeger connectivity
3
+ * Run with: bun check-jaeger.ts
4
+ */
5
+ export {};
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Quick script to verify Jaeger connectivity
3
+ * Run with: bun check-jaeger.ts
4
+ */
5
+ export {}; // Make this a module for top-level await
6
+ console.log("šŸ” Checking Jaeger connectivity...\n");
7
+ // Check if Jaeger collector is accepting OTLP on gRPC port
8
+ const checkPort = async (port, protocol) => {
9
+ try {
10
+ const net = await import("node:net");
11
+ const socket = new net.Socket();
12
+ return new Promise((resolve) => {
13
+ socket.setTimeout(2000);
14
+ socket.on("connect", () => {
15
+ console.log(`āœ… ${protocol} port ${port} is accepting connections`);
16
+ socket.destroy();
17
+ resolve(true);
18
+ });
19
+ socket.on("timeout", () => {
20
+ console.log(`āŒ ${protocol} port ${port} timed out`);
21
+ socket.destroy();
22
+ resolve(false);
23
+ });
24
+ socket.on("error", (error) => {
25
+ console.log(`āŒ ${protocol} port ${port} not reachable: ${error.message}`);
26
+ resolve(false);
27
+ });
28
+ socket.connect(port, "localhost");
29
+ });
30
+ }
31
+ catch (error) {
32
+ console.log(`āŒ Error checking ${protocol} port ${port}:`, error);
33
+ return false;
34
+ }
35
+ };
36
+ // Check Jaeger ports
37
+ console.log("Checking Jaeger ports:");
38
+ console.log("─────────────────────────────");
39
+ await checkPort(4317, "OTLP gRPC"); // Collector OTLP gRPC
40
+ await checkPort(4318, "OTLP HTTP"); // Collector OTLP HTTP
41
+ await checkPort(16686, "UI "); // Query UI
42
+ console.log("\nšŸ” Checking Docker container...\n");
43
+ // Check if Jaeger container is running
44
+ try {
45
+ const { execSync } = await import("node:child_process");
46
+ const output = execSync("docker ps --filter name=jaeger --format '{{.Status}}'", {
47
+ encoding: "utf-8",
48
+ }).trim();
49
+ if (output) {
50
+ console.log(`āœ… Jaeger container is running: ${output}`);
51
+ // Check container logs for OTLP
52
+ try {
53
+ const logs = execSync("docker logs jaeger 2>&1 | tail -20", {
54
+ encoding: "utf-8",
55
+ });
56
+ console.log("\nšŸ“‹ Recent container logs:");
57
+ console.log("─────────────────────────────");
58
+ console.log(logs);
59
+ }
60
+ catch (e) {
61
+ console.log("āš ļø Could not fetch container logs");
62
+ }
63
+ }
64
+ else {
65
+ console.log("āŒ No Jaeger container running with name 'jaeger'");
66
+ console.log("\nšŸ’” Start Jaeger with:");
67
+ console.log("docker run -d --name jaeger \\");
68
+ console.log(" -e COLLECTOR_OTLP_ENABLED=true \\");
69
+ console.log(" -p 16686:16686 \\");
70
+ console.log(" -p 4317:4317 \\");
71
+ console.log(" -p 4318:4318 \\");
72
+ console.log(" jaegertracing/all-in-one:latest");
73
+ }
74
+ }
75
+ catch (error) {
76
+ console.log("āš ļø Could not check Docker container:", error);
77
+ }
78
+ console.log("\nšŸŽÆ Next steps:");
79
+ console.log("─────────────────────────────");
80
+ console.log("1. Make sure ports above show āœ…");
81
+ console.log("2. Run the test: ENABLE_TELEMETRY=true bun test-telemetry.ts");
82
+ console.log("3. Check UI: http://localhost:16686");
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Helper script to test makeSubagentsTool
4
+ *
5
+ * Usage:
6
+ * bun packages/agent/run-subagents.ts
7
+ * bun packages/agent/run-subagents.ts "your custom query here"
8
+ */
9
+ export {};
@@ -0,0 +1,110 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Helper script to test makeSubagentsTool
4
+ *
5
+ * Usage:
6
+ * bun packages/agent/run-subagents.ts
7
+ * bun packages/agent/run-subagents.ts "your custom query here"
8
+ */
9
+ import { makeSubagentsTool } from "./utils";
10
+ import { makeRunnerFromDefinition } from "./runner";
11
+ // Default query if none provided
12
+ const defaultQuery = "Can you search for news about artificial intelligence?";
13
+ const userQuery = process.argv[2] || defaultQuery;
14
+ console.log("🧪 Testing makeSubagentsTool\n");
15
+ console.log("Query:", userQuery);
16
+ console.log("─".repeat(60));
17
+ // Create a simple subagent definition
18
+ const simpleSubagent = {
19
+ model: "claude-sonnet-4-5-20250929",
20
+ systemPrompt: "You are a helpful research assistant. Provide concise, informative responses.",
21
+ tools: [
22
+ "web_search",
23
+ "todo_write",
24
+ ],
25
+ mcps: [],
26
+ };
27
+ // Create the coordinator agent with subagent tool
28
+ const coordinatorAgent = {
29
+ model: "claude-sonnet-4-5-20250929",
30
+ systemPrompt: `You are a coordinator agent that delegates tasks to specialized subagents.
31
+ When you receive a query, evaluate if it needs to be delegated to a subagent.
32
+ If so, use the Task tool with the appropriate subagent.`,
33
+ tools: [
34
+ makeSubagentsTool([
35
+ {
36
+ agentName: "researcher",
37
+ description: "Use this agent to research topics, search the web, and gather information",
38
+ path: import.meta.filename, // Points to itself as a simple test
39
+ },
40
+ {
41
+ agentName: "simple",
42
+ description: "Use this for general tasks that don't require specialized tools",
43
+ path: import.meta.filename,
44
+ },
45
+ ]),
46
+ ],
47
+ mcps: [],
48
+ };
49
+ // Run the test
50
+ async function runTest() {
51
+ console.log("\nšŸ“ Creating runner...");
52
+ const runner = makeRunnerFromDefinition(coordinatorAgent);
53
+ console.log("šŸš€ Running query...\n");
54
+ try {
55
+ const stream = runner.invoke({
56
+ prompt: [
57
+ {
58
+ type: "text",
59
+ text: userQuery,
60
+ },
61
+ ],
62
+ sessionId: "test-session",
63
+ messageId: "msg-1",
64
+ });
65
+ console.log("šŸ“Š Stream output:");
66
+ console.log("─".repeat(60));
67
+ let messageCount = 0;
68
+ let toolCallCount = 0;
69
+ let lastTextContent = "";
70
+ for await (const chunk of stream) {
71
+ messageCount++;
72
+ // Pretty print different types of chunks
73
+ if (chunk.type === "agent_message_chunk") {
74
+ const content = chunk.content;
75
+ if (content.type === "text" && content.text) {
76
+ process.stdout.write(content.text);
77
+ lastTextContent += content.text;
78
+ }
79
+ else if (content.type === "tool_use") {
80
+ toolCallCount++;
81
+ console.log(`\n\nšŸ”§ Tool Call #${toolCallCount}: ${content.name}`);
82
+ console.log(" Input:", JSON.stringify(content.input, null, 2).split('\n').join('\n '));
83
+ }
84
+ }
85
+ else if (chunk.type === "tool_result") {
86
+ console.log("\n\nāœ… Tool Result:");
87
+ console.log(" ", JSON.stringify(chunk, null, 2).split('\n').join('\n '));
88
+ }
89
+ else {
90
+ // Print other chunk types for debugging
91
+ console.log("\n\nšŸ“¦ Chunk:", JSON.stringify(chunk, null, 2));
92
+ }
93
+ }
94
+ console.log("\n\n" + "─".repeat(60));
95
+ console.log("✨ Test completed!");
96
+ console.log(` Total chunks: ${messageCount}`);
97
+ console.log(` Tool calls: ${toolCallCount}`);
98
+ console.log("─".repeat(60));
99
+ }
100
+ catch (error) {
101
+ console.error("\nāŒ Error during test:");
102
+ console.error(error);
103
+ process.exit(1);
104
+ }
105
+ }
106
+ // Run the test
107
+ runTest().catch((error) => {
108
+ console.error("Fatal error:", error);
109
+ process.exit(1);
110
+ });
@@ -1,6 +1,4 @@
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: (
5
- definition: AgentDefinition,
6
- ) => AgentRunner;
4
+ export declare const makeRunnerFromDefinition: (definition: AgentDefinition) => AgentRunner;
@@ -0,0 +1,36 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * Custom stream events emitted by subagent tools via config.writer
4
+ */
5
+ export declare const SubagentToolCallEventSchema: z.ZodObject<{
6
+ type: z.ZodLiteral<"tool_call">;
7
+ toolName: z.ZodString;
8
+ }, z.core.$strip>;
9
+ export declare const SubagentMessageEventSchema: z.ZodObject<{
10
+ type: z.ZodLiteral<"message">;
11
+ text: z.ZodString;
12
+ }, z.core.$strip>;
13
+ export declare const SubagentEventSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
14
+ type: z.ZodLiteral<"tool_call">;
15
+ toolName: z.ZodString;
16
+ }, z.core.$strip>, z.ZodObject<{
17
+ type: z.ZodLiteral<"message">;
18
+ text: z.ZodString;
19
+ }, z.core.$strip>], "type">;
20
+ export type SubagentToolCallEvent = z.infer<typeof SubagentToolCallEventSchema>;
21
+ export type SubagentMessageEvent = z.infer<typeof SubagentMessageEventSchema>;
22
+ export type SubagentEvent = z.infer<typeof SubagentEventSchema>;
23
+ /**
24
+ * Wrapper for subagent events that includes the parent tool call ID
25
+ */
26
+ export declare const CustomStreamChunkSchema: z.ZodObject<{
27
+ parentToolCallId: z.ZodString;
28
+ event: z.ZodDiscriminatedUnion<[z.ZodObject<{
29
+ type: z.ZodLiteral<"tool_call">;
30
+ toolName: z.ZodString;
31
+ }, z.core.$strip>, z.ZodObject<{
32
+ type: z.ZodLiteral<"message">;
33
+ text: z.ZodString;
34
+ }, z.core.$strip>], "type">;
35
+ }, z.core.$strip>;
36
+ export type CustomStreamChunk = z.infer<typeof CustomStreamChunkSchema>;
@@ -0,0 +1,23 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * Custom stream events emitted by subagent tools via config.writer
4
+ */
5
+ export const SubagentToolCallEventSchema = z.object({
6
+ type: z.literal("tool_call"),
7
+ toolName: z.string(),
8
+ });
9
+ export const SubagentMessageEventSchema = z.object({
10
+ type: z.literal("message"),
11
+ text: z.string(),
12
+ });
13
+ export const SubagentEventSchema = z.discriminatedUnion("type", [
14
+ SubagentToolCallEventSchema,
15
+ SubagentMessageEventSchema,
16
+ ]);
17
+ /**
18
+ * Wrapper for subagent events that includes the parent tool call ID
19
+ */
20
+ export const CustomStreamChunkSchema = z.object({
21
+ parentToolCallId: z.string(),
22
+ event: SubagentEventSchema,
23
+ });
@@ -364,9 +364,12 @@ export class LangchainAgent {
364
364
  }
365
365
  // Create tool span within the invocation context
366
366
  // This makes the tool span a child of the invocation span
367
+ const toolInputJson = JSON.stringify(toolCall.args);
367
368
  const toolSpan = context.with(invocationContext, () => telemetry.startSpan("agent.tool_call", {
368
369
  "tool.name": toolCall.name,
369
370
  "tool.id": toolCall.id,
371
+ "tool.input": toolInputJson,
372
+ "agent.session_id": req.sessionId,
370
373
  }));
371
374
  this.toolSpans.set(toolCall.id, toolSpan);
372
375
  telemetry.log("info", `Tool call started: ${toolCall.name}`, {
@@ -553,6 +556,10 @@ export class LangchainAgent {
553
556
  // End telemetry span for this tool call
554
557
  const toolSpan = this.toolSpans.get(aiMessage.tool_call_id);
555
558
  if (toolSpan) {
559
+ // Add tool output to span before ending
560
+ telemetry.setSpanAttributes(toolSpan, {
561
+ "tool.output": aiMessage.content,
562
+ });
556
563
  telemetry.log("info", "Tool call completed", {
557
564
  toolCallId: aiMessage.tool_call_id,
558
565
  });
@@ -1,4 +1,4 @@
1
- import { context } from "@opentelemetry/api";
1
+ import { context, trace } from "@opentelemetry/api";
2
2
  import { telemetry } from "../../telemetry/index.js";
3
3
  /**
4
4
  * OpenTelemetry callback handler for LangChain LLM calls.
@@ -45,6 +45,38 @@ function extractSystemPrompt(messages) {
45
45
  return undefined;
46
46
  }
47
47
  }
48
+ /**
49
+ * Serializes LLM output to a string for logging.
50
+ * Preserves the raw provider format (content blocks, tool_calls, etc.)
51
+ */
52
+ function serializeOutput(output) {
53
+ try {
54
+ const generations = output.generations.flat();
55
+ const serialized = generations.map((gen) => {
56
+ // ChatGeneration has a message property with the full AIMessage
57
+ const chatGen = gen;
58
+ if (chatGen.message) {
59
+ const msg = chatGen.message;
60
+ const result = {
61
+ role: msg._getType?.() ?? "assistant",
62
+ content: msg.content, // Keep as-is: string or ContentBlock[]
63
+ };
64
+ // Include tool_calls if present (LangChain's normalized format)
65
+ const aiMsg = msg;
66
+ if (aiMsg.tool_calls && aiMsg.tool_calls.length > 0) {
67
+ result.tool_calls = aiMsg.tool_calls;
68
+ }
69
+ return result;
70
+ }
71
+ // Fallback for non-chat generations
72
+ return { text: gen.text };
73
+ });
74
+ return JSON.stringify(serialized);
75
+ }
76
+ catch (error) {
77
+ return `[Error serializing output: ${error}]`;
78
+ }
79
+ }
48
80
  /**
49
81
  * Creates OpenTelemetry callback handlers for LangChain LLM calls.
50
82
  * These handlers instrument model invocations with OTEL spans and record token usage.
@@ -84,6 +116,18 @@ export function makeOtelCallbacks(opts) {
84
116
  }));
85
117
  if (span) {
86
118
  spansByRunId.set(runId, span);
119
+ // Emit log for LLM request with trace context
120
+ const spanContext = span.spanContext();
121
+ telemetry.log("info", "LLM Request", {
122
+ "gen_ai.operation.name": "chat",
123
+ "gen_ai.provider.name": opts.provider,
124
+ "gen_ai.request.model": opts.model,
125
+ "gen_ai.input.messages": serializedMessages,
126
+ "langchain.run_id": runId,
127
+ // Include trace context for correlation
128
+ trace_id: spanContext.traceId,
129
+ span_id: spanContext.spanId,
130
+ });
87
131
  }
88
132
  },
89
133
  /**
@@ -105,6 +149,28 @@ export function makeOtelCallbacks(opts) {
105
149
  : 0);
106
150
  telemetry.recordTokenUsage(inputTokens, outputTokens, span);
107
151
  }
152
+ // Serialize output and attach to span
153
+ const serializedOutput = serializeOutput(output);
154
+ telemetry.setSpanAttributes(span, {
155
+ "gen_ai.output.messages": serializedOutput,
156
+ });
157
+ // Emit log for LLM response with trace context
158
+ const spanContext = span.spanContext();
159
+ telemetry.log("info", "LLM Response", {
160
+ "gen_ai.operation.name": "chat",
161
+ "gen_ai.output.messages": serializedOutput,
162
+ "langchain.run_id": runId,
163
+ // Include token usage in log
164
+ ...(tokenUsage
165
+ ? {
166
+ "gen_ai.usage.input_tokens": tokenUsage.inputTokens ?? 0,
167
+ "gen_ai.usage.output_tokens": tokenUsage.outputTokens ?? 0,
168
+ }
169
+ : {}),
170
+ // Include trace context for correlation
171
+ trace_id: spanContext.traceId,
172
+ span_id: spanContext.spanId,
173
+ });
108
174
  telemetry.endSpan(span);
109
175
  spansByRunId.delete(runId);
110
176
  },
@@ -0,0 +1,14 @@
1
+ import { z } from "zod";
2
+ export declare function makeBashTool(workingDirectory?: string): import("langchain").DynamicStructuredTool<z.ZodObject<{
3
+ command: z.ZodString;
4
+ timeout: z.ZodOptional<z.ZodNumber>;
5
+ description: z.ZodOptional<z.ZodString>;
6
+ }, z.core.$strip>, {
7
+ command: string;
8
+ timeout?: number | undefined;
9
+ description?: string | undefined;
10
+ }, {
11
+ command: string;
12
+ timeout?: number | undefined;
13
+ description?: string | undefined;
14
+ }, unknown>;
@@ -0,0 +1,135 @@
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,7 +1,8 @@
1
1
  /**
2
2
  * OpenTelemetry provider setup for @townco/agent
3
- * Initializes the trace provider, exporter, and propagator
3
+ * Initializes the trace provider, log provider, exporters, and propagator
4
4
  */
5
+ import { LoggerProvider } from "@opentelemetry/sdk-logs";
5
6
  import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
6
7
  export interface TelemetrySetupOptions {
7
8
  serviceName?: string;
@@ -14,6 +15,7 @@ export interface TelemetrySetupOptions {
14
15
  */
15
16
  export declare function initializeOpenTelemetry(options?: TelemetrySetupOptions): {
16
17
  provider: NodeTracerProvider;
18
+ loggerProvider: LoggerProvider;
17
19
  shutdown: () => Promise<void>;
18
20
  };
19
21
  /**