@segosolutions/auto-task 1.7.7 → 1.7.8

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.cjs CHANGED
File without changes
package/dist/index.mjs CHANGED
@@ -54,7 +54,7 @@ ${Yc(s)}`,i=[];for(let a of Im){let c=Lt.join(s,a),u=Nm(c);u!==null&&i.push({pat
54
54
  `)}function Zc(s){let e=Lt.join(s,"src/index.ts");return Nt.existsSync(e)}function Lm(s,e){let t=e;switch(s){case"Read":return{emoji:"\u{1F4D6}",message:`Reading file: ${t?.file_path||"unknown"}`};case"Write":return{emoji:"\u270F\uFE0F",message:`Writing file: ${t?.file_path||"unknown"}`};case"Edit":return{emoji:"\u{1F4DD}",message:`Editing file: ${t?.file_path||"unknown"}`};case"Glob":return{emoji:"\u{1F50D}",message:`Searching for files: ${t?.pattern||"unknown pattern"}`};case"Grep":return{emoji:"\u{1F50E}",message:`Searching code: ${t?.pattern||"unknown pattern"}`};case"Bash":return{emoji:"\u{1F4BB}",message:`Running command: ${String(t?.command||"").substring(0,80)}${String(t?.command||"").length>80?"...":""}`};case"WebSearch":return{emoji:"\u{1F310}",message:`Web search: ${t?.query||"unknown query"}`};case"WebFetch":return{emoji:"\u{1F310}",message:`Fetching URL: ${t?.url||"unknown"}`};case"Task":return{emoji:"\u{1F916}",message:`Running sub-agent: ${t?.description||"task"}`};case"TodoWrite":return{emoji:"\u{1F4CB}",message:"Updating task list"};default:return{emoji:"\u{1F527}",message:`Using tool: ${s}`}}}function $r(s){let e={type:s.type,timestamp:s.timestamp};switch(s.type){case"tool_start":{let t=s.data,{message:i,emoji:a}=Lm(t.tool,t.input);return{...e,emoji:a,message:i,data:{toolUseId:t.toolUseId,tool:t.tool}}}case"tool_end":{let t=s.data;return{...e,emoji:t.isError?"\u274C":"\u2705",message:t.isError?"Tool failed":"Tool completed",data:{toolUseId:t.toolUseId}}}case"thinking":{let t=s.data,i=t.text.substring(0,150);return{...e,emoji:"\u{1F4AD}",message:`${i}${t.text.length>150?"...":""}`}}case"assistant_message":{let t=s.data,i=t.text.substring(0,200);return{...e,emoji:"\u{1F4AC}",message:`${i}${t.text.length>200?"...":""}`,data:{text:t.text,uuid:t.uuid}}}case"result":{let t=s.data;return{...e,emoji:t.success?"\u{1F389}":"\u26A0\uFE0F",message:t.success?"Analysis complete":"Analysis completed with issues",data:t}}case"error":{let t=s.data;return{...e,emoji:"\u2757",message:`Error: ${t.error}`,data:t}}case"session_start":return{...e,emoji:"\u{1F680}",message:"Starting analysis..."};case"processing":{let t=s.data;return{...e,emoji:"\u23F3",message:t.message||`Processing... (${Math.round((t.elapsedMs||0)/1e3)}s)`,data:t}}case"phase":{let t=s.data;return{...e,emoji:{claiming:"\u{1F4CB}",analyzing:"\u{1F50D}",implementing:"\u{1F6E0}\uFE0F",testing:"\u{1F9EA}",committing:"\u{1F4BE}","schema-migration":"\u{1F5C4}\uFE0F",completed:"\u2705",error:"\u274C"}[t.phase]||"\u2139\uFE0F",message:t.message,data:t}}default:return{...e,emoji:"\u2139\uFE0F",message:`Event: ${s.type}`,data:s.data}}}function Dm(s){let e=["# Client Request Analysis","","You are an expert software architect and project manager. A client has submitted a request for their project.","Your job is to analyze this request and break it down into actionable development tasks.","","## Client Request","",s.description,"","## Project Context","",`**Project Name:** ${s.projectContext.projectName}`];return s.projectContext.projectDescription&&e.push(`**Description:** ${s.projectContext.projectDescription}`),s.projectContext.techStack&&s.projectContext.techStack.length>0&&e.push(`**Tech Stack:** ${s.projectContext.techStack.join(", ")}`),s.projectContext.existingFeatures&&s.projectContext.existingFeatures.length>0&&(e.push(""),e.push("**Existing Features/Tasks:**"),s.projectContext.existingFeatures.forEach(t=>{e.push(`- ${t}`)})),e.push(""),e.push("---"),e.push(""),e.push("## Instructions"),e.push(""),e.push("Analyze this client request and produce a structured JSON response. You have access to the full codebase, so:"),e.push("1. Explore the codebase to understand the existing architecture and patterns"),e.push("2. Identify the specific files and components that would need to be modified"),e.push("3. Break down the request into 2-6 specific, actionable tasks"),e.push("4. Provide accurate time estimates based on the actual complexity you observe in the code"),e.push(""),e.push("Output your analysis as a JSON object with this structure:"),e.push("```json"),e.push("{"),e.push(' "summary": "Brief summary of what the client wants",'),e.push(' "reasoning": "Your analysis of how to approach this",'),e.push(' "suggestedTasks": ['),e.push(" {"),e.push(' "title": "Task title",'),e.push(' "description": "Detailed description",'),e.push(' "acceptanceCriteria": ["Criterion 1", "Criterion 2"],'),e.push(' "estimatedHours": 4,'),e.push(' "priority": "MEDIUM",'),e.push(' "type": "FEATURE",'),e.push(' "technicalNotes": "Implementation details",'),e.push(' "questionsForClient": [],'),e.push(' "aiConfidence": 0.85'),e.push(" }"),e.push(" ],"),e.push(' "questionsForClient": ["Any clarifying questions"],'),e.push(' "estimatedTotalHours": 12,'),e.push(' "aiConfidence": 0.85'),e.push("}"),e.push("```"),e.push(""),e.push("Valid priority values: LOW, MEDIUM, HIGH, URGENT"),e.push("Valid type values: FEATURE, BUG, ENHANCEMENT, DOCUMENTATION, DESIGN, TECHNICAL_DEBT"),e.push("aiConfidence should be between 0 and 1"),e.push(""),e.push("IMPORTANT: Output ONLY the JSON object, no additional text before or after."),e.join(`
55
55
  `)}function tl(s){let e=s.match(/```(?:json)?\s*([\s\S]*?)```/);if(e)try{return JSON.parse(e[1].trim())}catch{}let t=s.match(/\{[\s\S]*\}/);if(t)try{return JSON.parse(t[0])}catch{}return null}async function sl(s,e={}){let{timeoutMs:t=3e5,verbose:i=!0,workingDirectory:a,onEvent:c}=e,u=a||process.cwd(),p=Dm(s),g=Date.now(),m="",_=!1;i&&(console.log("[Agent] Starting analysis with Claude Agent SDK..."),console.log("[Agent] Prompt length:",p.length,"characters"),console.log("[Agent] Working directory:",u),console.log("[Agent] Model: claude-opus-4-5-20250929"));let w=new AbortController,C=setTimeout(()=>{_=!0,w.abort(),i&&console.log("[Agent] Timeout reached, aborting...")},t),T=(S,O)=>{c&&c({type:S,timestamp:Date.now(),data:O})};T("session_start",{prompt:p.substring(0,200),cwd:u});try{let S=Br({prompt:p,options:{allowedTools:["Read","Edit","Glob","Grep","Bash","WebSearch"],permissionMode:"acceptEdits",maxTurns:30}});for await(let O of S)switch(O.type){case"assistant":if(O.message.content){for(let N of O.message.content)if(N.type==="text")m+=N.text,i&&process.stdout.write(N.text),T("assistant_message",{text:N.text,uuid:O.uuid});else if(N.type==="thinking"){let G=N;i&&console.log(`[Agent] Thinking: ${G.thinking.substring(0,100)}...`),T("thinking",{text:G.thinking,uuid:O.uuid})}else if(N.type==="tool_use"||"name"in N){let G=N;i&&console.log(`[Agent] Tool: ${G.name}`),T("tool_start",{tool:G.name,toolUseId:G.id,input:G.input})}}break;case"user":if(O.message.content){for(let N of O.message.content)if(typeof N=="object"&&N!==null&&"type"in N&&N.type==="tool_result"){let G=N;T("tool_end",{toolUseId:G.tool_use_id,isError:G.is_error||!1,hasContent:!!G.content})}}break;case"result":i&&(console.log(""),console.log(`[Agent] Completed in ${O.duration_ms}ms`),console.log(`[Agent] Cost: $${O.total_cost_usd?.toFixed(4)||"N/A"}`)),clearTimeout(C);let k=tl(m);if(k&&k.summary&&Array.isArray(k.suggestedTasks))return T("result",{success:!0,analysis:k,costUsd:O.total_cost_usd,usage:O.usage}),{success:!0,analysis:k,output:m,timedOut:!1,totalCostUsd:O.total_cost_usd,usage:O.usage?{inputTokens:O.usage.input_tokens,outputTokens:O.usage.output_tokens}:void 0};if(O.subtype!=="success"){let N="result"in O?O.result:O.subtype;return T("error",{error:O.subtype,result:N}),{success:!1,output:m,error:`Agent error: ${O.subtype} - ${N}`,timedOut:!1,totalCostUsd:O.total_cost_usd}}return{success:!1,output:m,error:"Failed to parse analysis JSON from output",timedOut:!1,totalCostUsd:O.total_cost_usd}}return clearTimeout(C),{success:!1,output:m,error:"Query stream ended without result",timedOut:_}}catch(S){clearTimeout(C);let O=S instanceof Error?S.message:String(S);i&&console.error("[Agent] Error:",O),T("error",{error:O});let k=tl(m);return k&&k.summary&&Array.isArray(k.suggestedTasks)?(i&&console.log("[Agent] Got valid output despite error - treating as success"),{success:!0,analysis:k,output:m,timedOut:!1}):{success:!1,output:m,error:_?"Process timed out":O,timedOut:_}}}function Um(s,e){let t=[];if(e&&t.push(Xc(e)),t.push(`# Task: ${s.title}`),t.push(""),t.push(`**Project:** ${s.projectContext.projectName}`),t.push(`**Priority:** ${s.priority}`),t.push(`**Type:** ${s.type}`),t.push(`**Estimated Hours:** ${s.estimatedHours||"N/A"}`),t.push(""),t.push("## Description"),t.push(s.description||"No description provided."),t.push(""),s.acceptanceCriteria&&s.acceptanceCriteria.length>0&&(t.push("## Acceptance Criteria"),s.acceptanceCriteria.forEach((i,a)=>{t.push(`${a+1}. ${i}`)}),t.push("")),s.technicalNotes&&(t.push("## Technical Notes"),t.push(s.technicalNotes),t.push("")),s.projectContext.projectDescription&&(t.push("## Project Description"),t.push(s.projectContext.projectDescription),t.push("")),s.projectContext.knowledgeBase){t.push("## Project Knowledge Base");let i=s.projectContext.knowledgeBase;i.length>1e4?t.push(i.substring(0,1e4)+`
56
56
 
57
- [... truncated ...]`):t.push(i),t.push("")}return t.push("---"),t.push(""),t.push("## Instructions"),t.push(""),t.push("Please work on this task. Implement the required changes according to the acceptance criteria."),t.push(""),e&&(t.push("**IMPORTANT - Context Already Provided:**"),t.push("- Project structure and key files are shown above - DO NOT run `find`, `ls`, or re-read these files"),t.push("- Start implementing immediately using the pre-loaded context"),t.push("- Only read additional files if specifically needed for implementation"),t.push("")),t.push("**Work efficiently:**"),t.push("- Focus only on what's needed to meet the acceptance criteria"),t.push("- Avoid unnecessary exploration or refactoring beyond the scope"),t.push("- Make targeted file reads instead of scanning the entire codebase"),t.push("- If you have enough context, proceed with implementation"),t.push(""),t.push('When you have completed the task, output "TASK_COMPLETE" on its own line.'),t.push('If you encounter issues that prevent completion, output "TASK_BLOCKED: <reason>" on its own line.'),t.join(`
57
+ [... truncated ...]`):t.push(i),t.push("")}return t.push("---"),t.push(""),t.push("## Instructions"),t.push(""),t.push("Please work on this task. Implement the required changes according to the acceptance criteria."),t.push(""),e&&(t.push("**IMPORTANT - Context Already Provided:**"),t.push("- Project structure and key files are shown above - DO NOT run `find`, `ls`, or re-read these files"),t.push("- Start implementing immediately using the pre-loaded context"),t.push("- Only read additional files if specifically needed for implementation"),t.push("")),t.push("**Work efficiently:**"),t.push("- Focus only on what's needed to meet the acceptance criteria"),t.push("- Avoid unnecessary exploration or refactoring beyond the scope"),t.push("- Make targeted file reads instead of scanning the entire codebase"),t.push("- If you have enough context, proceed with implementation"),t.push(""),t.push("**Verification and Stopping Rules (CRITICAL):**"),t.push("- After making code changes, verify with ONE build/test run"),t.push("- If verification fails due to YOUR code changes, fix them (max 2 fix attempts)"),t.push("- If verification fails due to ENVIRONMENT issues, STOP and use TASK_BLOCKED immediately"),t.push(""),t.push("**Environment issues that require immediate TASK_BLOCKED:**"),t.push("- Stale server processes or port conflicts"),t.push("- Multiple processes running from previous sessions"),t.push("- Build artifacts or caches showing outdated code"),t.push("- Cannot determine if your changes are actually running"),t.push("- Pre-existing TypeScript/lint errors unrelated to your changes"),t.push(""),t.push("**Anti-Rabbit-Hole Rules:**"),t.push("- NEVER spend more than 1 attempt fixing environment issues (pkill, port cleanup, etc.)"),t.push("- If process management becomes the focus, STOP - your job is code, not DevOps"),t.push("- If you're unsure whether your code or the environment is the problem, use TASK_BLOCKED"),t.push('- Do NOT substitute "the code looks right" for actual verification'),t.push(""),t.push('When you have completed AND verified the task, output "TASK_COMPLETE" on its own line.'),t.push('If you encounter ANY issues that prevent clean verification, output "TASK_BLOCKED: <reason>" with a specific reason.'),t.join(`
58
58
  `)}async function Hr(s,e={}){let{timeoutMs:t=12e5,verbose:i=!0,workingDirectory:a,onEvent:c}=e,u=a||process.cwd(),p;if(Zc(u))try{p=Qc(u),i&&console.log("[Agent] Generated pre-loaded context:",{fileTreeLines:p.fileTree.split(`
59
59
  `).length,keyFilesCount:p.keyFiles.length})}catch(O){i&&console.warn("[Agent] Failed to generate pre-loaded context:",O)}let g=Um(s,p),m=Date.now(),_="",w=!1;i&&(console.log("[Agent] Starting backlog task with Claude Agent SDK..."),console.log("[Agent] Task:",s.title),console.log("[Agent] Working directory:",u),console.log("[Agent] Model: claude-opus-4-5-20250929"));let C=new AbortController,T=setTimeout(()=>{w=!0,C.abort(),i&&console.log("[Agent] Timeout reached, aborting...")},t),S=(O,k)=>{c&&c({type:O,timestamp:Date.now(),data:k})};S("session_start",{task:s.title,cwd:u});try{let O=Br({prompt:g,options:{allowedTools:["Read","Edit","Glob","Grep","Bash","Write"],permissionMode:"acceptEdits",maxTurns:30}});for await(let k of O)switch(k.type){case"assistant":if(k.message.content){for(let Y of k.message.content)if(Y.type==="text")_+=Y.text,i&&process.stdout.write(Y.text);else if("name"in Y){let X=Y;i&&console.log(`[Agent] Tool: ${X.name}`),S("tool_start",{tool:X.name,toolUseId:X.id,input:X.input})}}break;case"result":clearTimeout(T),i&&(console.log(""),console.log(`[Agent] Completed in ${k.duration_ms}ms`),console.log(`[Agent] Cost: $${k.total_cost_usd?.toFixed(4)||"N/A"}`));let N=_.includes("TASK_COMPLETE"),G=_.match(/TASK_BLOCKED:\s*(.+)/);return G?{success:!1,output:_,error:`Task blocked: ${G[1]}`,timedOut:!1,totalCostUsd:k.total_cost_usd,inputTokens:k.usage?.input_tokens,outputTokens:k.usage?.output_tokens}:{success:N||k.subtype==="success",output:_,timedOut:!1,totalCostUsd:k.total_cost_usd,inputTokens:k.usage?.input_tokens,outputTokens:k.usage?.output_tokens}}return clearTimeout(T),{success:!1,output:_,error:"Query stream ended without result",timedOut:w}}catch(O){clearTimeout(T);let k=O instanceof Error?O.message:String(O);return i&&console.error("[Agent] Error:",k),S("error",{error:k}),{success:!1,output:_,error:w?"Process timed out":k,timedOut:w}}}async function nl(){try{return!0}catch{return!1}}function rl(s){return s.includes("[CONVERSATIONAL SESSION]")}function il(s){let e=Math.max(s.lastIndexOf("MODE: PLANNING"),s.lastIndexOf("[MODE: PLANNING")),t=Math.max(s.lastIndexOf("MODE: BUILD"),s.lastIndexOf("MODE: WORK"));return e>t?"planning":(t>e,"work")}function jm(s){let t=s.replace("[CONVERSATIONAL SESSION]","").trim().split(/\n---\nUser follow-up:\n/);if(t.length===1){let c=t[0].replace(/^User message:\s*/i,"").trim();return{initialMessage:c,followUps:[],latestMessage:c,isFollowUp:!1}}let i=t[0].replace(/^User message:\s*/i,"").trim(),a=t.slice(1).map(c=>c.trim());return{initialMessage:i,followUps:a,latestMessage:a[a.length-1],isFollowUp:!0}}function qm(s,e){let t=["# PLANNING MODE - Read-Only Exploration & Discovery","","## CRITICAL: THIS IS A READ-ONLY SESSION","","**You CANNOT make any changes to the codebase in this mode.**","","Planning mode is strictly read-only:","- You have access to read-only tools: Read, Glob, Grep, WebSearch, WebFetch","- Bash is available but LIMITED to read-only commands only (ls, git status, git log, git diff, pwd, etc.)","- Edit, Write, and NotebookEdit tools are NOT available","- You CANNOT modify any files or execute write operations","- Your role is purely to explore, understand, and discuss","","---","","## YOUR ROLE","","You are a thoughtful collaborator helping a user explore and refine their ideas. Your job is to ask questions, discuss trade-offs, and help clarify requirements.","","## STRICT RULES FOR PLANNING MODE","","**DO NOT generate any tasks.** This is a strict requirement.","- Never output <task>JSON</task> blocks","- Never suggest specific task titles or estimates","- Focus entirely on understanding and exploration","","**Your goals in planning mode:**","1. Ask clarifying questions to understand the user's goals","2. Discuss trade-offs and alternatives","3. Help the user think through their idea thoroughly","4. Explore the codebase to understand context (read-only exploration)","","---","",`**Project Name:** ${s.projectContext.projectName}`];return s.projectContext.projectDescription&&t.push(`**Project Description:** ${s.projectContext.projectDescription}`),s.projectContext.techStack&&s.projectContext.techStack.length>0&&t.push(`**Tech Stack:** ${s.projectContext.techStack.join(", ")}`),t.push(""),t.push("---"),t.push(""),e.isFollowUp?(t.push("## Conversation History"),t.push(""),t.push(`**Initial request:** ${e.initialMessage}`),t.push(""),e.followUps.length>1&&(t.push("**Previous follow-ups:**"),e.followUps.slice(0,-1).forEach((i,a)=>{t.push(`${a+1}. ${i}`)}),t.push("")),t.push("---"),t.push(""),t.push("## Latest Message"),t.push(""),t.push(e.latestMessage)):(t.push("## User's Message"),t.push(""),t.push(e.initialMessage)),t.push(""),t.push("---"),t.push(""),t.push("## IMPORTANT: Suggest Build Mode Proactively"),t.push(""),t.push("**Planning should be BRIEF.** After exploring the codebase and understanding the request:"),t.push(""),t.push("1. Ask AT MOST 2-3 clarifying questions"),t.push("2. Do NOT spend excessive time exploring - focus on key files only"),t.push("3. **Suggest Build mode quickly** - users want to create tasks, not have endless discussions"),t.push(""),t.push("When you are ready to proceed (which should be SOON), output:"),t.push(""),t.push("<suggest_build_mode>"),t.push("Brief reasoning for why we're ready to create tasks"),t.push("</suggest_build_mode>"),t.push(""),t.push("**Suggest Build mode when ANY of these are true:**"),t.push("- The user's request is reasonably clear (even if not perfect)"),t.push("- You've asked 2-3 questions and have enough context"),t.push("- The user seems ready to proceed"),t.push("- Basic scope is understood (details can be clarified during task creation)"),t.push(""),t.push("**DO NOT wait for perfect clarity.** Tasks can be refined later. The goal is to move forward, not to plan endlessly."),t.push(""),t.push("**IMPORTANT: ExitPlanMode tool is NOT available.** Use `<suggest_build_mode>` tags instead."),t.push(""),t.push("---"),t.push(""),t.push("## REMINDER: READ-ONLY MODE"),t.push(""),t.push("You are in Planning mode which is READ-ONLY:"),t.push("- You can READ files and search the codebase to understand context"),t.push("- You can run read-only Bash commands (ls, git status, git log, git diff, pwd, etc.)"),t.push("- You CANNOT modify files, edit code, or run write operations"),t.push("- You CANNOT generate tasks - only explore and discuss"),t.push("- ExitPlanMode tool is NOT available - use `<suggest_build_mode>` tags instead"),t.push("- Any actual implementation happens later, after tasks are created in Build mode"),t.join(`
60
60
  `)}function Bm(s){if(!s)return null;try{if(el.existsSync(s)){let e=el.readFileSync(s,"utf-8");return console.log(`[Agent] Successfully read plan file: ${s} (${e.length} chars)`),e}else return console.log(`[Agent] Plan file does not exist: ${s}`),null}catch(e){return console.error(`[Agent] Error reading plan file ${s}:`,e),null}}function $m(s,e){let t=[],i=Bm(s.planFilePath);return i&&(t.push("# PLANNING PHASE OUTPUT - FOLLOW THIS PLAN"),t.push(""),t.push("**CRITICAL: A planning phase was already completed.** The codebase has already been explored."),t.push(""),t.push("## DO NOT RE-EXPLORE"),t.push(""),t.push("- DO NOT search the codebase again - this was done in planning"),t.push('- DO NOT use Glob, Grep, or Read to "understand the codebase"'),t.push('- DO NOT say "let me explore" or "let me understand the implementation"'),t.push("- The planning phase already gathered all necessary context"),t.push(""),t.push("## YOUR ONLY JOB: Create Tasks From This Plan"),t.push(""),t.push("Review the plan below and immediately create <task>JSON</task> blocks based on it."),t.push("Only use read tools if you need a specific line number for a task description."),t.push(""),t.push("---"),t.push(""),t.push("## The Plan"),t.push(""),t.push("```markdown"),t.push(i),t.push("```"),t.push(""),t.push("---"),t.push("")),t.push("# BUILD MODE - Read-Only Task Creation"),t.push(""),t.push("## CRITICAL: THIS IS A READ-ONLY SESSION"),t.push(""),t.push("**You CANNOT make any changes to the codebase in this mode.**"),t.push(""),t.push("Build mode is strictly read-only:"),t.push("- You have access to read-only tools: Read, Glob, Grep, WebSearch, WebFetch"),t.push("- Bash is available but LIMITED to read-only commands only (ls, git status, git log, git diff, pwd, etc.)"),t.push("- Edit, Write, and NotebookEdit tools are NOT available"),t.push("- You CANNOT modify any files or execute write operations"),i?(t.push("- Your role is to CREATE TASK DEFINITIONS from the plan above"),t.push("- DO NOT re-explore - planning already did that")):t.push("- Your role is to explore, understand, and CREATE TASK DEFINITIONS"),t.push("- Actual implementation happens later, when tasks are executed separately"),t.push(""),i&&(t.push("**CRITICAL REMINDER:** The planning phase is COMPLETE. DO NOT explore the codebase again."),t.push("Immediately review the plan above and generate <task>JSON</task> blocks."),t.push("")),t.push("---"),t.push(""),t.push("## YOUR ROLE"),t.push(""),t.push("You are helping create actionable development tasks. Your goal is to generate well-structured task definitions based on the user's requirements."),t.push(""),t.push(`**Project Name:** ${s.projectContext.projectName}`),s.projectContext.projectDescription&&t.push(`**Project Description:** ${s.projectContext.projectDescription}`),s.projectContext.techStack&&s.projectContext.techStack.length>0&&t.push(`**Tech Stack:** ${s.projectContext.techStack.join(", ")}`),t.push(""),t.push("---"),t.push(""),e.isFollowUp?(t.push("## Conversation History"),t.push(""),t.push("This is an ongoing conversation. Here is what was discussed:"),t.push(""),t.push(`**Initial request:** ${e.initialMessage}`),t.push(""),e.followUps.length>1&&(t.push("**Previous follow-ups:**"),e.followUps.slice(0,-1).forEach((a,c)=>{t.push(`${c+1}. ${a}`)}),t.push("")),t.push("---"),t.push(""),t.push("## Latest Message (respond to this)"),t.push(""),t.push(e.latestMessage),t.push(""),t.push("---"),t.push(""),t.push("## Instructions"),t.push(""),t.push("This is a FOLLOW-UP message. DO NOT start over or re-introduce yourself."),t.push("Simply respond directly to their latest message, building on the context of the conversation."),t.push(""),i?(t.push("**IMPORTANT:** The planning phase already explored the codebase. DO NOT re-explore."),t.push("Use the plan above to generate tasks immediately.")):t.push("If you already explored the codebase in a previous turn, you do NOT need to explore it again unless the user asks about something new."),t.push(""),t.push("**Refinement mode:** If the user is providing feedback on suggested tasks, immediately update or regenerate the tasks with their input.")):(t.push("## User's Message"),t.push(""),t.push(e.initialMessage),t.push(""),t.push("---"),t.push(""),t.push("## Instructions"),t.push(""),i?(t.push("**A planning phase was completed.** The plan is shown above."),t.push(""),t.push("DO NOT explore the codebase - this was already done during planning."),t.push("Immediately generate <task>JSON</task> blocks based on the plan.")):(t.push("You have access to the full codebase, so explore it to understand the project structure."),t.push(""),t.push("**Your goal is to generate actionable tasks within this first exchange.** Don't spend time asking qualifying questions - use the codebase and project context to make informed assumptions. Briefly explore relevant files if needed, then propose concrete tasks."),t.push(""),t.push("The client should feel like their work is being shaped into actionable items immediately, not that they're entering an interview process."))),s.existingTasks&&s.existingTasks.length>0&&(t.push(""),t.push("## Existing Tasks in Project"),t.push(""),t.push("The following tasks already exist in this project. If the user wants to modify an existing task, use the <task_modify> format below:"),t.push(""),s.existingTasks.slice(0,20).forEach((a,c)=>{t.push(`- [${a.id}] "${a.title}" (${a.status})`)}),s.existingTasks.length>20&&t.push(`- ... and ${s.existingTasks.length-20} more tasks`),t.push("")),t.push(""),t.push("## Task Generation"),t.push(""),t.push("**IMPORTANT: Prioritize generating tasks quickly.** Clients want to feel like work is starting immediately."),t.push(""),t.push("- Generate initial task suggestions within your FIRST response whenever possible"),t.push("- Make reasonable assumptions based on the project context and codebase - don't ask questions you can answer yourself"),t.push("- If something is unclear, make a sensible default assumption, note it in the task, and let the client refine it"),t.push("- Only ask 1-2 critical questions if absolutely essential - prefer to suggest tasks with noted assumptions"),t.push("- Tasks can always be refined through follow-up conversation - the goal is momentum, not perfection"),t.push(""),t.push("### Creating New Tasks"),t.push(""),t.push("When you identify work that should become a NEW task, output it in this format:"),t.push("<task>"),t.push("{"),t.push(' "title": "Task title",'),t.push(' "description": "What needs to be done",'),t.push(' "acceptanceCriteria": ["Criterion 1", "Criterion 2"],'),t.push(' "estimatedHours": 4,'),t.push(' "priority": "MEDIUM",'),t.push(' "type": "FEATURE",'),t.push(' "technicalNotes": "Implementation notes (include any assumptions made)",'),t.push(' "aiConfidence": 0.85'),t.push("}"),t.push("</task>"),t.push(""),t.push("### Modifying Existing Tasks"),t.push(""),t.push("If the user wants to modify an existing task, use this format (only include fields that should change):"),t.push('<task_modify existingTaskId="[ID from existing tasks list]">'),t.push("{"),t.push(' "title": "Updated title",'),t.push(' "description": "Updated description",'),t.push(' "acceptanceCriteria": ["Updated criterion 1", "Updated criterion 2"],'),t.push(' "estimatedHours": 6,'),t.push(' "priority": "HIGH"'),t.push("}"),t.push("</task_modify>"),t.push(""),t.push('Include an "assumptions" section in technicalNotes if you made decisions the client might want to change.'),t.push(`After suggesting tasks, invite the client to refine: "These tasks are ready for review. Let me know if you'd like to adjust scope, estimates, or approach."`),t.push(""),t.push("Valid priority values: LOW, MEDIUM, HIGH, URGENT"),t.push("Valid type values: FEATURE, BUG, ENHANCEMENT, DOCUMENTATION, DESIGN, TECHNICAL_DEBT"),t.push(""),t.push("---"),t.push(""),t.push("## REMINDER: READ-ONLY MODE"),t.push(""),t.push("You are in Build mode which is READ-ONLY:"),t.push("- You can READ files and search the codebase to understand context"),t.push("- You can run read-only Bash commands (ls, git status, git log, git diff, pwd, etc.)"),t.push("- You CANNOT modify files, edit code, or run write operations"),t.push("- You CAN generate task definitions using <task>JSON</task> format"),t.push("- Any actual implementation happens later, when tasks are executed separately"),t.push("- DO NOT attempt to implement the changes yourself - only define the tasks"),t.join(`
@@ -84,10 +84,10 @@ ${p}`:"");return g.includes("Your database is now in sync")||g.includes("Databas
84
84
 
85
85
  [Output truncated]`:i;if(await this.client.completeTask(e,"COMPLETED",{comment:`## Auto-Task Completed
86
86
 
87
- ${g}${u}`,costUsd:a,tokensUsed:c}),a){let m=c?`, ${c.toLocaleString()} tokens`:"";console.log(`[Monitor] Task ${t.id} completed (cost: $${a.toFixed(4)}${m})`)}else console.log(`[Monitor] Task ${t.id} completed and moved to IN_REVIEW`)}async handleFailure(e,t,i,a,c){let p=a.length>3e3?`${a.substring(0,3e3)}...
87
+ ${g}${u}`,costUsd:a,tokensUsed:c}),a){let m=c?`, ${c.toLocaleString()} tokens`:"";console.log(`[Monitor] Task ${t.id} completed (cost: $${a.toFixed(4)}${m})`)}else console.log(`[Monitor] Task ${t.id} completed and moved to IN_REVIEW`)}async handleFailure(e,t,i,a,c){let g=(a.length>3e3?`${a.substring(0,3e3)}...
88
88
 
89
- [Output truncated]`:a,g=[`## Auto-Task ${i==="TIMEOUT"?"Timed Out":"Failed"}`,"",c?`**Error:** ${c}`:"","","### Output","```",p,"```"].filter(Boolean).join(`
90
- `);await this.client.completeTask(e,i,{comment:g,errorMessage:c}),console.log(`[Monitor] Task ${t.id} marked as ${i}, sending alert...`);try{let m=await this.client.sendAlert(e,i,c);console.log(`[Monitor] Alert sent to ${m.emailsSent} recipients`)}catch(m){console.error("[Monitor] Failed to send alert:",m)}}};import{createInterface as Rw}from"readline";import{writeFileSync as Vd,existsSync as Pw}from"fs";import{resolve as zd}from"path";function Iw(){let s=Rw({input:process.stdin,output:process.stdout});return{ask:e=>new Promise(t=>{s.question(e,i=>{t(i.trim())})}),close:()=>s.close()}}async function Kd(s,e){try{return(await fetch(`${s}/api/mcp/auth/validate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}})).ok}catch{return!1}}function Jd(s){let e=`# Sego Auto-Task Monitor Configuration
89
+ [Output truncated]`:a).replace(/\x1b\[[0-9;]*[a-zA-Z]/g,""),m=[`## Auto-Task ${i==="TIMEOUT"?"Timed Out":"Failed"}`,"",c?`**Error:** ${c}`:"","","<details>","<summary>Output (click to expand)</summary>","","```text",g,"```","</details>"].filter(Boolean).join(`
90
+ `);await this.client.completeTask(e,i,{comment:m,errorMessage:c}),console.log(`[Monitor] Task ${t.id} marked as ${i}, sending alert...`);try{let _=await this.client.sendAlert(e,i,c);console.log(`[Monitor] Alert sent to ${_.emailsSent} recipients`)}catch(_){console.error("[Monitor] Failed to send alert:",_)}}};import{createInterface as Rw}from"readline";import{writeFileSync as Vd,existsSync as Pw}from"fs";import{resolve as zd}from"path";function Iw(){let s=Rw({input:process.stdin,output:process.stdout});return{ask:e=>new Promise(t=>{s.question(e,i=>{t(i.trim())})}),close:()=>s.close()}}async function Kd(s,e){try{return(await fetch(`${s}/api/mcp/auth/validate`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}})).ok}catch{return!1}}function Jd(s){let e=`# Sego Auto-Task Monitor Configuration
91
91
  # Generated by sego-auto-task init
92
92
 
93
93
  # Required: Your Sego PM API key
@@ -101,7 +101,7 @@ SEGO_PROJECT_ID=${s.projectId}
101
101
  `),e}async function Qd(s={}){let e=s.yes||!1;if(console.log(""),console.log("=".repeat(50)),console.log(" Sego Auto-Task Monitor Setup Wizard"),console.log("=".repeat(50)),console.log(""),e){console.log("Running in non-interactive mode (--yes flag)"),console.log("");let i=process.env.SEGO_API_KEY,a=process.env.SEGO_API_URL||"https://sego.pm",c=process.env.SEGO_PROJECT_ID;i||(console.error("Error: SEGO_API_KEY environment variable is required in non-interactive mode."),console.error(""),console.error("Usage:"),console.error(" SEGO_API_KEY=your_key sego-auto-task init --yes"),console.error(""),console.error("Or run without --yes for interactive setup."),process.exit(1)),console.log("Validating API key..."),await Kd(a,i)||(console.error(`
102
102
  Error: Invalid API key or unable to connect to the API.`),console.error("Please check:"),console.error(" 1. Your API key is correct"),console.error(` 2. You can reach ${a}`),console.error(" 3. Your API key has not expired"),process.exit(1)),console.log("API key validated successfully!");let p={apiKey:i,apiUrl:a,projectId:c||void 0},g=zd(process.cwd(),".env"),m=Jd(p);Vd(g,m),Yd(g);return}let t=Iw();try{console.log("Step 1: API Key"),console.log("Get your API key from: https://sego.pm/developer/api-keys"),console.log("");let i=await t.ask("Enter your Sego PM API key: ");i||(console.error(`
103
103
  Error: API key is required.`),process.exit(1)),console.log(""),console.log("Step 2: API URL");let c=await t.ask("Enter API URL (press Enter for https://sego.pm): ")||"https://sego.pm";console.log(""),console.log("Validating API key..."),await Kd(c,i)||(console.error(`
104
- Error: Invalid API key or unable to connect to the API.`),console.error("Please check:"),console.error(" 1. Your API key is correct"),console.error(` 2. You can reach ${c}`),console.error(" 3. Your API key has not expired"),process.exit(1)),console.log("API key validated successfully!"),console.log(""),console.log("Step 3: Project ID (Optional)"),console.log("You can filter to a specific project, or monitor all projects.");let p=await t.ask("Enter Project ID (press Enter to skip): "),g={apiKey:i,apiUrl:c,projectId:p||void 0};console.log(""),console.log("Step 4: Save Configuration");let m=zd(process.cwd(),".env");if(Pw(m)&&(console.log(`Warning: .env file already exists at ${m}`),(await t.ask("Overwrite? (y/N): ")).toLowerCase()!=="y")){console.log(""),console.log("Configuration not saved. You can set these environment variables manually:"),console.log(""),console.log(`export SEGO_API_KEY="${g.apiKey}"`),console.log(`export SEGO_API_URL="${g.apiUrl}"`),g.projectId&&console.log(`export SEGO_PROJECT_ID="${g.projectId}"`),console.log(""),t.close();return}let w=Jd(g);Vd(m,w),Yd(m)}finally{t.close()}}function Yd(s){console.log(""),console.log("=".repeat(50)),console.log(" Setup Complete!"),console.log("=".repeat(50)),console.log(""),console.log(`Configuration saved to: ${s}`),console.log(""),console.log("Next steps:"),console.log(" 1. Make sure Claude Code CLI is installed and authenticated:"),console.log(" npm install -g @anthropic-ai/claude-code"),console.log(" claude auth login"),console.log(""),console.log(" 2. Start the monitor:"),console.log(" sego-auto-task"),console.log(""),console.log(" 3. Or run in dry-run mode to test:"),console.log(" sego-auto-task --dry-run"),console.log("")}import{existsSync as Zd,mkdirSync as Mw,readFileSync as xw,writeFileSync as Nw}from"fs";import{homedir as Lw}from"os";import{join as ef}from"path";var tf="@segosolutions/auto-task",Po=ef(Lw(),".sego-auto-task"),Io=ef(Po,"version-check.json"),Dw=24*60*60*1e3;function Xd(s,e){let t=s.replace(/^v/,"").split(".").map(Number),i=e.replace(/^v/,"").split(".").map(Number);for(let a=0;a<Math.max(t.length,i.length);a++){let c=t[a]||0,u=i[a]||0;if(c<u)return-1;if(c>u)return 1}return 0}function Uw(){try{if(!Zd(Io))return null;let s=JSON.parse(xw(Io,"utf-8"));return Date.now()-s.checkedAt<Dw?s:null}catch{return null}}function jw(s){try{Zd(Po)||Mw(Po,{recursive:!0});let e={latestVersion:s,checkedAt:Date.now()};Nw(Io,JSON.stringify(e,null,2))}catch{}}async function qw(){try{let s=new AbortController,e=setTimeout(()=>s.abort(),5e3),t=await fetch(`https://registry.npmjs.org/${encodeURIComponent(tf)}/latest`,{signal:s.signal});return clearTimeout(e),t.ok&&(await t.json()).version||null}catch{return null}}async function sf(s){let e=Uw();if(e)return{currentVersion:s,latestVersion:e.latestVersion,updateAvailable:Xd(s,e.latestVersion)<0};let t=await qw();return t&&jw(t),{currentVersion:s,latestVersion:t,updateAvailable:t?Xd(s,t)<0:!1}}function nf(s){!s.updateAvailable||!s.latestVersion||(console.log(""),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log("\x1B[33m Update available!\x1B[0m"),console.log(` Current version: \x1B[90m${s.currentVersion}\x1B[0m`),console.log(` Latest version: \x1B[32m${s.latestVersion}\x1B[0m`),console.log(""),console.log(" Run to update:"),console.log(` \x1B[36m npm update -g ${tf}\x1B[0m`),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log(""))}var af="1.7.7",Mo=null;ds.name("sego-auto-task").description(`Background task monitor for Sego PM - automatically processes high-confidence tasks using Claude.
104
+ Error: Invalid API key or unable to connect to the API.`),console.error("Please check:"),console.error(" 1. Your API key is correct"),console.error(` 2. You can reach ${c}`),console.error(" 3. Your API key has not expired"),process.exit(1)),console.log("API key validated successfully!"),console.log(""),console.log("Step 3: Project ID (Optional)"),console.log("You can filter to a specific project, or monitor all projects.");let p=await t.ask("Enter Project ID (press Enter to skip): "),g={apiKey:i,apiUrl:c,projectId:p||void 0};console.log(""),console.log("Step 4: Save Configuration");let m=zd(process.cwd(),".env");if(Pw(m)&&(console.log(`Warning: .env file already exists at ${m}`),(await t.ask("Overwrite? (y/N): ")).toLowerCase()!=="y")){console.log(""),console.log("Configuration not saved. You can set these environment variables manually:"),console.log(""),console.log(`export SEGO_API_KEY="${g.apiKey}"`),console.log(`export SEGO_API_URL="${g.apiUrl}"`),g.projectId&&console.log(`export SEGO_PROJECT_ID="${g.projectId}"`),console.log(""),t.close();return}let w=Jd(g);Vd(m,w),Yd(m)}finally{t.close()}}function Yd(s){console.log(""),console.log("=".repeat(50)),console.log(" Setup Complete!"),console.log("=".repeat(50)),console.log(""),console.log(`Configuration saved to: ${s}`),console.log(""),console.log("Next steps:"),console.log(" 1. Make sure Claude Code CLI is installed and authenticated:"),console.log(" npm install -g @anthropic-ai/claude-code"),console.log(" claude auth login"),console.log(""),console.log(" 2. Start the monitor:"),console.log(" sego-auto-task"),console.log(""),console.log(" 3. Or run in dry-run mode to test:"),console.log(" sego-auto-task --dry-run"),console.log("")}import{existsSync as Zd,mkdirSync as Mw,readFileSync as xw,writeFileSync as Nw}from"fs";import{homedir as Lw}from"os";import{join as ef}from"path";var tf="@segosolutions/auto-task",Po=ef(Lw(),".sego-auto-task"),Io=ef(Po,"version-check.json"),Dw=24*60*60*1e3;function Xd(s,e){let t=s.replace(/^v/,"").split(".").map(Number),i=e.replace(/^v/,"").split(".").map(Number);for(let a=0;a<Math.max(t.length,i.length);a++){let c=t[a]||0,u=i[a]||0;if(c<u)return-1;if(c>u)return 1}return 0}function Uw(){try{if(!Zd(Io))return null;let s=JSON.parse(xw(Io,"utf-8"));return Date.now()-s.checkedAt<Dw?s:null}catch{return null}}function jw(s){try{Zd(Po)||Mw(Po,{recursive:!0});let e={latestVersion:s,checkedAt:Date.now()};Nw(Io,JSON.stringify(e,null,2))}catch{}}async function qw(){try{let s=new AbortController,e=setTimeout(()=>s.abort(),5e3),t=await fetch(`https://registry.npmjs.org/${encodeURIComponent(tf)}/latest`,{signal:s.signal});return clearTimeout(e),t.ok&&(await t.json()).version||null}catch{return null}}async function sf(s){let e=Uw();if(e)return{currentVersion:s,latestVersion:e.latestVersion,updateAvailable:Xd(s,e.latestVersion)<0};let t=await qw();return t&&jw(t),{currentVersion:s,latestVersion:t,updateAvailable:t?Xd(s,t)<0:!1}}function nf(s){!s.updateAvailable||!s.latestVersion||(console.log(""),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log("\x1B[33m Update available!\x1B[0m"),console.log(` Current version: \x1B[90m${s.currentVersion}\x1B[0m`),console.log(` Latest version: \x1B[32m${s.latestVersion}\x1B[0m`),console.log(""),console.log(" Run to update:"),console.log(` \x1B[36m npm update -g ${tf}\x1B[0m`),console.log("\x1B[33m"+"=".repeat(60)+"\x1B[0m"),console.log(""))}var af="1.7.8",Mo=null;ds.name("sego-auto-task").description(`Background task monitor for Sego PM - automatically processes high-confidence tasks using Claude.
105
105
 
106
106
  Runs in hybrid mode:
107
107
  - SSE: Listens for client request events and processes them with local Claude
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segosolutions/auto-task",
3
- "version": "1.7.7",
3
+ "version": "1.7.8",
4
4
  "description": "Background task monitor for Sego PM - automatically processes high-confidence tasks using Claude",
5
5
  "type": "module",
6
6
  "main": "dist/index.mjs",
@@ -12,13 +12,6 @@
12
12
  "README.md",
13
13
  "LICENSE"
14
14
  ],
15
- "scripts": {
16
- "dev": "tsx watch src/index.ts",
17
- "build": "tsx build.ts",
18
- "start": "node dist/index.mjs",
19
- "typecheck": "tsc --noEmit",
20
- "prepublishOnly": "pnpm build"
21
- },
22
15
  "repository": {
23
16
  "type": "git",
24
17
  "url": "https://github.com/nickgs/sego-pm.git",
@@ -57,5 +50,11 @@
57
50
  "esbuild": "^0.24.0",
58
51
  "tsx": "^4.19.0",
59
52
  "typescript": "^5.3.0"
53
+ },
54
+ "scripts": {
55
+ "dev": "tsx watch src/index.ts",
56
+ "build": "tsx build.ts",
57
+ "start": "node dist/index.mjs",
58
+ "typecheck": "tsc --noEmit"
60
59
  }
61
- }
60
+ }