@posthog/agent 1.13.0 → 1.15.0

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 (42) hide show
  1. package/README.md +110 -0
  2. package/dist/src/agent.d.ts +3 -1
  3. package/dist/src/agent.d.ts.map +1 -1
  4. package/dist/src/agent.js +7 -0
  5. package/dist/src/agent.js.map +1 -1
  6. package/dist/src/agents/execution.d.ts +1 -1
  7. package/dist/src/agents/execution.d.ts.map +1 -1
  8. package/dist/src/agents/execution.js +27 -43
  9. package/dist/src/agents/execution.js.map +1 -1
  10. package/dist/src/agents/planning.d.ts +1 -1
  11. package/dist/src/agents/planning.d.ts.map +1 -1
  12. package/dist/src/agents/planning.js +60 -66
  13. package/dist/src/agents/planning.js.map +1 -1
  14. package/dist/src/agents/research.d.ts +1 -1
  15. package/dist/src/agents/research.d.ts.map +1 -1
  16. package/dist/src/agents/research.js +68 -88
  17. package/dist/src/agents/research.js.map +1 -1
  18. package/dist/src/prompt-builder.d.ts.map +1 -1
  19. package/dist/src/prompt-builder.js +68 -35
  20. package/dist/src/prompt-builder.js.map +1 -1
  21. package/dist/src/types.d.ts +4 -1
  22. package/dist/src/types.d.ts.map +1 -1
  23. package/dist/src/types.js.map +1 -1
  24. package/dist/src/workflow/steps/build.d.ts.map +1 -1
  25. package/dist/src/workflow/steps/build.js +22 -0
  26. package/dist/src/workflow/steps/build.js.map +1 -1
  27. package/dist/src/workflow/steps/plan.d.ts.map +1 -1
  28. package/dist/src/workflow/steps/plan.js +13 -0
  29. package/dist/src/workflow/steps/plan.js.map +1 -1
  30. package/dist/src/workflow/steps/research.d.ts.map +1 -1
  31. package/dist/src/workflow/steps/research.js +12 -0
  32. package/dist/src/workflow/steps/research.js.map +1 -1
  33. package/package.json +1 -1
  34. package/src/agent.ts +10 -2
  35. package/src/agents/execution.ts +27 -43
  36. package/src/agents/planning.ts +60 -66
  37. package/src/agents/research.ts +68 -88
  38. package/src/prompt-builder.ts +71 -35
  39. package/src/types.ts +12 -0
  40. package/src/workflow/steps/build.ts +23 -0
  41. package/src/workflow/steps/plan.ts +13 -0
  42. package/src/workflow/steps/research.ts +12 -0
package/README.md CHANGED
@@ -145,3 +145,113 @@ await agent.runTask(task, {
145
145
  }
146
146
  });
147
147
  ```
148
+
149
+ ## Fine-Grained Permissions
150
+
151
+ For advanced control over agent actions, you can provide a `canUseTool` callback that intercepts every tool use during the **build phase** (for task execution) or **direct run calls**. This allows you to implement custom approval flows, logging, or restrictions.
152
+
153
+ See the [Claude Agent SDK Permissions docs](https://docs.claude.com/en/api/agent-sdk/permissions) for more details.
154
+
155
+ ### Per-Agent Configuration
156
+
157
+ Apply the same permission hook to all task executions and direct runs:
158
+
159
+ ```typescript
160
+ import { Agent } from '@posthog/agent';
161
+ import type { PermissionResult } from '@posthog/agent';
162
+
163
+ const agent = new Agent({
164
+ workingDirectory: "/path/to/repo",
165
+ posthogApiUrl: "https://app.posthog.com",
166
+ posthogApiKey: process.env.POSTHOG_API_KEY,
167
+ canUseTool: async (toolName, input, { signal, suggestions }) => {
168
+ // Block destructive commands
169
+ if (toolName === 'Bash' && input.command?.includes('rm -rf')) {
170
+ return {
171
+ behavior: 'deny',
172
+ message: 'Destructive rm -rf commands are not allowed',
173
+ interrupt: true
174
+ };
175
+ }
176
+
177
+ // Allow everything else
178
+ return {
179
+ behavior: 'allow',
180
+ updatedInput: input
181
+ };
182
+ }
183
+ });
184
+ ```
185
+
186
+ ### Per-Task Configuration
187
+
188
+ Override permissions for specific tasks (only applied during build phase):
189
+
190
+ ```typescript
191
+ await agent.runTask(task, {
192
+ repositoryPath: "/path/to/repo",
193
+ permissionMode: PermissionMode.DEFAULT,
194
+ canUseTool: async (toolName, input, { signal, suggestions }) => {
195
+ // Custom approval UI
196
+ const approved = await showApprovalDialog({
197
+ tool: toolName,
198
+ input: input,
199
+ suggestions: suggestions // Permission updates for "always allow"
200
+ });
201
+
202
+ if (approved.action === 'allow') {
203
+ return {
204
+ behavior: 'allow',
205
+ updatedInput: approved.modifiedInput || input,
206
+ updatedPermissions: approved.rememberChoice ? suggestions : undefined
207
+ };
208
+ }
209
+
210
+ return {
211
+ behavior: 'deny',
212
+ message: approved.reason || 'User denied permission',
213
+ interrupt: !approved.continueWithGuidance
214
+ };
215
+ }
216
+ });
217
+ ```
218
+
219
+ ### Direct Run Example
220
+
221
+ For one-off queries with custom permissions:
222
+
223
+ ```typescript
224
+ const result = await agent.run("Fix the authentication bug", {
225
+ repositoryPath: "/path/to/repo",
226
+ permissionMode: PermissionMode.DEFAULT,
227
+ canUseTool: async (toolName, input, { signal }) => {
228
+ console.log(`Agent wants to use ${toolName}:`, input);
229
+
230
+ // Simple approval logic
231
+ if (toolName === 'Write' || toolName === 'Edit') {
232
+ const allowedFiles = ['src/', 'tests/'];
233
+ const filePath = input.file_path || input.path;
234
+ const isAllowed = allowedFiles.some(prefix => filePath?.startsWith(prefix));
235
+
236
+ if (!isAllowed) {
237
+ return {
238
+ behavior: 'deny',
239
+ message: `Can only modify files in: ${allowedFiles.join(', ')}`
240
+ };
241
+ }
242
+ }
243
+
244
+ return { behavior: 'allow', updatedInput: input };
245
+ }
246
+ });
247
+ ```
248
+
249
+ ### Available Tool Names
250
+
251
+ The `canUseTool` callback receives one of these tool names:
252
+ - **Read-only**: `Read`, `Glob`, `Grep`, `WebFetch`, `WebSearch`, `ListMcpResources`, `ReadMcpResource`
253
+ - **Modifications**: `Write`, `Edit`, `NotebookEdit`
254
+ - **Execution**: `Bash`, `BashOutput`, `KillBash`, `Task`
255
+ - **Planning**: `ExitPlanMode`, `TodoWrite`
256
+
257
+ **Note**: Research and planning phases have fixed, read-only tool sets. The `canUseTool` hook only applies to the build phase and direct run calls.
@@ -1,4 +1,4 @@
1
- import type { Task, ExecutionResult, AgentConfig } from './types.js';
1
+ import type { Task, ExecutionResult, AgentConfig, CanUseTool } from './types.js';
2
2
  import { PostHogAPIClient } from './posthog-api.js';
3
3
  import { type ExtractedQuestion, type ExtractedQuestionWithAnswer } from './structured-extraction.js';
4
4
  export declare class Agent {
@@ -15,6 +15,7 @@ export declare class Agent {
15
15
  private promptBuilder;
16
16
  private extractor?;
17
17
  private mcpServers?;
18
+ private canUseTool?;
18
19
  debug: boolean;
19
20
  constructor(config?: AgentConfig);
20
21
  /**
@@ -30,6 +31,7 @@ export declare class Agent {
30
31
  repositoryPath?: string;
31
32
  permissionMode?: import('./types.js').PermissionMode;
32
33
  queryOverrides?: Record<string, any>;
34
+ canUseTool?: CanUseTool;
33
35
  }): Promise<ExecutionResult>;
34
36
  fetchTask(taskId: string): Promise<Task>;
35
37
  getPostHogClient(): PostHogAPIClient | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../../src/agent.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAErE,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AASpD,OAAO,EAA4C,KAAK,iBAAiB,EAAE,KAAK,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AAIhJ,qBAAa,KAAK;IACd,OAAO,CAAC,gBAAgB,CAAS;IACjC,OAAO,CAAC,OAAO,CAAC,CAAuB;IACvC,OAAO,CAAC,WAAW,CAAc;IACjC,OAAO,CAAC,UAAU,CAAC,CAAmB;IACtC,OAAO,CAAC,WAAW,CAAqB;IACxC,OAAO,CAAC,UAAU,CAAa;IAC/B,OAAO,CAAC,eAAe,CAAkB;IACzC,OAAO,CAAC,OAAO,CAAkB;IACjC,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,gBAAgB,CAAuB;IAC/C,OAAO,CAAC,aAAa,CAAgB;IACrC,OAAO,CAAC,SAAS,CAAC,CAAsB;IACxC,OAAO,CAAC,UAAU,CAAC,CAAsB;IAClC,KAAK,EAAE,OAAO,CAAC;gBAEV,MAAM,GAAE,WAAgB;IA8DpC;;OAEG;IACH,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0B,CAAC,MAAM,EAAE,MAAM,EAAE,kBAAkB,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAOxF,oBAAoB,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAO9F,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAuBlH,uBAAuB,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAoB1F,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAczE,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAUhC,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI;YAUvC,iBAAiB;IAqB/B,OAAO,CAAC,sBAAsB;YAiBhB,iBAAiB;IAsC/B,OAAO,CAAC,SAAS;CAapB;AAED,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,YAAY,EAAE,IAAI,EAAE,cAAc,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC"}
package/dist/src/agent.js CHANGED
@@ -26,10 +26,12 @@ class Agent {
26
26
  promptBuilder;
27
27
  extractor;
28
28
  mcpServers;
29
+ canUseTool;
29
30
  debug;
30
31
  constructor(config = {}) {
31
32
  this.workingDirectory = config.workingDirectory || process.cwd();
32
33
  this.onEvent = config.onEvent;
34
+ this.canUseTool = config.canUseTool;
33
35
  this.debug = config.debug || false;
34
36
  // Build default PostHog MCP server configuration
35
37
  const posthogMcpUrl = config.posthogMcpUrl
@@ -162,6 +164,11 @@ class Agent {
162
164
  settingSources: ["local"],
163
165
  mcpServers: this.mcpServers,
164
166
  };
167
+ // Add canUseTool hook if provided (options take precedence over instance config)
168
+ const canUseTool = options.canUseTool || this.canUseTool;
169
+ if (canUseTool) {
170
+ baseOptions.canUseTool = canUseTool;
171
+ }
165
172
  const response = query({
166
173
  prompt,
167
174
  options: { ...baseOptions, ...(options.queryOverrides || {}) },
@@ -1 +1 @@
1
- {"version":3,"file":"agent.js","sources":["../../src/agent.ts"],"sourcesContent":["import { query } from \"@anthropic-ai/claude-agent-sdk\";\nimport type { Task, ExecutionResult, AgentConfig } from './types.js';\nimport { TaskManager } from './task-manager.js';\nimport { PostHogAPIClient } from './posthog-api.js';\nimport { PostHogFileManager } from './file-manager.js';\nimport { GitManager } from './git-manager.js';\nimport { TemplateManager } from './template-manager.js';\nimport { ClaudeAdapter } from './adapters/claude/claude-adapter.js';\nimport type { ProviderAdapter } from './adapters/types.js';\nimport { Logger } from './utils/logger.js';\nimport { PromptBuilder } from './prompt-builder.js';\nimport { TaskProgressReporter } from './task-progress-reporter.js';\nimport { AISDKExtractor, type StructuredExtractor, type ExtractedQuestion, type ExtractedQuestionWithAnswer } from './structured-extraction.js';\nimport { TASK_WORKFLOW } from './workflow/config.js';\nimport type { WorkflowRuntime } from './workflow/types.js';\n\nexport class Agent {\n private workingDirectory: string;\n private onEvent?: (event: any) => void;\n private taskManager: TaskManager;\n private posthogAPI?: PostHogAPIClient;\n private fileManager: PostHogFileManager;\n private gitManager: GitManager;\n private templateManager: TemplateManager;\n private adapter: ProviderAdapter;\n private logger: Logger;\n private progressReporter: TaskProgressReporter;\n private promptBuilder: PromptBuilder;\n private extractor?: StructuredExtractor;\n private mcpServers?: Record<string, any>;\n public debug: boolean;\n\n constructor(config: AgentConfig = {}) {\n this.workingDirectory = config.workingDirectory || process.cwd();\n this.onEvent = config.onEvent;\n this.debug = config.debug || false;\n\n // Build default PostHog MCP server configuration\n const posthogMcpUrl = config.posthogMcpUrl\n || process.env.POSTHOG_MCP_URL\n || 'https://mcp.posthog.com/mcp';\n\n // Add auth if API key provided\n const headers: Record<string, string> = {};\n if (config.posthogApiKey) {\n headers['Authorization'] = `Bearer ${config.posthogApiKey}`;\n }\n\n const defaultMcpServers = {\n posthog: {\n type: 'http' as const,\n url: posthogMcpUrl,\n ...(Object.keys(headers).length > 0 ? { headers } : {}),\n }\n };\n\n // Merge default PostHog MCP with user-provided servers (user config takes precedence)\n this.mcpServers = {\n ...defaultMcpServers,\n ...config.mcpServers\n };\n this.logger = new Logger({ debug: this.debug, prefix: '[PostHog Agent]' });\n this.taskManager = new TaskManager();\n // Hardcode Claude adapter for now - extensible for other providers later\n this.adapter = new ClaudeAdapter();\n\n this.fileManager = new PostHogFileManager(\n this.workingDirectory,\n this.logger.child('FileManager')\n );\n this.gitManager = new GitManager({\n repositoryPath: this.workingDirectory,\n logger: this.logger.child('GitManager')\n // TODO: Add author config from environment or config\n });\n this.templateManager = new TemplateManager();\n\n if (config.posthogApiUrl && config.posthogApiKey) {\n this.posthogAPI = new PostHogAPIClient({\n apiUrl: config.posthogApiUrl,\n apiKey: config.posthogApiKey,\n });\n }\n\n this.promptBuilder = new PromptBuilder({\n getTaskFiles: (taskId: string) => this.getTaskFiles(taskId),\n generatePlanTemplate: (vars) => this.templateManager.generatePlan(vars),\n posthogClient: this.posthogAPI,\n logger: this.logger.child('PromptBuilder')\n });\n this.progressReporter = new TaskProgressReporter(this.posthogAPI, this.logger);\n this.extractor = new AISDKExtractor(this.logger.child('AISDKExtractor'));\n }\n\n /**\n * Enable or disable debug logging\n */\n setDebug(enabled: boolean) {\n this.debug = enabled;\n this.logger.setDebug(enabled);\n }\n\n /**\n * Configure LLM gateway environment variables for Claude Code CLI\n */\n private async _configureLlmGateway(): Promise<void> {\n if (!this.posthogAPI) {\n return;\n }\n\n if (process.env.ANTHROPIC_BASE_URL && process.env.ANTHROPIC_AUTH_TOKEN) {\n this.ensureOpenAIGatewayEnv();\n return;\n }\n\n try {\n const gatewayUrl = await this.posthogAPI.getLlmGatewayUrl();\n const apiKey = this.posthogAPI.getApiKey();\n\n process.env.ANTHROPIC_BASE_URL = gatewayUrl;\n process.env.ANTHROPIC_AUTH_TOKEN = apiKey;\n this.ensureOpenAIGatewayEnv(gatewayUrl, apiKey);\n\n this.logger.debug('Configured LLM gateway', { gatewayUrl });\n } catch (error) {\n this.logger.error('Failed to configure LLM gateway', error);\n throw error;\n }\n }\n\n // Adaptive task execution orchestrated via workflow steps\n async runTask(taskOrId: Task | string, options: import('./types.js').TaskExecutionOptions = {}): Promise<void> {\n await this._configureLlmGateway();\n\n const task = typeof taskOrId === 'string' ? await this.fetchTask(taskOrId) : taskOrId;\n const cwd = options.repositoryPath || this.workingDirectory;\n const isCloudMode = options.isCloudMode ?? false;\n const taskSlug = (task as any).slug || task.id;\n\n this.logger.info('Starting adaptive task execution', { taskId: task.id, taskSlug, isCloudMode });\n\n // Initialize progress reporter for task run tracking (needed for PR attachment)\n await this.progressReporter.start(task.id, { totalSteps: TASK_WORKFLOW.length });\n this.emitEvent(this.adapter.createStatusEvent('run_started', { runId: this.progressReporter.runId }));\n\n await this.prepareTaskBranch(taskSlug, isCloudMode);\n\n const workflowContext: WorkflowRuntime = {\n task,\n taskSlug,\n cwd,\n isCloudMode,\n options,\n logger: this.logger,\n fileManager: this.fileManager,\n gitManager: this.gitManager,\n promptBuilder: this.promptBuilder,\n progressReporter: this.progressReporter,\n adapter: this.adapter,\n mcpServers: this.mcpServers,\n posthogAPI: this.posthogAPI,\n extractor: this.extractor,\n emitEvent: (event: any) => this.emitEvent(event),\n stepResults: {},\n };\n\n for (const step of TASK_WORKFLOW) {\n const result = await step.run({ step, context: workflowContext });\n if (result.halt) {\n return;\n }\n }\n\n if (isCloudMode) {\n await this.ensurePullRequest(task, workflowContext.stepResults);\n }\n\n await this.progressReporter.complete();\n this.logger.info('Task execution complete', { taskId: task.id });\n this.emitEvent(this.adapter.createStatusEvent('task_complete', { taskId: task.id }));\n }\n\n // Direct prompt execution - still supported for low-level usage\n async run(prompt: string, options: { repositoryPath?: string; permissionMode?: import('./types.js').PermissionMode; queryOverrides?: Record<string, any> } = {}): Promise<ExecutionResult> {\n await this._configureLlmGateway();\n const baseOptions: Record<string, any> = {\n model: \"claude-sonnet-4-5-20250929\",\n cwd: options.repositoryPath || this.workingDirectory,\n permissionMode: (options.permissionMode as any) || \"default\",\n settingSources: [\"local\"],\n mcpServers: this.mcpServers,\n };\n\n const response = query({\n prompt,\n options: { ...baseOptions, ...(options.queryOverrides || {}) },\n });\n\n const results = [];\n for await (const message of response) {\n this.logger.debug('Received message in direct run', message);\n // Emit raw SDK event\n this.emitEvent(this.adapter.createRawSDKEvent(message));\n // Emit transformed event\n const transformedEvent = this.adapter.transform(message);\n if (transformedEvent) {\n this.emitEvent(transformedEvent);\n }\n results.push(message);\n }\n \n return { results };\n }\n \n // PostHog task operations\n async fetchTask(taskId: string): Promise<Task> {\n this.logger.debug('Fetching task from PostHog', { taskId });\n if (!this.posthogAPI) {\n const error = new Error('PostHog API not configured. Provide posthogApiUrl and posthogApiKey in constructor.');\n this.logger.error('PostHog API not configured', error);\n throw error;\n }\n return this.posthogAPI.fetchTask(taskId);\n }\n\n getPostHogClient(): PostHogAPIClient | undefined {\n return this.posthogAPI;\n }\n \n async listTasks(filters?: {\n repository?: string;\n organization?: string;\n origin_product?: string;\n }): Promise<Task[]> {\n if (!this.posthogAPI) {\n throw new Error('PostHog API not configured. Provide posthogApiUrl and posthogApiKey in constructor.');\n }\n return this.posthogAPI.listTasks(filters);\n }\n \n // File system operations for task artifacts\n async writeTaskFile(taskId: string, fileName: string, content: string, type: 'plan' | 'context' | 'reference' | 'output' = 'reference'): Promise<void> {\n this.logger.debug('Writing task file', { taskId, fileName, type, contentLength: content.length });\n await this.fileManager.writeTaskFile(taskId, { name: fileName, content, type });\n }\n \n async readTaskFile(taskId: string, fileName: string): Promise<string | null> {\n this.logger.debug('Reading task file', { taskId, fileName });\n return await this.fileManager.readTaskFile(taskId, fileName);\n }\n \n async getTaskFiles(taskId: string): Promise<any[]> {\n this.logger.debug('Getting task files', { taskId });\n const files = await this.fileManager.getTaskFiles(taskId);\n this.logger.debug('Found task files', { taskId, fileCount: files.length });\n return files;\n }\n \n async writePlan(taskId: string, plan: string): Promise<void> {\n this.logger.info('Writing plan', { taskId, planLength: plan.length });\n await this.fileManager.writePlan(taskId, plan);\n }\n \n async readPlan(taskId: string): Promise<string | null> {\n this.logger.debug('Reading plan', { taskId });\n return await this.fileManager.readPlan(taskId);\n }\n\n async extractQuestionsFromResearch(taskId: string, includeAnswers: boolean = false): Promise<ExtractedQuestion[] | ExtractedQuestionWithAnswer[]> {\n this.logger.info('Extracting questions from research.md', { taskId, includeAnswers });\n \n if (!this.extractor) {\n throw new Error('OpenAI extractor not initialized. Ensure the LLM gateway is configured.');\n }\n\n const researchContent = await this.fileManager.readResearch(taskId);\n if (!researchContent) {\n throw new Error('research.md not found for task ' + taskId);\n }\n\n if (includeAnswers) {\n return await this.extractor.extractQuestionsWithAnswers(researchContent);\n } else {\n return await this.extractor.extractQuestions(researchContent);\n }\n }\n\n // Git operations for task execution\n async createPlanningBranch(taskId: string): Promise<string> {\n this.logger.info('Creating planning branch', { taskId });\n const branchName = await this.gitManager.createTaskPlanningBranch(taskId);\n this.logger.debug('Planning branch created', { taskId, branchName });\n // Only create gitignore after we're on the new branch\n await this.fileManager.ensureGitignore();\n return branchName;\n }\n \n async commitPlan(taskId: string, taskTitle: string): Promise<string> {\n this.logger.info('Committing plan', { taskId, taskTitle });\n const commitHash = await this.gitManager.commitPlan(taskId, taskTitle);\n this.logger.debug('Plan committed', { taskId, commitHash });\n return commitHash;\n }\n \n async createImplementationBranch(taskId: string, planningBranchName?: string): Promise<string> {\n this.logger.info('Creating implementation branch', { taskId, fromBranch: planningBranchName });\n const branchName = await this.gitManager.createTaskImplementationBranch(taskId, planningBranchName);\n this.logger.debug('Implementation branch created', { taskId, branchName });\n return branchName;\n }\n \n async commitImplementation(taskId: string, taskTitle: string, planSummary?: string): Promise<string> {\n this.logger.info('Committing implementation', { taskId, taskTitle });\n const commitHash = await this.gitManager.commitImplementation(taskId, taskTitle, planSummary);\n this.logger.debug('Implementation committed', { taskId, commitHash });\n return commitHash;\n }\n\n async createPullRequest(taskId: string, branchName: string, taskTitle: string, taskDescription: string): Promise<string> {\n this.logger.info('Creating pull request', { taskId, branchName, taskTitle });\n\n // Build PR body\n const prBody = `## Task Details\n**Task ID**: ${taskId}\n**Description**: ${taskDescription}\n\n## Changes\nThis PR implements the changes described in the task.\n\nGenerated by PostHog Agent`;\n\n const prUrl = await this.gitManager.createPullRequest(\n branchName,\n taskTitle,\n prBody\n );\n\n this.logger.info('Pull request created', { taskId, prUrl });\n return prUrl;\n }\n\n async attachPullRequestToTask(taskId: string, prUrl: string, branchName?: string): Promise<void> {\n this.logger.info('Attaching PR to task run', { taskId, prUrl, branchName });\n\n if (!this.posthogAPI || !this.progressReporter.runId) {\n const error = new Error('PostHog API not configured or no active run. Cannot attach PR to task.');\n this.logger.error('PostHog API not configured', error);\n throw error;\n }\n\n const updates: any = {\n output: { pr_url: prUrl }\n };\n if (branchName) {\n updates.branch = branchName;\n }\n\n await this.posthogAPI.updateTaskRun(taskId, this.progressReporter.runId, updates);\n this.logger.debug('PR attached to task run', { taskId, runId: this.progressReporter.runId, prUrl });\n }\n\n async updateTaskBranch(taskId: string, branchName: string): Promise<void> {\n this.logger.info('Updating task run branch', { taskId, branchName });\n\n if (!this.posthogAPI || !this.progressReporter.runId) {\n const error = new Error('PostHog API not configured or no active run. Cannot update branch.');\n this.logger.error('PostHog API not configured', error);\n throw error;\n }\n\n await this.posthogAPI.updateTaskRun(taskId, this.progressReporter.runId, { branch: branchName });\n this.logger.debug('Task run branch updated', { taskId, runId: this.progressReporter.runId, branchName });\n }\n\n // Execution management\n cancelTask(taskId: string): void {\n // Find the execution for this task and cancel it\n for (const [executionId, execution] of this.taskManager['executionStates']) {\n if (execution.taskId === taskId && execution.status === 'running') {\n this.taskManager.cancelExecution(executionId);\n break;\n }\n }\n }\n\n getTaskExecutionStatus(taskId: string): string | null {\n // Find the execution for this task\n for (const execution of this.taskManager['executionStates'].values()) {\n if (execution.taskId === taskId) {\n return execution.status;\n }\n }\n return null;\n }\n\n private async prepareTaskBranch(taskSlug: string, isCloudMode: boolean): Promise<void> {\n const existingBranch = await this.gitManager.getTaskBranch(taskSlug);\n if (!existingBranch) {\n this.logger.info('Creating task branch', { taskSlug });\n const branchName = `posthog/task-${taskSlug}`;\n await this.gitManager.createOrSwitchToBranch(branchName);\n this.emitEvent(this.adapter.createStatusEvent('branch_created', { branch: branchName }));\n\n await this.fileManager.ensureGitignore();\n await this.gitManager.addAllPostHogFiles();\n if (isCloudMode) {\n await this.gitManager.commitAndPush(`Initialize task ${taskSlug}`, { allowEmpty: true });\n } else {\n await this.gitManager.commitChanges(`Initialize task ${taskSlug}`);\n }\n } else {\n this.logger.info('Switching to existing task branch', { branch: existingBranch });\n await this.gitManager.switchToBranch(existingBranch);\n }\n }\n\n private ensureOpenAIGatewayEnv(baseUrl?: string, token?: string): void {\n const resolvedBaseUrl = baseUrl || process.env.ANTHROPIC_BASE_URL;\n const resolvedToken = token || process.env.ANTHROPIC_AUTH_TOKEN;\n\n if (resolvedBaseUrl) {\n process.env.OPENAI_BASE_URL = resolvedBaseUrl;\n }\n\n if (resolvedToken) {\n process.env.OPENAI_API_KEY = resolvedToken;\n }\n\n if (!this.extractor) {\n this.extractor = new AISDKExtractor(this.logger.child('AISDKExtractor'));\n }\n }\n\n private async ensurePullRequest(task: Task, stepResults: Record<string, any>): Promise<void> {\n const latestRun = task.latest_run;\n const existingPr =\n latestRun?.output && typeof latestRun.output === 'object'\n ? (latestRun.output as any).pr_url\n : null;\n\n if (existingPr) {\n this.logger.info('PR already exists, skipping creation', { taskId: task.id, prUrl: existingPr });\n return;\n }\n\n const buildResult = stepResults['build'];\n if (!buildResult?.commitCreated) {\n this.logger.warn('Build step did not produce a commit; skipping PR creation', { taskId: task.id });\n return;\n }\n\n const branchName = await this.gitManager.getCurrentBranch();\n const prUrl = await this.createPullRequest(\n task.id,\n branchName,\n task.title,\n task.description ?? ''\n );\n\n this.emitEvent(this.adapter.createStatusEvent('pr_created', { prUrl }));\n\n try {\n await this.attachPullRequestToTask(task.id, prUrl, branchName);\n this.logger.info('PR attached to task successfully', { taskId: task.id, prUrl });\n } catch (error) {\n this.logger.warn('Could not attach PR to task', {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n private emitEvent(event: any): void {\n if (this.debug && event.type !== 'token') {\n // Log all events except tokens (too verbose)\n this.logger.debug('Emitting event', { type: event.type, ts: event.ts });\n }\n const persistPromise = this.progressReporter.recordEvent(event);\n if (persistPromise && typeof persistPromise.then === 'function') {\n persistPromise.catch((error: Error) =>\n this.logger.debug('Failed to persist agent event', { message: error.message })\n );\n }\n this.onEvent?.(event);\n }\n}\n\nexport { PermissionMode } from './types.js';\nexport type { Task, SupportingFile, ExecutionResult, AgentConfig } from './types.js';\n"],"names":[],"mappings":";;;;;;;;;;;;;;MAgBa,KAAK,CAAA;AACN,IAAA,gBAAgB;AAChB,IAAA,OAAO;AACP,IAAA,WAAW;AACX,IAAA,UAAU;AACV,IAAA,WAAW;AACX,IAAA,UAAU;AACV,IAAA,eAAe;AACf,IAAA,OAAO;AACP,IAAA,MAAM;AACN,IAAA,gBAAgB;AAChB,IAAA,aAAa;AACb,IAAA,SAAS;AACT,IAAA,UAAU;AACX,IAAA,KAAK;AAEZ,IAAA,WAAA,CAAY,SAAsB,EAAE,EAAA;QAChC,IAAI,CAAC,gBAAgB,GAAG,MAAM,CAAC,gBAAgB,IAAI,OAAO,CAAC,GAAG,EAAE;AAChE,QAAA,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO;QAC7B,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,KAAK,IAAI,KAAK;;AAGlC,QAAA,MAAM,aAAa,GAAG,MAAM,CAAC;eACtB,OAAO,CAAC,GAAG,C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AAC,MAAM,CAAC,KAAK,CAAC,gBAAgB,EAAE,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,EAAE,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC;QAC3E;QACA,MAAM,cAAc,GAAG,IAAI,CAAC,gBAAgB,CAAC,WAAW,CAAC,KAAK,CAAC;QAC/D,IAAI,cAAc,IAAI,OAAO,cAAc,CAAC,IAAI,KAAK,UAAU,EAAE;YAC7D,cAAc,CAAC,KAAK,CAAC,CAAC,KAAY,KAC9B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,+BAA+B,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC,CACjF;QACL;AACA,QAAA,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;IACzB;AACH;;;;"}
1
+ {"version":3,"file":"agent.js","sources":["../../src/agent.ts"],"sourcesContent":["import { query } from \"@anthropic-ai/claude-agent-sdk\";\nimport type { Task, ExecutionResult, AgentConfig, CanUseTool } from './types.js';\nimport { TaskManager } from './task-manager.js';\nimport { PostHogAPIClient } from './posthog-api.js';\nimport { PostHogFileManager } from './file-manager.js';\nimport { GitManager } from './git-manager.js';\nimport { TemplateManager } from './template-manager.js';\nimport { ClaudeAdapter } from './adapters/claude/claude-adapter.js';\nimport type { ProviderAdapter } from './adapters/types.js';\nimport { Logger } from './utils/logger.js';\nimport { PromptBuilder } from './prompt-builder.js';\nimport { TaskProgressReporter } from './task-progress-reporter.js';\nimport { AISDKExtractor, type StructuredExtractor, type ExtractedQuestion, type ExtractedQuestionWithAnswer } from './structured-extraction.js';\nimport { TASK_WORKFLOW } from './workflow/config.js';\nimport type { WorkflowRuntime } from './workflow/types.js';\n\nexport class Agent {\n private workingDirectory: string;\n private onEvent?: (event: any) => void;\n private taskManager: TaskManager;\n private posthogAPI?: PostHogAPIClient;\n private fileManager: PostHogFileManager;\n private gitManager: GitManager;\n private templateManager: TemplateManager;\n private adapter: ProviderAdapter;\n private logger: Logger;\n private progressReporter: TaskProgressReporter;\n private promptBuilder: PromptBuilder;\n private extractor?: StructuredExtractor;\n private mcpServers?: Record<string, any>;\n private canUseTool?: CanUseTool;\n public debug: boolean;\n\n constructor(config: AgentConfig = {}) {\n this.workingDirectory = config.workingDirectory || process.cwd();\n this.onEvent = config.onEvent;\n this.canUseTool = config.canUseTool;\n this.debug = config.debug || false;\n\n // Build default PostHog MCP server configuration\n const posthogMcpUrl = config.posthogMcpUrl\n || process.env.POSTHOG_MCP_URL\n || 'https://mcp.posthog.com/mcp';\n\n // Add auth if API key provided\n const headers: Record<string, string> = {};\n if (config.posthogApiKey) {\n headers['Authorization'] = `Bearer ${config.posthogApiKey}`;\n }\n\n const defaultMcpServers = {\n posthog: {\n type: 'http' as const,\n url: posthogMcpUrl,\n ...(Object.keys(headers).length > 0 ? { headers } : {}),\n }\n };\n\n // Merge default PostHog MCP with user-provided servers (user config takes precedence)\n this.mcpServers = {\n ...defaultMcpServers,\n ...config.mcpServers\n };\n this.logger = new Logger({ debug: this.debug, prefix: '[PostHog Agent]' });\n this.taskManager = new TaskManager();\n // Hardcode Claude adapter for now - extensible for other providers later\n this.adapter = new ClaudeAdapter();\n\n this.fileManager = new PostHogFileManager(\n this.workingDirectory,\n this.logger.child('FileManager')\n );\n this.gitManager = new GitManager({\n repositoryPath: this.workingDirectory,\n logger: this.logger.child('GitManager')\n // TODO: Add author config from environment or config\n });\n this.templateManager = new TemplateManager();\n\n if (config.posthogApiUrl && config.posthogApiKey) {\n this.posthogAPI = new PostHogAPIClient({\n apiUrl: config.posthogApiUrl,\n apiKey: config.posthogApiKey,\n });\n }\n\n this.promptBuilder = new PromptBuilder({\n getTaskFiles: (taskId: string) => this.getTaskFiles(taskId),\n generatePlanTemplate: (vars) => this.templateManager.generatePlan(vars),\n posthogClient: this.posthogAPI,\n logger: this.logger.child('PromptBuilder')\n });\n this.progressReporter = new TaskProgressReporter(this.posthogAPI, this.logger);\n this.extractor = new AISDKExtractor(this.logger.child('AISDKExtractor'));\n }\n\n /**\n * Enable or disable debug logging\n */\n setDebug(enabled: boolean) {\n this.debug = enabled;\n this.logger.setDebug(enabled);\n }\n\n /**\n * Configure LLM gateway environment variables for Claude Code CLI\n */\n private async _configureLlmGateway(): Promise<void> {\n if (!this.posthogAPI) {\n return;\n }\n\n if (process.env.ANTHROPIC_BASE_URL && process.env.ANTHROPIC_AUTH_TOKEN) {\n this.ensureOpenAIGatewayEnv();\n return;\n }\n\n try {\n const gatewayUrl = await this.posthogAPI.getLlmGatewayUrl();\n const apiKey = this.posthogAPI.getApiKey();\n\n process.env.ANTHROPIC_BASE_URL = gatewayUrl;\n process.env.ANTHROPIC_AUTH_TOKEN = apiKey;\n this.ensureOpenAIGatewayEnv(gatewayUrl, apiKey);\n\n this.logger.debug('Configured LLM gateway', { gatewayUrl });\n } catch (error) {\n this.logger.error('Failed to configure LLM gateway', error);\n throw error;\n }\n }\n\n // Adaptive task execution orchestrated via workflow steps\n async runTask(taskOrId: Task | string, options: import('./types.js').TaskExecutionOptions = {}): Promise<void> {\n await this._configureLlmGateway();\n\n const task = typeof taskOrId === 'string' ? await this.fetchTask(taskOrId) : taskOrId;\n const cwd = options.repositoryPath || this.workingDirectory;\n const isCloudMode = options.isCloudMode ?? false;\n const taskSlug = (task as any).slug || task.id;\n\n this.logger.info('Starting adaptive task execution', { taskId: task.id, taskSlug, isCloudMode });\n\n // Initialize progress reporter for task run tracking (needed for PR attachment)\n await this.progressReporter.start(task.id, { totalSteps: TASK_WORKFLOW.length });\n this.emitEvent(this.adapter.createStatusEvent('run_started', { runId: this.progressReporter.runId }));\n\n await this.prepareTaskBranch(taskSlug, isCloudMode);\n\n const workflowContext: WorkflowRuntime = {\n task,\n taskSlug,\n cwd,\n isCloudMode,\n options,\n logger: this.logger,\n fileManager: this.fileManager,\n gitManager: this.gitManager,\n promptBuilder: this.promptBuilder,\n progressReporter: this.progressReporter,\n adapter: this.adapter,\n mcpServers: this.mcpServers,\n posthogAPI: this.posthogAPI,\n extractor: this.extractor,\n emitEvent: (event: any) => this.emitEvent(event),\n stepResults: {},\n };\n\n for (const step of TASK_WORKFLOW) {\n const result = await step.run({ step, context: workflowContext });\n if (result.halt) {\n return;\n }\n }\n\n if (isCloudMode) {\n await this.ensurePullRequest(task, workflowContext.stepResults);\n }\n\n await this.progressReporter.complete();\n this.logger.info('Task execution complete', { taskId: task.id });\n this.emitEvent(this.adapter.createStatusEvent('task_complete', { taskId: task.id }));\n }\n\n // Direct prompt execution - still supported for low-level usage\n async run(prompt: string, options: { repositoryPath?: string; permissionMode?: import('./types.js').PermissionMode; queryOverrides?: Record<string, any>; canUseTool?: CanUseTool } = {}): Promise<ExecutionResult> {\n await this._configureLlmGateway();\n const baseOptions: Record<string, any> = {\n model: \"claude-sonnet-4-5-20250929\",\n cwd: options.repositoryPath || this.workingDirectory,\n permissionMode: (options.permissionMode as any) || \"default\",\n settingSources: [\"local\"],\n mcpServers: this.mcpServers,\n };\n\n // Add canUseTool hook if provided (options take precedence over instance config)\n const canUseTool = options.canUseTool || this.canUseTool;\n if (canUseTool) {\n baseOptions.canUseTool = canUseTool;\n }\n\n const response = query({\n prompt,\n options: { ...baseOptions, ...(options.queryOverrides || {}) },\n });\n\n const results = [];\n for await (const message of response) {\n this.logger.debug('Received message in direct run', message);\n // Emit raw SDK event\n this.emitEvent(this.adapter.createRawSDKEvent(message));\n // Emit transformed event\n const transformedEvent = this.adapter.transform(message);\n if (transformedEvent) {\n this.emitEvent(transformedEvent);\n }\n results.push(message);\n }\n \n return { results };\n }\n \n // PostHog task operations\n async fetchTask(taskId: string): Promise<Task> {\n this.logger.debug('Fetching task from PostHog', { taskId });\n if (!this.posthogAPI) {\n const error = new Error('PostHog API not configured. Provide posthogApiUrl and posthogApiKey in constructor.');\n this.logger.error('PostHog API not configured', error);\n throw error;\n }\n return this.posthogAPI.fetchTask(taskId);\n }\n\n getPostHogClient(): PostHogAPIClient | undefined {\n return this.posthogAPI;\n }\n \n async listTasks(filters?: {\n repository?: string;\n organization?: string;\n origin_product?: string;\n }): Promise<Task[]> {\n if (!this.posthogAPI) {\n throw new Error('PostHog API not configured. Provide posthogApiUrl and posthogApiKey in constructor.');\n }\n return this.posthogAPI.listTasks(filters);\n }\n \n // File system operations for task artifacts\n async writeTaskFile(taskId: string, fileName: string, content: string, type: 'plan' | 'context' | 'reference' | 'output' = 'reference'): Promise<void> {\n this.logger.debug('Writing task file', { taskId, fileName, type, contentLength: content.length });\n await this.fileManager.writeTaskFile(taskId, { name: fileName, content, type });\n }\n \n async readTaskFile(taskId: string, fileName: string): Promise<string | null> {\n this.logger.debug('Reading task file', { taskId, fileName });\n return await this.fileManager.readTaskFile(taskId, fileName);\n }\n \n async getTaskFiles(taskId: string): Promise<any[]> {\n this.logger.debug('Getting task files', { taskId });\n const files = await this.fileManager.getTaskFiles(taskId);\n this.logger.debug('Found task files', { taskId, fileCount: files.length });\n return files;\n }\n \n async writePlan(taskId: string, plan: string): Promise<void> {\n this.logger.info('Writing plan', { taskId, planLength: plan.length });\n await this.fileManager.writePlan(taskId, plan);\n }\n \n async readPlan(taskId: string): Promise<string | null> {\n this.logger.debug('Reading plan', { taskId });\n return await this.fileManager.readPlan(taskId);\n }\n\n async extractQuestionsFromResearch(taskId: string, includeAnswers: boolean = false): Promise<ExtractedQuestion[] | ExtractedQuestionWithAnswer[]> {\n this.logger.info('Extracting questions from research.md', { taskId, includeAnswers });\n \n if (!this.extractor) {\n throw new Error('OpenAI extractor not initialized. Ensure the LLM gateway is configured.');\n }\n\n const researchContent = await this.fileManager.readResearch(taskId);\n if (!researchContent) {\n throw new Error('research.md not found for task ' + taskId);\n }\n\n if (includeAnswers) {\n return await this.extractor.extractQuestionsWithAnswers(researchContent);\n } else {\n return await this.extractor.extractQuestions(researchContent);\n }\n }\n\n // Git operations for task execution\n async createPlanningBranch(taskId: string): Promise<string> {\n this.logger.info('Creating planning branch', { taskId });\n const branchName = await this.gitManager.createTaskPlanningBranch(taskId);\n this.logger.debug('Planning branch created', { taskId, branchName });\n // Only create gitignore after we're on the new branch\n await this.fileManager.ensureGitignore();\n return branchName;\n }\n \n async commitPlan(taskId: string, taskTitle: string): Promise<string> {\n this.logger.info('Committing plan', { taskId, taskTitle });\n const commitHash = await this.gitManager.commitPlan(taskId, taskTitle);\n this.logger.debug('Plan committed', { taskId, commitHash });\n return commitHash;\n }\n \n async createImplementationBranch(taskId: string, planningBranchName?: string): Promise<string> {\n this.logger.info('Creating implementation branch', { taskId, fromBranch: planningBranchName });\n const branchName = await this.gitManager.createTaskImplementationBranch(taskId, planningBranchName);\n this.logger.debug('Implementation branch created', { taskId, branchName });\n return branchName;\n }\n \n async commitImplementation(taskId: string, taskTitle: string, planSummary?: string): Promise<string> {\n this.logger.info('Committing implementation', { taskId, taskTitle });\n const commitHash = await this.gitManager.commitImplementation(taskId, taskTitle, planSummary);\n this.logger.debug('Implementation committed', { taskId, commitHash });\n return commitHash;\n }\n\n async createPullRequest(taskId: string, branchName: string, taskTitle: string, taskDescription: string): Promise<string> {\n this.logger.info('Creating pull request', { taskId, branchName, taskTitle });\n\n // Build PR body\n const prBody = `## Task Details\n**Task ID**: ${taskId}\n**Description**: ${taskDescription}\n\n## Changes\nThis PR implements the changes described in the task.\n\nGenerated by PostHog Agent`;\n\n const prUrl = await this.gitManager.createPullRequest(\n branchName,\n taskTitle,\n prBody\n );\n\n this.logger.info('Pull request created', { taskId, prUrl });\n return prUrl;\n }\n\n async attachPullRequestToTask(taskId: string, prUrl: string, branchName?: string): Promise<void> {\n this.logger.info('Attaching PR to task run', { taskId, prUrl, branchName });\n\n if (!this.posthogAPI || !this.progressReporter.runId) {\n const error = new Error('PostHog API not configured or no active run. Cannot attach PR to task.');\n this.logger.error('PostHog API not configured', error);\n throw error;\n }\n\n const updates: any = {\n output: { pr_url: prUrl }\n };\n if (branchName) {\n updates.branch = branchName;\n }\n\n await this.posthogAPI.updateTaskRun(taskId, this.progressReporter.runId, updates);\n this.logger.debug('PR attached to task run', { taskId, runId: this.progressReporter.runId, prUrl });\n }\n\n async updateTaskBranch(taskId: string, branchName: string): Promise<void> {\n this.logger.info('Updating task run branch', { taskId, branchName });\n\n if (!this.posthogAPI || !this.progressReporter.runId) {\n const error = new Error('PostHog API not configured or no active run. Cannot update branch.');\n this.logger.error('PostHog API not configured', error);\n throw error;\n }\n\n await this.posthogAPI.updateTaskRun(taskId, this.progressReporter.runId, { branch: branchName });\n this.logger.debug('Task run branch updated', { taskId, runId: this.progressReporter.runId, branchName });\n }\n\n // Execution management\n cancelTask(taskId: string): void {\n // Find the execution for this task and cancel it\n for (const [executionId, execution] of this.taskManager['executionStates']) {\n if (execution.taskId === taskId && execution.status === 'running') {\n this.taskManager.cancelExecution(executionId);\n break;\n }\n }\n }\n\n getTaskExecutionStatus(taskId: string): string | null {\n // Find the execution for this task\n for (const execution of this.taskManager['executionStates'].values()) {\n if (execution.taskId === taskId) {\n return execution.status;\n }\n }\n return null;\n }\n\n private async prepareTaskBranch(taskSlug: string, isCloudMode: boolean): Promise<void> {\n const existingBranch = await this.gitManager.getTaskBranch(taskSlug);\n if (!existingBranch) {\n this.logger.info('Creating task branch', { taskSlug });\n const branchName = `posthog/task-${taskSlug}`;\n await this.gitManager.createOrSwitchToBranch(branchName);\n this.emitEvent(this.adapter.createStatusEvent('branch_created', { branch: branchName }));\n\n await this.fileManager.ensureGitignore();\n await this.gitManager.addAllPostHogFiles();\n if (isCloudMode) {\n await this.gitManager.commitAndPush(`Initialize task ${taskSlug}`, { allowEmpty: true });\n } else {\n await this.gitManager.commitChanges(`Initialize task ${taskSlug}`);\n }\n } else {\n this.logger.info('Switching to existing task branch', { branch: existingBranch });\n await this.gitManager.switchToBranch(existingBranch);\n }\n }\n\n private ensureOpenAIGatewayEnv(baseUrl?: string, token?: string): void {\n const resolvedBaseUrl = baseUrl || process.env.ANTHROPIC_BASE_URL;\n const resolvedToken = token || process.env.ANTHROPIC_AUTH_TOKEN;\n\n if (resolvedBaseUrl) {\n process.env.OPENAI_BASE_URL = resolvedBaseUrl;\n }\n\n if (resolvedToken) {\n process.env.OPENAI_API_KEY = resolvedToken;\n }\n\n if (!this.extractor) {\n this.extractor = new AISDKExtractor(this.logger.child('AISDKExtractor'));\n }\n }\n\n private async ensurePullRequest(task: Task, stepResults: Record<string, any>): Promise<void> {\n const latestRun = task.latest_run;\n const existingPr =\n latestRun?.output && typeof latestRun.output === 'object'\n ? (latestRun.output as any).pr_url\n : null;\n\n if (existingPr) {\n this.logger.info('PR already exists, skipping creation', { taskId: task.id, prUrl: existingPr });\n return;\n }\n\n const buildResult = stepResults['build'];\n if (!buildResult?.commitCreated) {\n this.logger.warn('Build step did not produce a commit; skipping PR creation', { taskId: task.id });\n return;\n }\n\n const branchName = await this.gitManager.getCurrentBranch();\n const prUrl = await this.createPullRequest(\n task.id,\n branchName,\n task.title,\n task.description ?? ''\n );\n\n this.emitEvent(this.adapter.createStatusEvent('pr_created', { prUrl }));\n\n try {\n await this.attachPullRequestToTask(task.id, prUrl, branchName);\n this.logger.info('PR attached to task successfully', { taskId: task.id, prUrl });\n } catch (error) {\n this.logger.warn('Could not attach PR to task', {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n private emitEvent(event: any): void {\n if (this.debug && event.type !== 'token') {\n // Log all events except tokens (too verbose)\n this.logger.debug('Emitting event', { type: event.type, ts: event.ts });\n }\n const persistPromise = this.progressReporter.recordEvent(event);\n if (persistPromise && typeof persistPromise.then === 'function') {\n persistPromise.catch((error: Error) =>\n this.logger.debug('Failed to persist agent event', { message: error.message })\n );\n }\n this.onEvent?.(event);\n }\n}\n\nexport { PermissionMode } from './types.js';\nexport type { Task, SupportingFile, ExecutionResult, AgentConfig } from './types.js';\n"],"names":[],"mappings":";;;;;;;;;;;;;;MAgBa,KAAK,CAAA;AACN,IAAA,gBAAgB;AAChB,IAAA,OAAO;AACP,IAAA,WAAW;AACX,IAAA,UAAU;AACV,IAAA,WAAW;AACX,IAAA,UAAU;AACV,IAAA,eAAe;AACf,IAAA,OAAO;AACP,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,YAAY,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;AAEvE,QAAA,IAAI;AACA,YAAA,MAAM,IAAI,CAAC,uBAAuB,CAAC,IAAI,CAAC,EAAE,EAAE,KAAK,EAAE,UAAU,CAAC;AAC9D,YAAA,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,kCAAkC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,KAAK,EAAE,CAAC;QACpF;QAAE,OAAO,KAAK,EAAE;AACZ,YAAA,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,6BAA6B,EAAE;AAC5C,gBAAA,KAAK,EAAE,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC;AAChE,aAAA,CAAC;QACN;IACJ;AAEQ,IAAA,SAAS,CAAC,KAAU,EAAA;QACxB,IAAI,IAAI,CAAC,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO,EAAE;;YAEtC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,gBAAgB,EAAE,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,EAAE,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC;QAC3E;QACA,MAAM,cAAc,GAAG,IAAI,CAAC,gBAAgB,CAAC,WAAW,CAAC,KAAK,CAAC;QAC/D,IAAI,cAAc,IAAI,OAAO,cAAc,CAAC,IAAI,KAAK,UAAU,EAAE;YAC7D,cAAc,CAAC,KAAK,CAAC,CAAC,KAAY,KAC9B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,+BAA+B,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC,CACjF;QACL;AACA,QAAA,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;IACzB;AACH;;;;"}
@@ -1,2 +1,2 @@
1
- export declare const EXECUTION_SYSTEM_PROMPT = "<context>\n You have access to the local repository files for fast read/write operations.\n You also have access to GitHub via the GitHub MCP server for additional repository operations.\n Work with local files for your main implementation, and use GitHub MCP for any additional repository queries.\n Commit changes to the repository regularly.\n</context>\n\n<role>\n PostHog AI Coding Agent \u2014 autonomously transform a ticket into a merge-ready pull request that follows existing project conventions.\n</role>\n\n<tools>\n Local file system (for main implementation work)\n PostHog MCP server (for PostHog operations)\n</tools>\n\n<constraints>\n - Follow existing style and patterns you discover in the repo.\n - Try not to add new external dependencies, only if needed.\n - Implement structured logging and error handling; never log secrets.\n - Avoid destructive shell commands.\n - ALWAYS create appropriate .gitignore files to exclude build artifacts, dependencies, and temporary files.\n</constraints>\n\n<checklist>\n - Created or updated .gitignore file with appropriate exclusions\n - Created dependency files (requirements.txt, package.json, etc.) with exact versions\n - Added clear setup/installation instructions to README.md\n - Code compiles and tests pass.\n - Added or updated tests.\n - Captured meaningful events with PostHog SDK.\n - Wrapped new logic in an PostHog feature flag.\n - Updated docs, readme or type hints if needed.\n - Verified no build artifacts or dependencies are being committed\n</checklist>\n\n<approach>\n- first make a plan and create a todo list\n- execute the todo list one by one\n- test the changes\n</approach>\n\n<output_format>\n Once finished respond with a summary of changes made\n</output_format>\n\n<thinking>\n Use this area as a private scratch-pad for step-by-step reasoning; erase before final output.\n</thinking>\n\n<task>\n Complete the ticket in a thoughtful step by step manner. Plan thoroughly and make sure to add logging and error handling as well as cover edge cases.\n</task>";
1
+ export declare const EXECUTION_SYSTEM_PROMPT = "<role>\nPostHog AI Execution Agent \u2014 autonomously implement tasks as merge-ready code following project conventions.\n</role>\n\n<context>\nYou have access to local repository files and PostHog MCP server. Work primarily with local files for implementation. Commit changes regularly.\n</context>\n\n<constraints>\n- Follow existing code style, patterns, and conventions found in the repository\n- Minimize new external dependencies \u2014 only add when necessary\n- Implement structured logging and error handling (never log secrets)\n- Avoid destructive shell commands\n- Create/update .gitignore to exclude build artifacts, dependencies, and temp files\n</constraints>\n\n<approach>\n1. Review the implementation plan if provided, or create your own todo list\n2. Execute changes step by step\n3. Test thoroughly and verify functionality\n4. Commit changes with clear messages\n</approach>\n\n<checklist>\nBefore completing the task, verify:\n- .gitignore includes build artifacts, node_modules, __pycache__, etc.\n- Dependency files (package.json, requirements.txt) use exact versions\n- Code compiles and tests pass\n- Added or updated relevant tests\n- Captured meaningful events with PostHog SDK where appropriate\n- Wrapped new logic in PostHog feature flags where appropriate\n- Updated documentation, README, or type hints as needed\n</checklist>\n\n<output_format>\nProvide a concise summary of changes made when finished.\n</output_format>";
2
2
  //# sourceMappingURL=execution.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"execution.d.ts","sourceRoot":"","sources":["../../../src/agents/execution.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,uBAAuB,+hEAoD5B,CAAC"}
1
+ {"version":3,"file":"execution.d.ts","sourceRoot":"","sources":["../../../src/agents/execution.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,uBAAuB,o7CAoCnB,CAAC"}
@@ -1,56 +1,40 @@
1
- const EXECUTION_SYSTEM_PROMPT = `<context>
2
- You have access to the local repository files for fast read/write operations.
3
- You also have access to GitHub via the GitHub MCP server for additional repository operations.
4
- Work with local files for your main implementation, and use GitHub MCP for any additional repository queries.
5
- Commit changes to the repository regularly.
6
- </context>
7
-
8
- <role>
9
- PostHog AI Coding Agent — autonomously transform a ticket into a merge-ready pull request that follows existing project conventions.
1
+ const EXECUTION_SYSTEM_PROMPT = `<role>
2
+ PostHog AI Execution Agent autonomously implement tasks as merge-ready code following project conventions.
10
3
  </role>
11
4
 
12
- <tools>
13
- Local file system (for main implementation work)
14
- PostHog MCP server (for PostHog operations)
15
- </tools>
5
+ <context>
6
+ You have access to local repository files and PostHog MCP server. Work primarily with local files for implementation. Commit changes regularly.
7
+ </context>
16
8
 
17
9
  <constraints>
18
- - Follow existing style and patterns you discover in the repo.
19
- - Try not to add new external dependencies, only if needed.
20
- - Implement structured logging and error handling; never log secrets.
21
- - Avoid destructive shell commands.
22
- - ALWAYS create appropriate .gitignore files to exclude build artifacts, dependencies, and temporary files.
10
+ - Follow existing code style, patterns, and conventions found in the repository
11
+ - Minimize new external dependencies only add when necessary
12
+ - Implement structured logging and error handling (never log secrets)
13
+ - Avoid destructive shell commands
14
+ - Create/update .gitignore to exclude build artifacts, dependencies, and temp files
23
15
  </constraints>
24
16
 
25
- <checklist>
26
- - Created or updated .gitignore file with appropriate exclusions
27
- - Created dependency files (requirements.txt, package.json, etc.) with exact versions
28
- - Added clear setup/installation instructions to README.md
29
- - Code compiles and tests pass.
30
- - Added or updated tests.
31
- - Captured meaningful events with PostHog SDK.
32
- - Wrapped new logic in an PostHog feature flag.
33
- - Updated docs, readme or type hints if needed.
34
- - Verified no build artifacts or dependencies are being committed
35
- </checklist>
36
-
37
17
  <approach>
38
- - first make a plan and create a todo list
39
- - execute the todo list one by one
40
- - test the changes
18
+ 1. Review the implementation plan if provided, or create your own todo list
19
+ 2. Execute changes step by step
20
+ 3. Test thoroughly and verify functionality
21
+ 4. Commit changes with clear messages
41
22
  </approach>
42
23
 
43
- <output_format>
44
- Once finished respond with a summary of changes made
45
- </output_format>
46
-
47
- <thinking>
48
- Use this area as a private scratch-pad for step-by-step reasoning; erase before final output.
49
- </thinking>
24
+ <checklist>
25
+ Before completing the task, verify:
26
+ - .gitignore includes build artifacts, node_modules, __pycache__, etc.
27
+ - Dependency files (package.json, requirements.txt) use exact versions
28
+ - Code compiles and tests pass
29
+ - Added or updated relevant tests
30
+ - Captured meaningful events with PostHog SDK where appropriate
31
+ - Wrapped new logic in PostHog feature flags where appropriate
32
+ - Updated documentation, README, or type hints as needed
33
+ </checklist>
50
34
 
51
- <task>
52
- Complete the ticket in a thoughtful step by step manner. Plan thoroughly and make sure to add logging and error handling as well as cover edge cases.
53
- </task>`;
35
+ <output_format>
36
+ Provide a concise summary of changes made when finished.
37
+ </output_format>`;
54
38
 
55
39
  export { EXECUTION_SYSTEM_PROMPT };
56
40
  //# sourceMappingURL=execution.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"execution.js","sources":["../../../src/agents/execution.ts"],"sourcesContent":["export const EXECUTION_SYSTEM_PROMPT = `<context>\n You have access to the local repository files for fast read/write operations.\n You also have access to GitHub via the GitHub MCP server for additional repository operations.\n Work with local files for your main implementation, and use GitHub MCP for any additional repository queries.\n Commit changes to the repository regularly.\n</context>\n\n<role>\n PostHog AI Coding Agent — autonomously transform a ticket into a merge-ready pull request that follows existing project conventions.\n</role>\n\n<tools>\n Local file system (for main implementation work)\n PostHog MCP server (for PostHog operations)\n</tools>\n\n<constraints>\n - Follow existing style and patterns you discover in the repo.\n - Try not to add new external dependencies, only if needed.\n - Implement structured logging and error handling; never log secrets.\n - Avoid destructive shell commands.\n - ALWAYS create appropriate .gitignore files to exclude build artifacts, dependencies, and temporary files.\n</constraints>\n\n<checklist>\n - Created or updated .gitignore file with appropriate exclusions\n - Created dependency files (requirements.txt, package.json, etc.) with exact versions\n - Added clear setup/installation instructions to README.md\n - Code compiles and tests pass.\n - Added or updated tests.\n - Captured meaningful events with PostHog SDK.\n - Wrapped new logic in an PostHog feature flag.\n - Updated docs, readme or type hints if needed.\n - Verified no build artifacts or dependencies are being committed\n</checklist>\n\n<approach>\n- first make a plan and create a todo list\n- execute the todo list one by one\n- test the changes\n</approach>\n\n<output_format>\n Once finished respond with a summary of changes made\n</output_format>\n\n<thinking>\n Use this area as a private scratch-pad for step-by-step reasoning; erase before final output.\n</thinking>\n\n<task>\n Complete the ticket in a thoughtful step by step manner. Plan thoroughly and make sure to add logging and error handling as well as cover edge cases.\n</task>`;"],"names":[],"mappings":"AAAO,MAAM,uBAAuB,GAAG,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"execution.js","sources":["../../../src/agents/execution.ts"],"sourcesContent":["export const EXECUTION_SYSTEM_PROMPT = `<role>\nPostHog AI Execution Agent — autonomously implement tasks as merge-ready code following project conventions.\n</role>\n\n<context>\nYou have access to local repository files and PostHog MCP server. Work primarily with local files for implementation. Commit changes regularly.\n</context>\n\n<constraints>\n- Follow existing code style, patterns, and conventions found in the repository\n- Minimize new external dependencies only add when necessary\n- Implement structured logging and error handling (never log secrets)\n- Avoid destructive shell commands\n- Create/update .gitignore to exclude build artifacts, dependencies, and temp files\n</constraints>\n\n<approach>\n1. Review the implementation plan if provided, or create your own todo list\n2. Execute changes step by step\n3. Test thoroughly and verify functionality\n4. Commit changes with clear messages\n</approach>\n\n<checklist>\nBefore completing the task, verify:\n- .gitignore includes build artifacts, node_modules, __pycache__, etc.\n- Dependency files (package.json, requirements.txt) use exact versions\n- Code compiles and tests pass\n- Added or updated relevant tests\n- Captured meaningful events with PostHog SDK where appropriate\n- Wrapped new logic in PostHog feature flags where appropriate\n- Updated documentation, README, or type hints as needed\n</checklist>\n\n<output_format>\nProvide a concise summary of changes made when finished.\n</output_format>`;"],"names":[],"mappings":"AAAO,MAAM,uBAAuB,GAAG,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -1,2 +1,2 @@
1
- export declare const PLANNING_SYSTEM_PROMPT = "# PostHog AI Coding Agent - Planning Mode\n\nYou are a PostHog AI Coding Agent operating in PLANNING mode.\n\n## Your Role\n\nYou are a specialized planning agent that analyzes codebases and creates detailed implementation plans for development tasks.\n\n## Important Constraints\n\n- **Read-Only Mode**: You can only read files, search code, and analyze the codebase\n- **No Modifications**: You cannot make any changes, edits, or execute commands\n- **Research Focus**: Your goal is understanding and planning, not implementation\n- **Response Format**: Respond only with the markdown content above, no other text or formatting, no acknowledgement, no explanation, no nothing.\n\n## Available Tools\n\n- File reading and exploration\n- Code search and analysis\n- Repository structure analysis\n- Documentation review\n\n## Planning Process\n\nWhen given a task, follow this systematic approach:\n\n1. **Codebase Analysis**\n - Explore the repository structure\n - Identify relevant files and components\n - Understand existing patterns and conventions\n - Review related code and dependencies\n\n2. **Requirements Analysis**\n - Break down the task requirements\n - Identify technical constraints\n - Note any existing implementations to build upon\n - Consider edge cases and potential issues\n\n3. **Implementation Planning**\n - Outline the step-by-step approach\n - Identify files that need to be created or modified\n - Plan the order of implementation\n - Note any dependencies or prerequisites\n\n4. **Documentation**\n - Create a clear, actionable plan\n - Include specific file paths and changes needed\n - Note any testing requirements\n - Highlight potential risks or considerations\n\n## Plan Output\n\n- **Summary**: Brief overview of the implementation approach\n- **Files to Create/Modify**: Specific paths and purposes\n- **Implementation Steps**: Ordered list of actions to take\n- **Considerations**: Dependencies, risks, and important notes\n- **Testing Strategy**: How to verify the implementation works\n\n## Context Integration\n\nIf supporting files are provided, incorporate them into your analysis:\n- **Context files**: Additional requirements or constraints\n- **Reference files**: Examples or documentation to follow\n- **Previous plans**: Build upon or refine existing planning work\n\nYour planning should be thorough enough that another agent in execution mode can implement the changes successfully.";
1
+ export declare const PLANNING_SYSTEM_PROMPT = "<role>\nPostHog AI Planning Agent \u2014 analyze codebases and create actionable implementation plans.\n</role>\n\n<constraints>\n- Read-only: analyze files, search code, explore structure\n- No modifications or edits\n- Output ONLY the plan markdown \u2014 no preamble, no acknowledgment, no meta-commentary\n</constraints>\n\n<objective>\nCreate a detailed, actionable implementation plan that an execution agent can follow to complete the task successfully.\n</objective>\n\n<process>\n1. Explore repository structure and identify relevant files/components\n2. Understand existing patterns, conventions, and dependencies\n3. Break down task requirements and identify technical constraints\n4. Define step-by-step implementation approach\n5. Specify files to modify/create with exact paths\n6. Identify testing requirements and potential risks\n</process>\n\n<output_format>\nOutput the plan DIRECTLY as markdown with NO preamble text. Do NOT say \"I'll create a plan\" or \"Here's the plan\" \u2014 just output the plan content.\n\nRequired sections (follow the template provided in the task prompt):\n- Summary: Brief overview of approach\n- Files to Create/Modify: Specific paths and purposes\n- Implementation Steps: Ordered list of actions\n- Testing Strategy: How to verify it works\n- Considerations: Dependencies, risks, edge cases\n</output_format>\n\n<examples>\n<bad_example>\n\"Sure! I'll create a detailed implementation plan for you to add authentication. Here's what we'll do...\"\nReason: No preamble \u2014 output the plan directly\n</bad_example>\n\n<good_example>\n\"# Implementation Plan\n\n## Summary\nAdd JWT-based authentication to API endpoints using existing middleware pattern...\n\n## Files to Modify\n- src/middleware/auth.ts: Add JWT verification\n...\"\nReason: Direct plan output with no meta-commentary\n</good_example>\n</examples>\n\n<context_integration>\nIf research findings, context files, or reference materials are provided:\n- Incorporate research findings into your analysis\n- Follow patterns and approaches identified in research\n- Build upon or refine any existing planning work\n- Reference specific files and components mentioned in context\n</context_integration>";
2
2
  //# sourceMappingURL=planning.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"planning.d.ts","sourceRoot":"","sources":["../../../src/agents/planning.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,sBAAsB,u6EAiEkF,CAAC"}
1
+ {"version":3,"file":"planning.d.ts","sourceRoot":"","sources":["../../../src/agents/planning.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,sBAAsB,2qEA2DZ,CAAC"}