@posthog/agent 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/CLAUDE.md +68 -35
  2. package/README.md +55 -14
  3. package/dist/index.d.ts +1 -1
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/src/agent.d.ts +5 -1
  6. package/dist/src/agent.d.ts.map +1 -1
  7. package/dist/src/agent.js +65 -11
  8. package/dist/src/agent.js.map +1 -1
  9. package/dist/src/event-transformer.d.ts +2 -0
  10. package/dist/src/event-transformer.d.ts.map +1 -1
  11. package/dist/src/event-transformer.js +53 -5
  12. package/dist/src/event-transformer.js.map +1 -1
  13. package/dist/src/posthog-api.d.ts +34 -0
  14. package/dist/src/posthog-api.d.ts.map +1 -1
  15. package/dist/src/posthog-api.js +38 -0
  16. package/dist/src/posthog-api.js.map +1 -1
  17. package/dist/src/stage-executor.d.ts +5 -2
  18. package/dist/src/stage-executor.d.ts.map +1 -1
  19. package/dist/src/stage-executor.js +20 -12
  20. package/dist/src/stage-executor.js.map +1 -1
  21. package/dist/src/task-progress-reporter.d.ts +44 -0
  22. package/dist/src/task-progress-reporter.d.ts.map +1 -0
  23. package/dist/src/task-progress-reporter.js +234 -0
  24. package/dist/src/task-progress-reporter.js.map +1 -0
  25. package/dist/src/types.d.ts +20 -0
  26. package/dist/src/types.d.ts.map +1 -1
  27. package/dist/src/types.js.map +1 -1
  28. package/package.json +2 -1
  29. package/src/agent.ts +77 -11
  30. package/src/event-transformer.ts +61 -7
  31. package/src/posthog-api.ts +79 -0
  32. package/src/stage-executor.ts +29 -15
  33. package/src/task-progress-reporter.ts +287 -0
  34. package/src/types.ts +30 -2
  35. package/dist/src/utils/mcp.d.ts +0 -10
  36. package/dist/src/utils/mcp.d.ts.map +0 -1
  37. package/dist/src/utils/mcp.js +0 -18
  38. package/dist/src/utils/mcp.js.map +0 -1
  39. package/src/utils/mcp.ts +0 -15
@@ -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';\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 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 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(this.agentRegistry, this.logger, promptBuilder);\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 // Workflow-based execution\n async runWorkflow(taskOrId: Task | string, workflowId: string, options: WorkflowExecutionOptions = {}): Promise<{ task: Task; workflow: WorkflowDefinition }> {\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\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\n try {\n const orderedStages = [...workflow.stages].sort((a, b) => a.position - b.position);\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 this.emitEvent(this.eventTransformer.createStatusEvent('no_next_stage', { stage: orderedStages[currIdx].key }));\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.executeStage(task, stage, options);\n if (options.autoProgress) {\n const hasNext = i < orderedStages.length - 1;\n if (hasNext) {\n await this.progressToNextStage(task.id);\n }\n }\n }\n this.taskManager.completeExecution(executionId, { task, workflow });\n return { task, workflow };\n } catch (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 } 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 }\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 }\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 }\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);\n this.emitEvent(this.eventTransformer.createStatusEvent('pr_created', { stage: 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 }\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);\n this.emitEvent(this.eventTransformer.createStatusEvent('pr_created', { stage: 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): Promise<void> {\n if (!this.posthogAPI) throw new Error('PostHog API not configured. Cannot progress stage.');\n await this.posthogAPI.progressTask(taskId, { auto: true });\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 const baseOptions: Record<string, any> = {\n model: \"claude-4-5-sonnet\",\n cwd: options.repositoryPath || this.workingDirectory,\n permissionMode: (options.permissionMode as any) || \"default\",\n settingSources: [\"local\"],\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', { type: message.type });\n const transformedEvent = this.eventTransformer.transform(message);\n this.onEvent?.(transformedEvent);\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 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): Promise<void> {\n this.logger.info('Attaching PR to task', { taskId, prUrl });\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.updateTask(taskId, { github_pr_url: prUrl });\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.updateTask(taskId, { github_branch: 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 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":";;;;;;;;;;;;;;MAiBa,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,gBAAgB;AAChB,IAAA,aAAa;AACd,IAAA,KAAK;AAEZ,IAAA,WAAA,CAAY,SAAsB,EAAE,EAAA;QAChC,IAAI,CAAC,gBAAgB,GAAG,MAAM,CAAC,gBAAgB,IAAI,OAAO,CAAC,GAAG,EAAE;AAChE,QAAA,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO;QAC7B,IAAI,CAAC,KAAK,GAAG,MAAM,CAAC,KAAK,IAAI,KAAK;AAClC,QAAA,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE,iBAAiB,EAAE,CAAC;AAC1E,QAAA,IAAI,CAAC,WAAW,GAAG,IAAI,WAAW,EAAE;AACpC,QAAA,IAAI,CAAC,gBAAgB,GAAG,IAAI,gBAAgB,EAAE;AAE9C,QAAA,IAAI,CAAC,WAAW,GAAG,IAAI,kBAAkB,CACrC,IAAI,CAAC,gBAAgB,EACrB,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,aAAa,CAAC,CACnC;AACD,QAAA,IAAI,CAAC,UAAU,GAAG,IAAI,UAAU,CAAC;YAC7B,cAAc,EAAE,IAAI,CAAC,gBAAgB;YACrC,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC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AAU,EAAE,CAAC;AACvE,QAAA,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,qBAAqB,EAAE,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC;IACpE;;AAGA,IAAA,UAAU,CAAC,MAAc,EAAA;;AAErB,QAAA,KAAK,MAAM,CAAC,WAAW,EAAE,SAAS,CAAC,IAAI,IAAI,CAAC,WAAW,CAAC,iBAAiB,CAAC,EAAE;AACxE,YAAA,IAAI,SAAS,CAAC,MAAM,KAAK,MAAM,IAAI,SAAS,CAAC,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;AACA,QAAA,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;IACzB;AACH;;;;"}
1
+ {"version":3,"file":"agent.js","sources":["../../src/agent.ts"],"sourcesContent":["import { query } from \"@anthropic-ai/claude-agent-sdk\";\nimport type { Task, ExecutionResult, 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 // Workflow-based execution\n async runWorkflow(taskOrId: Task | string, workflowId: string, options: WorkflowExecutionOptions = {}): Promise<{ task: Task; workflow: WorkflowDefinition }> {\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);\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): Promise<void> {\n if (!this.posthogAPI) throw new Error('PostHog API not configured. Cannot progress stage.');\n await this.posthogAPI.progressTask(taskId, { auto: true });\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 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 const transformedEvent = this.eventTransformer.transform(message);\n this.onEvent?.(transformedEvent);\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,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AAC,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;;;;"}
@@ -3,5 +3,7 @@ import type { SDKMessage } from '@anthropic-ai/claude-agent-sdk';
3
3
  export declare class EventTransformer {
4
4
  transform(sdkMessage: SDKMessage): AgentEvent | null;
5
5
  createStatusEvent(phase: string, additionalData?: any): AgentEvent;
6
+ private extractUserContent;
7
+ private extractFromObject;
6
8
  }
7
9
  //# sourceMappingURL=event-transformer.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"event-transformer.d.ts","sourceRoot":"","sources":["../../src/event-transformer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AAEjE,qBAAa,gBAAgB;IAC3B,SAAS,CAAC,UAAU,EAAE,UAAU,GAAG,UAAU,GAAG,IAAI;IAgLpD,iBAAiB,CAAC,KAAK,EAAE,MAAM,EAAE,cAAc,CAAC,EAAE,GAAG,GAAG,UAAU;CAQnE"}
1
+ {"version":3,"file":"event-transformer.d.ts","sourceRoot":"","sources":["../../src/event-transformer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AAEjE,qBAAa,gBAAgB;IAC3B,SAAS,CAAC,UAAU,EAAE,UAAU,GAAG,UAAU,GAAG,IAAI;IA+KpD,iBAAiB,CAAC,KAAK,EAAE,MAAM,EAAE,cAAc,CAAC,EAAE,GAAG,GAAG,UAAU;IASlE,OAAO,CAAC,kBAAkB;IAkC1B,OAAO,CAAC,iBAAiB;CAoB1B"}
@@ -105,14 +105,14 @@ class EventTransformer {
105
105
  }
106
106
  // Handle user messages
107
107
  if (sdkMessage.type === 'user') {
108
- const content = sdkMessage.message.content;
109
- const textContent = Array.isArray(content)
110
- ? content.find(c => c.type === 'text')?.text
111
- : typeof content === 'string' ? content : '';
108
+ const textContent = this.extractUserContent(sdkMessage.message?.content);
109
+ if (!textContent) {
110
+ return null;
111
+ }
112
112
  return {
113
113
  ...baseEvent,
114
114
  type: 'user_message',
115
- content: textContent || '',
115
+ content: textContent,
116
116
  isSynthetic: sdkMessage.isSynthetic
117
117
  };
118
118
  }
@@ -170,6 +170,54 @@ class EventTransformer {
170
170
  ...additionalData
171
171
  };
172
172
  }
173
+ extractUserContent(content) {
174
+ if (!content) {
175
+ return null;
176
+ }
177
+ if (typeof content === 'string') {
178
+ const trimmed = content.trim();
179
+ return trimmed.length > 0 ? trimmed : null;
180
+ }
181
+ if (Array.isArray(content)) {
182
+ const parts = [];
183
+ for (const block of content) {
184
+ const extracted = this.extractUserContent(block);
185
+ if (extracted) {
186
+ parts.push(extracted);
187
+ }
188
+ else if (block && typeof block === 'object') {
189
+ const candidate = this.extractFromObject(block);
190
+ if (candidate) {
191
+ parts.push(candidate);
192
+ }
193
+ }
194
+ }
195
+ const text = parts.join('\n').trim();
196
+ return text.length > 0 ? text : null;
197
+ }
198
+ if (typeof content === 'object') {
199
+ return this.extractFromObject(content);
200
+ }
201
+ return null;
202
+ }
203
+ extractFromObject(value) {
204
+ const preferredKeys = ['text', 'input_text', 'input', 'markdown', 'content', 'message'];
205
+ for (const key of preferredKeys) {
206
+ if (typeof value[key] === 'string') {
207
+ const trimmed = value[key].trim();
208
+ if (trimmed.length > 0) {
209
+ return trimmed;
210
+ }
211
+ }
212
+ }
213
+ for (const entry of Object.values(value)) {
214
+ const extracted = this.extractUserContent(entry);
215
+ if (extracted) {
216
+ return extracted;
217
+ }
218
+ }
219
+ return null;
220
+ }
173
221
  }
174
222
 
175
223
  export { EventTransformer };
@@ -1 +1 @@
1
- {"version":3,"file":"event-transformer.js","sources":["../../src/event-transformer.ts"],"sourcesContent":["import type { AgentEvent } from './types.js';\nimport type { SDKMessage } from '@anthropic-ai/claude-agent-sdk';\n\nexport class EventTransformer {\n transform(sdkMessage: SDKMessage): AgentEvent | null {\n const baseEvent = { ts: Date.now() };\n\n // Handle stream events\n if (sdkMessage.type === 'stream_event') {\n const event = sdkMessage.event;\n\n switch (event.type) {\n case 'message_start':\n return {\n ...baseEvent,\n type: 'message_start',\n messageId: event.message?.id,\n model: event.message?.model\n };\n\n case 'content_block_start':\n const contentBlock = event.content_block;\n if (!contentBlock) return null;\n\n return {\n ...baseEvent,\n type: 'content_block_start',\n index: event.index,\n contentType: contentBlock.type as 'text' | 'tool_use' | 'thinking',\n toolName: contentBlock.type === 'tool_use' ? contentBlock.name : undefined,\n toolId: contentBlock.type === 'tool_use' ? contentBlock.id : undefined\n };\n\n case 'content_block_delta':\n const delta = event.delta;\n if (!delta) return null;\n\n if (delta.type === 'text_delta') {\n return {\n ...baseEvent,\n type: 'token',\n content: delta.text,\n contentType: 'text'\n };\n } else if (delta.type === 'input_json_delta') {\n return {\n ...baseEvent,\n type: 'token',\n content: delta.partial_json,\n contentType: 'tool_input'\n };\n } else if (delta.type === 'thinking_delta') {\n return {\n ...baseEvent,\n type: 'token',\n content: delta.thinking,\n contentType: 'thinking'\n };\n }\n return null;\n\n case 'content_block_stop':\n return {\n ...baseEvent,\n type: 'content_block_stop',\n index: event.index\n };\n\n case 'message_delta':\n return {\n ...baseEvent,\n type: 'message_delta',\n stopReason: event.delta?.stop_reason,\n stopSequence: event.delta?.stop_sequence,\n usage: event.usage ? {\n outputTokens: event.usage.output_tokens\n } : undefined\n };\n\n case 'message_stop':\n return {\n ...baseEvent,\n type: 'message_stop'\n };\n\n case 'ping':\n // Ignore ping events\n return null;\n\n case 'error':\n return {\n ...baseEvent,\n type: 'error',\n message: event.error?.message || 'Unknown error',\n error: event.error,\n errorType: event.error?.type\n };\n\n default:\n return null;\n }\n }\n\n // Handle assistant messages (full message, not streaming)\n if (sdkMessage.type === 'assistant') {\n // Extract tool calls from assistant message\n const message = sdkMessage.message;\n // We could emit individual tool_call events here if needed\n // For now, just emit a status event\n return {\n ...baseEvent,\n type: 'status',\n phase: 'assistant_message',\n messageId: message.id,\n model: message.model\n };\n }\n\n // Handle user messages\n if (sdkMessage.type === 'user') {\n const content = sdkMessage.message.content;\n const textContent = Array.isArray(content)\n ? content.find(c => c.type === 'text')?.text\n : typeof content === 'string' ? content : '';\n\n return {\n ...baseEvent,\n type: 'user_message',\n content: textContent || '',\n isSynthetic: sdkMessage.isSynthetic\n };\n }\n\n // Handle result messages\n if (sdkMessage.type === 'result') {\n if (sdkMessage.subtype === 'success') {\n return {\n ...baseEvent,\n type: 'done',\n durationMs: sdkMessage.duration_ms,\n numTurns: sdkMessage.num_turns,\n totalCostUsd: sdkMessage.total_cost_usd,\n usage: sdkMessage.usage\n };\n } else {\n return {\n ...baseEvent,\n type: 'error',\n message: `Execution failed: ${sdkMessage.subtype}`,\n error: { subtype: sdkMessage.subtype },\n errorType: sdkMessage.subtype\n };\n }\n }\n\n // Handle system messages\n if (sdkMessage.type === 'system') {\n if (sdkMessage.subtype === 'init') {\n return {\n ...baseEvent,\n type: 'init',\n model: sdkMessage.model,\n tools: sdkMessage.tools,\n permissionMode: sdkMessage.permissionMode,\n cwd: sdkMessage.cwd,\n apiKeySource: sdkMessage.apiKeySource\n };\n } else if (sdkMessage.subtype === 'compact_boundary') {\n return {\n ...baseEvent,\n type: 'compact_boundary',\n trigger: sdkMessage.compact_metadata.trigger,\n preTokens: sdkMessage.compact_metadata.pre_tokens\n };\n }\n }\n\n return null;\n }\n \n createStatusEvent(phase: string, additionalData?: any): AgentEvent {\n return {\n type: 'status',\n ts: Date.now(),\n phase,\n ...additionalData\n };\n }\n}"],"names":[],"mappings":"MAGa,gBAAgB,CAAA;AAC3B,IAAA,SAAS,CAAC,UAAsB,EAAA;QAC9B,MAAM,SAAS,GAAG,EAAE,EAAE,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE;;AAGpC,QAAA,IAAI,UAAU,CAAC,IAAI,KAAK,cAAc,EAAE;AACtC,YAAA,MAAM,KAAK,GAAG,UAAU,CAAC,KAAK;AAE9B,YAAA,QAAQ,KAAK,CAAC,IAAI;AAChB,gBAAA,KAAK,eAAe;oBAClB,OAAO;AACL,wBAAA,GAAG,SAAS;AACZ,wBAAA,IAAI,EAAE,eAAe;AACrB,wBAAA,SAAS,EAAE,KAAK,CAAC,OAAO,EAAE,EAAE;AAC5B,wBAAA,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE;qBACvB;AAEH,gBAAA,KAAK,qBAAqB;AACxB,oBAAA,MAAM,YAAY,GAAG,KAAK,CAAC,a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B,cAAc,EAAE,UAAU,CAAC,cAAc;oBACzC,GAAG,EAAE,UAAU,CAAC,GAAG;oBACnB,YAAY,EAAE,UAAU,CAAC;iBAC1B;YACH;AAAO,iBAAA,IAAI,UAAU,CAAC,OAAO,KAAK,kBAAkB,EAAE;gBACpD,OAAO;AACL,oBAAA,GAAG,SAAS;AACZ,oBAAA,IAAI,EAAE,kBAAkB;AACxB,oBAAA,OAAO,EAAE,UAAU,CAAC,gBAAgB,CAAC,OAAO;AAC5C,oBAAA,SAAS,EAAE,UAAU,CAAC,gBAAgB,CAAC;iBACxC;YACH;QACF;AAEA,QAAA,OAAO,IAAI;IACb;IAEA,iBAAiB,CAAC,KAAa,EAAE,cAAoB,EAAA;QACnD,OAAO;AACL,YAAA,IAAI,EAAE,QAAQ;AACd,YAAA,EAAE,EAAE,IAAI,CAAC,GAAG,EAAE;YACd,KAAK;AACL,YAAA,GAAG;SACJ;IACH;AACD;;;;"}
1
+ {"version":3,"file":"event-transformer.js","sources":["../../src/event-transformer.ts"],"sourcesContent":["import type { AgentEvent } from './types.js';\nimport type { SDKMessage } from '@anthropic-ai/claude-agent-sdk';\n\nexport class EventTransformer {\n transform(sdkMessage: SDKMessage): AgentEvent | null {\n const baseEvent = { ts: Date.now() };\n\n // Handle stream events\n if (sdkMessage.type === 'stream_event') {\n const event = sdkMessage.event;\n\n switch (event.type) {\n case 'message_start':\n return {\n ...baseEvent,\n type: 'message_start',\n messageId: event.message?.id,\n model: event.message?.model\n };\n\n case 'content_block_start':\n const contentBlock = event.content_block;\n if (!contentBlock) return null;\n\n return {\n ...baseEvent,\n type: 'content_block_start',\n index: event.index,\n contentType: contentBlock.type as 'text' | 'tool_use' | 'thinking',\n toolName: contentBlock.type === 'tool_use' ? contentBlock.name : undefined,\n toolId: contentBlock.type === 'tool_use' ? contentBlock.id : undefined\n };\n\n case 'content_block_delta':\n const delta = event.delta;\n if (!delta) return null;\n\n if (delta.type === 'text_delta') {\n return {\n ...baseEvent,\n type: 'token',\n content: delta.text,\n contentType: 'text'\n };\n } else if (delta.type === 'input_json_delta') {\n return {\n ...baseEvent,\n type: 'token',\n content: delta.partial_json,\n contentType: 'tool_input'\n };\n } else if (delta.type === 'thinking_delta') {\n return {\n ...baseEvent,\n type: 'token',\n content: delta.thinking,\n contentType: 'thinking'\n };\n }\n return null;\n\n case 'content_block_stop':\n return {\n ...baseEvent,\n type: 'content_block_stop',\n index: event.index\n };\n\n case 'message_delta':\n return {\n ...baseEvent,\n type: 'message_delta',\n stopReason: event.delta?.stop_reason,\n stopSequence: event.delta?.stop_sequence,\n usage: event.usage ? {\n outputTokens: event.usage.output_tokens\n } : undefined\n };\n\n case 'message_stop':\n return {\n ...baseEvent,\n type: 'message_stop'\n };\n\n case 'ping':\n // Ignore ping events\n return null;\n\n case 'error':\n return {\n ...baseEvent,\n type: 'error',\n message: event.error?.message || 'Unknown error',\n error: event.error,\n errorType: event.error?.type\n };\n\n default:\n return null;\n }\n }\n\n // Handle assistant messages (full message, not streaming)\n if (sdkMessage.type === 'assistant') {\n // Extract tool calls from assistant message\n const message = sdkMessage.message;\n // We could emit individual tool_call events here if needed\n // For now, just emit a status event\n return {\n ...baseEvent,\n type: 'status',\n phase: 'assistant_message',\n messageId: message.id,\n model: message.model\n };\n }\n\n // Handle user messages\n if (sdkMessage.type === 'user') {\n const textContent = this.extractUserContent(sdkMessage.message?.content);\n if (!textContent) {\n return null;\n }\n return {\n ...baseEvent,\n type: 'user_message',\n content: textContent,\n isSynthetic: sdkMessage.isSynthetic\n };\n }\n\n // Handle result messages\n if (sdkMessage.type === 'result') {\n if (sdkMessage.subtype === 'success') {\n return {\n ...baseEvent,\n type: 'done',\n durationMs: sdkMessage.duration_ms,\n numTurns: sdkMessage.num_turns,\n totalCostUsd: sdkMessage.total_cost_usd,\n usage: sdkMessage.usage\n };\n } else {\n return {\n ...baseEvent,\n type: 'error',\n message: `Execution failed: ${sdkMessage.subtype}`,\n error: { subtype: sdkMessage.subtype },\n errorType: sdkMessage.subtype\n };\n }\n }\n\n // Handle system messages\n if (sdkMessage.type === 'system') {\n if (sdkMessage.subtype === 'init') {\n return {\n ...baseEvent,\n type: 'init',\n model: sdkMessage.model,\n tools: sdkMessage.tools,\n permissionMode: sdkMessage.permissionMode,\n cwd: sdkMessage.cwd,\n apiKeySource: sdkMessage.apiKeySource\n };\n } else if (sdkMessage.subtype === 'compact_boundary') {\n return {\n ...baseEvent,\n type: 'compact_boundary',\n trigger: sdkMessage.compact_metadata.trigger,\n preTokens: sdkMessage.compact_metadata.pre_tokens\n };\n }\n }\n\n return null;\n }\n \n createStatusEvent(phase: string, additionalData?: any): AgentEvent {\n return {\n type: 'status',\n ts: Date.now(),\n phase,\n ...additionalData\n };\n }\n\n private extractUserContent(content: unknown): string | null {\n if (!content) {\n return null;\n }\n\n if (typeof content === 'string') {\n const trimmed = content.trim();\n return trimmed.length > 0 ? trimmed : null;\n }\n\n if (Array.isArray(content)) {\n const parts: string[] = [];\n for (const block of content) {\n const extracted = this.extractUserContent(block);\n if (extracted) {\n parts.push(extracted);\n } else if (block && typeof block === 'object') {\n const candidate = this.extractFromObject(block as Record<string, unknown>);\n if (candidate) {\n parts.push(candidate);\n }\n }\n }\n const text = parts.join('\\n').trim();\n return text.length > 0 ? text : null;\n }\n\n if (typeof content === 'object') {\n return this.extractFromObject(content as Record<string, unknown>);\n }\n\n return null;\n }\n\n private extractFromObject(value: Record<string, unknown>): string | null {\n const preferredKeys = ['text', 'input_text', 'input', 'markdown', 'content', 'message'];\n for (const key of preferredKeys) {\n if (typeof value[key] === 'string') {\n const trimmed = (value[key] as string).trim();\n if (trimmed.length > 0) {\n return trimmed;\n }\n }\n }\n\n for (const entry of Object.values(value)) {\n const extracted = this.extractUserContent(entry);\n if (extracted) {\n return extracted;\n }\n }\n\n return null;\n }\n}\n"],"names":[],"mappings":"MAGa,gBAAgB,CAAA;AAC3B,IAAA,SAAS,CAAC,UAAsB,EAAA;QAC9B,MAAM,SAAS,GAAG,EAAE,EAAE,E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AAC,KAAK,CAAC,EAAE;YACxC,MAAM,SAAS,GAAG,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC;YAChD,IAAI,SAAS,EAAE;AACb,gBAAA,OAAO,SAAS;YAClB;QACF;AAEA,QAAA,OAAO,IAAI;IACb;AACD;;;;"}
@@ -17,6 +17,34 @@ interface TaskProgressResponse {
17
17
  workflow_run_id?: string;
18
18
  message?: string;
19
19
  }
20
+ export interface TaskProgressRecord {
21
+ id: string;
22
+ task: string;
23
+ status: "started" | "in_progress" | "completed" | "failed";
24
+ current_step?: string | null;
25
+ completed_steps?: number | null;
26
+ total_steps?: number | null;
27
+ progress_percentage?: number | null;
28
+ output_log?: string | null;
29
+ error_message?: string | null;
30
+ workflow_id?: string | null;
31
+ workflow_run_id?: string | null;
32
+ activity_id?: string | null;
33
+ created_at: string;
34
+ updated_at: string;
35
+ completed_at?: string | null;
36
+ }
37
+ export interface TaskProgressUpdate {
38
+ status?: TaskProgressRecord["status"];
39
+ current_step?: string | null;
40
+ completed_steps?: number | null;
41
+ total_steps?: number | null;
42
+ output_log?: string | null;
43
+ error_message?: string | null;
44
+ workflow_id?: string | null;
45
+ workflow_run_id?: string | null;
46
+ activity_id?: string | null;
47
+ }
20
48
  export declare class PostHogAPIClient {
21
49
  private config;
22
50
  private _teamId;
@@ -35,7 +63,13 @@ export declare class PostHogAPIClient {
35
63
  }): Promise<Task[]>;
36
64
  updateTask(taskId: string, updates: Partial<Task>): Promise<Task>;
37
65
  updateTaskStage(taskId: string, stageId: string): Promise<Task>;
66
+ setTaskBranch(taskId: string, branch: string): Promise<Task>;
67
+ attachTaskPullRequest(taskId: string, prUrl: string, branch?: string): Promise<Task>;
38
68
  getTaskProgress(taskId: string): Promise<TaskProgressResponse>;
69
+ createTaskProgress(taskId: string, payload: TaskProgressUpdate & {
70
+ status: TaskProgressRecord["status"];
71
+ }): Promise<TaskProgressRecord>;
72
+ updateTaskProgress(taskId: string, progressId: string, payload: TaskProgressUpdate): Promise<TaskProgressRecord>;
39
73
  fetchWorkflow(workflowId: string): Promise<WorkflowDefinition>;
40
74
  listWorkflows(): Promise<WorkflowDefinition[]>;
41
75
  listAgents(): Promise<AgentDefinition[]>;
@@ -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,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,MAAM,CAAmB;IACjC,OAAO,CAAC,OAAO,CAAuB;gBAE1B,MAAM,EAAE,gBAAgB;IAIpC,OAAO,KAAK,OAAO,GAKlB;IAED,OAAO,KAAK,OAAO,GAKlB;YAEa,UAAU;YA4BV,SAAS;IAiBjB,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;I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OAAO,CAAC,IAAI,CAAC;IAQ5D,qBAAqB,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAYpF,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAK9D,kBAAkB,CACtB,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,kBAAkB,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;CAOxG"}
@@ -81,10 +81,48 @@ class PostHogAPIClient {
81
81
  body: JSON.stringify({ current_stage: stageId }),
82
82
  });
83
83
  }
84
+ async setTaskBranch(taskId, branch) {
85
+ const teamId = await this.getTeamId();
86
+ return this.apiRequest(`/api/projects/${teamId}/tasks/${taskId}/set_branch/`, {
87
+ method: "POST",
88
+ body: JSON.stringify({ branch }),
89
+ });
90
+ }
91
+ async attachTaskPullRequest(taskId, prUrl, branch) {
92
+ const teamId = await this.getTeamId();
93
+ const payload = { pr_url: prUrl };
94
+ if (branch) {
95
+ payload.branch = branch;
96
+ }
97
+ return this.apiRequest(`/api/projects/${teamId}/tasks/${taskId}/attach_pr/`, {
98
+ method: "POST",
99
+ body: JSON.stringify(payload),
100
+ });
101
+ }
84
102
  async getTaskProgress(taskId) {
85
103
  const teamId = await this.getTeamId();
86
104
  return this.apiRequest(`/api/projects/${teamId}/tasks/${taskId}/progress/`);
87
105
  }
106
+ async createTaskProgress(taskId, payload) {
107
+ const teamId = await this.getTeamId();
108
+ return this.apiRequest(`/api/projects/${teamId}/task_progress/`, {
109
+ method: "POST",
110
+ body: JSON.stringify({
111
+ ...payload,
112
+ task: taskId,
113
+ }),
114
+ });
115
+ }
116
+ async updateTaskProgress(taskId, progressId, payload) {
117
+ const teamId = await this.getTeamId();
118
+ return this.apiRequest(`/api/projects/${teamId}/task_progress/${progressId}/`, {
119
+ method: "PATCH",
120
+ body: JSON.stringify({
121
+ ...payload,
122
+ task: taskId,
123
+ }),
124
+ });
125
+ }
88
126
  // Workflow endpoints
89
127
  async fetchWorkflow(workflowId) {
90
128
  const teamId = await this.getTeamId();
@@ -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 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 private 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 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 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 // Workflow endpoints\n async fetchWorkflow(workflowId: string): Promise<WorkflowDefinition> {\n const teamId = await this.getTeamId();\n return this.apiRequest<WorkflowDefinition>(`/api/projects/${teamId}/task_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}/task_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":"MA4Ba,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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A,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 } 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 private 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 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}/task_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}/task_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,IAAA,MAAM,UAAU,CACtB,QAA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MAAM,IAAI,CAAC,UAAU,CAAyC,CAAA,cAAA,EAAiB,MAAM,CAAA,gBAAA,CAAkB,CAAC;AACzH,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,6 +1,6 @@
1
1
  import { Logger } from './utils/logger.js';
2
2
  import { AgentRegistry } from './agent-registry.js';
3
- import type { Task } from './types.js';
3
+ import type { AgentEvent, Task, McpServerConfig } from './types.js';
4
4
  import type { WorkflowStage, WorkflowStageExecutionResult, WorkflowExecutionOptions } from './workflow-types.js';
5
5
  import { PromptBuilder } from './prompt-builder.js';
6
6
  export declare class StageExecutor {
@@ -8,7 +8,10 @@ export declare class StageExecutor {
8
8
  private logger;
9
9
  private eventTransformer;
10
10
  private promptBuilder;
11
- constructor(registry: AgentRegistry, logger: Logger, promptBuilder?: PromptBuilder);
11
+ private eventHandler?;
12
+ private mcpServers?;
13
+ constructor(registry: AgentRegistry, logger: Logger, promptBuilder?: PromptBuilder, eventHandler?: (event: AgentEvent) => void, mcpServers?: Record<string, McpServerConfig>);
14
+ setEventHandler(handler?: (event: AgentEvent) => void): void;
12
15
  execute(task: Task, stage: WorkflowStage, options: WorkflowExecutionOptions): Promise<WorkflowStageExecutionResult>;
13
16
  private runPlanning;
14
17
  private runExecution;
@@ -1 +1 @@
1
- {"version":3,"file":"stage-executor.d.ts","sourceRoot":"","sources":["../../src/stage-executor.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAE3C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,KAAK,EAAE,aAAa,EAAE,4BAA4B,EAAE,wBAAwB,EAAE,MAAM,qBAAqB,CAAC;AAGjH,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAGpD,qBAAa,aAAa;IACxB,OAAO,CAAC,QAAQ,CAAgB;IAChC,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,gBAAgB,CAAmB;IAC3C,OAAO,CAAC,aAAa,CAAgB;gBAEzB,QAAQ,EAAE,aAAa,EAAE,MAAM,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,aAAa;IAW5E,OAAO,CAAC,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,aAAa,EAAE,OAAO,EAAE,wBAAwB,GAAG,OAAO,CAAC,4BAA4B,CAAC;YA+B3G,WAAW;YAyCX,YAAY;CAkC3B"}
1
+ {"version":3,"file":"stage-executor.d.ts","sourceRoot":"","sources":["../../src/stage-executor.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAE3C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,KAAK,EAAE,UAAU,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AACpE,OAAO,KAAK,EAAE,aAAa,EAAE,4BAA4B,EAAE,wBAAwB,EAAE,MAAM,qBAAqB,CAAC;AAGjH,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,qBAAa,aAAa;IACxB,OAAO,CAAC,QAAQ,CAAgB;IAChC,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,gBAAgB,CAAmB;IAC3C,OAAO,CAAC,aAAa,CAAgB;IACrC,OAAO,CAAC,YAAY,CAAC,CAA8B;IACnD,OAAO,CAAC,UAAU,CAAC,CAAkC;gBAGnD,QAAQ,EAAE,aAAa,EACvB,MAAM,EAAE,MAAM,EACd,aAAa,CAAC,EAAE,aAAa,EAC7B,YAAY,CAAC,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,IAAI,EAC1C,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC;IAc9C,eAAe,CAAC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,IAAI,GAAG,IAAI;IAItD,OAAO,CAAC,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,aAAa,EAAE,OAAO,EAAE,wBAAwB,GAAG,OAAO,CAAC,4BAA4B,CAAC;YA+B3G,WAAW;YA0CX,YAAY;CAmC3B"}
@@ -4,14 +4,15 @@ import { EventTransformer } from './event-transformer.js';
4
4
  import { PLANNING_SYSTEM_PROMPT } from './agents/planning.js';
5
5
  import { EXECUTION_SYSTEM_PROMPT } from './agents/execution.js';
6
6
  import { PromptBuilder } from './prompt-builder.js';
7
- import { POSTHOG_MCP } from './utils/mcp.js';
8
7
 
9
8
  class StageExecutor {
10
9
  registry;
11
10
  logger;
12
11
  eventTransformer;
13
12
  promptBuilder;
14
- constructor(registry, logger, promptBuilder) {
13
+ eventHandler;
14
+ mcpServers;
15
+ constructor(registry, logger, promptBuilder, eventHandler, mcpServers) {
15
16
  this.registry = registry;
16
17
  this.logger = logger.child('StageExecutor');
17
18
  this.eventTransformer = new EventTransformer();
@@ -20,6 +21,11 @@ class StageExecutor {
20
21
  generatePlanTemplate: async () => '',
21
22
  logger,
22
23
  });
24
+ this.eventHandler = eventHandler;
25
+ this.mcpServers = mcpServers;
26
+ }
27
+ setEventHandler(handler) {
28
+ this.eventHandler = handler;
23
29
  }
24
30
  async execute(task, stage, options) {
25
31
  const isManual = stage.is_manual_only === true;
@@ -61,9 +67,7 @@ class StageExecutor {
61
67
  cwd,
62
68
  permissionMode: 'plan',
63
69
  settingSources: ['local'],
64
- mcpServers: {
65
- ...POSTHOG_MCP
66
- }
70
+ mcpServers: this.mcpServers
67
71
  };
68
72
  const response = query({
69
73
  prompt,
@@ -72,8 +76,11 @@ class StageExecutor {
72
76
  let plan = '';
73
77
  for await (const message of response) {
74
78
  const transformed = this.eventTransformer.transform(message);
75
- if (transformed && transformed.type !== 'token') {
76
- this.logger.debug('Planning event', { type: transformed.type });
79
+ if (transformed) {
80
+ if (transformed.type !== 'token') {
81
+ this.logger.debug('Planning event', { type: transformed.type });
82
+ }
83
+ this.eventHandler?.(transformed);
77
84
  }
78
85
  if (message.type === 'assistant' && message.message?.content) {
79
86
  for (const c of message.message.content) {
@@ -97,9 +104,7 @@ class StageExecutor {
97
104
  cwd,
98
105
  permissionMode,
99
106
  settingSources: ['local'],
100
- mcpServers: {
101
- ...POSTHOG_MCP
102
- }
107
+ mcpServers: this.mcpServers
103
108
  };
104
109
  const response = query({
105
110
  prompt,
@@ -108,8 +113,11 @@ class StageExecutor {
108
113
  const results = [];
109
114
  for await (const message of response) {
110
115
  const transformed = this.eventTransformer.transform(message);
111
- if (transformed && transformed.type !== 'token') {
112
- this.logger.debug('Execution event', { type: transformed.type });
116
+ if (transformed) {
117
+ if (transformed.type !== 'token') {
118
+ this.logger.debug('Execution event', { type: transformed.type });
119
+ }
120
+ this.eventHandler?.(transformed);
113
121
  }
114
122
  results.push(message);
115
123
  }