@posthog/agent 1.6.0 → 1.7.1

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.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export { Agent, } from './src/agent.js';
2
2
  export { PermissionMode, } from './src/types.js';
3
- export type { Task, SupportingFile, ExecutionResult, AgentConfig, McpServerConfig } from './src/types.js';
3
+ export type { Task, SupportingFile, ExecutionResult, AgentConfig, McpServerConfig, AgentEvent } from './src/types.js';
4
4
  export type { WorkflowDefinition, WorkflowStage, WorkflowExecutionOptions, AgentDefinition } from './src/workflow-types.js';
5
5
  export { Logger, LogLevel, } from './src/utils/logger.js';
6
6
  export type { LoggerConfig } from './src/utils/logger.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AACA,OAAO,EACH,KAAK,GACR,MAAM,gBAAgB,CAAC;AAExB,OAAO,EACH,cAAc,GACjB,MAAM,gBAAgB,CAAC;AAExB,YAAY,EACR,IAAI,EACJ,cAAc,EACd,eAAe,EACf,WAAW,EACX,eAAe,EAClB,MAAM,gBAAgB,CAAC;AAExB,YAAY,EACV,kBAAkB,EAClB,aAAa,EACb,wBAAwB,EACxB,eAAe,EAChB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EACH,MAAM,EACN,QAAQ,GACX,MAAM,uBAAuB,CAAC;AAE/B,YAAY,EACR,YAAY,EACf,MAAM,uBAAuB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AACA,OAAO,EACH,KAAK,GACR,MAAM,gBAAgB,CAAC;AAExB,OAAO,EACH,cAAc,GACjB,MAAM,gBAAgB,CAAC;AAExB,YAAY,EACR,IAAI,EACJ,cAAc,EACd,eAAe,EACf,WAAW,EACX,eAAe,EACf,UAAU,EACb,MAAM,gBAAgB,CAAC;AAExB,YAAY,EACV,kBAAkB,EA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
75
  const promptBuilder = new PromptBuilder({
76
76
  getTaskFiles: (taskId) => this.getTaskFiles(taskId),
77
77
  generatePlanTemplate: (vars) => this.templateManager.generatePlan(vars),
78
+ posthogClient: this.posthogAPI,
78
79
  logger: this.logger.child('PromptBuilder')
79
80
  });
80
81
  this.stageExecutor = new StageExecutor(this.agentRegistry, this.logger, promptBuilder, undefined, // eventHandler set via setEventHandler below
@@ -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, PlanResult, AgentConfig } from './types.js';\nimport type { WorkflowDefinition, WorkflowStage, WorkflowExecutionOptions } from './workflow-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 { EventTransformer } from './event-transformer.js';\nimport { PLANNING_SYSTEM_PROMPT } from './agents/planning.js';\nimport { EXECUTION_SYSTEM_PROMPT } from './agents/execution.js';\nimport { Logger } from './utils/logger.js';\nimport { AgentRegistry } from './agent-registry.js';\nimport { WorkflowRegistry } from './workflow-registry.js';\nimport { StageExecutor } from './stage-executor.js';\nimport { PromptBuilder } from './prompt-builder.js';\nimport { TaskProgressReporter } from './task-progress-reporter.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 eventTransformer: EventTransformer;\n private logger: Logger;\n private agentRegistry: AgentRegistry;\n private workflowRegistry: WorkflowRegistry;\n private stageExecutor: StageExecutor;\n private progressReporter: TaskProgressReporter;\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 this.eventTransformer = new EventTransformer();\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 this.agentRegistry = new AgentRegistry();\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.workflowRegistry = new WorkflowRegistry(this.posthogAPI);\n const promptBuilder = new PromptBuilder({\n getTaskFiles: (taskId: string) => this.getTaskFiles(taskId),\n generatePlanTemplate: (vars) => this.templateManager.generatePlan(vars),\n logger: this.logger.child('PromptBuilder')\n });\n this.stageExecutor = new StageExecutor(\n this.agentRegistry,\n this.logger,\n promptBuilder,\n undefined, // eventHandler set via setEventHandler below\n this.mcpServers\n );\n this.stageExecutor.setEventHandler((event) => this.emitEvent(event));\n this.progressReporter = new TaskProgressReporter(this.posthogAPI, this.logger);\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 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\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 // Workflow-based execution\n async runWorkflow(taskOrId: Task | string, workflowId: string, options: WorkflowExecutionOptions = {}): Promise<{ task: Task; workflow: WorkflowDefinition }> {\n await this._configureLlmGateway();\n\n const task = typeof taskOrId === 'string' ? await this.fetchTask(taskOrId) : taskOrId;\n await this.workflowRegistry.loadWorkflows();\n const workflow = this.workflowRegistry.getWorkflow(workflowId);\n if (!workflow) {\n throw new Error(`Workflow ${workflowId} not found`);\n }\n const orderedStages = [...workflow.stages].sort((a, b) => a.position - b.position);\n\n // Ensure task is assigned to workflow and positioned at first stage\n if (this.posthogAPI) {\n try {\n if ((task.workflow as any) !== workflowId) {\n await this.posthogAPI.updateTask(task.id, { workflow: workflowId } as any);\n (task as any).workflow = workflowId;\n }\n if (!(task as any).current_stage && workflow.stages.length > 0) {\n const firstStage = [...workflow.stages].sort((a, b) => a.position - b.position)[0];\n await this.posthogAPI.updateTaskStage(task.id, firstStage.id);\n (task as any).current_stage = firstStage.id;\n }\n } catch (e) {\n this.logger.warn('Failed to sync task workflow/stage before execution', { error: (e as Error).message });\n }\n }\n\n const executionId = this.taskManager.generateExecutionId();\n this.logger.info('Starting workflow execution', { taskId: task.id, workflowId, executionId });\n this.taskManager.startExecution(task.id, 'plan_and_build', executionId);\n await this.progressReporter.start(task.id, {\n workflowId,\n workflowRunId: executionId,\n totalSteps: orderedStages.length,\n });\n\n try {\n let startIndex = 0;\n const currentStageId = (task as any).current_stage as string | undefined;\n\n // If task is already at the last stage, fail gracefully without progressing\n if (currentStageId) {\n const currIdx = orderedStages.findIndex(s => s.id === currentStageId);\n const atLastStage = currIdx >= 0 && currIdx === orderedStages.length - 1;\n if (atLastStage) {\n const finalStageKey = orderedStages[currIdx]?.key;\n this.emitEvent(this.eventTransformer.createStatusEvent('no_next_stage', { stage: finalStageKey }));\n await this.progressReporter.noNextStage(finalStageKey);\n await this.progressReporter.complete();\n this.taskManager.completeExecution(executionId, { task, workflow });\n return { task, workflow };\n }\n }\n\n if (options.resumeFromCurrentStage && currentStageId) {\n const idx = orderedStages.findIndex(s => s.id === currentStageId);\n if (idx >= 0) startIndex = idx;\n }\n\n // Align server-side stage when restarting from the beginning\n if (this.posthogAPI) {\n const targetStage = orderedStages[startIndex];\n if (targetStage && targetStage.id !== currentStageId) {\n try { await this.posthogAPI.updateTaskStage(task.id, targetStage.id); (task as any).current_stage = targetStage.id; } catch {}\n }\n }\n\n for (let i = startIndex; i < orderedStages.length; i++) {\n const stage = orderedStages[i];\n await this.progressReporter.stageStarted(stage.key, i);\n await this.executeStage(task, stage, options);\n await this.progressReporter.stageCompleted(stage.key, i + 1);\n if (options.autoProgress) {\n const hasNext = i < orderedStages.length - 1;\n if (hasNext) {\n await this.progressToNextStage(task.id, stage.key);\n }\n }\n }\n await this.progressReporter.complete();\n this.taskManager.completeExecution(executionId, { task, workflow });\n return { task, workflow };\n } catch (error) {\n await this.progressReporter.fail(error as Error);\n this.taskManager.failExecution(executionId, error as Error);\n throw error;\n }\n }\n\n async executeStage(task: Task, stage: WorkflowStage, options: WorkflowExecutionOptions = {}): Promise<void> {\n this.emitEvent(this.eventTransformer.createStatusEvent('stage_start', { stage: stage.key }));\n const overrides = options.stageOverrides?.[stage.key];\n const agentName = stage.agent_name || 'code_generation';\n const agentDef = this.agentRegistry.getAgent(agentName);\n const isManual = stage.is_manual_only === true;\n const stageKeyLower = (stage.key || '').toLowerCase().trim();\n const isPlanningByKey = stageKeyLower === 'plan' || stageKeyLower.includes('plan');\n const isPlanning = !isManual && ((agentDef?.agent_type === 'planning') || isPlanningByKey);\n const shouldCreatePlanningBranch = overrides?.createPlanningBranch !== false; // default true\n const shouldCreateImplBranch = overrides?.createImplementationBranch !== false; // default true\n\n if (isPlanning && shouldCreatePlanningBranch) {\n const planningBranch = await this.createPlanningBranch(task.id);\n await this.updateTaskBranch(task.id, planningBranch);\n this.emitEvent(this.eventTransformer.createStatusEvent('branch_created', { stage: stage.key, branch: planningBranch }));\n await this.progressReporter.branchCreated(stage.key, planningBranch);\n } else if (!isPlanning && !isManual && shouldCreateImplBranch) {\n const implBranch = await this.createImplementationBranch(task.id);\n await this.updateTaskBranch(task.id, implBranch);\n this.emitEvent(this.eventTransformer.createStatusEvent('branch_created', { stage: stage.key, branch: implBranch }));\n await this.progressReporter.branchCreated(stage.key, implBranch);\n }\n\n const result = await this.stageExecutor.execute(task, stage, options);\n\n if (result.plan) {\n await this.writePlan(task.id, result.plan);\n await this.commitPlan(task.id, task.title);\n this.emitEvent(this.eventTransformer.createStatusEvent('commit_made', { stage: stage.key, kind: 'plan' }));\n await this.progressReporter.commitMade(stage.key, 'plan');\n }\n\n if (isManual) {\n const defaultOpenPR = true; // manual stages default to PR for review\n const openPR = overrides?.openPullRequest ?? defaultOpenPR;\n if (openPR) {\n // Ensure we're on an implementation branch for PRs\n let branchName = await this.gitManager.getCurrentBranch();\n const onTaskBranch = branchName.includes(`posthog/task-${task.id}`);\n if (!onTaskBranch && (overrides?.createImplementationBranch !== false)) {\n const implBranch = await this.createImplementationBranch(task.id);\n await this.updateTaskBranch(task.id, implBranch);\n branchName = implBranch;\n this.emitEvent(this.eventTransformer.createStatusEvent('branch_created', { stage: stage.key, branch: implBranch }));\n await this.progressReporter.branchCreated(stage.key, implBranch);\n }\n try {\n const prUrl = await this.createPullRequest(task.id, branchName, task.title, task.description);\n await this.updateTaskBranch(task.id, branchName);\n await this.attachPullRequestToTask(task.id, prUrl, branchName);\n this.emitEvent(this.eventTransformer.createStatusEvent('pr_created', { stage: stage.key, prUrl }));\n await this.progressReporter.pullRequestCreated(stage.key, prUrl);\n } catch {}\n }\n // Do not auto-progress on manual stages\n this.emitEvent(this.eventTransformer.createStatusEvent('stage_complete', { stage: stage.key }));\n return;\n }\n\n if (result.results) {\n const existingPlan = await this.readPlan(task.id);\n const planSummary = existingPlan ? existingPlan.split('\\n')[0] : undefined;\n await this.commitImplementation(task.id, task.title, planSummary);\n this.emitEvent(this.eventTransformer.createStatusEvent('commit_made', { stage: stage.key, kind: 'implementation' }));\n await this.progressReporter.commitMade(stage.key, 'implementation');\n }\n\n // PR creation on complete stage (or if explicitly requested), regardless of whether edits occurred\n {\n const defaultOpenPR = stage.key.toLowerCase().includes('complete');\n const openPR = overrides?.openPullRequest ?? defaultOpenPR;\n if (openPR) {\n const branchName = await this.gitManager.getCurrentBranch();\n try {\n const prUrl = await this.createPullRequest(task.id, branchName, task.title, task.description);\n await this.updateTaskBranch(task.id, branchName);\n await this.attachPullRequestToTask(task.id, prUrl, branchName);\n this.emitEvent(this.eventTransformer.createStatusEvent('pr_created', { stage: stage.key, prUrl }));\n await this.progressReporter.pullRequestCreated(stage.key, prUrl);\n } catch {}\n }\n }\n\n this.emitEvent(this.eventTransformer.createStatusEvent('stage_complete', { stage: stage.key }));\n }\n\n async progressToNextStage(taskId: string, currentStageKey?: string): Promise<void> {\n if (!this.posthogAPI) throw new Error('PostHog API not configured. Cannot progress stage.');\n try {\n await this.posthogAPI.progressTask(taskId, { auto: true });\n } catch (error) {\n if (error instanceof Error && error.message.includes('No next stage available')) {\n this.logger.warn('No next stage available when attempting to progress task', {\n taskId,\n stage: currentStageKey,\n error: error.message,\n });\n this.emitEvent(this.eventTransformer.createStatusEvent('no_next_stage', { stage: currentStageKey }));\n await this.progressReporter.noNextStage(currentStageKey);\n return;\n }\n throw error;\n }\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.eventTransformer.createRawSDKEvent(message));\n // Emit transformed event\n const transformedEvent = this.eventTransformer.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 workflow?: string;\n current_stage?: 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 // Git operations for task workflow\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', { taskId, prUrl, branchName });\n\n if (!this.posthogAPI) {\n const error = new Error('PostHog API not configured. Cannot attach PR to task.');\n this.logger.error('PostHog API not configured', error);\n throw error;\n }\n\n await this.posthogAPI.attachTaskPullRequest(taskId, prUrl, branchName);\n this.logger.debug('PR attached to task', { taskId, prUrl });\n }\n\n async updateTaskBranch(taskId: string, branchName: string): Promise<void> {\n this.logger.info('Updating task branch', { taskId, branchName });\n\n if (!this.posthogAPI) {\n const error = new Error('PostHog API not configured. Cannot update task branch.');\n this.logger.error('PostHog API not configured', error);\n throw error;\n }\n\n await this.posthogAPI.setTaskBranch(taskId, branchName);\n this.logger.debug('Task branch updated', { taskId, 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 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';\nexport type { WorkflowDefinition, WorkflowStage, WorkflowExecutionOptions } from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3,"file":"agent.js","sources":["../../src/agent.ts"],"sourcesContent":["import { query } from \"@anthropic-ai/claude-agent-sdk\";\nimport type { Task, ExecutionResult, PlanResult, AgentConfig } from './types.js';\nimport type { WorkflowDefinition, WorkflowStage, WorkflowExecutionOptions } from './workflow-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 { EventTransformer } from './event-transformer.js';\nimport { PLANNING_SYSTEM_PROMPT } from './agents/planning.js';\nimport { EXECUTION_SYSTEM_PROMPT } from './agents/execution.js';\nimport { Logger } from './utils/logger.js';\nimport { AgentRegistry } from './agent-registry.js';\nimport { WorkflowRegistry } from './workflow-registry.js';\nimport { StageExecutor } from './stage-executor.js';\nimport { PromptBuilder } from './prompt-builder.js';\nimport { TaskProgressReporter } from './task-progress-reporter.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 eventTransformer: EventTransformer;\n private logger: Logger;\n private agentRegistry: AgentRegistry;\n private workflowRegistry: WorkflowRegistry;\n private stageExecutor: StageExecutor;\n private progressReporter: TaskProgressReporter;\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 this.eventTransformer = new EventTransformer();\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 this.agentRegistry = new AgentRegistry();\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.workflowRegistry = new WorkflowRegistry(this.posthogAPI);\n const 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.stageExecutor = new StageExecutor(\n this.agentRegistry,\n this.logger,\n promptBuilder,\n undefined, // eventHandler set via setEventHandler below\n this.mcpServers\n );\n this.stageExecutor.setEventHandler((event) => this.emitEvent(event));\n this.progressReporter = new TaskProgressReporter(this.posthogAPI, this.logger);\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 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\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 // Workflow-based execution\n async runWorkflow(taskOrId: Task | string, workflowId: string, options: WorkflowExecutionOptions = {}): Promise<{ task: Task; workflow: WorkflowDefinition }> {\n await this._configureLlmGateway();\n\n const task = typeof taskOrId === 'string' ? await this.fetchTask(taskOrId) : taskOrId;\n await this.workflowRegistry.loadWorkflows();\n const workflow = this.workflowRegistry.getWorkflow(workflowId);\n if (!workflow) {\n throw new Error(`Workflow ${workflowId} not found`);\n }\n const orderedStages = [...workflow.stages].sort((a, b) => a.position - b.position);\n\n // Ensure task is assigned to workflow and positioned at first stage\n if (this.posthogAPI) {\n try {\n if ((task.workflow as any) !== workflowId) {\n await this.posthogAPI.updateTask(task.id, { workflow: workflowId } as any);\n (task as any).workflow = workflowId;\n }\n if (!(task as any).current_stage && workflow.stages.length > 0) {\n const firstStage = [...workflow.stages].sort((a, b) => a.position - b.position)[0];\n await this.posthogAPI.updateTaskStage(task.id, firstStage.id);\n (task as any).current_stage = firstStage.id;\n }\n } catch (e) {\n this.logger.warn('Failed to sync task workflow/stage before execution', { error: (e as Error).message });\n }\n }\n\n const executionId = this.taskManager.generateExecutionId();\n this.logger.info('Starting workflow execution', { taskId: task.id, workflowId, executionId });\n this.taskManager.startExecution(task.id, 'plan_and_build', executionId);\n await this.progressReporter.start(task.id, {\n workflowId,\n workflowRunId: executionId,\n totalSteps: orderedStages.length,\n });\n\n try {\n let startIndex = 0;\n const currentStageId = (task as any).current_stage as string | undefined;\n\n // If task is already at the last stage, fail gracefully without progressing\n if (currentStageId) {\n const currIdx = orderedStages.findIndex(s => s.id === currentStageId);\n const atLastStage = currIdx >= 0 && currIdx === orderedStages.length - 1;\n if (atLastStage) {\n const finalStageKey = orderedStages[currIdx]?.key;\n this.emitEvent(this.eventTransformer.createStatusEvent('no_next_stage', { stage: finalStageKey }));\n await this.progressReporter.noNextStage(finalStageKey);\n await this.progressReporter.complete();\n this.taskManager.completeExecution(executionId, { task, workflow });\n return { task, workflow };\n }\n }\n\n if (options.resumeFromCurrentStage && currentStageId) {\n const idx = orderedStages.findIndex(s => s.id === currentStageId);\n if (idx >= 0) startIndex = idx;\n }\n\n // Align server-side stage when restarting from the beginning\n if (this.posthogAPI) {\n const targetStage = orderedStages[startIndex];\n if (targetStage && targetStage.id !== currentStageId) {\n try { await this.posthogAPI.updateTaskStage(task.id, targetStage.id); (task as any).current_stage = targetStage.id; } catch {}\n }\n }\n\n for (let i = startIndex; i < orderedStages.length; i++) {\n const stage = orderedStages[i];\n await this.progressReporter.stageStarted(stage.key, i);\n await this.executeStage(task, stage, options);\n await this.progressReporter.stageCompleted(stage.key, i + 1);\n if (options.autoProgress) {\n const hasNext = i < orderedStages.length - 1;\n if (hasNext) {\n await this.progressToNextStage(task.id, stage.key);\n }\n }\n }\n await this.progressReporter.complete();\n this.taskManager.completeExecution(executionId, { task, workflow });\n return { task, workflow };\n } catch (error) {\n await this.progressReporter.fail(error as Error);\n this.taskManager.failExecution(executionId, error as Error);\n throw error;\n }\n }\n\n async executeStage(task: Task, stage: WorkflowStage, options: WorkflowExecutionOptions = {}): Promise<void> {\n this.emitEvent(this.eventTransformer.createStatusEvent('stage_start', { stage: stage.key }));\n const overrides = options.stageOverrides?.[stage.key];\n const agentName = stage.agent_name || 'code_generation';\n const agentDef = this.agentRegistry.getAgent(agentName);\n const isManual = stage.is_manual_only === true;\n const stageKeyLower = (stage.key || '').toLowerCase().trim();\n const isPlanningByKey = stageKeyLower === 'plan' || stageKeyLower.includes('plan');\n const isPlanning = !isManual && ((agentDef?.agent_type === 'planning') || isPlanningByKey);\n const shouldCreatePlanningBranch = overrides?.createPlanningBranch !== false; // default true\n const shouldCreateImplBranch = overrides?.createImplementationBranch !== false; // default true\n\n if (isPlanning && shouldCreatePlanningBranch) {\n const planningBranch = await this.createPlanningBranch(task.id);\n await this.updateTaskBranch(task.id, planningBranch);\n this.emitEvent(this.eventTransformer.createStatusEvent('branch_created', { stage: stage.key, branch: planningBranch }));\n await this.progressReporter.branchCreated(stage.key, planningBranch);\n } else if (!isPlanning && !isManual && shouldCreateImplBranch) {\n const implBranch = await this.createImplementationBranch(task.id);\n await this.updateTaskBranch(task.id, implBranch);\n this.emitEvent(this.eventTransformer.createStatusEvent('branch_created', { stage: stage.key, branch: implBranch }));\n await this.progressReporter.branchCreated(stage.key, implBranch);\n }\n\n const result = await this.stageExecutor.execute(task, stage, options);\n\n if (result.plan) {\n await this.writePlan(task.id, result.plan);\n await this.commitPlan(task.id, task.title);\n this.emitEvent(this.eventTransformer.createStatusEvent('commit_made', { stage: stage.key, kind: 'plan' }));\n await this.progressReporter.commitMade(stage.key, 'plan');\n }\n\n if (isManual) {\n const defaultOpenPR = true; // manual stages default to PR for review\n const openPR = overrides?.openPullRequest ?? defaultOpenPR;\n if (openPR) {\n // Ensure we're on an implementation branch for PRs\n let branchName = await this.gitManager.getCurrentBranch();\n const onTaskBranch = branchName.includes(`posthog/task-${task.id}`);\n if (!onTaskBranch && (overrides?.createImplementationBranch !== false)) {\n const implBranch = await this.createImplementationBranch(task.id);\n await this.updateTaskBranch(task.id, implBranch);\n branchName = implBranch;\n this.emitEvent(this.eventTransformer.createStatusEvent('branch_created', { stage: stage.key, branch: implBranch }));\n await this.progressReporter.branchCreated(stage.key, implBranch);\n }\n try {\n const prUrl = await this.createPullRequest(task.id, branchName, task.title, task.description);\n await this.updateTaskBranch(task.id, branchName);\n await this.attachPullRequestToTask(task.id, prUrl, branchName);\n this.emitEvent(this.eventTransformer.createStatusEvent('pr_created', { stage: stage.key, prUrl }));\n await this.progressReporter.pullRequestCreated(stage.key, prUrl);\n } catch {}\n }\n // Do not auto-progress on manual stages\n this.emitEvent(this.eventTransformer.createStatusEvent('stage_complete', { stage: stage.key }));\n return;\n }\n\n if (result.results) {\n const existingPlan = await this.readPlan(task.id);\n const planSummary = existingPlan ? existingPlan.split('\\n')[0] : undefined;\n await this.commitImplementation(task.id, task.title, planSummary);\n this.emitEvent(this.eventTransformer.createStatusEvent('commit_made', { stage: stage.key, kind: 'implementation' }));\n await this.progressReporter.commitMade(stage.key, 'implementation');\n }\n\n // PR creation on complete stage (or if explicitly requested), regardless of whether edits occurred\n {\n const defaultOpenPR = stage.key.toLowerCase().includes('complete');\n const openPR = overrides?.openPullRequest ?? defaultOpenPR;\n if (openPR) {\n const branchName = await this.gitManager.getCurrentBranch();\n try {\n const prUrl = await this.createPullRequest(task.id, branchName, task.title, task.description);\n await this.updateTaskBranch(task.id, branchName);\n await this.attachPullRequestToTask(task.id, prUrl, branchName);\n this.emitEvent(this.eventTransformer.createStatusEvent('pr_created', { stage: stage.key, prUrl }));\n await this.progressReporter.pullRequestCreated(stage.key, prUrl);\n } catch {}\n }\n }\n\n this.emitEvent(this.eventTransformer.createStatusEvent('stage_complete', { stage: stage.key }));\n }\n\n async progressToNextStage(taskId: string, currentStageKey?: string): Promise<void> {\n if (!this.posthogAPI) throw new Error('PostHog API not configured. Cannot progress stage.');\n try {\n await this.posthogAPI.progressTask(taskId, { auto: true });\n } catch (error) {\n if (error instanceof Error && error.message.includes('No next stage available')) {\n this.logger.warn('No next stage available when attempting to progress task', {\n taskId,\n stage: currentStageKey,\n error: error.message,\n });\n this.emitEvent(this.eventTransformer.createStatusEvent('no_next_stage', { stage: currentStageKey }));\n await this.progressReporter.noNextStage(currentStageKey);\n return;\n }\n throw error;\n }\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.eventTransformer.createRawSDKEvent(message));\n // Emit transformed event\n const transformedEvent = this.eventTransformer.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 workflow?: string;\n current_stage?: 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 // Git operations for task workflow\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', { taskId, prUrl, branchName });\n\n if (!this.posthogAPI) {\n const error = new Error('PostHog API not configured. Cannot attach PR to task.');\n this.logger.error('PostHog API not configured', error);\n throw error;\n }\n\n await this.posthogAPI.attachTaskPullRequest(taskId, prUrl, branchName);\n this.logger.debug('PR attached to task', { taskId, prUrl });\n }\n\n async updateTaskBranch(taskId: string, branchName: string): Promise<void> {\n this.logger.info('Updating task branch', { taskId, branchName });\n\n if (!this.posthogAPI) {\n const error = new Error('PostHog API not configured. Cannot update task branch.');\n this.logger.error('PostHog API not configured', error);\n throw error;\n }\n\n await this.posthogAPI.setTaskBranch(taskId, branchName);\n this.logger.debug('Task branch updated', { taskId, 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 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';\nexport type { WorkflowDefinition, WorkflowStage, WorkflowExecutionOptions } from './workflow-types.js';\n"],"names":[],"mappings":";;;;;;;;;;;;;;;MAkBa,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,gBAAgB;AAChB,IAAA,MAAM;AACN,IAAA,aAAa;AACb,IAAA,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C,MAAM,KAAK,SAAS,EAAE;AAC/D,gBAAA,IAAI,CAAC,WAAW,CAAC,eAAe,CAAC,WAAW,CAAC;gBAC7C;YACJ;QACJ;IACJ;AAEA,IAAA,sBAAsB,CAAC,MAAc,EAAA;;AAEjC,QAAA,KAAK,MAAM,SAAS,IAAI,IAAI,CAAC,WAAW,CAAC,iBAAiB,CAAC,CAAC,MAAM,EAAE,EAAE;AAClE,YAAA,IAAI,SAAS,CAAC,MAAM,KAAK,MAAM,EAAE;gBAC7B,OAAO,SAAS,CAAC,MAAM;YAC3B;QACJ;AACA,QAAA,OAAO,IAAI;IACf;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,4 +1,4 @@
1
- import type { Task, PostHogAPIConfig } from './types.js';
1
+ import type { Task, PostHogAPIConfig, PostHogResource, UrlMention } from './types.js';
2
2
  import type { WorkflowDefinition, AgentDefinition } from './workflow-types.js';
3
3
  interface TaskProgressResponse {
4
4
  has_progress: boolean;
@@ -80,6 +80,18 @@ export declare class PostHogAPIClient {
80
80
  next_stage_id?: string;
81
81
  auto?: boolean;
82
82
  }): Promise<Task>;
83
+ /**
84
+ * Fetch error details from PostHog error tracking
85
+ */
86
+ fetchErrorDetails(errorId: string, projectId?: string): Promise<PostHogResource>;
87
+ /**
88
+ * Generic resource fetcher by URL or ID
89
+ */
90
+ fetchResourceByUrl(urlMention: UrlMention): Promise<PostHogResource>;
91
+ /**
92
+ * Format error data for agent consumption
93
+ */
94
+ private formatErrorContent;
83
95
  }
84
96
  export {};
85
97
  //# sourceMappingURL=posthog-api.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"posthog-api.d.ts","sourceRoot":"","sources":["../../src/posthog-api.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAkB,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACzE,OAAO,KAAK,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAS/E,UAAU,oBAAoB;IAC5B,YAAY,EAAE,OAAO,CAAC;IACtB,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,MAAM,CAAC,EAAE,SAAS,GAAG,aAAa,GAAG,WAAW,GAAG,QAAQ,CAAC;IAC5D,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,kBAAkB;IACjC,EAAE,EAAE,MAAM,CAAC;IACX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,GAAG;QAAE,MAAM,EAAE,kBAAkB,CAAC,QAAQ,CAAC,CAAA;KAAE,GACrE,OAAO,CAAC,kBAAkB,CAAC;IAWxB,kBAAkB,CACtB,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,kBAAkB,GAC1B,OAAO,CAAC,kBAAkB,CAAC;IAYxB,aAAa,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAK9D,aAAa,IAAI,OAAO,CAAC,kBAAkB,EAAE,CAAC;IAO9C,UAAU,IAAI,OAAO,CAAC,eAAe,EAAE,CAAC;IAIxC,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,aAAa,CAAC,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAQvG;;OAEG;IACG,iBAAiB,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC;IA4BtF;;OAEG;IACG,kBAAkB,CAAC,UAAU,EAAE,UAAU,GAAG,OAAO,CAAC,eAAe,CAAC;IAmC1E;;OAEG;IACH,OAAO,CAAC,kBAAkB;CAkC3B"}
@@ -154,6 +154,97 @@ class PostHogAPIClient {
154
154
  body: JSON.stringify(options || {}),
155
155
  });
156
156
  }
157
+ /**
158
+ * Fetch error details from PostHog error tracking
159
+ */
160
+ async fetchErrorDetails(errorId, projectId) {
161
+ const teamId = projectId ? parseInt(projectId) : await this.getTeamId();
162
+ try {
163
+ const errorData = await this.apiRequest(`/api/projects/${teamId}/error_tracking/${errorId}/`);
164
+ // Format error details for agent consumption
165
+ const content = this.formatErrorContent(errorData);
166
+ return {
167
+ type: 'error',
168
+ id: errorId,
169
+ url: `${this.baseUrl}/project/${teamId}/error_tracking/${errorId}`,
170
+ title: errorData.exception_type || 'Unknown Error',
171
+ content,
172
+ metadata: {
173
+ exception_type: errorData.exception_type,
174
+ first_seen: errorData.first_seen,
175
+ last_seen: errorData.last_seen,
176
+ volume: errorData.volume,
177
+ users_affected: errorData.users_affected,
178
+ },
179
+ };
180
+ }
181
+ catch (error) {
182
+ throw new Error(`Failed to fetch error details for ${errorId}: ${error}`);
183
+ }
184
+ }
185
+ /**
186
+ * Generic resource fetcher by URL or ID
187
+ */
188
+ async fetchResourceByUrl(urlMention) {
189
+ switch (urlMention.type) {
190
+ case 'error':
191
+ if (!urlMention.id) {
192
+ throw new Error('Error ID is required for error resources');
193
+ }
194
+ // Extract project ID from URL if available, otherwise use default team
195
+ let projectId;
196
+ if (urlMention.url) {
197
+ const projectIdMatch = urlMention.url.match(/\/project\/(\d+)\//);
198
+ projectId = projectIdMatch ? projectIdMatch[1] : undefined;
199
+ }
200
+ return this.fetchErrorDetails(urlMention.id, projectId);
201
+ case 'experiment':
202
+ case 'insight':
203
+ case 'feature_flag':
204
+ throw new Error(`Resource type '${urlMention.type}' not yet implemented`);
205
+ case 'generic':
206
+ // Return a minimal resource for generic URLs
207
+ return {
208
+ type: 'generic',
209
+ id: '',
210
+ url: urlMention.url,
211
+ title: 'Generic Resource',
212
+ content: `Generic resource: ${urlMention.url}`,
213
+ metadata: {},
214
+ };
215
+ default:
216
+ throw new Error(`Unknown resource type: ${urlMention.type}`);
217
+ }
218
+ }
219
+ /**
220
+ * Format error data for agent consumption
221
+ */
222
+ formatErrorContent(errorData) {
223
+ const sections = [];
224
+ if (errorData.exception_type) {
225
+ sections.push(`**Error Type**: ${errorData.exception_type}`);
226
+ }
227
+ if (errorData.exception_message) {
228
+ sections.push(`**Message**: ${errorData.exception_message}`);
229
+ }
230
+ if (errorData.stack_trace) {
231
+ sections.push(`**Stack Trace**:\n\`\`\`\n${errorData.stack_trace}\n\`\`\``);
232
+ }
233
+ if (errorData.volume) {
234
+ sections.push(`**Volume**: ${errorData.volume} occurrences`);
235
+ }
236
+ if (errorData.users_affected) {
237
+ sections.push(`**Users Affected**: ${errorData.users_affected}`);
238
+ }
239
+ if (errorData.first_seen && errorData.last_seen) {
240
+ sections.push(`**First Seen**: ${errorData.first_seen}`);
241
+ sections.push(`**Last Seen**: ${errorData.last_seen}`);
242
+ }
243
+ if (errorData.properties && Object.keys(errorData.properties).length > 0) {
244
+ sections.push(`**Properties**: ${JSON.stringify(errorData.properties, null, 2)}`);
245
+ }
246
+ return sections.join('\n\n');
247
+ }
157
248
  }
158
249
 
159
250
  export { PostHogAPIClient };
@@ -1 +1 @@
1
- {"version":3,"file":"posthog-api.js","sources":["../../src/posthog-api.ts"],"sourcesContent":["import type { Task, SupportingFile, PostHogAPIConfig } from './types.js';\nimport type { WorkflowDefinition, AgentDefinition } from './workflow-types.js';\n\ninterface PostHogApiResponse<T> {\n results?: T[];\n count?: number;\n next?: string | null;\n previous?: string | null;\n}\n\ninterface TaskProgressResponse {\n has_progress: boolean;\n id?: string;\n status?: \"started\" | \"in_progress\" | \"completed\" | \"failed\";\n current_step?: string;\n completed_steps?: number;\n total_steps?: number;\n progress_percentage?: number;\n output_log?: string;\n error_message?: string;\n created_at?: string;\n updated_at?: string;\n completed_at?: string;\n workflow_id?: string;\n workflow_run_id?: string;\n message?: string;\n}\n\nexport interface TaskProgressRecord {\n id: string;\n task: string;\n status: \"started\" | \"in_progress\" | \"completed\" | \"failed\";\n current_step?: string | null;\n completed_steps?: number | null;\n total_steps?: number | null;\n progress_percentage?: number | null;\n output_log?: string | null;\n error_message?: string | null;\n workflow_id?: string | null;\n workflow_run_id?: string | null;\n activity_id?: string | null;\n created_at: string;\n updated_at: string;\n completed_at?: string | null;\n}\n\nexport interface TaskProgressUpdate {\n status?: TaskProgressRecord[\"status\"];\n current_step?: string | null;\n completed_steps?: number | null;\n total_steps?: number | null;\n output_log?: string | null;\n error_message?: string | null;\n workflow_id?: string | null;\n workflow_run_id?: string | null;\n activity_id?: string | null;\n}\n\nexport class PostHogAPIClient {\n private config: PostHogAPIConfig;\n private _teamId: number | null = null;\n\n constructor(config: PostHogAPIConfig) {\n this.config = config;\n }\n\n private get baseUrl(): string {\n const host = this.config.apiUrl.endsWith(\"/\") \n ? this.config.apiUrl.slice(0, -1) \n : this.config.apiUrl;\n return host;\n }\n\n private get headers(): Record<string, string> {\n return {\n 'Authorization': `Bearer ${this.config.apiKey}`,\n 'Content-Type': 'application/json',\n };\n }\n\n private async apiRequest<T>(\n endpoint: string, \n options: RequestInit = {}\n ): Promise<T> {\n const url = `${this.baseUrl}${endpoint}`;\n \n const response = await fetch(url, {\n ...options,\n headers: {\n ...this.headers,\n ...options.headers,\n },\n });\n\n if (!response.ok) {\n let errorMessage: string;\n try {\n const errorResponse = await response.json();\n errorMessage = `Failed request: [${response.status}] ${JSON.stringify(errorResponse)}`;\n } catch {\n errorMessage = `Failed request: [${response.status}] ${response.statusText}`;\n }\n throw new Error(errorMessage);\n }\n\n return response.json();\n }\n\n async getTeamId(): Promise<number> {\n if (this._teamId !== null) {\n return this._teamId;\n }\n\n // Fetch user info to get team ID (following Array's pattern)\n const userResponse = await this.apiRequest<any>('/api/users/@me/');\n\n if (!userResponse.team?.id) {\n throw new Error('No team found for user');\n }\n\n const teamId = Number(userResponse.team.id);\n this._teamId = teamId;\n return teamId;\n }\n\n getBaseUrl(): string {\n return this.baseUrl;\n }\n\n getApiKey(): string {\n return this.config.apiKey;\n }\n\n async getLlmGatewayUrl(): Promise<string> {\n const teamId = await this.getTeamId();\n return `${this.baseUrl}/api/projects/${teamId}/llm_gateway`;\n }\n\n async fetchTask(taskId: string): Promise<Task> {\n const teamId = await this.getTeamId();\n return this.apiRequest<Task>(`/api/projects/${teamId}/tasks/${taskId}/`);\n }\n\n async listTasks(filters?: {\n repository?: string;\n organization?: string;\n origin_product?: string;\n workflow?: string;\n current_stage?: string;\n }): Promise<Task[]> {\n const teamId = await this.getTeamId();\n const url = new URL(`${this.baseUrl}/api/projects/${teamId}/tasks/`);\n \n if (filters) {\n Object.entries(filters).forEach(([key, value]) => {\n if (value) url.searchParams.append(key, value);\n });\n }\n\n const response = await this.apiRequest<PostHogApiResponse<Task>>(\n url.pathname + url.search\n );\n \n return response.results || [];\n }\n\n async updateTask(taskId: string, updates: Partial<Task>): Promise<Task> {\n const teamId = await this.getTeamId();\n return this.apiRequest<Task>(`/api/projects/${teamId}/tasks/${taskId}/`, {\n method: 'PATCH',\n body: JSON.stringify(updates),\n });\n }\n\n async updateTaskStage(taskId: string, stageId: string): Promise<Task> {\n const teamId = await this.getTeamId();\n return this.apiRequest<Task>(`/api/projects/${teamId}/tasks/${taskId}/update_stage/`, {\n method: 'PATCH',\n body: JSON.stringify({ current_stage: stageId }),\n });\n }\n\n async setTaskBranch(taskId: string, branch: string): Promise<Task> {\n const teamId = await this.getTeamId();\n return this.apiRequest<Task>(`/api/projects/${teamId}/tasks/${taskId}/set_branch/`, {\n method: \"POST\",\n body: JSON.stringify({ branch }),\n });\n }\n\n async attachTaskPullRequest(taskId: string, prUrl: string, branch?: string): Promise<Task> {\n const teamId = await this.getTeamId();\n const payload: Record<string, string> = { pr_url: prUrl };\n if (branch) {\n payload.branch = branch;\n }\n return this.apiRequest<Task>(`/api/projects/${teamId}/tasks/${taskId}/attach_pr/`, {\n method: \"POST\",\n body: JSON.stringify(payload),\n });\n }\n\n async getTaskProgress(taskId: string): Promise<TaskProgressResponse> {\n const teamId = await this.getTeamId();\n return this.apiRequest<TaskProgressResponse>(`/api/projects/${teamId}/tasks/${taskId}/progress/`);\n }\n\n async createTaskProgress(\n taskId: string,\n payload: TaskProgressUpdate & { status: TaskProgressRecord[\"status\"] }\n ): Promise<TaskProgressRecord> {\n const teamId = await this.getTeamId();\n return this.apiRequest<TaskProgressRecord>(`/api/projects/${teamId}/task_progress/`, {\n method: \"POST\",\n body: JSON.stringify({\n ...payload,\n task: taskId,\n }),\n });\n }\n\n async updateTaskProgress(\n taskId: string,\n progressId: string,\n payload: TaskProgressUpdate\n ): Promise<TaskProgressRecord> {\n const teamId = await this.getTeamId();\n return this.apiRequest<TaskProgressRecord>(`/api/projects/${teamId}/task_progress/${progressId}/`, {\n method: \"PATCH\",\n body: JSON.stringify({\n ...payload,\n task: taskId,\n }),\n });\n }\n\n // Workflow endpoints\n async fetchWorkflow(workflowId: string): Promise<WorkflowDefinition> {\n const teamId = await this.getTeamId();\n return this.apiRequest<WorkflowDefinition>(`/api/projects/${teamId}/workflows/${workflowId}/`);\n }\n\n async listWorkflows(): Promise<WorkflowDefinition[]> {\n const teamId = await this.getTeamId();\n const response = await this.apiRequest<PostHogApiResponse<WorkflowDefinition>>(`/api/projects/${teamId}/workflows/`);\n return response.results || [];\n }\n\n // Agent catalog exposure\n async listAgents(): Promise<AgentDefinition[]> {\n return this.apiRequest<AgentDefinition[]>(`/api/agents/`);\n }\n\n async progressTask(taskId: string, options?: { next_stage_id?: string; auto?: boolean }): Promise<Task> {\n const teamId = await this.getTeamId();\n return this.apiRequest<Task>(`/api/projects/${teamId}/tasks/${taskId}/progress_task/`, {\n method: 'POST',\n body: JSON.stringify(options || {}),\n });\n }\n}\n"],"names":[],"mappings":"MA0Da,gBAAgB,CAAA;AACnB,IAAA,MAAM;IACN,OAAO,GAAkB,IAAI;AAErC,IAAA,WAAA,CAAY,MAAwB,EAAA;AAClC,QAAA,IAAI,CAAC,MAAM,GAAG,MAAM;IACtB;AAEA,IAAA,IAAY,OAAO,GAAA;QACjB,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG;AAC1C,cAAE,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE;AAChC,cAAE,IAAI,CAAC,MAAM,CAAC,MAAM;AACtB,QAAA,OAAO,IAAI;IACb;AAEA,IAAA,IAAY,OAAO,GAAA;QACjB,OAAO;AACL,YAAA,eAAe,EAAE,CAAA,OAAA,EAAU,IAAI,CAAC,MAAM,CAAC,MAAM,CAAA,CAAE;AAC/C,YAAA,cAAc,EAAE,kBAAkB;SACnC;IACH;AAEQ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MAAM,aAAa,CAAC,UAAkB,EAAA;AACpC,QAAA,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,SAAS,EAAE;QACrC,OAAO,IAAI,CAAC,UAAU,CAAqB,CAAA,cAAA,EAAiB,MAAM,CAAA,WAAA,EAAc,UAAU,CAAA,CAAA,CAAG,CAAC;IAChG;AAEA,IAAA,MAAM,aAAa,GAAA;AACjB,QAAA,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,SAAS,EAAE;QACrC,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,UAAU,CAAyC,CAAA,cAAA,EAAiB,MAAM,CAAA,WAAA,CAAa,CAAC;AACpH,QAAA,OAAO,QAAQ,CAAC,OAAO,IAAI,EAAE;IAC/B;;AAGA,IAAA,MAAM,UAAU,GAAA;AACd,QAAA,OAAO,IAAI,CAAC,UAAU,CAAoB,CAAA,YAAA,CAAc,CAAC;IAC3D;AAEA,IAAA,MAAM,YAAY,CAAC,MAAc,EAAE,OAAoD,EAAA;AACrF,QAAA,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,SAAS,EAAE;QACrC,OAAO,IAAI,CAAC,UAAU,CAAO,iBAAiB,MAAM,CAAA,OAAA,EAAU,MAAM,CAAA,eAAA,CAAiB,EAAE;AACrF,YAAA,MAAM,EAAE,MAAM;YACd,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,IAAI,EAAE,CAAC;AACpC,SAAA,CAAC;IACJ;AACD;;;;"}
1
+ {"version":3,"file":"posthog-api.js","sources":["../../src/posthog-api.ts"],"sourcesContent":["import type { Task, SupportingFile, PostHogAPIConfig, PostHogResource, ResourceType, UrlMention } from './types.js';\nimport type { WorkflowDefinition, AgentDefinition } from './workflow-types.js';\n\ninterface PostHogApiResponse<T> {\n results?: T[];\n count?: number;\n next?: string | null;\n previous?: string | null;\n}\n\ninterface TaskProgressResponse {\n has_progress: boolean;\n id?: string;\n status?: \"started\" | \"in_progress\" | \"completed\" | \"failed\";\n current_step?: string;\n completed_steps?: number;\n total_steps?: number;\n progress_percentage?: number;\n output_log?: string;\n error_message?: string;\n created_at?: string;\n updated_at?: string;\n completed_at?: string;\n workflow_id?: string;\n workflow_run_id?: string;\n message?: string;\n}\n\nexport interface TaskProgressRecord {\n id: string;\n task: string;\n status: \"started\" | \"in_progress\" | \"completed\" | \"failed\";\n current_step?: string | null;\n completed_steps?: number | null;\n total_steps?: number | null;\n progress_percentage?: number | null;\n output_log?: string | null;\n error_message?: string | null;\n workflow_id?: string | null;\n workflow_run_id?: string | null;\n activity_id?: string | null;\n created_at: string;\n updated_at: string;\n completed_at?: string | null;\n}\n\nexport interface TaskProgressUpdate {\n status?: TaskProgressRecord[\"status\"];\n current_step?: string | null;\n completed_steps?: number | null;\n total_steps?: number | null;\n output_log?: string | null;\n error_message?: string | null;\n workflow_id?: string | null;\n workflow_run_id?: string | null;\n activity_id?: string | null;\n}\n\nexport class PostHogAPIClient {\n private config: PostHogAPIConfig;\n private _teamId: number | null = null;\n\n constructor(config: PostHogAPIConfig) {\n this.config = config;\n }\n\n private get baseUrl(): string {\n const host = this.config.apiUrl.endsWith(\"/\") \n ? this.config.apiUrl.slice(0, -1) \n : this.config.apiUrl;\n return host;\n }\n\n private get headers(): Record<string, string> {\n return {\n 'Authorization': `Bearer ${this.config.apiKey}`,\n 'Content-Type': 'application/json',\n };\n }\n\n private async apiRequest<T>(\n endpoint: string, \n options: RequestInit = {}\n ): Promise<T> {\n const url = `${this.baseUrl}${endpoint}`;\n \n const response = await fetch(url, {\n ...options,\n headers: {\n ...this.headers,\n ...options.headers,\n },\n });\n\n if (!response.ok) {\n let errorMessage: string;\n try {\n const errorResponse = await response.json();\n errorMessage = `Failed request: [${response.status}] ${JSON.stringify(errorResponse)}`;\n } catch {\n errorMessage = `Failed request: [${response.status}] ${response.statusText}`;\n }\n throw new Error(errorMessage);\n }\n\n return response.json();\n }\n\n async getTeamId(): Promise<number> {\n if (this._teamId !== null) {\n return this._teamId;\n }\n\n // Fetch user info to get team ID (following Array's pattern)\n const userResponse = await this.apiRequest<any>('/api/users/@me/');\n\n if (!userResponse.team?.id) {\n throw new Error('No team found for user');\n }\n\n const teamId = Number(userResponse.team.id);\n this._teamId = teamId;\n return teamId;\n }\n\n getBaseUrl(): string {\n return this.baseUrl;\n }\n\n getApiKey(): string {\n return this.config.apiKey;\n }\n\n async getLlmGatewayUrl(): Promise<string> {\n const teamId = await this.getTeamId();\n return `${this.baseUrl}/api/projects/${teamId}/llm_gateway`;\n }\n\n async fetchTask(taskId: string): Promise<Task> {\n const teamId = await this.getTeamId();\n return this.apiRequest<Task>(`/api/projects/${teamId}/tasks/${taskId}/`);\n }\n\n async listTasks(filters?: {\n repository?: string;\n organization?: string;\n origin_product?: string;\n workflow?: string;\n current_stage?: string;\n }): Promise<Task[]> {\n const teamId = await this.getTeamId();\n const url = new URL(`${this.baseUrl}/api/projects/${teamId}/tasks/`);\n \n if (filters) {\n Object.entries(filters).forEach(([key, value]) => {\n if (value) url.searchParams.append(key, value);\n });\n }\n\n const response = await this.apiRequest<PostHogApiResponse<Task>>(\n url.pathname + url.search\n );\n \n return response.results || [];\n }\n\n async updateTask(taskId: string, updates: Partial<Task>): Promise<Task> {\n const teamId = await this.getTeamId();\n return this.apiRequest<Task>(`/api/projects/${teamId}/tasks/${taskId}/`, {\n method: 'PATCH',\n body: JSON.stringify(updates),\n });\n }\n\n async updateTaskStage(taskId: string, stageId: string): Promise<Task> {\n const teamId = await this.getTeamId();\n return this.apiRequest<Task>(`/api/projects/${teamId}/tasks/${taskId}/update_stage/`, {\n method: 'PATCH',\n body: JSON.stringify({ current_stage: stageId }),\n });\n }\n\n async setTaskBranch(taskId: string, branch: string): Promise<Task> {\n const teamId = await this.getTeamId();\n return this.apiRequest<Task>(`/api/projects/${teamId}/tasks/${taskId}/set_branch/`, {\n method: \"POST\",\n body: JSON.stringify({ branch }),\n });\n }\n\n async attachTaskPullRequest(taskId: string, prUrl: string, branch?: string): Promise<Task> {\n const teamId = await this.getTeamId();\n const payload: Record<string, string> = { pr_url: prUrl };\n if (branch) {\n payload.branch = branch;\n }\n return this.apiRequest<Task>(`/api/projects/${teamId}/tasks/${taskId}/attach_pr/`, {\n method: \"POST\",\n body: JSON.stringify(payload),\n });\n }\n\n async getTaskProgress(taskId: string): Promise<TaskProgressResponse> {\n const teamId = await this.getTeamId();\n return this.apiRequest<TaskProgressResponse>(`/api/projects/${teamId}/tasks/${taskId}/progress/`);\n }\n\n async createTaskProgress(\n taskId: string,\n payload: TaskProgressUpdate & { status: TaskProgressRecord[\"status\"] }\n ): Promise<TaskProgressRecord> {\n const teamId = await this.getTeamId();\n return this.apiRequest<TaskProgressRecord>(`/api/projects/${teamId}/task_progress/`, {\n method: \"POST\",\n body: JSON.stringify({\n ...payload,\n task: taskId,\n }),\n });\n }\n\n async updateTaskProgress(\n taskId: string,\n progressId: string,\n payload: TaskProgressUpdate\n ): Promise<TaskProgressRecord> {\n const teamId = await this.getTeamId();\n return this.apiRequest<TaskProgressRecord>(`/api/projects/${teamId}/task_progress/${progressId}/`, {\n method: \"PATCH\",\n body: JSON.stringify({\n ...payload,\n task: taskId,\n }),\n });\n }\n\n // Workflow endpoints\n async fetchWorkflow(workflowId: string): Promise<WorkflowDefinition> {\n const teamId = await this.getTeamId();\n return this.apiRequest<WorkflowDefinition>(`/api/projects/${teamId}/workflows/${workflowId}/`);\n }\n\n async listWorkflows(): Promise<WorkflowDefinition[]> {\n const teamId = await this.getTeamId();\n const response = await this.apiRequest<PostHogApiResponse<WorkflowDefinition>>(`/api/projects/${teamId}/workflows/`);\n return response.results || [];\n }\n\n // Agent catalog exposure\n async listAgents(): Promise<AgentDefinition[]> {\n return this.apiRequest<AgentDefinition[]>(`/api/agents/`);\n }\n\n async progressTask(taskId: string, options?: { next_stage_id?: string; auto?: boolean }): Promise<Task> {\n const teamId = await this.getTeamId();\n return this.apiRequest<Task>(`/api/projects/${teamId}/tasks/${taskId}/progress_task/`, {\n method: 'POST',\n body: JSON.stringify(options || {}),\n });\n }\n\n /**\n * Fetch error details from PostHog error tracking\n */\n async fetchErrorDetails(errorId: string, projectId?: string): Promise<PostHogResource> {\n const teamId = projectId ? parseInt(projectId) : await this.getTeamId();\n \n try {\n const errorData = await this.apiRequest<any>(`/api/projects/${teamId}/error_tracking/${errorId}/`);\n \n // Format error details for agent consumption\n const content = this.formatErrorContent(errorData);\n \n return {\n type: 'error',\n id: errorId,\n url: `${this.baseUrl}/project/${teamId}/error_tracking/${errorId}`,\n title: errorData.exception_type || 'Unknown Error',\n content,\n metadata: {\n exception_type: errorData.exception_type,\n first_seen: errorData.first_seen,\n last_seen: errorData.last_seen,\n volume: errorData.volume,\n users_affected: errorData.users_affected,\n },\n };\n } catch (error) {\n throw new Error(`Failed to fetch error details for ${errorId}: ${error}`);\n }\n }\n\n /**\n * Generic resource fetcher by URL or ID\n */\n async fetchResourceByUrl(urlMention: UrlMention): Promise<PostHogResource> {\n switch (urlMention.type) {\n case 'error':\n if (!urlMention.id) {\n throw new Error('Error ID is required for error resources');\n }\n // Extract project ID from URL if available, otherwise use default team\n let projectId: string | undefined;\n if (urlMention.url) {\n const projectIdMatch = urlMention.url.match(/\\/project\\/(\\d+)\\//);\n projectId = projectIdMatch ? projectIdMatch[1] : undefined;\n }\n return this.fetchErrorDetails(urlMention.id, projectId);\n \n case 'experiment':\n case 'insight':\n case 'feature_flag':\n throw new Error(`Resource type '${urlMention.type}' not yet implemented`);\n \n case 'generic':\n // Return a minimal resource for generic URLs\n return {\n type: 'generic',\n id: '',\n url: urlMention.url,\n title: 'Generic Resource',\n content: `Generic resource: ${urlMention.url}`,\n metadata: {},\n };\n \n default:\n throw new Error(`Unknown resource type: ${urlMention.type}`);\n }\n }\n\n /**\n * Format error data for agent consumption\n */\n private formatErrorContent(errorData: any): string {\n const sections = [];\n \n if (errorData.exception_type) {\n sections.push(`**Error Type**: ${errorData.exception_type}`);\n }\n \n if (errorData.exception_message) {\n sections.push(`**Message**: ${errorData.exception_message}`);\n }\n \n if (errorData.stack_trace) {\n sections.push(`**Stack Trace**:\\n\\`\\`\\`\\n${errorData.stack_trace}\\n\\`\\`\\``);\n }\n \n if (errorData.volume) {\n sections.push(`**Volume**: ${errorData.volume} occurrences`);\n }\n \n if (errorData.users_affected) {\n sections.push(`**Users Affected**: ${errorData.users_affected}`);\n }\n \n if (errorData.first_seen && errorData.last_seen) {\n sections.push(`**First Seen**: ${errorData.first_seen}`);\n sections.push(`**Last Seen**: ${errorData.last_seen}`);\n }\n \n if (errorData.properties && Object.keys(errorData.properties).length > 0) {\n sections.push(`**Properties**: ${JSON.stringify(errorData.properties, null, 2)}`);\n }\n \n return sections.join('\\n\\n');\n }\n}\n"],"names":[],"mappings":"MA0Da,gBAAgB,CAAA;AACnB,IAAA,MAAM;IACN,OAAO,GAAkB,IAAI;AAErC,IAAA,WAAA,CAAY,MAAwB,EAAA;AAClC,QAAA,IAAI,CAAC,MAAM,GAAG,MAAM;IACtB;AAEA,IAAA,IAAY,OAAO,GAAA;QACjB,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG;AAC1C,cAAE,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE;AAChC,cAAE,IAAI,CAAC,MAAM,CAAC,MAAM;AACtB,QAAA,OAAO,IAAI;IACb;AAEA,IAAA,IAAY,OAAO,GAAA;QACjB,OAAO;AACL,YAAA,eAAe,EAAE,CAAA,OAAA,EAAU,IAAI,CAAC,MAAM,CAAC,MAAM,CAAA,CAAE;AAC/C,YAAA,cAAc,EAAE,kBAAkB;SACnC;IACH;AAEQ,IAAA,MAAM,UAAU,CACtB,QAAgB,EAChB,UAAuB,EAAE,EAAA;QAEzB,MAAM,GAAG,GAAG,CAAA,EAAG,IAAI,CAAC,OAAO,CAAA,EAAG,QAAQ,CAAA,CAAE;AAExC,QAAA,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,EAAE;AAChC,YA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,CAAE,CAAC;YACxD,QAAQ,CAAC,IAAI,CAAC,CAAA,eAAA,EAAkB,SAAS,CAAC,SAAS,CAAA,CAAE,CAAC;QACxD;AAEA,QAAA,IAAI,SAAS,CAAC,UAAU,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;AACxE,YAAA,QAAQ,CAAC,IAAI,CAAC,mBAAmB,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC,CAAA,CAAE,CAAC;QACnF;AAEA,QAAA,OAAO,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC;IAC9B;AACD;;;;"}
@@ -1,14 +1,18 @@
1
- import type { Task } from './types.js';
1
+ import type { Task, UrlMention, PostHogResource } from './types.js';
2
2
  import type { TemplateVariables } from './template-manager.js';
3
3
  import { Logger } from './utils/logger.js';
4
4
  export interface PromptBuilderDeps {
5
5
  getTaskFiles: (taskId: string) => Promise<any[]>;
6
6
  generatePlanTemplate: (vars: TemplateVariables) => Promise<string>;
7
+ posthogClient?: {
8
+ fetchResourceByUrl: (mention: UrlMention) => Promise<PostHogResource>;
9
+ };
7
10
  logger?: Logger;
8
11
  }
9
12
  export declare class PromptBuilder {
10
13
  private getTaskFiles;
11
14
  private generatePlanTemplate;
15
+ private posthogClient?;
12
16
  private logger;
13
17
  constructor(deps: PromptBuilderDeps);
14
18
  /**
@@ -20,6 +24,19 @@ export declare class PromptBuilder {
20
24
  * Read file contents from repository
21
25
  */
22
26
  private readFileContent;
27
+ /**
28
+ * Extract URL mentions from XML tags in description
29
+ * Formats: <error id="..." />, <experiment id="..." />, <url href="..." />
30
+ */
31
+ private extractUrlMentions;
32
+ /**
33
+ * Generate a display label for a URL mention
34
+ */
35
+ private generateUrlLabel;
36
+ /**
37
+ * Process URL references and fetch their content
38
+ */
39
+ private processUrlReferences;
23
40
  /**
24
41
  * Process description to extract file tags and read contents
25
42
  * Returns processed description and referenced file contents
@@ -1 +1 @@
1
- {"version":3,"file":"prompt-builder.d.ts","sourceRoot":"","sources":["../../src/prompt-builder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAC/D,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAI3C,MAAM,WAAW,iBAAiB;IAChC,YAAY,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;IACjD,oBAAoB,EAAE,CAAC,IAAI,EAAE,iBAAiB,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IACnE,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,qBAAa,aAAa;IACxB,OAAO,CAAC,YAAY,CAAoC;IACxD,OAAO,CAAC,oBAAoB,CAA4C;IACxE,OAAO,CAAC,MAAM,CAAS;gBAEX,IAAI,EAAE,iBAAiB;IAMnC;;;OAGG;IACH,OAAO,CAAC,gBAAgB;IAYxB;;OAEG;YACW,eAAe;IAW7B;;;OAGG;YACW,qBAAqB;IAgC7B,mBAAmB,CAAC,IAAI,EAAE,IAAI,EAAE,cAAc,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAkDzE,oBAAoB,CAAC,IAAI,EAAE,IAAI,EAAE,cAAc,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;CA8CjF"}
1
+ {"version":3,"file":"prompt-builder.d.ts","sourceRoot":"","sources":["../../src/prompt-builder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AACpE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAC/D,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAI3C,MAAM,WAAW,iBAAiB;IAChC,YAAY,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;IACjD,oBAAoB,EAAE,CAAC,IAAI,EAAE,iBAAiB,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IACnE,aAAa,CAAC,EAAE;QAAE,kBAAkB,EAAE,CAAC,OAAO,EAAE,UAAU,KAAK,OAAO,CAAC,eAAe,CAAC,CAAA;KAAE,CAAC;IAC1F,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,qBAAa,aAAa;IACxB,OAAO,CAAC,YAAY,CAAoC;IACxD,OAAO,CAAC,oBAAoB,CAA4C;IACxE,OAAO,CAAC,aAAa,CAAC,CAAqC;IAC3D,OAAO,CAAC,MAAM,CAAS;gBAEX,IAAI,EAAE,iBAAiB;IAOnC;;;OAGG;IACH,OAAO,CAAC,gBAAgB;IAYxB;;OAEG;YACW,eAAe;IAW7B;;;OAGG;IACH,OAAO,CAAC,kBAAkB;IA+B1B;;OAEG;IACH,OAAO,CAAC,gBAAgB;IAsBxB;;OAEG;YACW,oBAAoB;IAqDlC;;;OAGG;YACW,qBAAqB;IAgC7B,mBAAmB,CAAC,IAAI,EAAE,IAAI,EAAE,cAAc,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IA+DzE,oBAAoB,CAAC,IAAI,EAAE,IAAI,EAAE,cAAc,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;CA2DjF"}
@@ -5,10 +5,12 @@ import { join } from 'path';
5
5
  class PromptBuilder {
6
6
  getTaskFiles;
7
7
  generatePlanTemplate;
8
+ posthogClient;
8
9
  logger;
9
10
  constructor(deps) {
10
11
  this.getTaskFiles = deps.getTaskFiles;
11
12
  this.generatePlanTemplate = deps.generatePlanTemplate;
13
+ this.posthogClient = deps.posthogClient;
12
14
  this.logger = deps.logger || new Logger({ debug: false, prefix: '[PromptBuilder]' });
13
15
  }
14
16
  /**
@@ -38,6 +40,106 @@ class PromptBuilder {
38
40
  return null;
39
41
  }
40
42
  }
43
+ /**
44
+ * Extract URL mentions from XML tags in description
45
+ * Formats: <error id="..." />, <experiment id="..." />, <url href="..." />
46
+ */
47
+ extractUrlMentions(description) {
48
+ const mentions = [];
49
+ // PostHog resource mentions: <error id="..." />, <experiment id="..." />, etc.
50
+ const resourceRegex = /<(error|experiment|insight|feature_flag)\s+id="([^"]+)"\s*\/>/g;
51
+ let match;
52
+ while ((match = resourceRegex.exec(description)) !== null) {
53
+ const [, type, id] = match;
54
+ mentions.push({
55
+ url: '', // Will be reconstructed if needed
56
+ type: type,
57
+ id,
58
+ label: this.generateUrlLabel('', type),
59
+ });
60
+ }
61
+ // Generic URL mentions: <url href="..." />
62
+ const urlRegex = /<url\s+href="([^"]+)"\s*\/>/g;
63
+ while ((match = urlRegex.exec(description)) !== null) {
64
+ const [, url] = match;
65
+ mentions.push({
66
+ url,
67
+ type: 'generic',
68
+ label: this.generateUrlLabel(url, 'generic'),
69
+ });
70
+ }
71
+ return mentions;
72
+ }
73
+ /**
74
+ * Generate a display label for a URL mention
75
+ */
76
+ generateUrlLabel(url, type) {
77
+ try {
78
+ const urlObj = new URL(url);
79
+ switch (type) {
80
+ case 'error':
81
+ const errorMatch = url.match(/error_tracking\/([a-f0-9-]+)/);
82
+ return errorMatch ? `Error ${errorMatch[1].slice(0, 8)}...` : 'Error';
83
+ case 'experiment':
84
+ const expMatch = url.match(/experiments\/(\d+)/);
85
+ return expMatch ? `Experiment #${expMatch[1]}` : 'Experiment';
86
+ case 'insight':
87
+ return 'Insight';
88
+ case 'feature_flag':
89
+ return 'Feature Flag';
90
+ default:
91
+ return urlObj.hostname;
92
+ }
93
+ }
94
+ catch {
95
+ return 'URL';
96
+ }
97
+ }
98
+ /**
99
+ * Process URL references and fetch their content
100
+ */
101
+ async processUrlReferences(description) {
102
+ const urlMentions = this.extractUrlMentions(description);
103
+ const referencedResources = [];
104
+ if (urlMentions.length === 0 || !this.posthogClient) {
105
+ return { description, referencedResources };
106
+ }
107
+ // Fetch all referenced resources
108
+ for (const mention of urlMentions) {
109
+ try {
110
+ const resource = await this.posthogClient.fetchResourceByUrl(mention);
111
+ referencedResources.push(resource);
112
+ }
113
+ catch (error) {
114
+ this.logger.warn(`Failed to fetch resource from URL: ${mention.url}`, { error });
115
+ // Add a placeholder resource for failed fetches
116
+ referencedResources.push({
117
+ type: mention.type,
118
+ id: mention.id || '',
119
+ url: mention.url,
120
+ title: mention.label || 'Unknown Resource',
121
+ content: `Failed to fetch resource from ${mention.url}: ${error}`,
122
+ metadata: {},
123
+ });
124
+ }
125
+ }
126
+ // Replace URL tags with just the label for readability
127
+ let processedDescription = description;
128
+ for (const mention of urlMentions) {
129
+ if (mention.type === 'generic') {
130
+ // Generic URLs: <url href="..." />
131
+ const escapedUrl = mention.url.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
132
+ processedDescription = processedDescription.replace(new RegExp(`<url\\s+href="${escapedUrl}"\\s*/>`, 'g'), `@${mention.label}`);
133
+ }
134
+ else {
135
+ // PostHog resources: <error id="..." />, <experiment id="..." />, etc.
136
+ const escapedType = mention.type.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
137
+ const escapedId = mention.id ? mention.id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') : '';
138
+ processedDescription = processedDescription.replace(new RegExp(`<${escapedType}\\s+id="${escapedId}"\\s*/>`, 'g'), `@${mention.label}`);
139
+ }
140
+ }
141
+ return { description: processedDescription, referencedResources };
142
+ }
41
143
  /**
42
144
  * Process description to extract file tags and read contents
43
145
  * Returns processed description and referenced file contents
@@ -65,7 +167,9 @@ class PromptBuilder {
65
167
  }
66
168
  async buildPlanningPrompt(task, repositoryPath) {
67
169
  // Process file references in description
68
- const { description: processedDescription, referencedFiles } = await this.processFileReferences(task.description, repositoryPath);
170
+ const { description: descriptionAfterFiles, referencedFiles } = await this.processFileReferences(task.description, repositoryPath);
171
+ // Process URL references in description
172
+ const { description: processedDescription, referencedResources } = await this.processUrlReferences(descriptionAfterFiles);
69
173
  let prompt = '';
70
174
  prompt += `## Current Task\n\n**Task**: ${task.title}\n**Description**: ${processedDescription}`;
71
175
  if (task.primary_repository) {
@@ -78,6 +182,13 @@ class PromptBuilder {
78
182
  prompt += `### ${file.path}\n\`\`\`\n${file.content}\n\`\`\`\n\n`;
79
183
  }
80
184
  }
185
+ // Add referenced resources from URL mentions
186
+ if (referencedResources.length > 0) {
187
+ prompt += `\n\n## Referenced Resources\n\n`;
188
+ for (const resource of referencedResources) {
189
+ prompt += `### ${resource.title} (${resource.type})\n**URL**: ${resource.url}\n\n${resource.content}\n\n`;
190
+ }
191
+ }
81
192
  try {
82
193
  const taskFiles = await this.getTaskFiles(task.id);
83
194
  const contextFiles = taskFiles.filter((f) => f.type === 'context' || f.type === 'reference');
@@ -104,7 +215,9 @@ class PromptBuilder {
104
215
  }
105
216
  async buildExecutionPrompt(task, repositoryPath) {
106
217
  // Process file references in description
107
- const { description: processedDescription, referencedFiles } = await this.processFileReferences(task.description, repositoryPath);
218
+ const { description: descriptionAfterFiles, referencedFiles } = await this.processFileReferences(task.description, repositoryPath);
219
+ // Process URL references in description
220
+ const { description: processedDescription, referencedResources } = await this.processUrlReferences(descriptionAfterFiles);
108
221
  let prompt = '';
109
222
  prompt += `## Current Task\n\n**Task**: ${task.title}\n**Description**: ${processedDescription}`;
110
223
  if (task.primary_repository) {
@@ -117,6 +230,13 @@ class PromptBuilder {
117
230
  prompt += `### ${file.path}\n\`\`\`\n${file.content}\n\`\`\`\n\n`;
118
231
  }
119
232
  }
233
+ // Add referenced resources from URL mentions
234
+ if (referencedResources.length > 0) {
235
+ prompt += `\n\n## Referenced Resources\n\n`;
236
+ for (const resource of referencedResources) {
237
+ prompt += `### ${resource.title} (${resource.type})\n**URL**: ${resource.url}\n\n${resource.content}\n\n`;
238
+ }
239
+ }
120
240
  try {
121
241
  const taskFiles = await this.getTaskFiles(task.id);
122
242
  const hasPlan = taskFiles.some((f) => f.type === 'plan');
@@ -1 +1 @@
1
- {"version":3,"file":"prompt-builder.js","sources":["../../src/prompt-builder.ts"],"sourcesContent":["import type { Task } from './types.js';\nimport type { TemplateVariables } from './template-manager.js';\nimport { Logger } from './utils/logger.js';\nimport { promises as fs } from 'fs';\nimport { join } from 'path';\n\nexport interface PromptBuilderDeps {\n getTaskFiles: (taskId: string) => Promise<any[]>;\n generatePlanTemplate: (vars: TemplateVariables) => Promise<string>;\n logger?: Logger;\n}\n\nexport class PromptBuilder {\n private getTaskFiles: PromptBuilderDeps['getTaskFiles'];\n private generatePlanTemplate: PromptBuilderDeps['generatePlanTemplate'];\n private logger: Logger;\n\n constructor(deps: PromptBuilderDeps) {\n this.getTaskFiles = deps.getTaskFiles;\n this.generatePlanTemplate = deps.generatePlanTemplate;\n this.logger = deps.logger || new Logger({ debug: false, prefix: '[PromptBuilder]' });\n }\n\n /**\n * Extract file paths from XML tags in description\n * Format: <file path=\"relative/path.ts\" />\n */\n private extractFilePaths(description: string): string[] {\n const fileTagRegex = /<file\\s+path=\"([^\"]+)\"\\s*\\/>/g;\n const paths: string[] = [];\n let match: RegExpExecArray | null;\n\n while ((match = fileTagRegex.exec(description)) !== null) {\n paths.push(match[1]);\n }\n\n return paths;\n }\n\n /**\n * Read file contents from repository\n */\n private async readFileContent(repositoryPath: string, filePath: string): Promise<string | null> {\n try {\n const fullPath = join(repositoryPath, filePath);\n const content = await fs.readFile(fullPath, 'utf8');\n return content;\n } catch (error) {\n this.logger.warn(`Failed to read referenced file: ${filePath}`, { error });\n return null;\n }\n }\n\n /**\n * Process description to extract file tags and read contents\n * Returns processed description and referenced file contents\n */\n private async processFileReferences(\n description: string,\n repositoryPath?: string\n ): Promise<{ description: string; referencedFiles: Array<{ path: string; content: string }> }> {\n const filePaths = this.extractFilePaths(description);\n const referencedFiles: Array<{ path: string; content: string }> = [];\n\n if (filePaths.length === 0 || !repositoryPath) {\n return { description, referencedFiles };\n }\n\n // Read all referenced files\n for (const filePath of filePaths) {\n const content = await this.readFileContent(repositoryPath, filePath);\n if (content !== null) {\n referencedFiles.push({ path: filePath, content });\n }\n }\n\n // Replace file tags with just the filename for readability\n let processedDescription = description;\n for (const filePath of filePaths) {\n const fileName = filePath.split('/').pop() || filePath;\n processedDescription = processedDescription.replace(\n new RegExp(`<file\\\\s+path=\"${filePath.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\"\\\\s*/>`, 'g'),\n `@${fileName}`\n );\n }\n\n return { description: processedDescription, referencedFiles };\n }\n\n async buildPlanningPrompt(task: Task, repositoryPath?: string): Promise<string> {\n // Process file references in description\n const { description: processedDescription, referencedFiles } = await this.processFileReferences(\n task.description,\n repositoryPath\n );\n\n let prompt = '';\n prompt += `## Current Task\\n\\n**Task**: ${task.title}\\n**Description**: ${processedDescription}`;\n\n if ((task as any).primary_repository) {\n prompt += `\\n**Repository**: ${(task as any).primary_repository}`;\n }\n\n // Add referenced files from @ mentions\n if (referencedFiles.length > 0) {\n prompt += `\\n\\n## Referenced Files\\n\\n`;\n for (const file of referencedFiles) {\n prompt += `### ${file.path}\\n\\`\\`\\`\\n${file.content}\\n\\`\\`\\`\\n\\n`;\n }\n }\n\n try {\n const taskFiles = await this.getTaskFiles(task.id);\n const contextFiles = taskFiles.filter((f: any) => f.type === 'context' || f.type === 'reference');\n if (contextFiles.length > 0) {\n prompt += `\\n\\n## Supporting Files`;\n for (const file of contextFiles) {\n prompt += `\\n\\n### ${file.name} (${file.type})\\n${file.content}`;\n }\n }\n } catch (error) {\n this.logger.debug('No existing task files found for planning', { taskId: task.id });\n }\n\n const templateVariables = {\n task_id: task.id,\n task_title: task.title,\n task_description: processedDescription,\n date: new Date().toISOString().split('T')[0],\n repository: ((task as any).primary_repository || '') as string,\n };\n\n const planTemplate = await this.generatePlanTemplate(templateVariables);\n\n prompt += `\\n\\nPlease analyze the codebase and create a detailed implementation plan for this task. Use the following template structure for your plan:\\n\\n${planTemplate}\\n\\nFill in each section with specific, actionable information based on your analysis. Replace all placeholder content with actual details about this task.`;\n\n return prompt;\n }\n\n async buildExecutionPrompt(task: Task, repositoryPath?: string): Promise<string> {\n // Process file references in description\n const { description: processedDescription, referencedFiles } = await this.processFileReferences(\n task.description,\n repositoryPath\n );\n\n let prompt = '';\n prompt += `## Current Task\\n\\n**Task**: ${task.title}\\n**Description**: ${processedDescription}`;\n\n if ((task as any).primary_repository) {\n prompt += `\\n**Repository**: ${(task as any).primary_repository}`;\n }\n\n // Add referenced files from @ mentions\n if (referencedFiles.length > 0) {\n prompt += `\\n\\n## Referenced Files\\n\\n`;\n for (const file of referencedFiles) {\n prompt += `### ${file.path}\\n\\`\\`\\`\\n${file.content}\\n\\`\\`\\`\\n\\n`;\n }\n }\n\n try {\n const taskFiles = await this.getTaskFiles(task.id);\n const hasPlan = taskFiles.some((f: any) => f.type === 'plan');\n if (taskFiles.length > 0) {\n prompt += `\\n\\n## Context and Supporting Information`;\n for (const file of taskFiles) {\n if (file.type === 'plan') {\n prompt += `\\n\\n### Execution Plan\\n${file.content}`;\n } else {\n prompt += `\\n\\n### ${file.name} (${file.type})\\n${file.content}`;\n }\n }\n }\n if (hasPlan) {\n prompt += `\\n\\nPlease implement the changes described in the execution plan above. Follow the plan step-by-step and make the necessary file modifications. You must actually edit files and make changes - do not just analyze or review.`;\n } else {\n prompt += `\\n\\nPlease implement the changes described in the task above. You must actually edit files and make changes - do not just analyze or review.`;\n }\n } catch (error) {\n this.logger.debug('No supporting files found for execution', { taskId: task.id });\n prompt += `\\n\\nPlease implement the changes described in the task above.`;\n }\n return prompt;\n }\n}\n\n\n"],"names":["fs"],"mappings":";;;;MAYa,aAAa,CAAA;AAChB,IAAA,YAAY;AACZ,IAAA,oBAAoB;AACpB,IAAA,MAAM;AAEd,IAAA,WAAA,CAAY,IAAuB,EAAA;AACjC,QAAA,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,YAAY;AACrC,QAAA,IAAI,CAAC,oBAAoB,GAAG,IAAI,CAAC,o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,IAAI,CAAA,QAAA,EAAW,IAAI,CAAC,IAAI,CAAA,EAAA,EAAK,IAAI,CAAC,IAAI,CAAA,GAAA,EAAM,IAAI,CAAC,OAAO,EAAE;oBAClE;gBACF;YACF;YACA,IAAI,OAAO,EAAE;gBACX,MAAM,IAAI,gOAAgO;YAC5O;iBAAO;gBACL,MAAM,IAAI,8IAA8I;YAC1J;QACF;QAAE,OAAO,KAAK,EAAE;AACd,YAAA,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,yCAAyC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;YACjF,MAAM,IAAI,+DAA+D;QAC3E;AACA,QAAA,OAAO,MAAM;IACf;AACD;;;;"}
1
+ {"version":3,"file":"prompt-builder.js","sources":["../../src/prompt-builder.ts"],"sourcesContent":["import type { Task, UrlMention, PostHogResource } from './types.js';\nimport type { TemplateVariables } from './template-manager.js';\nimport { Logger } from './utils/logger.js';\nimport { promises as fs } from 'fs';\nimport { join } from 'path';\n\nexport interface PromptBuilderDeps {\n getTaskFiles: (taskId: string) => Promise<any[]>;\n generatePlanTemplate: (vars: TemplateVariables) => Promise<string>;\n posthogClient?: { fetchResourceByUrl: (mention: UrlMention) => Promise<PostHogResource> };\n logger?: Logger;\n}\n\nexport class PromptBuilder {\n private getTaskFiles: PromptBuilderDeps['getTaskFiles'];\n private generatePlanTemplate: PromptBuilderDeps['generatePlanTemplate'];\n private posthogClient?: PromptBuilderDeps['posthogClient'];\n private logger: Logger;\n\n constructor(deps: PromptBuilderDeps) {\n this.getTaskFiles = deps.getTaskFiles;\n this.generatePlanTemplate = deps.generatePlanTemplate;\n this.posthogClient = deps.posthogClient;\n this.logger = deps.logger || new Logger({ debug: false, prefix: '[PromptBuilder]' });\n }\n\n /**\n * Extract file paths from XML tags in description\n * Format: <file path=\"relative/path.ts\" />\n */\n private extractFilePaths(description: string): string[] {\n const fileTagRegex = /<file\\s+path=\"([^\"]+)\"\\s*\\/>/g;\n const paths: string[] = [];\n let match: RegExpExecArray | null;\n\n while ((match = fileTagRegex.exec(description)) !== null) {\n paths.push(match[1]);\n }\n\n return paths;\n }\n\n /**\n * Read file contents from repository\n */\n private async readFileContent(repositoryPath: string, filePath: string): Promise<string | null> {\n try {\n const fullPath = join(repositoryPath, filePath);\n const content = await fs.readFile(fullPath, 'utf8');\n return content;\n } catch (error) {\n this.logger.warn(`Failed to read referenced file: ${filePath}`, { error });\n return null;\n }\n }\n\n /**\n * Extract URL mentions from XML tags in description\n * Formats: <error id=\"...\" />, <experiment id=\"...\" />, <url href=\"...\" />\n */\n private extractUrlMentions(description: string): UrlMention[] {\n const mentions: UrlMention[] = [];\n \n // PostHog resource mentions: <error id=\"...\" />, <experiment id=\"...\" />, etc.\n const resourceRegex = /<(error|experiment|insight|feature_flag)\\s+id=\"([^\"]+)\"\\s*\\/>/g;\n let match: RegExpExecArray | null;\n\n while ((match = resourceRegex.exec(description)) !== null) {\n const [, type, id] = match;\n mentions.push({\n url: '', // Will be reconstructed if needed\n type: type as any,\n id,\n label: this.generateUrlLabel('', type as any),\n });\n }\n\n // Generic URL mentions: <url href=\"...\" />\n const urlRegex = /<url\\s+href=\"([^\"]+)\"\\s*\\/>/g;\n while ((match = urlRegex.exec(description)) !== null) {\n const [, url] = match;\n mentions.push({\n url,\n type: 'generic',\n label: this.generateUrlLabel(url, 'generic'),\n });\n }\n\n return mentions;\n }\n\n /**\n * Generate a display label for a URL mention\n */\n private generateUrlLabel(url: string, type: string): string {\n try {\n const urlObj = new URL(url);\n switch (type) {\n case 'error':\n const errorMatch = url.match(/error_tracking\\/([a-f0-9-]+)/);\n return errorMatch ? `Error ${errorMatch[1].slice(0, 8)}...` : 'Error';\n case 'experiment':\n const expMatch = url.match(/experiments\\/(\\d+)/);\n return expMatch ? `Experiment #${expMatch[1]}` : 'Experiment';\n case 'insight':\n return 'Insight';\n case 'feature_flag':\n return 'Feature Flag';\n default:\n return urlObj.hostname;\n }\n } catch {\n return 'URL';\n }\n }\n\n /**\n * Process URL references and fetch their content\n */\n private async processUrlReferences(\n description: string\n ): Promise<{ description: string; referencedResources: PostHogResource[] }> {\n const urlMentions = this.extractUrlMentions(description);\n const referencedResources: PostHogResource[] = [];\n\n if (urlMentions.length === 0 || !this.posthogClient) {\n return { description, referencedResources };\n }\n\n // Fetch all referenced resources\n for (const mention of urlMentions) {\n try {\n const resource = await this.posthogClient.fetchResourceByUrl(mention);\n referencedResources.push(resource);\n } catch (error) {\n this.logger.warn(`Failed to fetch resource from URL: ${mention.url}`, { error });\n // Add a placeholder resource for failed fetches\n referencedResources.push({\n type: mention.type,\n id: mention.id || '',\n url: mention.url,\n title: mention.label || 'Unknown Resource',\n content: `Failed to fetch resource from ${mention.url}: ${error}`,\n metadata: {},\n });\n }\n }\n\n // Replace URL tags with just the label for readability\n let processedDescription = description;\n for (const mention of urlMentions) {\n if (mention.type === 'generic') {\n // Generic URLs: <url href=\"...\" />\n const escapedUrl = mention.url.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n processedDescription = processedDescription.replace(\n new RegExp(`<url\\\\s+href=\"${escapedUrl}\"\\\\s*/>`, 'g'),\n `@${mention.label}`\n );\n } else {\n // PostHog resources: <error id=\"...\" />, <experiment id=\"...\" />, etc.\n const escapedType = mention.type.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const escapedId = mention.id ? mention.id.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&') : '';\n processedDescription = processedDescription.replace(\n new RegExp(`<${escapedType}\\\\s+id=\"${escapedId}\"\\\\s*/>`, 'g'),\n `@${mention.label}`\n );\n }\n }\n\n return { description: processedDescription, referencedResources };\n }\n\n /**\n * Process description to extract file tags and read contents\n * Returns processed description and referenced file contents\n */\n private async processFileReferences(\n description: string,\n repositoryPath?: string\n ): Promise<{ description: string; referencedFiles: Array<{ path: string; content: string }> }> {\n const filePaths = this.extractFilePaths(description);\n const referencedFiles: Array<{ path: string; content: string }> = [];\n\n if (filePaths.length === 0 || !repositoryPath) {\n return { description, referencedFiles };\n }\n\n // Read all referenced files\n for (const filePath of filePaths) {\n const content = await this.readFileContent(repositoryPath, filePath);\n if (content !== null) {\n referencedFiles.push({ path: filePath, content });\n }\n }\n\n // Replace file tags with just the filename for readability\n let processedDescription = description;\n for (const filePath of filePaths) {\n const fileName = filePath.split('/').pop() || filePath;\n processedDescription = processedDescription.replace(\n new RegExp(`<file\\\\s+path=\"${filePath.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\"\\\\s*/>`, 'g'),\n `@${fileName}`\n );\n }\n\n return { description: processedDescription, referencedFiles };\n }\n\n async buildPlanningPrompt(task: Task, repositoryPath?: string): Promise<string> {\n // Process file references in description\n const { description: descriptionAfterFiles, referencedFiles } = await this.processFileReferences(\n task.description,\n repositoryPath\n );\n\n // Process URL references in description \n const { description: processedDescription, referencedResources } = await this.processUrlReferences(\n descriptionAfterFiles\n );\n\n let prompt = '';\n prompt += `## Current Task\\n\\n**Task**: ${task.title}\\n**Description**: ${processedDescription}`;\n\n if ((task as any).primary_repository) {\n prompt += `\\n**Repository**: ${(task as any).primary_repository}`;\n }\n\n // Add referenced files from @ mentions\n if (referencedFiles.length > 0) {\n prompt += `\\n\\n## Referenced Files\\n\\n`;\n for (const file of referencedFiles) {\n prompt += `### ${file.path}\\n\\`\\`\\`\\n${file.content}\\n\\`\\`\\`\\n\\n`;\n }\n }\n\n // Add referenced resources from URL mentions\n if (referencedResources.length > 0) {\n prompt += `\\n\\n## Referenced Resources\\n\\n`;\n for (const resource of referencedResources) {\n prompt += `### ${resource.title} (${resource.type})\\n**URL**: ${resource.url}\\n\\n${resource.content}\\n\\n`;\n }\n }\n\n try {\n const taskFiles = await this.getTaskFiles(task.id);\n const contextFiles = taskFiles.filter((f: any) => f.type === 'context' || f.type === 'reference');\n if (contextFiles.length > 0) {\n prompt += `\\n\\n## Supporting Files`;\n for (const file of contextFiles) {\n prompt += `\\n\\n### ${file.name} (${file.type})\\n${file.content}`;\n }\n }\n } catch (error) {\n this.logger.debug('No existing task files found for planning', { taskId: task.id });\n }\n\n const templateVariables = {\n task_id: task.id,\n task_title: task.title,\n task_description: processedDescription,\n date: new Date().toISOString().split('T')[0],\n repository: ((task as any).primary_repository || '') as string,\n };\n\n const planTemplate = await this.generatePlanTemplate(templateVariables);\n\n prompt += `\\n\\nPlease analyze the codebase and create a detailed implementation plan for this task. Use the following template structure for your plan:\\n\\n${planTemplate}\\n\\nFill in each section with specific, actionable information based on your analysis. Replace all placeholder content with actual details about this task.`;\n\n return prompt;\n }\n\n async buildExecutionPrompt(task: Task, repositoryPath?: string): Promise<string> {\n // Process file references in description\n const { description: descriptionAfterFiles, referencedFiles } = await this.processFileReferences(\n task.description,\n repositoryPath\n );\n\n // Process URL references in description \n const { description: processedDescription, referencedResources } = await this.processUrlReferences(\n descriptionAfterFiles\n );\n\n let prompt = '';\n prompt += `## Current Task\\n\\n**Task**: ${task.title}\\n**Description**: ${processedDescription}`;\n\n if ((task as any).primary_repository) {\n prompt += `\\n**Repository**: ${(task as any).primary_repository}`;\n }\n\n // Add referenced files from @ mentions\n if (referencedFiles.length > 0) {\n prompt += `\\n\\n## Referenced Files\\n\\n`;\n for (const file of referencedFiles) {\n prompt += `### ${file.path}\\n\\`\\`\\`\\n${file.content}\\n\\`\\`\\`\\n\\n`;\n }\n }\n\n // Add referenced resources from URL mentions\n if (referencedResources.length > 0) {\n prompt += `\\n\\n## Referenced Resources\\n\\n`;\n for (const resource of referencedResources) {\n prompt += `### ${resource.title} (${resource.type})\\n**URL**: ${resource.url}\\n\\n${resource.content}\\n\\n`;\n }\n }\n\n try {\n const taskFiles = await this.getTaskFiles(task.id);\n const hasPlan = taskFiles.some((f: any) => f.type === 'plan');\n if (taskFiles.length > 0) {\n prompt += `\\n\\n## Context and Supporting Information`;\n for (const file of taskFiles) {\n if (file.type === 'plan') {\n prompt += `\\n\\n### Execution Plan\\n${file.content}`;\n } else {\n prompt += `\\n\\n### ${file.name} (${file.type})\\n${file.content}`;\n }\n }\n }\n if (hasPlan) {\n prompt += `\\n\\nPlease implement the changes described in the execution plan above. Follow the plan step-by-step and make the necessary file modifications. You must actually edit files and make changes - do not just analyze or review.`;\n } else {\n prompt += `\\n\\nPlease implement the changes described in the task above. You must actually edit files and make changes - do not just analyze or review.`;\n }\n } catch (error) {\n this.logger.debug('No supporting files found for execution', { taskId: task.id });\n prompt += `\\n\\nPlease implement the changes described in the task above.`;\n }\n return prompt;\n }\n}\n\n\n"],"names":["fs"],"mappings":";;;;MAaa,aAAa,CAAA;AAChB,IAAA,YAAY;AACZ,IAAA,oBAAoB;AACpB,IAAA,aAAa;AACb,IAAA,MAAM;AAEd,IAAA,WAAA,CAAY,IAAuB,EAAA;AACjC,QAAA,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,YAAY;AACrC,QAAA,IAAI,CAAC,oBAAoB,GAAG,IAAI,CAAC,oBAAoB;AACrD,QAAA,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,aAAa;QACvC,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,IAAI,IAAI,MAAM,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,iBAAiB,EAAE,CAAC;IACtF;AAEA;;;AAGG;AACK,IAAA,gBAAgB,CAAC,WAAmB,EAAA;QAC1C,MAAM,YAAY,GAAG,+BAA+B;QACpD,MAAM,KAAK,GAAa,EAAE;AAC1B,QAAA,IAAI,KAA6B;AAEjC,QAAA,OAAO,CAAC,KAAK,GAAG,YAAY,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,IAAI,EAAE;YACxD,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACtB;AAEA,QAAA,OAAO,KAAK;IACd;AAEA;;AAEG;AACK,IAAA,MAAM,eAAe,CAAC,cAAsB,EAAE,QAAgB,EAAA;AACpE,QAAA,IAAI;YACF,MAAM,QAAQ,GAAG,IAAI,CAAC,cAAc,EAAE,QAAQ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AA,IAAI,IAAI,CAAC,IAAI,KAAK,MAAM,EAAE;AACxB,wBAAA,MAAM,IAAI,CAAA,wBAAA,EAA2B,IAAI,CAAC,OAAO,EAAE;oBACrD;yBAAO;AACL,wBAAA,MAAM,IAAI,CAAA,QAAA,EAAW,IAAI,CAAC,IAAI,CAAA,EAAA,EAAK,IAAI,CAAC,IAAI,CAAA,GAAA,EAAM,IAAI,CAAC,OAAO,EAAE;oBAClE;gBACF;YACF;YACA,IAAI,OAAO,EAAE;gBACX,MAAM,IAAI,gOAAgO;YAC5O;iBAAO;gBACL,MAAM,IAAI,8IAA8I;YAC1J;QACF;QAAE,OAAO,KAAK,EAAE;AACd,YAAA,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,yCAAyC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;YACjF,MAAM,IAAI,+DAA+D;QAC3E;AACA,QAAA,OAAO,MAAM;IACf;AACD;;;;"}
@@ -185,5 +185,20 @@ export interface PostHogAPIConfig {
185
185
  apiUrl: string;
186
186
  apiKey: string;
187
187
  }
188
+ export type ResourceType = 'error' | 'experiment' | 'insight' | 'feature_flag' | 'generic';
189
+ export interface PostHogResource {
190
+ type: ResourceType;
191
+ id: string;
192
+ url: string;
193
+ title?: string;
194
+ content: string;
195
+ metadata?: Record<string, any>;
196
+ }
197
+ export interface UrlMention {
198
+ url: string;
199
+ type: ResourceType;
200
+ id?: string;
201
+ label?: string;
202
+ }
188
203
  export {};
189
204
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AACA,MAAM,WAAW,IAAI;IACnB,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,cAAc,EAAE,gBAAgB,GAAG,eAAe,GAAG,cAAc,GAAG,eAAe,GAAG,mBAAmB,CAAC;IAC5G,Q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gB,CAAC,EAAE,MAAM,CAAC;IAC1B,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,IAAI,CAAC;IAGtC,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,aAAa,CAAC,EAAE,MAAM,CAAC;IAGvB,aAAa,CAAC,EAAE,MAAM,CAAC;IAKvB,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;IAG7C,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED,MAAM,WAAW,gBAAgB;IAC/B,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CAChB;AAGD,MAAM,MAAM,YAAY,GAAG,OAAO,GAAG,YAAY,GAAG,SAAS,GAAG,cAAc,GAAG,SAAS,CAAC;AAE3F,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,YAAY,CAAC;IACnB,EAAE,EAAE,MAAM,CAAC;IACX,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;CAChC;AAED,MAAM,WAAW,UAAU;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,YAAY,CAAC;IACnB,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sources":["../../src/types.ts"],"sourcesContent":["// PostHog Task model (matches Array's OpenAPI schema)\nexport interface Task {\n id: string;\n title: string;\n description: string;\n origin_product: 'error_tracking' | 'eval_clusters' | 'user_created' | 'support_queue' | 'session_summaries';\n position?: number;\n workflow?: string | null;\n current_stage?: string | null;\n github_integration?: number | null;\n repository_config?: unknown; // JSONField\n repository_list: string;\n primary_repository: string;\n github_branch: string | null;\n github_pr_url: string | null;\n created_at: string;\n updated_at: string;\n}\n\nexport interface SupportingFile {\n name: string;\n content: string;\n type: 'plan' | 'context' | 'reference' | 'output';\n created_at: string;\n}\n\n// Removed legacy ExecutionMode in favor of configurable workflows\n\nexport enum PermissionMode {\n PLAN = \"plan\",\n DEFAULT = \"default\",\n ACCEPT_EDITS = \"acceptEdits\",\n BYPASS = \"bypassPermissions\"\n}\n\nexport interface ExecutionOptions {\n repositoryPath?: string;\n permissionMode?: PermissionMode;\n}\n\n// Base event with timestamp\ninterface BaseEvent {\n ts: number;\n}\n\n// Streaming content events\nexport interface TokenEvent extends BaseEvent {\n type: 'token';\n content: string;\n contentType?: 'text' | 'thinking' | 'tool_input';\n}\n\nexport interface ContentBlockStartEvent extends BaseEvent {\n type: 'content_block_start';\n index: number;\n contentType: 'text' | 'tool_use' | 'thinking';\n toolName?: string;\n toolId?: string;\n}\n\nexport interface ContentBlockStopEvent extends BaseEvent {\n type: 'content_block_stop';\n index: number;\n}\n\n// Tool events\nexport interface ToolCallEvent extends BaseEvent {\n type: 'tool_call';\n toolName: string;\n callId: string;\n args: Record<string, any>;\n}\n\nexport interface ToolResultEvent extends BaseEvent {\n type: 'tool_result';\n toolName: string;\n callId: string;\n result: any;\n}\n\n// Message lifecycle events\nexport interface MessageStartEvent extends BaseEvent {\n type: 'message_start';\n messageId?: string;\n model?: string;\n}\n\nexport interface MessageDeltaEvent extends BaseEvent {\n type: 'message_delta';\n stopReason?: string;\n stopSequence?: string;\n usage?: {\n outputTokens: number;\n };\n}\n\nexport interface MessageStopEvent extends BaseEvent {\n type: 'message_stop';\n}\n\n// User message events\nexport interface UserMessageEvent extends BaseEvent {\n type: 'user_message';\n content: string;\n isSynthetic?: boolean;\n}\n\n// System events\nexport interface StatusEvent extends BaseEvent {\n type: 'status';\n phase: string;\n [key: string]: any;\n}\n\nexport interface InitEvent extends BaseEvent {\n type: 'init';\n model: string;\n tools: string[];\n permissionMode: string;\n cwd: string;\n apiKeySource: string;\n}\n\nexport interface CompactBoundaryEvent extends BaseEvent {\n type: 'compact_boundary';\n trigger: 'manual' | 'auto';\n preTokens: number;\n}\n\n// Result events\nexport interface DoneEvent extends BaseEvent {\n type: 'done';\n durationMs?: number;\n numTurns?: number;\n totalCostUsd?: number;\n usage?: any;\n}\n\nexport interface ErrorEvent extends BaseEvent {\n type: 'error';\n message: string;\n error?: any;\n errorType?: string;\n context?: Record<string, any>; // Partial error context for debugging\n sdkError?: any; // Original SDK error object\n}\n\n// Legacy events (keeping for backwards compatibility)\nexport interface DiffEvent extends BaseEvent {\n type: 'diff';\n file: string;\n patch: string;\n summary?: string;\n}\n\nexport interface FileWriteEvent extends BaseEvent {\n type: 'file_write';\n path: string;\n bytes: number;\n}\n\nexport interface MetricEvent extends BaseEvent {\n type: 'metric';\n key: string;\n value: number;\n unit?: string;\n}\n\nexport interface ArtifactEvent extends BaseEvent {\n type: 'artifact';\n kind: string;\n content: any;\n}\n\nexport interface RawSDKEvent extends BaseEvent {\n type: 'raw_sdk_event';\n sdkMessage: any; // Full SDK message for debugging\n}\n\nexport type AgentEvent =\n | TokenEvent\n | ContentBlockStartEvent\n | ContentBlockStopEvent\n | ToolCallEvent\n | ToolResultEvent\n | MessageStartEvent\n | MessageDeltaEvent\n | MessageStopEvent\n | UserMessageEvent\n | StatusEvent\n | InitEvent\n | CompactBoundaryEvent\n | DoneEvent\n | ErrorEvent\n | DiffEvent\n | FileWriteEvent\n | MetricEvent\n | ArtifactEvent\n | RawSDKEvent;\n\nexport interface ExecutionResult {\n results: any[];\n}\n\nexport interface PlanResult {\n plan: string;\n}\n\nexport interface TaskExecutionResult {\n task: Task;\n plan?: string;\n executionResult?: ExecutionResult;\n // Deprecated: mode removed in workflow-based execution\n}\n\n// MCP Server configuration types (re-exported from Claude SDK for convenience)\nexport type McpServerConfig = {\n type?: 'stdio';\n command: string;\n args?: string[];\n env?: Record<string, string>;\n} | {\n type: 'sse';\n url: string;\n headers?: Record<string, string>;\n} | {\n type: 'http';\n url: string;\n headers?: Record<string, string>;\n} | {\n type: 'sdk';\n name: string;\n instance?: any; // McpServer instance\n};\n\nexport interface AgentConfig {\n workingDirectory?: string;\n onEvent?: (event: AgentEvent) => void;\n\n // PostHog API configuration\n posthogApiUrl?: string;\n posthogApiKey?: string;\n\n // PostHog MCP configuration\n posthogMcpUrl?: string;\n\n // MCP Server configuration\n // Additional MCP servers (PostHog MCP is always included by default)\n // You can override the PostHog MCP config by providing mcpServers.posthog\n mcpServers?: Record<string, McpServerConfig>;\n\n // Logging configuration\n debug?: boolean;\n}\n\nexport interface PostHogAPIConfig {\n apiUrl: string;\n apiKey: string;\n}"],"names":[],"mappings":"AA0BA;IAEY;AAAZ,CAAA,UAAY,cAAc,EAAA;AACxB,IAAA,cAAA,CAAA,MAAA,CAAA,GAAA,MAAa;AACb,IAAA,cAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACnB,IAAA,cAAA,CAAA,cAAA,CAAA,GAAA,aAA4B;AAC5B,IAAA,cAAA,CAAA,QAAA,CAAA,GAAA,mBAA4B;AAC9B,CAAC,EALW,cAAc,KAAd,cAAc,GAAA,EAAA,CAAA,CAAA;;;;"}
1
+ {"version":3,"file":"types.js","sources":["../../src/types.ts"],"sourcesContent":["// PostHog Task model (matches Array's OpenAPI schema)\nexport interface Task {\n id: string;\n title: string;\n description: string;\n origin_product: 'error_tracking' | 'eval_clusters' | 'user_created' | 'support_queue' | 'session_summaries';\n position?: number;\n workflow?: string | null;\n current_stage?: string | null;\n github_integration?: number | null;\n repository_config?: unknown; // JSONField\n repository_list: string;\n primary_repository: string;\n github_branch: string | null;\n github_pr_url: string | null;\n created_at: string;\n updated_at: string;\n}\n\nexport interface SupportingFile {\n name: string;\n content: string;\n type: 'plan' | 'context' | 'reference' | 'output';\n created_at: string;\n}\n\n// Removed legacy ExecutionMode in favor of configurable workflows\n\nexport enum PermissionMode {\n PLAN = \"plan\",\n DEFAULT = \"default\",\n ACCEPT_EDITS = \"acceptEdits\",\n BYPASS = \"bypassPermissions\"\n}\n\nexport interface ExecutionOptions {\n repositoryPath?: string;\n permissionMode?: PermissionMode;\n}\n\n// Base event with timestamp\ninterface BaseEvent {\n ts: number;\n}\n\n// Streaming content events\nexport interface TokenEvent extends BaseEvent {\n type: 'token';\n content: string;\n contentType?: 'text' | 'thinking' | 'tool_input';\n}\n\nexport interface ContentBlockStartEvent extends BaseEvent {\n type: 'content_block_start';\n index: number;\n contentType: 'text' | 'tool_use' | 'thinking';\n toolName?: string;\n toolId?: string;\n}\n\nexport interface ContentBlockStopEvent extends BaseEvent {\n type: 'content_block_stop';\n index: number;\n}\n\n// Tool events\nexport interface ToolCallEvent extends BaseEvent {\n type: 'tool_call';\n toolName: string;\n callId: string;\n args: Record<string, any>;\n}\n\nexport interface ToolResultEvent extends BaseEvent {\n type: 'tool_result';\n toolName: string;\n callId: string;\n result: any;\n}\n\n// Message lifecycle events\nexport interface MessageStartEvent extends BaseEvent {\n type: 'message_start';\n messageId?: string;\n model?: string;\n}\n\nexport interface MessageDeltaEvent extends BaseEvent {\n type: 'message_delta';\n stopReason?: string;\n stopSequence?: string;\n usage?: {\n outputTokens: number;\n };\n}\n\nexport interface MessageStopEvent extends BaseEvent {\n type: 'message_stop';\n}\n\n// User message events\nexport interface UserMessageEvent extends BaseEvent {\n type: 'user_message';\n content: string;\n isSynthetic?: boolean;\n}\n\n// System events\nexport interface StatusEvent extends BaseEvent {\n type: 'status';\n phase: string;\n [key: string]: any;\n}\n\nexport interface InitEvent extends BaseEvent {\n type: 'init';\n model: string;\n tools: string[];\n permissionMode: string;\n cwd: string;\n apiKeySource: string;\n}\n\nexport interface CompactBoundaryEvent extends BaseEvent {\n type: 'compact_boundary';\n trigger: 'manual' | 'auto';\n preTokens: number;\n}\n\n// Result events\nexport interface DoneEvent extends BaseEvent {\n type: 'done';\n durationMs?: number;\n numTurns?: number;\n totalCostUsd?: number;\n usage?: any;\n}\n\nexport interface ErrorEvent extends BaseEvent {\n type: 'error';\n message: string;\n error?: any;\n errorType?: string;\n context?: Record<string, any>; // Partial error context for debugging\n sdkError?: any; // Original SDK error object\n}\n\n// Legacy events (keeping for backwards compatibility)\nexport interface DiffEvent extends BaseEvent {\n type: 'diff';\n file: string;\n patch: string;\n summary?: string;\n}\n\nexport interface FileWriteEvent extends BaseEvent {\n type: 'file_write';\n path: string;\n bytes: number;\n}\n\nexport interface MetricEvent extends BaseEvent {\n type: 'metric';\n key: string;\n value: number;\n unit?: string;\n}\n\nexport interface ArtifactEvent extends BaseEvent {\n type: 'artifact';\n kind: string;\n content: any;\n}\n\nexport interface RawSDKEvent extends BaseEvent {\n type: 'raw_sdk_event';\n sdkMessage: any; // Full SDK message for debugging\n}\n\nexport type AgentEvent =\n | TokenEvent\n | ContentBlockStartEvent\n | ContentBlockStopEvent\n | ToolCallEvent\n | ToolResultEvent\n | MessageStartEvent\n | MessageDeltaEvent\n | MessageStopEvent\n | UserMessageEvent\n | StatusEvent\n | InitEvent\n | CompactBoundaryEvent\n | DoneEvent\n | ErrorEvent\n | DiffEvent\n | FileWriteEvent\n | MetricEvent\n | ArtifactEvent\n | RawSDKEvent;\n\nexport interface ExecutionResult {\n results: any[];\n}\n\nexport interface PlanResult {\n plan: string;\n}\n\nexport interface TaskExecutionResult {\n task: Task;\n plan?: string;\n executionResult?: ExecutionResult;\n // Deprecated: mode removed in workflow-based execution\n}\n\n// MCP Server configuration types (re-exported from Claude SDK for convenience)\nexport type McpServerConfig = {\n type?: 'stdio';\n command: string;\n args?: string[];\n env?: Record<string, string>;\n} | {\n type: 'sse';\n url: string;\n headers?: Record<string, string>;\n} | {\n type: 'http';\n url: string;\n headers?: Record<string, string>;\n} | {\n type: 'sdk';\n name: string;\n instance?: any; // McpServer instance\n};\n\nexport interface AgentConfig {\n workingDirectory?: string;\n onEvent?: (event: AgentEvent) => void;\n\n // PostHog API configuration\n posthogApiUrl?: string;\n posthogApiKey?: string;\n\n // PostHog MCP configuration\n posthogMcpUrl?: string;\n\n // MCP Server configuration\n // Additional MCP servers (PostHog MCP is always included by default)\n // You can override the PostHog MCP config by providing mcpServers.posthog\n mcpServers?: Record<string, McpServerConfig>;\n\n // Logging configuration\n debug?: boolean;\n}\n\nexport interface PostHogAPIConfig {\n apiUrl: string;\n apiKey: string;\n}\n\n// URL mention types\nexport type ResourceType = 'error' | 'experiment' | 'insight' | 'feature_flag' | 'generic';\n\nexport interface PostHogResource {\n type: ResourceType;\n id: string;\n url: string;\n title?: string;\n content: string;\n metadata?: Record<string, any>;\n}\n\nexport interface UrlMention {\n url: string;\n type: ResourceType;\n id?: string;\n label?: string;\n}"],"names":[],"mappings":"AA0BA;IAEY;AAAZ,CAAA,UAAY,cAAc,EAAA;AACxB,IAAA,cAAA,CAAA,MAAA,CAAA,GAAA,MAAa;AACb,IAAA,cAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACnB,IAAA,cAAA,CAAA,cAAA,CAAA,GAAA,aAA4B;AAC5B,IAAA,cAAA,CAAA,QAAA,CAAA,GAAA,mBAA4B;AAC9B,CAAC,EALW,cAAc,KAAd,cAAc,GAAA,EAAA,CAAA,CAAA;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@posthog/agent",
3
- "version": "1.6.0",
3
+ "version": "1.7.1",
4
4
  "description": "TypeScript agent framework wrapping Claude Agent SDK with Git-based workflow for PostHog tasks",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",
package/src/agent.ts CHANGED
@@ -89,6 +89,7 @@ export class Agent {
89
89
  const promptBuilder = new PromptBuilder({
90
90
  getTaskFiles: (taskId: string) => this.getTaskFiles(taskId),
91
91
  generatePlanTemplate: (vars) => this.templateManager.generatePlan(vars),
92
+ posthogClient: this.posthogAPI,
92
93
  logger: this.logger.child('PromptBuilder')
93
94
  });
94
95
  this.stageExecutor = new StageExecutor(
@@ -1,4 +1,4 @@
1
- import type { Task, SupportingFile, PostHogAPIConfig } from './types.js';
1
+ import type { Task, SupportingFile, PostHogAPIConfig, PostHogResource, ResourceType, UrlMention } from './types.js';
2
2
  import type { WorkflowDefinition, AgentDefinition } from './workflow-types.js';
3
3
 
4
4
  interface PostHogApiResponse<T> {
@@ -258,4 +258,111 @@ export class PostHogAPIClient {
258
258
  body: JSON.stringify(options || {}),
259
259
  });
260
260
  }
261
+
262
+ /**
263
+ * Fetch error details from PostHog error tracking
264
+ */
265
+ async fetchErrorDetails(errorId: string, projectId?: string): Promise<PostHogResource> {
266
+ const teamId = projectId ? parseInt(projectId) : await this.getTeamId();
267
+
268
+ try {
269
+ const errorData = await this.apiRequest<any>(`/api/projects/${teamId}/error_tracking/${errorId}/`);
270
+
271
+ // Format error details for agent consumption
272
+ const content = this.formatErrorContent(errorData);
273
+
274
+ return {
275
+ type: 'error',
276
+ id: errorId,
277
+ url: `${this.baseUrl}/project/${teamId}/error_tracking/${errorId}`,
278
+ title: errorData.exception_type || 'Unknown Error',
279
+ content,
280
+ metadata: {
281
+ exception_type: errorData.exception_type,
282
+ first_seen: errorData.first_seen,
283
+ last_seen: errorData.last_seen,
284
+ volume: errorData.volume,
285
+ users_affected: errorData.users_affected,
286
+ },
287
+ };
288
+ } catch (error) {
289
+ throw new Error(`Failed to fetch error details for ${errorId}: ${error}`);
290
+ }
291
+ }
292
+
293
+ /**
294
+ * Generic resource fetcher by URL or ID
295
+ */
296
+ async fetchResourceByUrl(urlMention: UrlMention): Promise<PostHogResource> {
297
+ switch (urlMention.type) {
298
+ case 'error':
299
+ if (!urlMention.id) {
300
+ throw new Error('Error ID is required for error resources');
301
+ }
302
+ // Extract project ID from URL if available, otherwise use default team
303
+ let projectId: string | undefined;
304
+ if (urlMention.url) {
305
+ const projectIdMatch = urlMention.url.match(/\/project\/(\d+)\//);
306
+ projectId = projectIdMatch ? projectIdMatch[1] : undefined;
307
+ }
308
+ return this.fetchErrorDetails(urlMention.id, projectId);
309
+
310
+ case 'experiment':
311
+ case 'insight':
312
+ case 'feature_flag':
313
+ throw new Error(`Resource type '${urlMention.type}' not yet implemented`);
314
+
315
+ case 'generic':
316
+ // Return a minimal resource for generic URLs
317
+ return {
318
+ type: 'generic',
319
+ id: '',
320
+ url: urlMention.url,
321
+ title: 'Generic Resource',
322
+ content: `Generic resource: ${urlMention.url}`,
323
+ metadata: {},
324
+ };
325
+
326
+ default:
327
+ throw new Error(`Unknown resource type: ${urlMention.type}`);
328
+ }
329
+ }
330
+
331
+ /**
332
+ * Format error data for agent consumption
333
+ */
334
+ private formatErrorContent(errorData: any): string {
335
+ const sections = [];
336
+
337
+ if (errorData.exception_type) {
338
+ sections.push(`**Error Type**: ${errorData.exception_type}`);
339
+ }
340
+
341
+ if (errorData.exception_message) {
342
+ sections.push(`**Message**: ${errorData.exception_message}`);
343
+ }
344
+
345
+ if (errorData.stack_trace) {
346
+ sections.push(`**Stack Trace**:\n\`\`\`\n${errorData.stack_trace}\n\`\`\``);
347
+ }
348
+
349
+ if (errorData.volume) {
350
+ sections.push(`**Volume**: ${errorData.volume} occurrences`);
351
+ }
352
+
353
+ if (errorData.users_affected) {
354
+ sections.push(`**Users Affected**: ${errorData.users_affected}`);
355
+ }
356
+
357
+ if (errorData.first_seen && errorData.last_seen) {
358
+ sections.push(`**First Seen**: ${errorData.first_seen}`);
359
+ sections.push(`**Last Seen**: ${errorData.last_seen}`);
360
+ }
361
+
362
+ if (errorData.properties && Object.keys(errorData.properties).length > 0) {
363
+ sections.push(`**Properties**: ${JSON.stringify(errorData.properties, null, 2)}`);
364
+ }
365
+
366
+ return sections.join('\n\n');
367
+ }
261
368
  }
@@ -1,4 +1,4 @@
1
- import type { Task } from './types.js';
1
+ import type { Task, UrlMention, PostHogResource } from './types.js';
2
2
  import type { TemplateVariables } from './template-manager.js';
3
3
  import { Logger } from './utils/logger.js';
4
4
  import { promises as fs } from 'fs';
@@ -7,17 +7,20 @@ import { join } from 'path';
7
7
  export interface PromptBuilderDeps {
8
8
  getTaskFiles: (taskId: string) => Promise<any[]>;
9
9
  generatePlanTemplate: (vars: TemplateVariables) => Promise<string>;
10
+ posthogClient?: { fetchResourceByUrl: (mention: UrlMention) => Promise<PostHogResource> };
10
11
  logger?: Logger;
11
12
  }
12
13
 
13
14
  export class PromptBuilder {
14
15
  private getTaskFiles: PromptBuilderDeps['getTaskFiles'];
15
16
  private generatePlanTemplate: PromptBuilderDeps['generatePlanTemplate'];
17
+ private posthogClient?: PromptBuilderDeps['posthogClient'];
16
18
  private logger: Logger;
17
19
 
18
20
  constructor(deps: PromptBuilderDeps) {
19
21
  this.getTaskFiles = deps.getTaskFiles;
20
22
  this.generatePlanTemplate = deps.generatePlanTemplate;
23
+ this.posthogClient = deps.posthogClient;
21
24
  this.logger = deps.logger || new Logger({ debug: false, prefix: '[PromptBuilder]' });
22
25
  }
23
26
 
@@ -51,6 +54,122 @@ export class PromptBuilder {
51
54
  }
52
55
  }
53
56
 
57
+ /**
58
+ * Extract URL mentions from XML tags in description
59
+ * Formats: <error id="..." />, <experiment id="..." />, <url href="..." />
60
+ */
61
+ private extractUrlMentions(description: string): UrlMention[] {
62
+ const mentions: UrlMention[] = [];
63
+
64
+ // PostHog resource mentions: <error id="..." />, <experiment id="..." />, etc.
65
+ const resourceRegex = /<(error|experiment|insight|feature_flag)\s+id="([^"]+)"\s*\/>/g;
66
+ let match: RegExpExecArray | null;
67
+
68
+ while ((match = resourceRegex.exec(description)) !== null) {
69
+ const [, type, id] = match;
70
+ mentions.push({
71
+ url: '', // Will be reconstructed if needed
72
+ type: type as any,
73
+ id,
74
+ label: this.generateUrlLabel('', type as any),
75
+ });
76
+ }
77
+
78
+ // Generic URL mentions: <url href="..." />
79
+ const urlRegex = /<url\s+href="([^"]+)"\s*\/>/g;
80
+ while ((match = urlRegex.exec(description)) !== null) {
81
+ const [, url] = match;
82
+ mentions.push({
83
+ url,
84
+ type: 'generic',
85
+ label: this.generateUrlLabel(url, 'generic'),
86
+ });
87
+ }
88
+
89
+ return mentions;
90
+ }
91
+
92
+ /**
93
+ * Generate a display label for a URL mention
94
+ */
95
+ private generateUrlLabel(url: string, type: string): string {
96
+ try {
97
+ const urlObj = new URL(url);
98
+ switch (type) {
99
+ case 'error':
100
+ const errorMatch = url.match(/error_tracking\/([a-f0-9-]+)/);
101
+ return errorMatch ? `Error ${errorMatch[1].slice(0, 8)}...` : 'Error';
102
+ case 'experiment':
103
+ const expMatch = url.match(/experiments\/(\d+)/);
104
+ return expMatch ? `Experiment #${expMatch[1]}` : 'Experiment';
105
+ case 'insight':
106
+ return 'Insight';
107
+ case 'feature_flag':
108
+ return 'Feature Flag';
109
+ default:
110
+ return urlObj.hostname;
111
+ }
112
+ } catch {
113
+ return 'URL';
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Process URL references and fetch their content
119
+ */
120
+ private async processUrlReferences(
121
+ description: string
122
+ ): Promise<{ description: string; referencedResources: PostHogResource[] }> {
123
+ const urlMentions = this.extractUrlMentions(description);
124
+ const referencedResources: PostHogResource[] = [];
125
+
126
+ if (urlMentions.length === 0 || !this.posthogClient) {
127
+ return { description, referencedResources };
128
+ }
129
+
130
+ // Fetch all referenced resources
131
+ for (const mention of urlMentions) {
132
+ try {
133
+ const resource = await this.posthogClient.fetchResourceByUrl(mention);
134
+ referencedResources.push(resource);
135
+ } catch (error) {
136
+ this.logger.warn(`Failed to fetch resource from URL: ${mention.url}`, { error });
137
+ // Add a placeholder resource for failed fetches
138
+ referencedResources.push({
139
+ type: mention.type,
140
+ id: mention.id || '',
141
+ url: mention.url,
142
+ title: mention.label || 'Unknown Resource',
143
+ content: `Failed to fetch resource from ${mention.url}: ${error}`,
144
+ metadata: {},
145
+ });
146
+ }
147
+ }
148
+
149
+ // Replace URL tags with just the label for readability
150
+ let processedDescription = description;
151
+ for (const mention of urlMentions) {
152
+ if (mention.type === 'generic') {
153
+ // Generic URLs: <url href="..." />
154
+ const escapedUrl = mention.url.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
155
+ processedDescription = processedDescription.replace(
156
+ new RegExp(`<url\\s+href="${escapedUrl}"\\s*/>`, 'g'),
157
+ `@${mention.label}`
158
+ );
159
+ } else {
160
+ // PostHog resources: <error id="..." />, <experiment id="..." />, etc.
161
+ const escapedType = mention.type.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
162
+ const escapedId = mention.id ? mention.id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') : '';
163
+ processedDescription = processedDescription.replace(
164
+ new RegExp(`<${escapedType}\\s+id="${escapedId}"\\s*/>`, 'g'),
165
+ `@${mention.label}`
166
+ );
167
+ }
168
+ }
169
+
170
+ return { description: processedDescription, referencedResources };
171
+ }
172
+
54
173
  /**
55
174
  * Process description to extract file tags and read contents
56
175
  * Returns processed description and referenced file contents
@@ -89,11 +208,16 @@ export class PromptBuilder {
89
208
 
90
209
  async buildPlanningPrompt(task: Task, repositoryPath?: string): Promise<string> {
91
210
  // Process file references in description
92
- const { description: processedDescription, referencedFiles } = await this.processFileReferences(
211
+ const { description: descriptionAfterFiles, referencedFiles } = await this.processFileReferences(
93
212
  task.description,
94
213
  repositoryPath
95
214
  );
96
215
 
216
+ // Process URL references in description
217
+ const { description: processedDescription, referencedResources } = await this.processUrlReferences(
218
+ descriptionAfterFiles
219
+ );
220
+
97
221
  let prompt = '';
98
222
  prompt += `## Current Task\n\n**Task**: ${task.title}\n**Description**: ${processedDescription}`;
99
223
 
@@ -109,6 +233,14 @@ export class PromptBuilder {
109
233
  }
110
234
  }
111
235
 
236
+ // Add referenced resources from URL mentions
237
+ if (referencedResources.length > 0) {
238
+ prompt += `\n\n## Referenced Resources\n\n`;
239
+ for (const resource of referencedResources) {
240
+ prompt += `### ${resource.title} (${resource.type})\n**URL**: ${resource.url}\n\n${resource.content}\n\n`;
241
+ }
242
+ }
243
+
112
244
  try {
113
245
  const taskFiles = await this.getTaskFiles(task.id);
114
246
  const contextFiles = taskFiles.filter((f: any) => f.type === 'context' || f.type === 'reference');
@@ -139,11 +271,16 @@ export class PromptBuilder {
139
271
 
140
272
  async buildExecutionPrompt(task: Task, repositoryPath?: string): Promise<string> {
141
273
  // Process file references in description
142
- const { description: processedDescription, referencedFiles } = await this.processFileReferences(
274
+ const { description: descriptionAfterFiles, referencedFiles } = await this.processFileReferences(
143
275
  task.description,
144
276
  repositoryPath
145
277
  );
146
278
 
279
+ // Process URL references in description
280
+ const { description: processedDescription, referencedResources } = await this.processUrlReferences(
281
+ descriptionAfterFiles
282
+ );
283
+
147
284
  let prompt = '';
148
285
  prompt += `## Current Task\n\n**Task**: ${task.title}\n**Description**: ${processedDescription}`;
149
286
 
@@ -159,6 +296,14 @@ export class PromptBuilder {
159
296
  }
160
297
  }
161
298
 
299
+ // Add referenced resources from URL mentions
300
+ if (referencedResources.length > 0) {
301
+ prompt += `\n\n## Referenced Resources\n\n`;
302
+ for (const resource of referencedResources) {
303
+ prompt += `### ${resource.title} (${resource.type})\n**URL**: ${resource.url}\n\n${resource.content}\n\n`;
304
+ }
305
+ }
306
+
162
307
  try {
163
308
  const taskFiles = await this.getTaskFiles(task.id);
164
309
  const hasPlan = taskFiles.some((f: any) => f.type === 'plan');
package/src/types.ts CHANGED
@@ -256,4 +256,23 @@ export interface AgentConfig {
256
256
  export interface PostHogAPIConfig {
257
257
  apiUrl: string;
258
258
  apiKey: string;
259
+ }
260
+
261
+ // URL mention types
262
+ export type ResourceType = 'error' | 'experiment' | 'insight' | 'feature_flag' | 'generic';
263
+
264
+ export interface PostHogResource {
265
+ type: ResourceType;
266
+ id: string;
267
+ url: string;
268
+ title?: string;
269
+ content: string;
270
+ metadata?: Record<string, any>;
271
+ }
272
+
273
+ export interface UrlMention {
274
+ url: string;
275
+ type: ResourceType;
276
+ id?: string;
277
+ label?: string;
259
278
  }