glenn-code 1.0.25 → 1.0.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  // Glenn Code - Bundled and minified
2
2
  // (c) DNM Lab - All rights reserved
3
3
 
4
- import G from"inquirer";import*as F from"fs";import*as V from"path";import*as en from"os";import{fileURLToPath as Mn}from"url";import{createSdkMcpServer as rn}from"@anthropic-ai/claude-agent-sdk";import{tool as he}from"@anthropic-ai/claude-agent-sdk";import{z as me}from"zod";import*as ye from"fs";import*as Ct from"path";var K=null;function ce(n){K=n}function qe(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}var Jn=he("save_specification",`Save a specification to the database.
4
+ import G from"inquirer";import*as M from"fs";import*as z from"path";import*as nn from"os";import{fileURLToPath as $n}from"url";import{createSdkMcpServer as cn}from"@anthropic-ai/claude-agent-sdk";import{tool as ye}from"@anthropic-ai/claude-agent-sdk";import{z as he}from"zod";import*as be from"fs";import*as Pt from"path";var K=null;function le(n){K=n}function We(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}var Zn=ye("save_specification",`Save a specification to the database.
5
5
 
6
6
  IMPORTANT: First write the specification content to a file using the Write tool, then call this with the file path.
7
7
 
@@ -12,50 +12,50 @@ Workflow:
12
12
 
13
13
  Example:
14
14
  1. Write tool \u2192 save to /tmp/user-auth-spec.md
15
- 2. save_specification(name: "User Authentication", filePath: "/tmp/user-auth-spec.md")`,{name:me.string().describe("Specification name (e.g., 'User Authentication')"),filePath:me.string().describe("Path to the file containing the specification content (written via Write tool)")},async n=>{if(!K)return{content:[{type:"text",text:"\u274C Planning transport not initialized"}]};let e=Ct.resolve(n.filePath);if(!ye.existsSync(e))return{content:[{type:"text",text:`\u274C File not found: ${n.filePath}. Use Write tool first to create the file.`}]};let t=ye.readFileSync(e,"utf-8"),o=qe(n.name);return await K.saveSpecification(o,t),{content:[{type:"text",text:`\u2705 Saved specification: ${o}.spec.md`}]}}),Xn=he("read_specification","Read the content of a specification.",{name:me.string().describe("Name of the specification to read")},async n=>{if(!K)return{content:[{type:"text",text:"\u274C Planning transport not initialized"}]};let e=qe(n.name),t=await K.getSpecification(e);return t?{content:[{type:"text",text:t}]}:{content:[{type:"text",text:`\u274C Specification "${n.name}" not found.`}]}}),Zn=he("list_specifications","List all specifications.",{},async()=>{if(!K)return{content:[{type:"text",text:"\u274C Planning transport not initialized"}]};let n=await K.listSpecifications();return n.length===0?{content:[{type:"text",text:"\u{1F4CB} No specifications found."}]}:{content:[{type:"text",text:`\u{1F4CB} Specifications:
15
+ 2. save_specification(name: "User Authentication", filePath: "/tmp/user-auth-spec.md")`,{name:he.string().describe("Specification name (e.g., 'User Authentication')"),filePath:he.string().describe("Path to the file containing the specification content (written via Write tool)")},async n=>{if(!K)return{content:[{type:"text",text:"\u274C Planning transport not initialized"}]};let e=Pt.resolve(n.filePath);if(!be.existsSync(e))return{content:[{type:"text",text:`\u274C File not found: ${n.filePath}. Use Write tool first to create the file.`}]};let t=be.readFileSync(e,"utf-8"),o=We(n.name);return await K.saveSpecification(o,t),{content:[{type:"text",text:`\u2705 Saved specification: ${o}.spec.md`}]}}),eo=ye("read_specification","Read the content of a specification.",{name:he.string().describe("Name of the specification to read")},async n=>{if(!K)return{content:[{type:"text",text:"\u274C Planning transport not initialized"}]};let e=We(n.name),t=await K.getSpecification(e);return t?{content:[{type:"text",text:t}]}:{content:[{type:"text",text:`\u274C Specification "${n.name}" not found.`}]}}),to=ye("list_specifications","List all specifications.",{},async()=>{if(!K)return{content:[{type:"text",text:"\u274C Planning transport not initialized"}]};let n=await K.listSpecifications();return n.length===0?{content:[{type:"text",text:"\u{1F4CB} No specifications found."}]}:{content:[{type:"text",text:`\u{1F4CB} Specifications:
16
16
 
17
17
  ${n.map(t=>`- ${t.name} (${t.slug}.spec.md)`).join(`
18
- `)}`}]}}),eo=he("delete_specification","Delete a specification.",{name:me.string().describe("Name of the specification to delete")},async n=>{if(!K)return{content:[{type:"text",text:"\u274C Planning transport not initialized"}]};let e=qe(n.name);return await K.deleteSpecification(e)?{content:[{type:"text",text:`\u{1F5D1}\uFE0F Deleted: ${e}.spec.md`}]}:{content:[{type:"text",text:`\u274C Specification "${n.name}" not found.`}]}});import{tool as J}from"@anthropic-ai/claude-agent-sdk";import{z as se}from"zod";var P=null;function be(n){P=n}var _t=J("restart_services",`Rebuild and restart services. Call this after making backend changes (.cs files) to apply them.
18
+ `)}`}]}}),no=ye("delete_specification","Delete a specification.",{name:he.string().describe("Name of the specification to delete")},async n=>{if(!K)return{content:[{type:"text",text:"\u274C Planning transport not initialized"}]};let e=We(n.name);return await K.deleteSpecification(e)?{content:[{type:"text",text:`\u{1F5D1}\uFE0F Deleted: ${e}.spec.md`}]}:{content:[{type:"text",text:`\u274C Specification "${n.name}" not found.`}]}});import{tool as X}from"@anthropic-ai/claude-agent-sdk";import{z as re}from"zod";var R=null;function Se(n){R=n}var Rt=X("restart_services",`Rebuild and restart services. Call this after making backend changes (.cs files) to apply them.
19
19
 
20
20
  Parameters:
21
21
  - target: "backend" (default) | "frontend" | "both"
22
22
 
23
23
  Use target="backend" after .cs file changes (faster, only restarts .NET).
24
24
  Use target="frontend" if Vite is stuck (rare, HMR usually works).
25
- Use target="both" if unsure or both need restart.`,{target:se.enum(["backend","frontend","both"]).default("backend").describe("Which service to restart")},async n=>{if(!P)return{content:[{type:"text",text:"\u274C Service manager not initialized"}]};let e=n.target||"backend";console.log(`[MCP] restart_services called (target: ${e})`);let t=await P.restartServices(e);if(!t.success){let s=[];return t.backendError&&s.push(`Backend: ${t.backendError}`),t.frontendError&&s.push(`Frontend: ${t.frontendError}`),{content:[{type:"text",text:`\u274C Restart failed:
25
+ Use target="both" if unsure or both need restart.`,{target:re.enum(["backend","frontend","both"]).default("backend").describe("Which service to restart")},async n=>{if(!R)return{content:[{type:"text",text:"\u274C Service manager not initialized"}]};let e=n.target||"backend";console.log(`[MCP] restart_services called (target: ${e})`);let t=await R.restartServices(e);if(!t.success){let s=[];return t.backendError&&s.push(`Backend: ${t.backendError}`),t.frontendError&&s.push(`Frontend: ${t.frontendError}`),{content:[{type:"text",text:`\u274C Restart failed:
26
26
  ${s.join(`
27
27
 
28
- `)}`}]}}return{content:[{type:"text",text:`\u2705 ${e==="both"?"Backend and frontend":e==="backend"?"Backend":"Frontend"} restarted successfully.`}]}}),Rt=J("stop_services",`Stop running services. Call this BEFORE running scaffold to prevent port conflicts and ensure clean migrations.
28
+ `)}`}]}}return{content:[{type:"text",text:`\u2705 ${e==="both"?"Backend and frontend":e==="backend"?"Backend":"Frontend"} restarted successfully.`}]}}),Tt=X("stop_services",`Stop running services. Call this BEFORE running scaffold to prevent port conflicts and ensure clean migrations.
29
29
 
30
30
  Parameters:
31
31
  - target: "backend" (default) | "frontend" | "both"
32
32
 
33
- Use target="backend" before running scaffold (required for migrations).`,{target:se.enum(["backend","frontend","both"]).default("backend").describe("Which service to stop")},async n=>{if(!P)return{content:[{type:"text",text:"\u274C Service manager not initialized"}]};let e=n.target||"backend";console.log(`[MCP] stop_services called (target: ${e})`);let t=e==="backend"||e==="both",o=e==="frontend"||e==="both";t&&await P.stopBackend(),o&&await P.stopFrontend();let s=5e3,r=Date.now(),i=!t,a=!o;for(;Date.now()-r<s;){let u=await P.checkHealth();if(t&&!u.api&&(i=!0),o&&!u.web&&(a=!0),i&&a)break;await new Promise(d=>setTimeout(d,500))}let c=e==="both"?"Backend and frontend":e==="backend"?"Backend":"Frontend";return{content:[{type:"text",text:i&&a?`\u2705 ${c} stopped successfully.`:`\u26A0\uFE0F ${c} stop requested but health check still shows running. Proceeding anyway.`}]}}),Pt=J("start_services",`Start services. Call this AFTER running scaffold to bring services back up.
33
+ Use target="backend" before running scaffold (required for migrations).`,{target:re.enum(["backend","frontend","both"]).default("backend").describe("Which service to stop")},async n=>{if(!R)return{content:[{type:"text",text:"\u274C Service manager not initialized"}]};let e=n.target||"backend";console.log(`[MCP] stop_services called (target: ${e})`);let t=e==="backend"||e==="both",o=e==="frontend"||e==="both";t&&await R.stopBackend(),o&&await R.stopFrontend();let s=5e3,r=Date.now(),i=!t,a=!o;for(;Date.now()-r<s;){let u=await R.checkHealth();if(t&&!u.api&&(i=!0),o&&!u.web&&(a=!0),i&&a)break;await new Promise(d=>setTimeout(d,500))}let c=e==="both"?"Backend and frontend":e==="backend"?"Backend":"Frontend";return{content:[{type:"text",text:i&&a?`\u2705 ${c} stopped successfully.`:`\u26A0\uFE0F ${c} stop requested but health check still shows running. Proceeding anyway.`}]}}),It=X("start_services",`Start services. Call this AFTER running scaffold to bring services back up.
34
34
 
35
35
  Parameters:
36
36
  - target: "backend" (default) | "frontend" | "both"
37
37
 
38
- Use target="backend" after running scaffold.`,{target:se.enum(["backend","frontend","both"]).default("backend").describe("Which service to start")},async n=>{if(!P)return{content:[{type:"text",text:"\u274C Service manager not initialized"}]};let e=n.target||"backend";console.log(`[MCP] start_services called (target: ${e})`);let t=e==="backend"||e==="both",o=e==="frontend"||e==="both";t&&await P.startBackend(),o&&await P.startFrontend();let s=await P.waitForHealth(15e3),r=!t||s.api,i=!o||s.web,a=r&&i,c=e==="both"?"Backend and frontend":e==="backend"?"Backend":"Frontend";if(!a){let l=[];return t&&!s.api&&l.push("Backend failed to start"),o&&!s.web&&l.push("Frontend failed to start"),{content:[{type:"text",text:`\u274C ${c} failed to start: ${l.join(", ")}`}]}}return{content:[{type:"text",text:`\u2705 ${c} started successfully.`}]}}),Tt=J("check_service_health",`Check if services are running and healthy. Returns current status of backend API and frontend.
39
- Note: This only checks if ports are responding, NOT build/type errors. Use check_backend_build or check_frontend_types for that.`,{},async()=>{if(!P)return{content:[{type:"text",text:"\u274C Service manager not initialized"}]};let n=await P.checkHealth();return{content:[{type:"text",text:`Service Health:
38
+ Use target="backend" after running scaffold.`,{target:re.enum(["backend","frontend","both"]).default("backend").describe("Which service to start")},async n=>{if(!R)return{content:[{type:"text",text:"\u274C Service manager not initialized"}]};let e=n.target||"backend";console.log(`[MCP] start_services called (target: ${e})`);let t=e==="backend"||e==="both",o=e==="frontend"||e==="both";t&&await R.startBackend(),o&&await R.startFrontend();let s=await R.waitForHealth(15e3),r=!t||s.api,i=!o||s.web,a=r&&i,c=e==="both"?"Backend and frontend":e==="backend"?"Backend":"Frontend";if(!a){let l=[];return t&&!s.api&&l.push("Backend failed to start"),o&&!s.web&&l.push("Frontend failed to start"),{content:[{type:"text",text:`\u274C ${c} failed to start: ${l.join(", ")}`}]}}return{content:[{type:"text",text:`\u2705 ${c} started successfully.`}]}}),Et=X("check_service_health",`Check if services are running and healthy. Returns current status of backend API and frontend.
39
+ Note: This only checks if ports are responding, NOT build/type errors. Use check_backend_build or check_frontend_types for that.`,{},async()=>{if(!R)return{content:[{type:"text",text:"\u274C Service manager not initialized"}]};let n=await R.checkHealth();return{content:[{type:"text",text:`Service Health:
40
40
  \u{1F5A5}\uFE0F Backend API: ${n.api?"\u2705 running":"\u274C not running"}
41
- \u{1F310} Frontend: ${n.web?"\u2705 running":"\u274C not running"}`}]}}),It=J("check_backend_build","Run dotnet build to check for C# compilation errors. Use this after fixing backend code to verify the fix works.",{},async()=>{if(!P)return{content:[{type:"text",text:"\u274C Service manager not initialized"}]};console.log("[MCP] check_backend_build called");let n=await P.checkBackendBuild();return n.success?{content:[{type:"text",text:"\u2705 Backend build succeeded - no errors"}]}:{content:[{type:"text",text:`\u274C Backend build failed:
41
+ \u{1F310} Frontend: ${n.web?"\u2705 running":"\u274C not running"}`}]}}),At=X("check_backend_build","Run dotnet build to check for C# compilation errors. Use this after fixing backend code to verify the fix works.",{},async()=>{if(!R)return{content:[{type:"text",text:"\u274C Service manager not initialized"}]};console.log("[MCP] check_backend_build called");let n=await R.checkBackendBuild();return n.success?{content:[{type:"text",text:"\u2705 Backend build succeeded - no errors"}]}:{content:[{type:"text",text:`\u274C Backend build failed:
42
42
 
43
- ${n.errors}`}]}}),Et=J("check_frontend_types","Run TypeScript type check (tsc) on frontend code. Use this after fixing frontend code to verify the fix works.",{},async()=>{if(!P)return{content:[{type:"text",text:"\u274C Service manager not initialized"}]};console.log("[MCP] check_frontend_types called");let n=await P.checkFrontendTypes();return n.success?{content:[{type:"text",text:"\u2705 Frontend type check passed - no errors"}]}:{content:[{type:"text",text:`\u274C Frontend type errors:
43
+ ${n.errors}`}]}}),xt=X("check_frontend_types","Run TypeScript type check (tsc) on frontend code. Use this after fixing frontend code to verify the fix works.",{},async()=>{if(!R)return{content:[{type:"text",text:"\u274C Service manager not initialized"}]};console.log("[MCP] check_frontend_types called");let n=await R.checkFrontendTypes();return n.success?{content:[{type:"text",text:"\u2705 Frontend type check passed - no errors"}]}:{content:[{type:"text",text:`\u274C Frontend type errors:
44
44
 
45
- ${n.errors}`}]}}),so=J("tail_service_log",`Get the last N lines of service logs. Use this to debug startup failures or verify that the application is running correctly.
45
+ ${n.errors}`}]}}),io=X("tail_service_log",`Get the last N lines of service logs. Use this to debug startup failures or verify that the application is running correctly.
46
46
 
47
47
  Parameters:
48
48
  - target: "backend" | "frontend"
49
- - lines: number (default 50)`,{target:se.enum(["backend","frontend"]).describe("Which log to read"),lines:se.number().default(50).describe("Number of lines to read")},async n=>{if(!P)return{content:[{type:"text",text:"\u274C Service manager not initialized"}]};let e=await P.tailLogs(n.target,n.lines);return{content:[{type:"text",text:`Last ${n.lines} lines of ${n.target} log:
49
+ - lines: number (default 50)`,{target:re.enum(["backend","frontend"]).describe("Which log to read"),lines:re.number().default(50).describe("Number of lines to read")},async n=>{if(!R)return{content:[{type:"text",text:"\u274C Service manager not initialized"}]};let e=await R.tailLogs(n.target,n.lines);return{content:[{type:"text",text:`Last ${n.lines} lines of ${n.target} log:
50
50
 
51
51
  ${e.join(`
52
- `)}`}]}}),ro=J("check_swagger_endpoints",`Search for endpoints in the generated swagger.json. Use this to verify that new backend endpoints are correctly exposed.
52
+ `)}`}]}}),ao=X("check_swagger_endpoints",`Search for endpoints in the generated swagger.json. Use this to verify that new backend endpoints are correctly exposed.
53
53
 
54
54
  Parameters:
55
- - pattern: string (e.g., "users", "api/reports")`,{pattern:se.string().describe("Text to search for in endpoint paths")},async n=>{if(!P)return{content:[{type:"text",text:"\u274C Service manager not initialized"}]};let e=await P.checkSwaggerEndpoints(n.pattern);return e.foundEndpoints.length===0?{content:[{type:"text",text:`\u274C No endpoints found matching "${n.pattern}" (Total endpoints: ${e.totalEndpoints})`}]}:{content:[{type:"text",text:`\u2705 Found ${e.foundEndpoints.length} matching endpoints:
55
+ - pattern: string (e.g., "users", "api/reports")`,{pattern:re.string().describe("Text to search for in endpoint paths")},async n=>{if(!R)return{content:[{type:"text",text:"\u274C Service manager not initialized"}]};let e=await R.checkSwaggerEndpoints(n.pattern);return e.foundEndpoints.length===0?{content:[{type:"text",text:`\u274C No endpoints found matching "${n.pattern}" (Total endpoints: ${e.totalEndpoints})`}]}:{content:[{type:"text",text:`\u2705 Found ${e.foundEndpoints.length} matching endpoints:
56
56
 
57
57
  ${e.foundEndpoints.join(`
58
- `)}`}]}});import*as le from"fs";import*as sn from"path";import*as x from"fs";import*as Se from"path";function pe(n){let e=Se.join(n,".sdd","specifications");function t(){x.existsSync(e)||x.mkdirSync(e,{recursive:!0})}function o(s){return Se.join(e,`${s}.spec.md`)}return{async saveSpecification(s,r){t(),x.writeFileSync(o(s),r,"utf-8")},async getSpecification(s){t();let r=o(s);return x.existsSync(r)?x.readFileSync(r,"utf-8"):null},async listSpecifications(){return t(),x.readdirSync(e).filter(r=>r.endsWith(".spec.md")).map(r=>{let i=x.readFileSync(Se.join(e,r),"utf-8"),a=i.match(/name: "([^"]+)"/),c=i.match(/status: (\w+)/),l=i.match(/version: "([^"]+)"/);return{slug:r.replace(".spec.md",""),name:a?.[1]||r,status:c?.[1]||"unknown",version:l?.[1]||"1.0.0"}})},async deleteSpecification(s){t();let r=o(s);return x.existsSync(r)?(x.unlinkSync(r),!0):!1},async specificationExists(s){return t(),x.existsSync(o(s))}}}function Ge(){return rn({name:"agent-insights",version:"1.0.0",tools:[_t,Rt,Pt,Tt,It,Et]})}import{query as _n}from"@anthropic-ai/claude-agent-sdk";var We={description:"Delegate to this agent when scaffolding new entities or creating CRUD features. This agent handles entity generation using the scaffold CLI with multi-entity support.",model:"inherit",prompt:`You are a scaffolding specialist. Your ONLY job is:
58
+ `)}`}]}});import*as pe from"fs";import*as an from"path";import*as x from"fs";import*as we from"path";function de(n){let e=we.join(n,".sdd","specifications");function t(){x.existsSync(e)||x.mkdirSync(e,{recursive:!0})}function o(s){return we.join(e,`${s}.spec.md`)}return{async saveSpecification(s,r){t(),x.writeFileSync(o(s),r,"utf-8")},async getSpecification(s){t();let r=o(s);return x.existsSync(r)?x.readFileSync(r,"utf-8"):null},async listSpecifications(){return t(),x.readdirSync(e).filter(r=>r.endsWith(".spec.md")).map(r=>{let i=x.readFileSync(we.join(e,r),"utf-8"),a=i.match(/name: "([^"]+)"/),c=i.match(/status: (\w+)/),l=i.match(/version: "([^"]+)"/);return{slug:r.replace(".spec.md",""),name:a?.[1]||r,status:c?.[1]||"unknown",version:l?.[1]||"1.0.0"}})},async deleteSpecification(s){t();let r=o(s);return x.existsSync(r)?(x.unlinkSync(r),!0):!1},async specificationExists(s){return t(),x.existsSync(o(s))}}}function Ke(){return cn({name:"agent-insights",version:"1.0.0",tools:[Rt,Tt,It,Et,At,xt]})}import{query as Rn}from"@anthropic-ai/claude-agent-sdk";var Ye={description:"Delegate to this agent when scaffolding new entities or creating CRUD features. This agent handles entity generation using the scaffold CLI with multi-entity support.",model:"inherit",prompt:`You are a scaffolding specialist. Your ONLY job is:
59
59
  1. Read the spec if referenced in the card description
60
60
  2. Check existing features (quick ls)
61
61
  3. Write ALL entities to ONE /tmp/scaffold.json (big bang, no phasing!)
@@ -262,7 +262,7 @@ DO NOT phase/split into multiple runs - that's slower and error-prone.
262
262
  - Enrollment depends on Student + CourseOffering - CLI handles it
263
263
  - ONE scaffold run creates ALL 6 entities with correct FK relationships
264
264
 
265
- REMEMBER: Read spec (if referenced) \u2192 ls \u2192 Write \u2192 Run \u2192 Restart \u2192 STOP. No verification needed.`};var we={description:"Delegate to this agent to fix errors, type issues, or bugs in the code",model:"inherit",prompt:`You are a bug-fixing specialist. Your job is to FIX errors, not just report them.
265
+ REMEMBER: Read spec (if referenced) \u2192 ls \u2192 Write \u2192 Run \u2192 Restart \u2192 STOP. No verification needed.`};var ke={description:"Delegate to this agent to fix errors, type issues, or bugs in the code",model:"inherit",prompt:`You are a bug-fixing specialist. Your job is to FIX errors, not just report them.
266
266
 
267
267
  ## Process
268
268
  1. Read the error message carefully - understand WHAT and WHERE
@@ -292,7 +292,7 @@ REMEMBER: Read spec (if referenced) \u2192 ls \u2192 Write \u2192 Run \u2192 Res
292
292
  - Fix the ROOT CAUSE, not symptoms
293
293
  - Make minimal changes
294
294
  - Don't add unnecessary code
295
- - If multiple files have the same issue, fix all of them`};var ke={description:"Delegate to this agent for specification-driven development. Use when the user wants to plan, specify, or design a feature before implementation.",model:"inherit",prompt:`You are a Spec-Driven Development (SDD) specialist.
295
+ - If multiple files have the same issue, fix all of them`};var ve={description:"Delegate to this agent for specification-driven development. Use when the user wants to plan, specify, or design a feature before implementation.",model:"inherit",prompt:`You are a Spec-Driven Development (SDD) specialist.
296
296
 
297
297
  ## \u26D4 CRITICAL RULES - READ FIRST
298
298
 
@@ -451,7 +451,7 @@ Save your spec. The spec will appear in the user's UI.
451
451
  - Ask ONE question at a time (not all at once!)
452
452
  - STOP asking if user says "start implementing"
453
453
  - NEVER output the spec as text - use save_specification
454
- - Maximum 7 questions - don't exhaust the user!`};var Ke={description:"Delegate to this agent for writing new backend features (non-scaffold). Custom endpoints, queries, commands, business logic.",model:"inherit",prompt:`You are a backend specialist for .NET 9 / ASP.NET Core.
454
+ - Maximum 7 questions - don't exhaust the user!`};var Qe={description:"Delegate to this agent for writing new backend features (non-scaffold). Custom endpoints, queries, commands, business logic.",model:"inherit",prompt:`You are a backend specialist for .NET 9 / ASP.NET Core.
455
455
 
456
456
  ## YOUR ROLE
457
457
  Write custom backend code that goes BEYOND what scaffold generates:
@@ -543,7 +543,7 @@ public class Get{EntityB}LookupHandler : IQueryHandler<Get{EntityB}LookupQuery,
543
543
  2. If build succeeds, generate swagger: \`mcp__agent-insights__restart_services\` (this regenerates swagger)
544
544
  3. Report what you created and STOP
545
545
 
546
- **\u26A0\uFE0F CRITICAL:** Always generate swagger before frontend work begins!`};var Ye={description:"Delegate to this agent for writing frontend features. Components, hooks, pages using generated API hooks.",model:"inherit",prompt:`You are a frontend specialist for React 19 + TypeScript + MUI.
546
+ **\u26A0\uFE0F CRITICAL:** Always generate swagger before frontend work begins!`};var Ve={description:"Delegate to this agent for writing frontend features. Components, hooks, pages using generated API hooks.",model:"inherit",prompt:`You are a frontend specialist for React 19 + TypeScript + MUI.
547
547
 
548
548
  ## YOUR ROLE
549
549
  Write frontend code using GENERATED API hooks (never manual fetch):
@@ -636,7 +636,7 @@ queryClient.invalidateQueries({ queryKey: getGetApi{Entities}QueryKey() })
636
636
  ## WHEN DONE
637
637
  1. Run typecheck: \`cd /workspace/packages/backoffice-web && npx tsc --noEmit\`
638
638
  2. If errors, fix them
639
- 3. Report what you created and STOP`};var ve={description:"Delegate to this agent to help the user write or improve their project context. This agent researches the codebase, asks strategic questions about product goals and users, then writes comprehensive project context.",model:"inherit",prompt:`You are a Project Context Specialist - an expert at understanding codebases and extracting the essential context that helps AI agents work effectively on projects.
639
+ 3. Report what you created and STOP`};var Ce={description:"Delegate to this agent to help the user write or improve their project context. This agent researches the codebase, asks strategic questions about product goals and users, then writes comprehensive project context.",model:"inherit",prompt:`You are a Project Context Specialist - an expert at understanding codebases and extracting the essential context that helps AI agents work effectively on projects.
640
640
 
641
641
  ## \u26D4 CRITICAL RULES - READ FIRST
642
642
 
@@ -830,13 +830,13 @@ Before saving, verify your context:
830
830
  3. **Show patterns** - Include small code examples for common tasks
831
831
  4. **Prioritize** - Put most critical info in <critical_rules>
832
832
  5. **Keep it scannable** - Use bullets, clear sections
833
- 6. **Update, don't replace** - If context exists, improve it rather than starting fresh`};import*as re from"fs";import*as Dt from"path";var Ce=class{buffer=[];flushInterval=null;sessionId=null;outputDir;flushIntervalMs;constructor(e){this.outputDir=e.outputDir||"/tmp/agent-debug",this.flushIntervalMs=e.flushIntervalMs||3e3,e.enabled&&(this.ensureOutputDir(),this.startFlushInterval())}ensureOutputDir(){re.existsSync(this.outputDir)||re.mkdirSync(this.outputDir,{recursive:!0})}startFlushInterval(){this.flushInterval=setInterval(()=>{this.flush()},this.flushIntervalMs)}setSessionId(e){this.sessionId=e}log(e){let o={timestamp:new Date().toISOString(),message:e};this.buffer.push(JSON.stringify(o,null,2)+`
833
+ 6. **Update, don't replace** - If context exists, improve it rather than starting fresh`};import*as ie from"fs";import*as Ot from"path";var _e=class{buffer=[];flushInterval=null;sessionId=null;outputDir;flushIntervalMs;constructor(e){this.outputDir=e.outputDir||"/tmp/agent-debug",this.flushIntervalMs=e.flushIntervalMs||3e3,e.enabled&&(this.ensureOutputDir(),this.startFlushInterval())}ensureOutputDir(){ie.existsSync(this.outputDir)||ie.mkdirSync(this.outputDir,{recursive:!0})}startFlushInterval(){this.flushInterval=setInterval(()=>{this.flush()},this.flushIntervalMs)}setSessionId(e){this.sessionId=e}log(e){let o={timestamp:new Date().toISOString(),message:e};this.buffer.push(JSON.stringify(o,null,2)+`
834
834
  ---
835
- `)}getLogFilePath(){let t=(this.sessionId||"unknown").replace(/[^a-zA-Z0-9-]/g,"_").slice(0,50),o=new Date().toISOString().split("T")[0];return Dt.join(this.outputDir,`session-${o}-${t}.log`)}flush(){if(this.buffer.length===0)return;let e=this.buffer.join("");this.buffer=[];let t=this.getLogFilePath();re.appendFileSync(t,e)}stop(){this.flushInterval&&(clearInterval(this.flushInterval),this.flushInterval=null),this.flush()}};function jt(n){return n?typeof n=="boolean"?n?new Ce({enabled:!0}):null:n.enabled?new Ce(n):null:null}import{z as h}from"zod";import*as Re from"fs/promises";import*as X from"path";var Ot=h.object({port:h.number(),startCommand:h.string(),buildCommand:h.string().optional(),typecheckCommand:h.string().optional(),logFile:h.string().optional(),healthEndpoint:h.string().optional(),extensions:h.array(h.string())}),an=h.object({port:h.number(),type:h.enum(["postgres","mysql","sqlite","mongodb"])}),cn=h.object({command:h.string(),schemaPath:h.string().optional()}),ln=h.object({email:h.string().optional(),name:h.string().optional(),commitPrefix:h.string().optional()}),pn=h.object({enabled:h.boolean(),port:h.number().optional()}),_e=h.object({version:h.literal("1.0"),paths:h.object({workspace:h.string(),backend:h.string().optional(),frontend:h.string().optional(),features:h.object({backend:h.string().optional(),frontend:h.string().optional()}).optional()}),services:h.object({backend:Ot.optional(),frontend:Ot.optional(),database:an.optional()}).optional(),scaffold:cn.optional(),git:ln.optional(),techStack:h.object({backend:h.array(h.string()).optional(),frontend:h.array(h.string()).optional(),patterns:h.array(h.string()).optional()}).optional(),tunnel:pn.optional()});function Y(n){return{version:"1.0",paths:{workspace:n||process.env.WORKSPACE_DIR||"/workspace",backend:"packages/dotnet-api",frontend:"packages/backoffice-web",features:{backend:"Source/Features",frontend:"src/applications/super-admin/features"}},services:{backend:{port:5338,startCommand:"dotnet run",buildCommand:"dotnet build",typecheckCommand:"dotnet build --no-restore",logFile:"/tmp/api.log",healthEndpoint:"http://localhost:5338",extensions:[".cs",".csproj"]},frontend:{port:5173,startCommand:"npm run dev",typecheckCommand:"npx tsc -p tsconfig.app.json --noEmit",logFile:"/tmp/web.log",healthEndpoint:"http://localhost:5173",extensions:[".ts",".tsx",".json"]},database:{port:43594,type:"postgres"}},scaffold:{command:"scaffold --schema /tmp/scaffold.json --output /workspace --force --full",schemaPath:"/tmp/scaffold.json"},git:{email:"agent@dotnetmentor.se",name:"Agent",commitPrefix:"[agent]"},techStack:{backend:[".NET 9","PostgreSQL","MediatR (CQRS)","EF Core"],frontend:["React 19","TypeScript","Vite","MUI","TanStack Query"],patterns:["Vertical slices","CQRS","Soft delete","Timestamps"]},tunnel:{enabled:!0,port:5173}}}var dn="project-config.json",un=".sdd";async function Pe(n){let{workspaceDir:e,providedConfig:t,requireConfig:o}=n;if(t)return{config:_e.parse(t),source:"provided"};let s=X.join(e,un,dn);try{let r=await Re.readFile(s,"utf-8"),i=JSON.parse(r);return{config:_e.parse(i),source:"file",configPath:s}}catch(r){r instanceof Error&&"code"in r&&r.code!=="ENOENT"&&console.warn(`[Config] Warning: Invalid project-config.json at ${s}:`,r instanceof h.ZodError?r.errors:r.message)}if(o)throw new Error(`No project configuration found at ${s} and requireConfig is true`);return{config:Y(e),source:"default"}}function Te(n,e){if(e)return X.isAbsolute(e)?e:X.join(n.paths.workspace,e)}function B(n){return Te(n,n.paths.backend)}function q(n){return Te(n,n.paths.frontend)}function Ie(n){let e=B(n);if(!(!e||!n.paths.features?.backend))return X.join(e,n.paths.features.backend)}function de(n){let e=q(n);if(!(!e||!n.paths.features?.frontend))return X.join(e,n.paths.features.frontend)}function Ee(n){let e=[];return n.techStack?.backend?.length&&e.push(`**Backend:** ${n.techStack.backend.join(", ")}`),n.techStack?.frontend?.length&&e.push(`**Frontend:** ${n.techStack.frontend.join(", ")}`),n.techStack?.patterns?.length&&e.push(`**Patterns:** ${n.techStack.patterns.join(", ")}`),e.join(`
836
- `)}function Ae(n){let e=[];return n.services?.backend&&e.push(`| Backend | ${B(n)} | ${n.services.backend.port} | ${n.services.backend.logFile||"N/A"} |`),n.services?.frontend&&e.push(`| Frontend | ${q(n)} | ${n.services.frontend.port} | ${n.services.frontend.logFile||"N/A"} |`),n.services?.database&&e.push(`| Database (${n.services.database.type}) | localhost | ${n.services.database.port} | - |`),e.length===0?"":`| Service | Location | Port | Logs |
835
+ `)}getLogFilePath(){let t=(this.sessionId||"unknown").replace(/[^a-zA-Z0-9-]/g,"_").slice(0,50),o=new Date().toISOString().split("T")[0];return Ot.join(this.outputDir,`session-${o}-${t}.log`)}flush(){if(this.buffer.length===0)return;let e=this.buffer.join("");this.buffer=[];let t=this.getLogFilePath();ie.appendFileSync(t,e)}stop(){this.flushInterval&&(clearInterval(this.flushInterval),this.flushInterval=null),this.flush()}};function Nt(n){return n?typeof n=="boolean"?n?new _e({enabled:!0}):null:n.enabled?new _e(n):null:null}import{z as h}from"zod";import*as Re from"fs/promises";import*as Z from"path";var Ut=h.object({port:h.number(),startCommand:h.string(),buildCommand:h.string().optional(),typecheckCommand:h.string().optional(),logFile:h.string().optional(),healthEndpoint:h.string().optional(),extensions:h.array(h.string())}),ln=h.object({port:h.number(),type:h.enum(["postgres","mysql","sqlite","mongodb"])}),pn=h.object({command:h.string(),schemaPath:h.string().optional()}),dn=h.object({email:h.string().optional(),name:h.string().optional(),commitPrefix:h.string().optional()}),un=h.object({enabled:h.boolean(),port:h.number().optional()}),Pe=h.object({version:h.literal("1.0"),paths:h.object({workspace:h.string(),backend:h.string().optional(),frontend:h.string().optional(),features:h.object({backend:h.string().optional(),frontend:h.string().optional()}).optional()}),services:h.object({backend:Ut.optional(),frontend:Ut.optional(),database:ln.optional()}).optional(),scaffold:pn.optional(),git:dn.optional(),techStack:h.object({backend:h.array(h.string()).optional(),frontend:h.array(h.string()).optional(),patterns:h.array(h.string()).optional()}).optional(),tunnel:un.optional()});function Y(n){return{version:"1.0",paths:{workspace:n||process.env.WORKSPACE_DIR||"/workspace",backend:"packages/dotnet-api",frontend:"packages/backoffice-web",features:{backend:"Source/Features",frontend:"src/applications/super-admin/features"}},services:{backend:{port:5338,startCommand:"dotnet run",buildCommand:"dotnet build",typecheckCommand:"dotnet build --no-restore",logFile:"/tmp/api.log",healthEndpoint:"http://localhost:5338",extensions:[".cs",".csproj"]},frontend:{port:5173,startCommand:"npm run dev",typecheckCommand:"npx tsc -p tsconfig.app.json --noEmit",logFile:"/tmp/web.log",healthEndpoint:"http://localhost:5173",extensions:[".ts",".tsx",".json"]},database:{port:43594,type:"postgres"}},scaffold:{command:"scaffold --schema /tmp/scaffold.json --output /workspace --force --full",schemaPath:"/tmp/scaffold.json"},git:{email:"agent@dotnetmentor.se",name:"Agent",commitPrefix:"[agent]"},techStack:{backend:[".NET 9","PostgreSQL","MediatR (CQRS)","EF Core"],frontend:["React 19","TypeScript","Vite","MUI","TanStack Query"],patterns:["Vertical slices","CQRS","Soft delete","Timestamps"]},tunnel:{enabled:!0,port:5173}}}var gn="project-config.json",fn=".sdd";async function Te(n){let{workspaceDir:e,providedConfig:t,requireConfig:o}=n;if(t)return{config:Pe.parse(t),source:"provided"};let s=Z.join(e,fn,gn);try{let r=await Re.readFile(s,"utf-8"),i=JSON.parse(r);return{config:Pe.parse(i),source:"file",configPath:s}}catch(r){r instanceof Error&&"code"in r&&r.code!=="ENOENT"&&console.warn(`[Config] Warning: Invalid project-config.json at ${s}:`,r instanceof h.ZodError?r.errors:r.message)}if(o)throw new Error(`No project configuration found at ${s} and requireConfig is true`);return{config:Y(e),source:"default"}}function Ie(n,e){if(e)return Z.isAbsolute(e)?e:Z.join(n.paths.workspace,e)}function B(n){return Ie(n,n.paths.backend)}function q(n){return Ie(n,n.paths.frontend)}function Ee(n){let e=B(n);if(!(!e||!n.paths.features?.backend))return Z.join(e,n.paths.features.backend)}function ue(n){let e=q(n);if(!(!e||!n.paths.features?.frontend))return Z.join(e,n.paths.features.frontend)}function Ae(n){let e=[];return n.techStack?.backend?.length&&e.push(`**Backend:** ${n.techStack.backend.join(", ")}`),n.techStack?.frontend?.length&&e.push(`**Frontend:** ${n.techStack.frontend.join(", ")}`),n.techStack?.patterns?.length&&e.push(`**Patterns:** ${n.techStack.patterns.join(", ")}`),e.join(`
836
+ `)}function xe(n){let e=[];return n.services?.backend&&e.push(`| Backend | ${B(n)} | ${n.services.backend.port} | ${n.services.backend.logFile||"N/A"} |`),n.services?.frontend&&e.push(`| Frontend | ${q(n)} | ${n.services.frontend.port} | ${n.services.frontend.logFile||"N/A"} |`),n.services?.database&&e.push(`| Database (${n.services.database.type}) | localhost | ${n.services.database.port} | - |`),e.length===0?"":`| Service | Location | Port | Logs |
837
837
  |---------|----------|------|------|
838
838
  ${e.join(`
839
- `)}`}function Ut(n={}){let{debugMode:e=!1,projectPrompt:t=null,isLocal:o=!1,projectConfig:s=Y(),useDefaultStack:r=!0}=n,i=t?`
839
+ `)}`}function Mt(n={}){let{debugMode:e=!1,projectPrompt:t=null,isLocal:o=!1,projectConfig:s=Y(),useDefaultStack:r=!0}=n,i=t?`
840
840
  <project_context>
841
841
  ${t}
842
842
  </project_context>
@@ -881,7 +881,7 @@ Then STOP. Do not continue. Do not try to fix it. Wait for user.
881
881
 
882
882
  ---
883
883
 
884
- `:"",c=yn(s),l=bn(s,o),u=kn(s,r),d=Sn(r),g=r?vn(s):"",w=r?Cn(s,o):"",v=wn(r);return`${i}${a}# Agent Instructions
884
+ `:"",c=Sn(s),l=wn(s,o),u=Cn(s,r),d=kn(r),g=r?_n(s):"",w=r?Pn(s,o):"",v=vn(r);return`${i}${a}# Agent Instructions
885
885
 
886
886
  ## \u26D4 CRITICAL: EVERYTHING IS A KANBAN TASK
887
887
 
@@ -1038,7 +1038,7 @@ ${v}
1038
1038
  ${g}
1039
1039
 
1040
1040
  ${w}
1041
- `}function yn(n){let e=Ee(n),t=B(n),o=q(n),s=Ie(n),r=de(n),i=[];s&&i.push(`- Backend: "${s}/{Entity}/"`),r&&i.push(`- Frontend: "${r}/{entity}/"`);let a=n.techStack?.patterns?.length?`
1041
+ `}function Sn(n){let e=Ae(n),t=B(n),o=q(n),s=Ee(n),r=ue(n),i=[];s&&i.push(`- Backend: "${s}/{Entity}/"`),r&&i.push(`- Frontend: "${r}/{entity}/"`);let a=n.techStack?.patterns?.length?`
1042
1042
  **Key patterns:**
1043
1043
  ${n.techStack.patterns.map(u=>`- ${u}`).join(`
1044
1044
  `)}`:"",l=n.techStack?.backend?.some(u=>u.includes(".NET")||u.includes("C#"))??!1?`
@@ -1050,7 +1050,7 @@ ${i.length>0?`
1050
1050
  ${i.join(`
1051
1051
  `)}`:""}
1052
1052
  ${a}${l}
1053
- </tech-stack>`}function bn(n,e){return e?`<environment>
1053
+ </tech-stack>`}function wn(n,e){return e?`<environment>
1054
1054
  **LOCAL MODE - User manages their own services.**
1055
1055
 
1056
1056
  You are running on the user's local machine, NOT in a Docker container.
@@ -1071,11 +1071,11 @@ The user is responsible for:
1071
1071
  </environment>`:`<environment>
1072
1072
  Docker container with pre-started services:
1073
1073
 
1074
- ${Ae(n)}
1074
+ ${xe(n)}
1075
1075
  ${n.tunnel?.enabled?"| Tunnel | - | - | Exposes frontend to user |":""}
1076
1076
 
1077
1077
  User sees app through **Cloudflare tunnel** (live preview in browser).
1078
- </environment>`}function Sn(n){return n?`**\u2705 ALWAYS delegate to these subagents:**
1078
+ </environment>`}function kn(n){return n?`**\u2705 ALWAYS delegate to these subagents:**
1079
1079
 
1080
1080
  | Trigger | Subagent | Example |
1081
1081
  |---------|----------|---------|
@@ -1097,7 +1097,7 @@ User sees app through **Cloudflare tunnel** (live preview in browser).
1097
1097
  **Flow:** @planning \u2192 @kanban (creates detailed tasks) \u2192 Execute work \u2192 @debugger (if issues)
1098
1098
 
1099
1099
  Note: For this project, you implement the code directly after planning (no stack-specific subagents).
1100
- Check \`.claude/skills/\` for project-specific patterns and conventions.`}function wn(n){return n?`<workflow>
1100
+ Check \`.claude/skills/\` for project-specific patterns and conventions.`}function vn(n){return n?`<workflow>
1101
1101
  **Standard feature flow:**
1102
1102
  1. **@planning** - Gather requirements, design spec, saves it.
1103
1103
  2. **\u23F8\uFE0F STOP & WAIT** - Tell user: "Spec is ready! Review it and tell me when to implement."
@@ -1189,7 +1189,7 @@ Check \`.claude/skills/\` for project-specific patterns and conventions.`}functi
1189
1189
  - Always read the referenced spec before starting work on a card
1190
1190
  - Check project's existing code for patterns before implementing
1191
1191
  - Use @debugger if you encounter build errors or bugs
1192
- </workflow>`}function kn(n,e){let t=`**@planning** - Design before building:
1192
+ </workflow>`}function Cn(n,e){let t=`**@planning** - Design before building:
1193
1193
  - Complex features \u2192 plan first
1194
1194
  - Asks questions, designs spec
1195
1195
  - **Saves spec using save_specification MCP tool**
@@ -1227,7 +1227,7 @@ ${r?"- **Must complete before @frontend starts!**":""}
1227
1227
  **\u26A0\uFE0F MANDATORY DELEGATION - You MUST use subagents:**
1228
1228
 
1229
1229
  ${t}
1230
- </subagents>`}function vn(n){return n.services?.frontend?n.techStack?.frontend?.some(t=>t.includes("TanStack")||t.includes("React Query")||t.includes("MUI"))??!1?`<frontend-api>
1230
+ </subagents>`}function _n(n){return n.services?.frontend?n.techStack?.frontend?.some(t=>t.includes("TanStack")||t.includes("React Query")||t.includes("MUI"))??!1?`<frontend-api>
1231
1231
  ## Orval-Generated API Hooks
1232
1232
 
1233
1233
  Frontend uses **Orval** to auto-generate React Query hooks from Swagger. Import from 'api/queries-commands.ts'.
@@ -1265,7 +1265,7 @@ queryClient.invalidateQueries({ queryKey: getGetApiPeopleQueryKey() })
1265
1265
 
1266
1266
  Check the project's existing patterns for API calls and data fetching.
1267
1267
  Look for existing feature code to understand the correct patterns before writing new API calls.
1268
- </frontend-api>`:""}function Cn(n,e){if(!n.services?.frontend)return"";let t=n.services.frontend.port,o=de(n),s=`http://localhost:${t}`;return`<ui-verification>
1268
+ </frontend-api>`:""}function Pn(n,e){if(!n.services?.frontend)return"";let t=n.services.frontend.port,o=ue(n),s=`http://localhost:${t}`;return`<ui-verification>
1269
1269
  ## \u{1F50D} UI Verification with Playwright
1270
1270
 
1271
1271
  You have access to **Playwright MCP** tools to verify the UI works correctly after making changes.
@@ -1347,15 +1347,15 @@ You have access to **Playwright MCP** tools to verify the UI works correctly aft
1347
1347
  - **Multi-tab apps**: Use \`browser_tabs\` to manage multiple windows/tabs in legacy applications
1348
1348
  - **Large snapshots**: For pages with huge dropdowns (e.g., country lists), use \`browser_evaluate\` to collapse them first
1349
1349
  - ${e?"In local mode, the browser window will be visible to you":"In container mode, browser runs headless"}
1350
- </ui-verification>`}function ue(n){return n&&n.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,"\uFFFD")}var xe=null;function Qe(n){xe=ue(n),console.log(`[ProjectPrompt] Updated (${xe?xe.length:0} chars)`)}function Nt(){return ue(xe)}import*as te from"path";import*as ze from"fs";import{fileURLToPath as Rn}from"url";var Pn=Ge(),Ve=te.dirname(Rn(import.meta.url)),Ft=[te.resolve(Ve,"../mcps/stdio-server.js"),te.resolve(Ve,"./adapters/mcps/stdio-server.js")],ge=Ft.find(n=>ze.existsSync(n))||Ft[0];console.log("[MCP] Stdio server path resolved:",ge);console.log("[MCP] __dirname:",Ve);console.log("[MCP] File exists:",ze.existsSync(ge));async function De(n,e={}){let{model:t,sessionId:o=null,projectId:s=null,apiUrl:r=null,callbacks:i={},debugLog:a,abortController:c,debugMode:l=!1,isLocal:u=process.env.LOCAL_MODE==="true",projectConfig:d=Y(process.env.WORKSPACE_DIR||process.cwd()),useDefaultStack:g=!0}=e,w=jt(a),v=new Set,A=o||"",D,b,f,O=!1,W=!1,M=process.env.WORKSPACE_DIR||process.cwd();console.log("[MCP] Configuring agent-planning stdio server:"),console.log("[MCP] Command: node"),console.log("[MCP] Args:",[ge]),console.log("[MCP] Env: API_URL=",process.env.API_URL||"http://localhost:5338",", PROJECT_ID=",s||process.env.PROJECT_ID||"",", PROJECT_KEY=",process.env.PROJECT_KEY?"***set***":"(not set)",", WORKSPACE_DIR=",M),console.log("[MCP] File exists check:",ge);try{for await(let p of _n({prompt:n,options:{abortController:c,cwd:M,resume:o??void 0,allowedTools:["Bash","Read","Write","Edit","MultiEdit","Glob","Grep","LS","WebFetch","NotebookRead","NotebookEdit","Skill","mcp__agent-insights__check_backend_build","mcp__agent-insights__check_frontend_types","mcp__agent-insights__check_service_health",...u?[]:["mcp__agent-insights__stop_services","mcp__agent-insights__start_services","mcp__agent-insights__restart_services"],"mcp__agent-planning__start_question_session","mcp__agent-planning__ask_question","mcp__agent-planning__end_question_session","mcp__agent-planning__save_specification","mcp__agent-planning__list_specifications","mcp__agent-planning__read_specification","mcp__agent-planning__delete_specification","mcp__agent-planning__report_learning","mcp__agent-planning__report_bug","mcp__agent-planning__report_debug_insight","mcp__agent-planning__get_kanban_board","mcp__agent-planning__get_column_cards","mcp__agent-planning__get_card_details","mcp__agent-planning__create_kanban_card","mcp__agent-planning__update_kanban_card","mcp__agent-planning__move_kanban_card","mcp__agent-planning__delete_kanban_card","mcp__agent-planning__create_subtask","mcp__agent-planning__toggle_subtask","mcp__agent-planning__delete_subtask","mcp__agent-planning__get_project_prompt","mcp__agent-planning__update_project_prompt","mcp__agent-planning__create_command","mcp__agent-planning__get_test_suites","mcp__agent-planning__get_test_suite_details","mcp__agent-planning__get_test_details","mcp__agent-planning__run_test","mcp__agent-planning__run_test_suite","mcp__agent-planning__report_test_status","mcp__agent-planning__create_test_suite","mcp__agent-planning__create_test","mcp__agent-planning__update_test","mcp__agent-planning__reference_projects_list","mcp__agent-planning__reference_project_tree","mcp__agent-planning__reference_project_read_file","mcp__agent-planning__reference_project_download","mcp__agent-planning__reference_project_update_status","mcp__playwright__browser_navigate","mcp__playwright__browser_snapshot","mcp__playwright__browser_take_screenshot","mcp__playwright__browser_click","mcp__playwright__browser_type","mcp__playwright__browser_scroll_down","mcp__playwright__browser_scroll_up","mcp__playwright__browser_go_back","mcp__playwright__browser_go_forward","mcp__playwright__browser_wait","mcp__playwright__browser_fill_form","mcp__playwright__browser_select_option","mcp__playwright__browser_press_key","mcp__playwright__browser_hover","mcp__playwright__browser_drag","mcp__playwright__browser_file_upload","mcp__playwright__browser_handle_dialog","mcp__playwright__browser_close","mcp__playwright__browser_resize","mcp__playwright__browser_console_messages","mcp__playwright__browser_network_requests","mcp__playwright__browser_screen_capture","mcp__playwright__browser_screen_move_mouse","mcp__playwright__browser_screen_click","mcp__playwright__browser_screen_drag","mcp__playwright__browser_screen_type","mcp__playwright__browser_evaluate","mcp__playwright__browser_run_code","mcp__playwright__browser_tabs","mcp__playwright__browser_tab_list","mcp__playwright__browser_tab_new","mcp__playwright__browser_tab_select","mcp__playwright__browser_tab_close"],model:t,mcpServers:{"agent-insights":Pn,"agent-planning":{type:"stdio",command:"node",args:[ge],env:{WORKSPACE_DIR:M,API_URL:r||process.env.API_URL||process.env.MASTER_URL||"http://localhost:5338",PROJECT_ID:s||process.env.PROJECT_ID||"",PROJECT_KEY:process.env.PROJECT_KEY||""}},playwright:{type:"stdio",command:"npx",args:["@playwright/mcp@latest",...u?[]:["--browser=firefox"],"--caps=vision",`--user-data-dir=${te.join(M,".playwright-data")}`,...u?[]:["--headless"]]}},settingSources:["project"],disallowedTools:["AskUserQuestion","TodoWrite","EnterPlanMode"],agents:g?{scaffolding:We,debugger:we,planning:ke,backend:Ke,frontend:Ye,"project-context":ve}:{debugger:we,planning:ke,"project-context":ve},systemPrompt:Ut({debugMode:l,projectPrompt:Nt(),isLocal:u,projectConfig:d,useDefaultStack:g})}}))if(!(!p.uuid||v.has(p.uuid))){switch(v.add(p.uuid),w?.log(p),i.onRawMessage?.(p),p.type){case"assistant":if(p.message?.content)for(let C of p.message.content)C.type==="text"?i.onAssistantText?.(C.text):C.type==="tool_use"?i.onAssistantToolUse?.(C.name,C.input):C.type==="tool_result"&&i.onAssistantToolResult?.(C.tool_use_id,C.content);break;case"user":i.onUserMessage?.(p);break;case"result":if(p.subtype==="success")D=p.result,b=p.total_cost_usd,i.onResult?.(p.result,p.total_cost_usd);else{let C=`Agent error: ${p.subtype}`;f=C,i.onError?.(C)}W=!0;break;case"system":switch(p.subtype){case"init":A=p.session_id,w?.setSessionId(p.session_id),i.onSystemInit?.(p.session_id);break;case"status":i.onSystemStatus?.(JSON.stringify(p));break;case"compact_boundary":break;case"hook_response":break}break;case"stream_event":i.onStreamEvent?.(p);break;case"tool_progress":i.onToolProgress?.(p);break;case"auth_status":i.onAuthStatus?.(p);break}if(W)break}}catch(p){p instanceof Error&&p.name==="AbortError"||p instanceof Error&&p.message.includes("aborted by user")?(O=!0,i.onAborted?.()):(f=p instanceof Error?p.message:String(p),i.onError?.(f))}finally{w?.stop()}return console.log("after try"),{sessionId:A,result:D,cost:b,error:f,aborted:O}}import{spawn as Mt,execSync as ne}from"child_process";import*as T from"fs";import*as Lt from"http";import*as Z from"path";function je(n){let{workspaceDir:e,apiPort:t,webPort:o,onBackendError:s,onFrontendError:r,projectConfig:i=Y(e)}=n,a=t??i.services?.backend?.port??5338,c=o??i.services?.frontend?.port??5173,l=B(i),u=q(i),d=i.services?.backend?.startCommand??"dotnet run",g=i.services?.backend?.buildCommand??"dotnet build",w=i.services?.backend?.typecheckCommand??"dotnet build --no-restore",v=i.services?.frontend?.startCommand??"npm run dev",A=i.services?.frontend?.typecheckCommand??"npx tsc -p tsconfig.app.json --noEmit",D=i.services?.backend?.logFile??"/tmp/api.log",b=i.services?.frontend?.logFile??"/tmp/web.log",f=null,O=null,W=y=>new Promise(m=>{let S=setTimeout(()=>m(!1),3e3);Lt.get(`http://localhost:${y}`,j=>{clearTimeout(S),m(j.statusCode!==void 0&&j.statusCode<500)}).on("error",()=>{clearTimeout(S),m(!1)})}),M=y=>{try{let m=ne(`lsof -ti:${y} 2>/dev/null || true`,{encoding:"utf-8"}).trim();if(m){let S=m.split(`
1351
- `).filter(Boolean);console.log(`[Services] Killing ${S.length} process(es) on port ${y}: ${S.join(", ")}`);for(let _ of S)try{process.kill(parseInt(_,10),"SIGKILL")}catch{}}}catch{try{ne(`fuser -k ${y}/tcp 2>/dev/null || true`,{encoding:"utf-8"})}catch{}}},p=(y,m)=>new Promise(S=>{if(!y||!y.pid){S();return}console.log(`[Services] Stopping ${m} (PID: ${y.pid})...`);try{process.kill(-y.pid,"SIGTERM")}catch{try{y.kill("SIGTERM")}catch{}}setTimeout(S,500)}),C=async()=>{if(!l||!T.existsSync(l)){console.log("[Services] No backend found, skipping backend start");return}M(a),console.log(`[Services] Starting backend with: ${d}...`);let y=Z.dirname(D);T.existsSync(y)||T.mkdirSync(y,{recursive:!0});let m=T.createWriteStream(D,{flags:"a"}),[S,..._]=d.split(" ");f=Mt(S,_,{cwd:l,stdio:["ignore","pipe","pipe"],detached:!0,shell:!0});let j="",E=R=>{let z=R.toString();m.write(z);let $=(j+z).split(`
1352
- `);j=$.pop()||"";for(let H of $)H&&In(H)&&s&&s(H)};f.stdout?.on("data",E),f.stderr?.on("data",E),f.on("exit",R=>{m.end(),R!==0&&R!==null&&s&&s(`Process exited with code ${R}`)}),f.unref()},L=async()=>{if(!u||!T.existsSync(Z.join(u,"package.json"))){console.log("[Services] No frontend found, skipping frontend start");return}M(c),console.log(`[Services] Starting frontend with: ${v}...`);let y=Z.dirname(b);T.existsSync(y)||T.mkdirSync(y,{recursive:!0});let[m,...S]=v.split(" ");O=Mt(m,S,{cwd:u,stdio:["ignore",T.openSync(b,"w"),T.openSync(b,"w")],detached:!0,shell:!0}),O.unref()},ae=async()=>{await p(f,"backend"),f=null,M(a)},fe=async()=>{await p(O,"frontend"),O=null,M(c)},Be=async()=>{let[y,m]=await Promise.all([W(a),W(c)]);return{api:y,web:m}},St=async(y=15e3)=>{let m=Date.now(),S=1e3,_=0,j=null,E=null;for(console.log(`[Services] Waiting for health (timeout: ${y}ms)...`);Date.now()-m<y;){_++;let $=await Be(),H=Date.now()-m;if($.web&&E===null&&(E=H,console.log(`[Services] \u2713 Frontend (Vite) ready after ${H}ms`)),$.api&&j===null&&(j=H,console.log(`[Services] \u2713 Backend (dotnet) ready after ${H}ms`)),console.log(`[Services] Health poll #${_} (${H}ms): api=${$.api}, web=${$.web}`),$.api&&$.web)return console.log(`[Services] \u2713 Both services healthy after ${H}ms (${_} polls)`),$;await new Promise(on=>setTimeout(on,S))}let R=await Be(),z=Date.now()-m;return R.web&&E===null&&console.log(`[Services] \u2713 Frontend (Vite) ready after ${z}ms`),R.api&&j===null&&console.log(`[Services] \u2713 Backend (dotnet) ready after ${z}ms`),console.log(`[Services] \u26A0 Health timeout after ${z}ms: api=${R.api}, web=${R.web}`),R},tn=async y=>{console.log(`[Services] Restarting ${y}...`);let m={success:!0},S=y==="backend"||y==="both",_=y==="frontend"||y==="both";if(S&&await ae(),_&&await fe(),S&&l&&T.existsSync(l)){console.log(`[Services] Building backend with: ${g}...`);try{ne(g,{cwd:l,stdio:"pipe",timeout:12e4,encoding:"utf-8"}),console.log("[Services] \u2713 Backend build succeeded")}catch(E){let R=E;m.success=!1,m.backendError=R.stderr||R.stdout||"Build failed",console.error("[Services] \u2717 Backend build failed")}}if(_&&u&&T.existsSync(Z.join(u,"package.json"))){console.log(`[Services] Type-checking frontend with: ${A}...`);try{ne(A,{cwd:u,stdio:"pipe",timeout:6e4,encoding:"utf-8"}),console.log("[Services] \u2713 Frontend types OK")}catch(E){let R=E;m.success=!1,m.frontendError=R.stderr||R.stdout||"Type check failed",console.error("[Services] \u2717 Frontend type check failed")}}console.log(`[Services] Starting ${y}...`),S&&await C(),_&&await L();let j=await St(1e4);if(S&&!j.api){m.success=!1;let E=await vt("backend",20),R=E.length>0?`
1350
+ </ui-verification>`}function ge(n){return n&&n.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,"\uFFFD")}var De=null;function ze(n){De=ge(n),console.log(`[ProjectPrompt] Updated (${De?De.length:0} chars)`)}function Ft(){return ge(De)}import*as ne from"path";import*as Xe from"fs";import{fileURLToPath as Tn}from"url";var In=Ke(),Je=ne.dirname(Tn(import.meta.url)),Lt=[ne.resolve(Je,"../mcps/stdio-server.js"),ne.resolve(Je,"./adapters/mcps/stdio-server.js")],fe=Lt.find(n=>Xe.existsSync(n))||Lt[0];console.log("[MCP] Stdio server path resolved:",fe);console.log("[MCP] __dirname:",Je);console.log("[MCP] File exists:",Xe.existsSync(fe));async function je(n,e={}){let{model:t,sessionId:o=null,projectId:s=null,apiUrl:r=null,callbacks:i={},debugLog:a,abortController:c,debugMode:l=!1,isLocal:u=process.env.LOCAL_MODE==="true",projectConfig:d=Y(process.env.WORKSPACE_DIR||process.cwd()),useDefaultStack:g=!0}=e,w=Nt(a),v=new Set,A=o||"",D,b,f,O=!1,W=!1,F=process.env.WORKSPACE_DIR||process.cwd();console.log("[MCP] Configuring agent-planning stdio server:"),console.log("[MCP] Command: node"),console.log("[MCP] Args:",[fe]),console.log("[MCP] Env: API_URL=",process.env.API_URL||"http://localhost:5338",", PROJECT_ID=",s||process.env.PROJECT_ID||"",", PROJECT_KEY=",process.env.PROJECT_KEY?"***set***":"(not set)",", WORKSPACE_DIR=",F),console.log("[MCP] File exists check:",fe);try{for await(let p of Rn({prompt:n,options:{abortController:c,cwd:F,resume:o??void 0,allowedTools:["Bash","Read","Write","Edit","MultiEdit","Glob","Grep","LS","WebFetch","NotebookRead","NotebookEdit","Skill","mcp__agent-insights__check_backend_build","mcp__agent-insights__check_frontend_types","mcp__agent-insights__check_service_health",...u?[]:["mcp__agent-insights__stop_services","mcp__agent-insights__start_services","mcp__agent-insights__restart_services"],"mcp__agent-planning__start_question_session","mcp__agent-planning__ask_question","mcp__agent-planning__end_question_session","mcp__agent-planning__save_specification","mcp__agent-planning__list_specifications","mcp__agent-planning__read_specification","mcp__agent-planning__delete_specification","mcp__agent-planning__report_learning","mcp__agent-planning__report_bug","mcp__agent-planning__report_debug_insight","mcp__agent-planning__get_kanban_board","mcp__agent-planning__get_column_cards","mcp__agent-planning__get_card_details","mcp__agent-planning__create_kanban_card","mcp__agent-planning__update_kanban_card","mcp__agent-planning__move_kanban_card","mcp__agent-planning__delete_kanban_card","mcp__agent-planning__create_subtask","mcp__agent-planning__toggle_subtask","mcp__agent-planning__delete_subtask","mcp__agent-planning__get_project_prompt","mcp__agent-planning__update_project_prompt","mcp__agent-planning__create_command","mcp__agent-planning__get_test_suites","mcp__agent-planning__get_test_suite_details","mcp__agent-planning__get_test_details","mcp__agent-planning__run_test","mcp__agent-planning__run_test_suite","mcp__agent-planning__report_test_status","mcp__agent-planning__create_test_suite","mcp__agent-planning__create_test","mcp__agent-planning__update_test","mcp__agent-planning__reference_projects_list","mcp__agent-planning__reference_project_tree","mcp__agent-planning__reference_project_read_file","mcp__agent-planning__reference_project_download","mcp__agent-planning__reference_project_update_status","mcp__playwright__browser_navigate","mcp__playwright__browser_snapshot","mcp__playwright__browser_take_screenshot","mcp__playwright__browser_click","mcp__playwright__browser_type","mcp__playwright__browser_scroll_down","mcp__playwright__browser_scroll_up","mcp__playwright__browser_go_back","mcp__playwright__browser_go_forward","mcp__playwright__browser_wait","mcp__playwright__browser_fill_form","mcp__playwright__browser_select_option","mcp__playwright__browser_press_key","mcp__playwright__browser_hover","mcp__playwright__browser_drag","mcp__playwright__browser_file_upload","mcp__playwright__browser_handle_dialog","mcp__playwright__browser_close","mcp__playwright__browser_resize","mcp__playwright__browser_console_messages","mcp__playwright__browser_network_requests","mcp__playwright__browser_screen_capture","mcp__playwright__browser_screen_move_mouse","mcp__playwright__browser_screen_click","mcp__playwright__browser_screen_drag","mcp__playwright__browser_screen_type","mcp__playwright__browser_evaluate","mcp__playwright__browser_run_code","mcp__playwright__browser_tabs","mcp__playwright__browser_tab_list","mcp__playwright__browser_tab_new","mcp__playwright__browser_tab_select","mcp__playwright__browser_tab_close"],model:t,mcpServers:{"agent-insights":In,"agent-planning":{type:"stdio",command:"node",args:[fe],env:{WORKSPACE_DIR:F,API_URL:r||process.env.API_URL||process.env.MASTER_URL||"http://localhost:5338",PROJECT_ID:s||process.env.PROJECT_ID||"",PROJECT_KEY:process.env.PROJECT_KEY||""}},playwright:{type:"stdio",command:"npx",args:["@playwright/mcp@latest",...u?[]:["--browser=firefox"],"--caps=vision",`--user-data-dir=${ne.join(F,".playwright-data")}`,...u?[]:["--headless"]]}},settingSources:["project"],disallowedTools:["AskUserQuestion","TodoWrite","EnterPlanMode"],agents:g?{scaffolding:Ye,debugger:ke,planning:ve,backend:Qe,frontend:Ve,"project-context":Ce}:{debugger:ke,planning:ve,"project-context":Ce},systemPrompt:Mt({debugMode:l,projectPrompt:Ft(),isLocal:u,projectConfig:d,useDefaultStack:g})}}))if(!(!p.uuid||v.has(p.uuid))){switch(v.add(p.uuid),w?.log(p),i.onRawMessage?.(p),p.type){case"assistant":if(p.message?.content)for(let C of p.message.content)C.type==="text"?i.onAssistantText?.(C.text):C.type==="tool_use"?i.onAssistantToolUse?.(C.name,C.input):C.type==="tool_result"&&i.onAssistantToolResult?.(C.tool_use_id,C.content);break;case"user":i.onUserMessage?.(p);break;case"result":if(p.subtype==="success")D=p.result,b=p.total_cost_usd,i.onResult?.(p.result,p.total_cost_usd);else{let C=`Agent error: ${p.subtype}`;f=C,i.onError?.(C)}W=!0;break;case"system":switch(p.subtype){case"init":A=p.session_id,w?.setSessionId(p.session_id),i.onSystemInit?.(p.session_id);break;case"status":i.onSystemStatus?.(JSON.stringify(p));break;case"compact_boundary":break;case"hook_response":break}break;case"stream_event":i.onStreamEvent?.(p);break;case"tool_progress":i.onToolProgress?.(p);break;case"auth_status":i.onAuthStatus?.(p);break}if(W)break}}catch(p){p instanceof Error&&p.name==="AbortError"||p instanceof Error&&p.message.includes("aborted by user")?(O=!0,i.onAborted?.()):(f=p instanceof Error?p.message:String(p),i.onError?.(f))}finally{w?.stop()}return console.log("after try"),{sessionId:A,result:D,cost:b,error:f,aborted:O}}import{spawn as $t,execSync as oe}from"child_process";import*as T from"fs";import*as Ht from"http";import*as ee from"path";function Oe(n){let{workspaceDir:e,apiPort:t,webPort:o,onBackendError:s,onFrontendError:r,projectConfig:i=Y(e)}=n,a=t??i.services?.backend?.port??5338,c=o??i.services?.frontend?.port??5173,l=B(i),u=q(i),d=i.services?.backend?.startCommand??"dotnet run",g=i.services?.backend?.buildCommand??"dotnet build",w=i.services?.backend?.typecheckCommand??"dotnet build --no-restore",v=i.services?.frontend?.startCommand??"npm run dev",A=i.services?.frontend?.typecheckCommand??"npx tsc -p tsconfig.app.json --noEmit",D=i.services?.backend?.logFile??"/tmp/api.log",b=i.services?.frontend?.logFile??"/tmp/web.log",f=null,O=null,W=y=>new Promise(m=>{let S=setTimeout(()=>m(!1),3e3);Ht.get(`http://localhost:${y}`,j=>{clearTimeout(S),m(j.statusCode!==void 0&&j.statusCode<500)}).on("error",()=>{clearTimeout(S),m(!1)})}),F=y=>{try{let m=oe(`lsof -ti:${y} 2>/dev/null || true`,{encoding:"utf-8"}).trim();if(m){let S=m.split(`
1351
+ `).filter(Boolean);console.log(`[Services] Killing ${S.length} process(es) on port ${y}: ${S.join(", ")}`);for(let _ of S)try{process.kill(parseInt(_,10),"SIGKILL")}catch{}}}catch{try{oe(`fuser -k ${y}/tcp 2>/dev/null || true`,{encoding:"utf-8"})}catch{}}},p=(y,m)=>new Promise(S=>{if(!y||!y.pid){S();return}console.log(`[Services] Stopping ${m} (PID: ${y.pid})...`);try{process.kill(-y.pid,"SIGTERM")}catch{try{y.kill("SIGTERM")}catch{}}setTimeout(S,500)}),C=async()=>{if(!l||!T.existsSync(l)){console.log("[Services] No backend found, skipping backend start");return}F(a),console.log(`[Services] Starting backend with: ${d}...`);let y=ee.dirname(D);T.existsSync(y)||T.mkdirSync(y,{recursive:!0});let m=T.createWriteStream(D,{flags:"a"}),[S,..._]=d.split(" ");f=$t(S,_,{cwd:l,stdio:["ignore","pipe","pipe"],detached:!0,shell:!0});let j="",E=P=>{let J=P.toString();m.write(J);let $=(j+J).split(`
1352
+ `);j=$.pop()||"";for(let H of $)H&&An(H)&&s&&s(H)};f.stdout?.on("data",E),f.stderr?.on("data",E),f.on("exit",P=>{m.end(),P!==0&&P!==null&&s&&s(`Process exited with code ${P}`)}),f.unref()},L=async()=>{if(!u||!T.existsSync(ee.join(u,"package.json"))){console.log("[Services] No frontend found, skipping frontend start");return}F(c),console.log(`[Services] Starting frontend with: ${v}...`);let y=ee.dirname(b);T.existsSync(y)||T.mkdirSync(y,{recursive:!0});let[m,...S]=v.split(" ");O=$t(m,S,{cwd:u,stdio:["ignore",T.openSync(b,"w"),T.openSync(b,"w")],detached:!0,shell:!0}),O.unref()},ce=async()=>{await p(f,"backend"),f=null,F(a)},me=async()=>{await p(O,"frontend"),O=null,F(c)},Ge=async()=>{let[y,m]=await Promise.all([W(a),W(c)]);return{api:y,web:m}},kt=async(y=15e3)=>{let m=Date.now(),S=1e3,_=0,j=null,E=null;for(console.log(`[Services] Waiting for health (timeout: ${y}ms)...`);Date.now()-m<y;){_++;let $=await Ge(),H=Date.now()-m;if($.web&&E===null&&(E=H,console.log(`[Services] \u2713 Frontend (Vite) ready after ${H}ms`)),$.api&&j===null&&(j=H,console.log(`[Services] \u2713 Backend (dotnet) ready after ${H}ms`)),console.log(`[Services] Health poll #${_} (${H}ms): api=${$.api}, web=${$.web}`),$.api&&$.web)return console.log(`[Services] \u2713 Both services healthy after ${H}ms (${_} polls)`),$;await new Promise(rn=>setTimeout(rn,S))}let P=await Ge(),J=Date.now()-m;return P.web&&E===null&&console.log(`[Services] \u2713 Frontend (Vite) ready after ${J}ms`),P.api&&j===null&&console.log(`[Services] \u2713 Backend (dotnet) ready after ${J}ms`),console.log(`[Services] \u26A0 Health timeout after ${J}ms: api=${P.api}, web=${P.web}`),P},on=async y=>{console.log(`[Services] Restarting ${y}...`);let m={success:!0},S=y==="backend"||y==="both",_=y==="frontend"||y==="both";if(S&&await ce(),_&&await me(),S&&l&&T.existsSync(l)){console.log(`[Services] Building backend with: ${g}...`);try{oe(g,{cwd:l,stdio:"pipe",timeout:12e4,encoding:"utf-8"}),console.log("[Services] \u2713 Backend build succeeded")}catch(E){let P=E;m.success=!1,m.backendError=P.stderr||P.stdout||"Build failed",console.error("[Services] \u2717 Backend build failed")}}if(_&&u&&T.existsSync(ee.join(u,"package.json"))){console.log(`[Services] Type-checking frontend with: ${A}...`);try{oe(A,{cwd:u,stdio:"pipe",timeout:6e4,encoding:"utf-8"}),console.log("[Services] \u2713 Frontend types OK")}catch(E){let P=E;m.success=!1,m.frontendError=P.stderr||P.stdout||"Type check failed",console.error("[Services] \u2717 Frontend type check failed")}}console.log(`[Services] Starting ${y}...`),S&&await C(),_&&await L();let j=await kt(1e4);if(S&&!j.api){m.success=!1;let E=await _t("backend",20),P=E.length>0?`
1353
1353
  Recent logs:
1354
1354
  ${E.join(`
1355
- `)}`:"";m.backendError||(m.backendError=`Backend failed to start.${R}`)}return _&&!j.web&&(m.success=!1,m.frontendError||(m.frontendError="Frontend failed to start")),m},wt=async()=>{if(!l||!T.existsSync(l))return{success:!0};try{return ne(w,{cwd:l,stdio:"pipe",timeout:12e4,encoding:"utf-8"}),{success:!0}}catch(y){let m=y;return{success:!1,errors:m.stdout||m.stderr||"Build failed"}}},kt=async()=>{if(!u||!T.existsSync(Z.join(u,"package.json")))return{success:!0};try{return ne(A,{cwd:u,stdio:"pipe",timeout:6e4,encoding:"utf-8"}),{success:!0}}catch(y){let m=y;return{success:!1,errors:m.stdout||m.stderr||"Type check failed"}}},nn=async()=>{let[y,m]=await Promise.all([wt(),kt()]);return{backend:y,frontend:m}},vt=async(y,m)=>{let S=y==="backend"?D:b;if(!T.existsSync(S))return[`Log file not found: ${S}`];try{return ne(`tail -n ${m} ${S}`,{encoding:"utf-8"}).split(`
1356
- `).filter(Boolean)}catch(_){return[`Error reading logs: ${_ instanceof Error?_.message:String(_)}`]}};return{startBackend:C,startFrontend:L,stopBackend:ae,stopFrontend:fe,restartServices:tn,checkHealth:Be,waitForHealth:St,getProcesses:()=>({backend:f,frontend:O}),checkBackendBuild:wt,checkFrontendTypes:kt,runTypeChecks:nn,tailLogs:vt,checkSwaggerEndpoints:async y=>{let m=Z.join(e,"swagger.json");if(!T.existsSync(m))return{foundEndpoints:["Error: swagger.json not found"],totalEndpoints:0};try{let S=JSON.parse(T.readFileSync(m,"utf-8")),_=Object.keys(S.paths||{}),j=[];for(let E of _)if(E.toLowerCase().includes(y.toLowerCase())){let R=Object.keys(S.paths[E]);for(let z of R)j.push(`${z.toUpperCase()} ${E}`)}return{foundEndpoints:j,totalEndpoints:_.length}}catch(S){return{foundEndpoints:[`Error parsing swagger.json: ${S instanceof Error?S.message:String(S)}`],totalEndpoints:0}}}}}function In(n){let e=n.toLowerCase();return e.includes("exception")||e.includes("fail:")||e.includes("[err]")||e.includes("[error]")}import{execSync as oe}from"child_process";function Oe(n){let e=async()=>{try{return oe("git status --porcelain",{cwd:n,encoding:"utf-8"}).trim().length>0}catch{return!1}},t=async()=>{try{return oe("git branch --show-current",{cwd:n,encoding:"utf-8"}).trim()}catch{return"unknown"}};return{hasChanges:e,commitAndPush:async(s,r)=>{try{if(!await e())return{success:!0,noChanges:!0};let i=s.length>60?s.substring(0,60)+"...":s,c=`${r?"[agent] (partial)":"[agent]"} ${i}`;oe("git add -A",{cwd:n}),oe(`git commit -m "${c.replace(/"/g,'\\"')}"`,{cwd:n,encoding:"utf-8"});let l=oe("git rev-parse --short HEAD",{cwd:n,encoding:"utf-8"}).trim();try{oe("git push",{cwd:n,stdio:"pipe"})}catch(u){let d=u instanceof Error?u.message:String(u);if(d.includes("no upstream branch")){let g=await t();oe(`git push --set-upstream origin ${g}`,{cwd:n,stdio:"pipe"})}else return console.error("[Git] Push failed:",d),{success:!1,commitHash:l,commitSucceeded:!0,pushFailed:!0,error:d}}return{success:!0,commitHash:l}}catch(i){let a=i instanceof Error?i.message:String(i);return console.error("[Git] Error:",a),{success:!1,error:a}}},getCurrentBranch:t}}import*as ee from"@microsoft/signalr";import*as Bt from"fs";import*as qt from"os";import*as Gt from"path";import{exec as En}from"child_process";import{promisify as An}from"util";var Q=class{constructor(e,t){this.connection=e;this.receiverMethod=t}dispose=()=>{for(let e of this.receiverMethod)this.connection.off(e.methodName,e.method)}},$t=n=>{if(n==="IDeploymentWatcherHub")return Je.Instance;if(n==="IDeploymentHub")return Ze.Instance;if(n==="IKanbanHub")return tt.Instance;if(n==="IAgentHub")return ot.Instance;if(n==="ISlaveHub")return rt.Instance;if(n==="ITestHub")return at.Instance},Ht=n=>{if(n==="IDeploymentWatcherClient")return lt.Instance;if(n==="IDeploymentHubClient")return pt.Instance;if(n==="IKanbanBoardClient")return dt.Instance;if(n==="IAgentReceiver")return ut.Instance;if(n==="IBackofficeReceiver")return gt.Instance;if(n==="ISlaveHubClient")return ft.Instance;if(n==="ITestHubClient")return mt.Instance},Je=class n{static Instance=new n;constructor(){}createHubProxy=e=>new Xe(e)},Xe=class{constructor(e){this.connection=e}watchMachine=async e=>await this.connection.invoke("WatchMachine",e);unwatchMachine=async e=>await this.connection.invoke("UnwatchMachine",e);startStreamingLogs=async e=>await this.connection.invoke("StartStreamingLogs",e);stopStreamingLogs=async e=>await this.connection.invoke("StopStreamingLogs",e)},Ze=class n{static Instance=new n;constructor(){}createHubProxy=e=>new et(e)},et=class{constructor(e){this.connection=e}registerMachine=async(e,t)=>await this.connection.invoke("RegisterMachine",e,t);reportDeploymentStatus=async e=>await this.connection.invoke("ReportDeploymentStatus",e);reportHealth=async e=>await this.connection.invoke("ReportHealth",e);reportMachineStatus=async e=>await this.connection.invoke("ReportMachineStatus",e);sendDeploymentLog=async e=>await this.connection.invoke("SendDeploymentLog",e)},tt=class n{static Instance=new n;constructor(){}createHubProxy=e=>new nt(e)},nt=class{constructor(e){this.connection=e}joinBoard=async e=>await this.connection.invoke("JoinBoard",e);leaveBoard=async e=>await this.connection.invoke("LeaveBoard",e)},ot=class n{static Instance=new n;constructor(){}createHubProxy=e=>new st(e)},st=class{constructor(e){this.connection=e}registerAgent=async e=>await this.connection.invoke("RegisterAgent",e);getSecrets=async()=>await this.connection.invoke("GetSecrets");reportStatus=async(e,t)=>await this.connection.invoke("ReportStatus",e,t);reportSessionOutput=async(e,t,o)=>await this.connection.invoke("ReportSessionOutput",e,t,o);reportSessionCost=async(e,t,o)=>await this.connection.invoke("ReportSessionCost",e,t,o);reportInsight=async(e,t)=>await this.connection.invoke("ReportInsight",e,t);setClaudeSessionId=async(e,t)=>await this.connection.invoke("SetClaudeSessionId",e,t);sessionCompleted=async(e,t,o)=>await this.connection.invoke("SessionCompleted",e,t,o);initSessionCompleted=async(e,t,o,s)=>await this.connection.invoke("InitSessionCompleted",e,t,o,s);reportPreviewBuild=async(e,t,o)=>await this.connection.invoke("ReportPreviewBuild",e,t,o);saveSpecification=async(e,t,o,s)=>await this.connection.invoke("SaveSpecification",e,t,o,s);getSpecification=async(e,t)=>await this.connection.invoke("GetSpecification",e,t);listSpecifications=async e=>await this.connection.invoke("ListSpecifications",e);deleteSpecification=async(e,t)=>await this.connection.invoke("DeleteSpecification",e,t);watchContainer=async e=>await this.connection.invoke("WatchContainer",e);watchSession=async e=>await this.connection.invoke("WatchSession",e);watchSlaves=async()=>await this.connection.invoke("WatchSlaves");unwatchSlaves=async()=>await this.connection.invoke("UnwatchSlaves");sendPrompt=async(e,t,o,s)=>await this.connection.invoke("SendPrompt",e,t,o,s);stopSession=async e=>await this.connection.invoke("StopSession",e);switchSession=async(e,t)=>await this.connection.invoke("SwitchSession",e,t);createSession=async e=>await this.connection.invoke("CreateSession",e);refreshGitHubToken=async()=>await this.connection.invoke("RefreshGitHubToken");reportError=async(e,t)=>await this.connection.invoke("ReportError",e,t)},rt=class n{static Instance=new n;constructor(){}createHubProxy=e=>new it(e)},it=class{constructor(e){this.connection=e}register=async(e,t)=>await this.connection.invoke("Register",e,t);getSecrets=async()=>await this.connection.invoke("GetSecrets");containerCreated=async e=>await this.connection.invoke("ContainerCreated",e);containerReady=async e=>await this.connection.invoke("ContainerReady",e);reportCapacity=async e=>await this.connection.invoke("ReportCapacity",e);reportError=async e=>await this.connection.invoke("ReportError",e)},at=class n{static Instance=new n;constructor(){}createHubProxy=e=>new ct(e)},ct=class{constructor(e){this.connection=e}joinProject=async e=>await this.connection.invoke("JoinProject",e);leaveProject=async e=>await this.connection.invoke("LeaveProject",e)},lt=class n{static Instance=new n;constructor(){}register=(e,t)=>{let o=(...a)=>t.deploymentStatusUpdated(...a),s=(...a)=>t.deploymentLogReceived(...a),r=(...a)=>t.machineStatusUpdated(...a);e.on("DeploymentStatusUpdated",o),e.on("DeploymentLogReceived",s),e.on("MachineStatusUpdated",r);let i=[{methodName:"DeploymentStatusUpdated",method:o},{methodName:"DeploymentLogReceived",method:s},{methodName:"MachineStatusUpdated",method:r}];return new Q(e,i)}},pt=class n{static Instance=new n;constructor(){}register=(e,t)=>{let o=(...c)=>t.deploy(...c),s=(...c)=>t.stop(...c),r=(...c)=>t.startLogStreaming(...c),i=(...c)=>t.stopLogStreaming(...c);e.on("Deploy",o),e.on("Stop",s),e.on("StartLogStreaming",r),e.on("StopLogStreaming",i);let a=[{methodName:"Deploy",method:o},{methodName:"Stop",method:s},{methodName:"StartLogStreaming",method:r},{methodName:"StopLogStreaming",method:i}];return new Q(e,a)}},dt=class n{static Instance=new n;constructor(){}register=(e,t)=>{let o=(...f)=>t.boardUpdated(...f),s=(...f)=>t.boardDeleted(...f),r=(...f)=>t.columnCreated(...f),i=(...f)=>t.columnUpdated(...f),a=(...f)=>t.columnDeleted(...f),c=(...f)=>t.cardCreated(...f),l=(...f)=>t.cardUpdated(...f),u=(...f)=>t.cardDeleted(...f),d=(...f)=>t.subtaskCreated(...f),g=(...f)=>t.subtaskUpdated(...f),w=(...f)=>t.subtaskDeleted(...f),v=(...f)=>t.noteCreated(...f),A=(...f)=>t.noteUpdated(...f),D=(...f)=>t.noteDeleted(...f);e.on("BoardUpdated",o),e.on("BoardDeleted",s),e.on("ColumnCreated",r),e.on("ColumnUpdated",i),e.on("ColumnDeleted",a),e.on("CardCreated",c),e.on("CardUpdated",l),e.on("CardDeleted",u),e.on("SubtaskCreated",d),e.on("SubtaskUpdated",g),e.on("SubtaskDeleted",w),e.on("NoteCreated",v),e.on("NoteUpdated",A),e.on("NoteDeleted",D);let b=[{methodName:"BoardUpdated",method:o},{methodName:"BoardDeleted",method:s},{methodName:"ColumnCreated",method:r},{methodName:"ColumnUpdated",method:i},{methodName:"ColumnDeleted",method:a},{methodName:"CardCreated",method:c},{methodName:"CardUpdated",method:l},{methodName:"CardDeleted",method:u},{methodName:"SubtaskCreated",method:d},{methodName:"SubtaskUpdated",method:g},{methodName:"SubtaskDeleted",method:w},{methodName:"NoteCreated",method:v},{methodName:"NoteUpdated",method:A},{methodName:"NoteDeleted",method:D}];return new Q(e,b)}},ut=class n{static Instance=new n;constructor(){}register=(e,t)=>{let o=(...d)=>t.initSession(...d),s=(...d)=>t.runPrompt(...d),r=(...d)=>t.setModel(...d),i=()=>t.stopAgent(),a=()=>t.ping(),c=(...d)=>t.switchSession(...d),l=(...d)=>t.projectPromptUpdated(...d);e.on("InitSession",o),e.on("RunPrompt",s),e.on("SetModel",r),e.on("StopAgent",i),e.on("Ping",a),e.on("SwitchSession",c),e.on("ProjectPromptUpdated",l);let u=[{methodName:"InitSession",method:o},{methodName:"RunPrompt",method:s},{methodName:"SetModel",method:r},{methodName:"StopAgent",method:i},{methodName:"Ping",method:a},{methodName:"SwitchSession",method:c},{methodName:"ProjectPromptUpdated",method:l}];return new Q(e,u)}},gt=class n{static Instance=new n;constructor(){}register=(e,t)=>{let o=(...b)=>t.sessionOutput(...b),s=(...b)=>t.sessionCost(...b),r=(...b)=>t.sessionCompleted(...b),i=(...b)=>t.containerStatus(...b),a=(...b)=>t.slaveCapacityUpdate(...b),c=(...b)=>t.previewBuildStatus(...b),l=(...b)=>t.previewReload(...b),u=(...b)=>t.questionsReceived(...b),d=(...b)=>t.specificationUpdated(...b),g=(...b)=>t.singleQuestionReceived(...b),w=(...b)=>t.questionSessionEnded(...b),v=(...b)=>t.creditsUpdated(...b),A=(...b)=>t.insufficientCredits(...b);e.on("SessionOutput",o),e.on("SessionCost",s),e.on("SessionCompleted",r),e.on("ContainerStatus",i),e.on("SlaveCapacityUpdate",a),e.on("PreviewBuildStatus",c),e.on("PreviewReload",l),e.on("QuestionsReceived",u),e.on("SpecificationUpdated",d),e.on("SingleQuestionReceived",g),e.on("QuestionSessionEnded",w),e.on("CreditsUpdated",v),e.on("InsufficientCredits",A);let D=[{methodName:"SessionOutput",method:o},{methodName:"SessionCost",method:s},{methodName:"SessionCompleted",method:r},{methodName:"ContainerStatus",method:i},{methodName:"SlaveCapacityUpdate",method:a},{methodName:"PreviewBuildStatus",method:c},{methodName:"PreviewReload",method:l},{methodName:"QuestionsReceived",method:u},{methodName:"SpecificationUpdated",method:d},{methodName:"SingleQuestionReceived",method:g},{methodName:"QuestionSessionEnded",method:w},{methodName:"CreditsUpdated",method:v},{methodName:"InsufficientCredits",method:A}];return new Q(e,D)}},ft=class n{static Instance=new n;constructor(){}register=(e,t)=>{let o=(...c)=>t.startContainer(...c),s=(...c)=>t.terminateContainer(...c),r=()=>t.reconnect(),i=(...c)=>t.getContainerLogs(...c);e.on("StartContainer",o),e.on("TerminateContainer",s),e.on("Reconnect",r),e.on("GetContainerLogs",i);let a=[{methodName:"StartContainer",method:o},{methodName:"TerminateContainer",method:s},{methodName:"Reconnect",method:r},{methodName:"GetContainerLogs",method:i}];return new Q(e,a)}},mt=class n{static Instance=new n;constructor(){}register=(e,t)=>{let o=(...l)=>t.testRunCreated(...l),s=(...l)=>t.testRunUpdated(...l),r=(...l)=>t.testSuiteCreated(...l),i=(...l)=>t.testCreated(...l),a=(...l)=>t.testUpdated(...l);e.on("TestRunCreated",o),e.on("TestRunUpdated",s),e.on("TestSuiteCreated",r),e.on("TestCreated",i),e.on("TestUpdated",a);let c=[{methodName:"TestRunCreated",method:o},{methodName:"TestRunUpdated",method:s},{methodName:"TestSuiteCreated",method:r},{methodName:"TestCreated",method:i},{methodName:"TestUpdated",method:a}];return new Q(e,c)}};var xn=An(En),Ue=class{constructor(e){this.config=e;let t={"X-Container-Id":e.containerId,"X-Project-Key":e.projectKey};e.isByok&&(t["X-Is-Byok"]="true"),this.connection=new ee.HubConnectionBuilder().withUrl(`${e.masterUrl}/api/hubs/agent`,{headers:t}).withAutomaticReconnect({nextRetryDelayInMilliseconds:o=>{let s=o.previousRetryCount+1,r=Math.min(1e3*Math.pow(2,o.previousRetryCount),6e4);return console.log(`[SignalR] Reconnect attempt ${s} (will retry in ${r}ms)`),r}}).withServerTimeout(3e5).withKeepAliveInterval(1e4).configureLogging(ee.LogLevel.Information).build(),this.hubProxy=$t("IAgentHub").createHubProxy(this.connection),this.connection.onreconnecting(o=>{console.warn("[SignalR] Connection lost, attempting to reconnect...",o?.message)}),this.connection.onreconnected(async o=>{console.log("[SignalR] Reconnected to gateway (connectionId:",o,")");try{await this.hubProxy.registerAgent(this.config.containerId),console.log(`[SignalR] Re-registered as agent for container: ${this.config.containerId}`),await this.reportStatus(this.currentStatus,void 0,this.currentSessionId??void 0,this.currentProjectId??void 0)}catch(s){console.error("[SignalR] Failed to re-register agent after reconnect:",s instanceof Error?s.message:s)}}),this.connection.onclose(o=>{console.error("[SignalR] Connection closed:",o?.message),console.error("[SignalR] Connection state at close:",this.connection.state),process.exit(1)})}connection;hubProxy;receiverSubscription=null;currentStatus="WarmingUp";currentSessionId=null;currentProjectId=null;tunnelUrl=null;tokenRefreshInterval=null;currentRepoFullName=null;heartbeatInterval=null;async connect(){console.log(`[SignalR] Connecting to gateway: ${this.config.masterUrl}/api/hubs/agent`),this.config.isByok&&console.log("[SignalR] BYOK mode enabled - credits will not be deducted"),await this.connection.start();let e=this.connection.connection?.transport;console.log("[SignalR] Connected to gateway!"),console.log(`[SignalR] Transport: ${e?.constructor?.name||"unknown"}`),console.log(`[SignalR] Connection ID: ${this.connection.connectionId}`),await this.hubProxy.registerAgent(this.config.containerId),console.log(`[SignalR] Registered as agent for container: ${this.config.containerId}`)}registerReceiver(e){this.receiverSubscription&&this.receiverSubscription.dispose(),this.receiverSubscription=Ht("IAgentReceiver").register(this.connection,e)}getHubProxy(){return this.hubProxy}getMasterUrl(){return this.config.masterUrl}getProjectKey(){return this.config.projectKey}getConnection(){return this.connection}setTunnelUrl(e){this.tunnelUrl=e}async reportStatus(e,t,o,s){if(this.currentStatus=e,o&&(this.currentSessionId=o),s&&(this.currentProjectId=s),this.connection.state===ee.HubConnectionState.Connected)try{let r={status:e,error:t,sessionId:o,projectId:s,tunnelUrl:this.tunnelUrl??void 0};await this.hubProxy.reportStatus(this.config.containerId,r),console.log(`[Status] ${e}${t?` (${t})`:""}${this.tunnelUrl?` [${this.tunnelUrl}]`:""}${o?` [session: ${o}]`:""}`)}catch(r){console.error("[SignalR] Failed to report status:",r)}}async getSecrets(){let e=await this.hubProxy.getSecrets();if(!e.success)throw new Error(`Failed to get secrets: ${e.error}`);return e.secrets||{}}startHeartbeat(e=3e4){this.heartbeatInterval||(this.heartbeatInterval=setInterval(async()=>{if(this.connection.state===ee.HubConnectionState.Connected)try{await this.hubProxy.reportStatus(this.config.containerId,{status:this.currentStatus,sessionId:this.currentSessionId??void 0,projectId:this.currentProjectId??void 0,tunnelUrl:this.tunnelUrl??void 0})}catch(t){console.error("[Heartbeat] Failed:",t instanceof Error?t.message:t)}},e),console.log(`[Heartbeat] Started (every ${e/1e3}s)`))}stopHeartbeat(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null,console.log("[Heartbeat] Stopped"))}async startTokenRefresh(){await this.refreshGitHubToken(),this.tokenRefreshInterval=setInterval(async()=>{await this.refreshGitHubToken()},3e6),console.log("[TokenRefresh] Started (refreshing every 50 minutes)")}stopTokenRefresh(){this.tokenRefreshInterval&&(clearInterval(this.tokenRefreshInterval),this.tokenRefreshInterval=null,console.log("[TokenRefresh] Stopped"))}async refreshGitHubToken(){try{let e=await this.hubProxy.refreshGitHubToken();if(!e.success){console.error(`[TokenRefresh] Failed: ${e.error}`);return}if(!e.token){console.error("[TokenRefresh] No token returned");return}if(await this.updateGitCredentials(e.token,e.repoFullName??void 0),e.expiresAt){let t=new Date(e.expiresAt).toISOString();console.log(`[TokenRefresh] Refreshed, expires: ${t}${e.repoFullName?` (repo: ${e.repoFullName})`:""}`)}else console.log("[TokenRefresh] Token refreshed (PAT mode, no expiry)");this.currentRepoFullName=e.repoFullName??null}catch(e){console.error("[TokenRefresh] Error:",e instanceof Error?e.message:e)}}async reportError(e){if(this.connection.state!==ee.HubConnectionState.Connected){console.error("[SignalR] Cannot report error - not connected");return}try{let t={message:e.message,stackTrace:e.stackTrace,errorType:e.errorType,operation:e.operation,sessionId:e.sessionId??this.currentSessionId??void 0,isFatal:e.isFatal??!1},o=await this.hubProxy.reportError(this.config.containerId,t);o.success?console.log(`[Error Report] Reported: ${e.errorType??"Error"} - ${e.message}`):console.error(`[Error Report] Failed to report: ${o.error}`)}catch(t){console.error("[SignalR] Failed to report error:",t instanceof Error?t.message:t)}}async updateGitCredentials(e,t){let o=Gt.join(qt.homedir(),".git-credentials"),s=`https://x-access-token:${e}@github.com
1357
- `;if(await Bt.promises.writeFile(o,s,{mode:384}),t)try{let r=`https://x-access-token:${e}@github.com/${t}.git`;await xn(`git remote set-url origin "${r}"`,{cwd:"/workspace"})}catch(r){console.error("[TokenRefresh] Could not update remote URL:",r instanceof Error?r.message:r)}}};function Dn(n){let e=n.match(/name:\s*"([^"]+)"/);if(e)return e[1];let t=n.match(/^#\s+(.+)$/m);return t?t[1].trim():"Untitled Specification"}var Ne=class{constructor(e,t){this.hubProxy=e;this.projectId=t}async saveSpecification(e,t){let o=Dn(t),s=await this.hubProxy.saveSpecification(this.projectId,e,o,t);if(!s.success)throw new Error(s.error||"Failed to save specification")}async getSpecification(e){let t=await this.hubProxy.getSpecification(this.projectId,e);return t.success&&t.content||null}async listSpecifications(){let e=await this.hubProxy.listSpecifications(this.projectId);return!e.success||!e.specifications?[]:e.specifications.map(t=>({slug:t.slug,name:t.name,status:t.status,version:"1.0.0"}))}async deleteSpecification(e){return(await this.hubProxy.deleteSpecification(this.projectId,e)).success}async specificationExists(e){let t=await this.hubProxy.getSpecification(this.projectId,e);return t.success&&t.content!=null}};import{exec as jn,execSync as On,spawn as Un}from"child_process";import{promisify as Nn}from"util";import{createHash as Wt}from"crypto";import*as k from"fs";import*as N from"path";var Fe=class{domain;accountId;tunnelId;apiToken;zoneId;tunnelApiBase;constructor(){this.domain=process.env.CLOUDFLARE_DEPLOY_DOMAIN||process.env.DEPLOY_DOMAIN||"vibecodementor.net",this.accountId=process.env.CLOUDFLARE_ACCOUNT_ID||"",this.tunnelId=process.env.CLOUDFLARE_TUNNEL_ID||"",this.apiToken=process.env.CLOUDFLARE_API_TOKEN||"",this.zoneId=process.env.CLOUDFLARE_ZONE_ID||"",this.tunnelApiBase=`https://api.cloudflare.com/client/v4/accounts/${this.accountId}/cfd_tunnel/${this.tunnelId}/configurations`}isConfigured(){return!!(this.accountId&&this.tunnelId&&this.apiToken&&this.zoneId)}buildHostname(e){let t=this.domain.split("."),o=t.length>2?t.slice(-2).join("."):this.domain;return`${e}.${o}`}async addRoute(e,t){let o=this.buildHostname(e);if(console.log(`[TunnelManager] Adding route: ${o} -> localhost:${t}`),!this.isConfigured())return console.log("[TunnelManager] Not configured, skipping route addition"),`https://${o}`;try{let s=await this.getConfig(),r=s.ingress.findIndex(a=>a.hostname===o);if(r!==-1)s.ingress[r].service=`http://localhost:${t}`;else{let a=s.ingress.findIndex(l=>!l.hostname),c={hostname:o,service:`http://localhost:${t}`};a!==-1?s.ingress.splice(a,0,c):(s.ingress.push(c),s.ingress.push({service:"http_status:404"}))}await this.putConfig(s),await this.ensureDnsPointsToTunnel(o);let i=`https://${o}`;return console.log(`[TunnelManager] \u2713 Route added: ${i}`),i}catch(s){throw console.error("[TunnelManager] Failed to add route:",s),s}}async removeRoute(e){let t=this.buildHostname(e);if(console.log(`[TunnelManager] Removing route: ${t}`),!this.isConfigured()){console.log("[TunnelManager] Not configured, skipping route removal");return}try{let o=await this.getConfig();o.ingress=o.ingress.filter(s=>s.hostname!==t),o.ingress.some(s=>!s.hostname)||o.ingress.push({service:"http_status:404"}),await this.putConfig(o),console.log(`[TunnelManager] \u2713 Route removed: ${t}`)}catch(o){throw console.error("[TunnelManager] Failed to remove route:",o),o}}async getConfig(){let t=await(await fetch(this.tunnelApiBase,{method:"GET",headers:{Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"}})).json();if(!t.success)throw new Error(`Cloudflare API error: ${t.errors.map(o=>o.message).join(", ")}`);return t.result?.config||{ingress:[{service:"http_status:404"}]}}async putConfig(e){let o=await(await fetch(this.tunnelApiBase,{method:"PUT",headers:{Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},body:JSON.stringify({config:e})})).json();if(!o.success)throw new Error(`Cloudflare API error: ${o.errors.map(s=>s.message).join(", ")}`);console.log("[TunnelManager] Configuration updated via Cloudflare API")}async ensureDnsPointsToTunnel(e){let t=`${this.tunnelId}.cfargotunnel.com`,o=`https://api.cloudflare.com/client/v4/zones/${this.zoneId}/dns_records`;try{let r=await(await fetch(`${o}?name=${e}&type=CNAME`,{method:"GET",headers:{Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"}})).json();if(!r.success||!r.result?.length){console.log(`[TunnelManager] No DNS record found for ${e}, skipping DNS update`);return}let i=r.result[0];if(i.content===t){console.log(`[TunnelManager] DNS already points to correct tunnel: ${e}`);return}console.log(`[TunnelManager] Updating DNS: ${e} from ${i.content} to ${t}`);let c=await(await fetch(`${o}/${i.id}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},body:JSON.stringify({type:"CNAME",name:e,content:t,proxied:!0})})).json();c.success?console.log(`[TunnelManager] \u2713 DNS updated: ${e} -> ${t}`):console.error(`[TunnelManager] Failed to update DNS: ${c.errors.map(l=>l.message).join(", ")}`)}catch(s){console.error(`[TunnelManager] Error updating DNS for ${e}:`,s)}}};var Kt=Nn(jn),I=class{start;label;constructor(e){this.label=e,this.start=Date.now(),console.log(`[TIMING] \u23F1 START: ${e}`)}stop(){let e=Date.now()-this.start,t=(e/1e3).toFixed(2);return console.log(`[TIMING] \u2713 DONE: ${this.label} (${t}s)`),e}};function U(n,e={}){return new Promise((t,o)=>{let s=Un(n,[],{shell:!0,stdio:"inherit",cwd:e.cwd}),r=null;e.timeout&&(r=setTimeout(()=>{s.kill(),o(new Error(`Command timed out: ${n}`))},e.timeout)),s.on("close",i=>{r&&clearTimeout(r),i===0?t():o(new Error(`Command failed with code ${i}: ${n}`))}),s.on("error",i=>{r&&clearTimeout(r),o(i)})})}var Yt="main",Me=class{constructor(e,t,o,s){this.connection=e;this.serviceManager=t;this.workspaceDir=o;this.gitHubPat=s}currentBranchName=Yt;currentRepoUrl="";lastLockfileHash=null;tunnelManager=null;currentPreviewSubdomain=null;getTunnelManager(){return this.tunnelManager||(this.tunnelManager=new Fe),this.tunnelManager}async prewarmWorkspace(){let e=new I("TOTAL INIT"),t=process.env.REPO_URL,o=process.env.BRANCH_NAME||Yt,s=process.env.PREVIEW_SUBDOMAIN,r=process.env.PREVIEW_HOSTNAME,i=process.env.PROJECT_GITHUB_PAT;if(console.log("[Init] Starting single-phase init..."),console.log(`[Init] Repo: ${t?this.extractRepoPath(t):"NOT SET"}`),console.log(`[Init] Branch: ${o}`),console.log(`[Init] Preview: ${s||"none"}`),!t)throw console.error("[Init] \u274C REPO_URL not set - cannot initialize workspace"),new Error("REPO_URL environment variable is required");i&&(this.gitHubPat=i);let a=new I("Clean workspace");On("rm -rf /workspace/* /workspace/.* 2>/dev/null || true",{stdio:"inherit"}),a.stop();let c=new I("Clone repository");await this.cloneRepository(t,o),this.currentRepoUrl=t,this.currentBranchName=o,c.stop(),await this.installDependencies(),this.lastLockfileHash=this.getLockfileHash(),console.log("[Init] Starting services...");let l=new I("Start backend (dotnet)");await this.serviceManager.startBackend(),l.stop();let u=new I("Start frontend (vite)");await this.serviceManager.startFrontend(),u.stop();let d=new I("Wait for health check");await this.serviceManager.waitForHealth(3e4),d.stop(),s&&r&&await this.setupPreviewSubdomainFromEnv(s,r),await this.connection.startTokenRefresh(),e.stop(),console.log("[Init] \u2713 Workspace ready")}async handleInitSession(e){console.log(`[InitSession] Session ${e.sessionId} starting...`);let t=this.extractRepoPath(e.repoUrl),o=this.extractRepoPath(this.currentRepoUrl),s=t!==o,r=e.branchName!==this.currentBranchName;s||r?(console.log("[InitSession] Repo/branch mismatch - updating workspace..."),console.log(`[InitSession] Current: ${o}@${this.currentBranchName}`),console.log(`[InitSession] Requested: ${t}@${e.branchName}`),await this.connection.reportStatus("Ready",void 0,e.sessionId,e.projectId),await this.connection.getHubProxy().initSessionCompleted(process.env.CONTAINER_ID||"unknown",e.sessionId,!0,""),this.handleRepoChange(e).catch(async a=>{let c=a instanceof Error?a.message:"Unknown error";console.error("[InitSession] Background update failed:",c),await this.connection.reportStatus("Error",c,e.sessionId,e.projectId)})):(console.log("[InitSession] Workspace already matches - ready immediately"),await this.connection.reportStatus("Ready",void 0,e.sessionId,e.projectId),await this.connection.getHubProxy().initSessionCompleted(process.env.CONTAINER_ID||"unknown",e.sessionId,!0,"")),console.log(`[InitSession] \u2713 Ready for session ${e.sessionId}`)}async setupPreviewSubdomainFromEnv(e,t){let o=new I("Setup preview subdomain");console.log(`[Preview] Setting up preview subdomain: ${e} (${t})`);let s=this.getTunnelManager();if(!s){console.log("[Preview] TunnelManager not available, skipping subdomain setup"),o.stop();return}if(!s.isConfigured()){console.log("[Preview] Cloudflare not configured, skipping subdomain setup"),o.stop();return}try{let r=parseInt(process.env.ALLOCATED_HOST_PORT||"5173"),i=await s.addRoute(e,r);this.currentPreviewSubdomain=e,this.connection.setTunnelUrl(i),o.stop(),console.log(`[Preview] \u2713 Preview subdomain configured: ${i}`)}catch(r){o.stop(),console.error("[Preview] Failed to set up subdomain route:",r)}}async handleRepoChange(e){let t=new I("TOTAL REPO CHANGE");e.gitHubPat&&e.gitHubPat!==this.gitHubPat&&(console.log("[RepoChange] Updating git credentials"),this.gitHubPat=e.gitHubPat,await U(`echo "https://${e.gitHubPat}@github.com" > ~/.git-credentials`));let o=this.extractRepoPath(e.repoUrl),s=this.extractRepoPath(this.currentRepoUrl);if(o!==s){let i=new I("Clone new repository");await this.cloneRepository(e.repoUrl,e.branchName),this.currentRepoUrl=e.repoUrl,this.currentBranchName=e.branchName,i.stop(),await this.installDependencies();let a=new I("Restart services");await this.serviceManager.restartServices("both"),a.stop()}else{let i=new I(`Switch branch to ${e.branchName}`);await this.switchBranch(e.branchName),i.stop(),await this.checkNeedsReinstall()&&await this.installDependencies();let c=new I("Restart services");await this.serviceManager.restartServices("both"),c.stop()}e.previewSubdomain&&e.previewHostname&&await this.setupPreviewSubdomainFromEnv(e.previewSubdomain,e.previewHostname),t.stop(),console.log("[RepoChange] \u2713 Workspace updated")}extractRepoPath(e){let t=e.match(/github\.com[:/]([^/]+\/[^/]+?)(?:\.git)?$/);return t?t[1]:e}async cloneRepository(e,t){console.log(`[Clone] Clearing workspace and cloning ${this.extractRepoPath(e)} @ ${t}`),await U("rm -rf /workspace/* /workspace/.* 2>/dev/null || true");try{await U(`git clone -b ${t} "${e}" /workspace`,{timeout:12e4})}catch(o){let s=o instanceof Error?o.message:String(o);throw await this.connection.reportError({message:`Git clone failed: ${s}`,errorType:"GitCloneError",operation:"cloneRepository",isFatal:!0}),o}await U('cd /workspace && git config user.email "agent@dotnetmentor.se" && git config user.name "Agent"'),console.log("[Clone] \u2713 Repository cloned")}async switchBranch(e){if(console.log(`[Branch] Switching from ${this.currentBranchName} to ${e}`),e===this.currentBranchName)console.log(`[Branch] Already on ${e}, pulling latest...`),await U(`git pull origin ${e}`,{cwd:this.workspaceDir,timeout:6e4});else{await U("git fetch origin",{cwd:this.workspaceDir,timeout:6e4});let{stdout:t}=await Kt(`git ls-remote --heads origin ${e}`,{cwd:this.workspaceDir,timeout:3e4});t.trim().length>0?await U(`git checkout -B ${e} origin/${e}`,{cwd:this.workspaceDir,timeout:3e4}):(console.log(`[Branch] Branch ${e} doesn't exist on remote, creating from main...`),await U(`git checkout -b ${e}`,{cwd:this.workspaceDir,timeout:3e4})),this.currentBranchName=e}console.log(`[Branch] \u2713 Now on ${e}`)}getLockfileHash(){let e=N.join(this.workspaceDir,"packages/backoffice-web/package-lock.json");return k.existsSync(e)?Wt("sha256").update(k.readFileSync(e)).digest("hex"):null}async checkNeedsReinstall(){let e=this.getLockfileHash();return!e||!this.lastLockfileHash?!0:e!==this.lastLockfileHash}async checkCodeDiff(e,t){if(e===t)return!1;try{let{stdout:o}=await Kt(`git diff ${e}..HEAD --name-only`,{cwd:this.workspaceDir,timeout:3e4}),s=o.trim();if(!s)return console.log(`[CodeDiff] No file differences between ${e} and ${t}`),!1;let r=s.split(`
1358
- `).filter(c=>c.length>0);console.log(`[CodeDiff] ${r.length} files changed between ${e} and ${t}`);let i=[".cs",".tsx",".ts",".json",".csproj"],a=r.some(c=>i.some(l=>c.endsWith(l)));return a&&console.log("[CodeDiff] Found code changes that require service restart"),a}catch(o){return console.error("[CodeDiff] Failed to check diff:",o instanceof Error?o.message:o),!0}}async installDependencies(){let e=new I("TOTAL INSTALL DEPENDENCIES");if(k.existsSync(N.join(this.workspaceDir,"packages/dotnet-api"))){let t=new I("dotnet restore");await U("dotnet restore",{cwd:N.join(this.workspaceDir,"packages/dotnet-api"),timeout:12e4}),t.stop()}if(k.existsSync(N.join(this.workspaceDir,"packages/backoffice-web/package.json"))){let t=N.join(this.workspaceDir,"packages/backoffice-web"),o=N.join(t,"node_modules"),s=N.join(t,"package-lock.json"),r=N.join(o,".lockhash"),i="/opt/cache";k.mkdirSync(i,{recursive:!0});let a=k.existsSync(s)?Wt("sha256").update(k.readFileSync(s)).digest("hex"):null,c=k.existsSync(r)?k.readFileSync(r,"utf-8").trim():null,l=N.join(i,"node_modules","current_hash"),u=k.existsSync(l)?k.readFileSync(l,"utf-8").trim():null,d=u?N.join(i,"node_modules",u):null,g=a?N.join(i,"node_modules",a):null;if(console.log(`[Install] node_modules exists: ${k.existsSync(o)}`),console.log(`[Install] lockHash (current branch): ${a?.substring(0,8)||"null"}`),console.log(`[Install] installedHash: ${c?.substring(0,8)||"null"}`),console.log(`[Install] dockerCacheHash (from image): ${u?.substring(0,8)||"null"}`),console.log(`[Install] exactMatchCache exists: ${g?k.existsSync(g):!1}`),console.log(`[Install] dockerCachedNodeModules exists: ${d?k.existsSync(d):!1}`),!k.existsSync(o)){if(g&&k.existsSync(g)){let v=new I("Copy exact-match cached node_modules");console.log(`[Install] Copying exact-match cached node_modules (hash ${a?.substring(0,8)})...`),await U(`cp -r "${g}" "${o}"`),a&&k.writeFileSync(r,a),c=a,v.stop()}else if(d&&k.existsSync(d)){let v=new I("Copy Docker-cached node_modules (as base)");console.log(`[Install] Copying Docker-cached node_modules as base (hash ${u?.substring(0,8)}, need ${a?.substring(0,8)})...`),await U(`cp -r "${d}" "${o}"`),v.stop()}}let w=!k.existsSync(o)||a&&a!==c;if(console.log(`[Install] needsInstall: ${w}`),!w)console.log("[Install] npm install skipped (cache OK)");else{let v=new I("npm install --prefer-offline");await U("npm install --prefer-offline --no-progress --fund=false",{cwd:t,timeout:18e4}),v.stop(),a&&(k.mkdirSync(o,{recursive:!0}),k.writeFileSync(r,a))}this.lastLockfileHash=a}e.stop()}};function Qt(n,e,t){let o=n.getHubProxy(),s=process.env.CONTAINER_ID||"unknown";return{onAssistantText:async r=>{let i={type:"Text",content:r,isError:!1};await o.reportSessionOutput(s,e,i).catch(a=>{console.error("Failed to report assistant text:",a)})},onAssistantToolUse:async(r,i)=>{if(["Write","Edit","MultiEdit"].includes(r)){let c=i,l=c.file_path||c.target_file;l&&t.onFileModified(l)}let a={type:"ToolUse",toolName:r,toolInput:JSON.stringify(i),isError:!1};await o.reportSessionOutput(s,e,a).catch(c=>{console.error("Failed to report tool use:",c)})},onResult:async(r,i)=>{let a={type:"System",event:"completed",content:r,cost:i,isError:!1};await o.reportSessionOutput(s,e,a).catch(c=>{console.error("Failed to report result:",c)})},onError:async r=>{let i={type:"System",event:"error",content:r,isError:!0};await o.reportSessionOutput(s,e,i).catch(a=>{console.error("Failed to report error:",a)})},onAborted:async()=>{let r={type:"System",event:"aborted",content:"Agent stopped by user",isError:!1};await o.reportSessionOutput(s,e,r).catch(i=>{console.error("Failed to report abort:",i)})},onSystemInit:async r=>{console.log(`[Callbacks] Claude session initialized: ${r}`),t.onClaudeSessionId(r),await o.setClaudeSessionId(e,r).catch(i=>{console.error("Failed to set Claude session ID:",i)})},onRawMessage:r=>{if(r.type==="assistant"&&r.message?.usage){let i=r.message.usage,a={totalCostUsd:Fn(i),inputTokens:i.input_tokens||0,outputTokens:i.output_tokens||0,cacheCreationTokens:i.cache_creation_input_tokens||0,cacheReadTokens:i.cache_read_input_tokens||0};o.reportSessionCost(s,e,a).catch(c=>{console.error("Failed to report cost:",c)})}}}}var Le={inputPerMillion:3,outputPerMillion:15,cacheReadPerMillion:.3,cacheCreationPerMillion:3.75};function Fn(n){return(n.input_tokens||0)/1e6*Le.inputPerMillion+(n.output_tokens||0)/1e6*Le.outputPerMillion+(n.cache_read_input_tokens||0)/1e6*Le.cacheReadPerMillion+(n.cache_creation_input_tokens||0)/1e6*Le.cacheCreationPerMillion}import*as ie from"fs";import*as Vt from"path";function zt(n,e){let t=Vt.join(n,`.agent-questions-${e}.json`);if(!ie.existsSync(t))return null;try{let o=ie.readFileSync(t,"utf-8");return ie.unlinkSync(t),JSON.parse(o)}catch(o){return console.error("Failed to read questions file:",o),null}}async function Jt(n,e,t,o){if(e.size===0)return console.log("[TypeCheck] No code changes, skipping type checks"),{passed:!0};let s=o?B(o):`${t}/packages/dotnet-api`,r=o?q(o):`${t}/packages/backoffice-web`,i=o?.services?.backend?.extensions??[".cs",".csproj"],a=o?.services?.frontend?.extensions??[".ts",".tsx"],c=s&&[...e].some(g=>g.includes(s)||i.some(w=>g.endsWith(w))),l=r&&[...e].some(g=>g.includes(r)||a.some(w=>g.endsWith(w)));if(!c&&!l)return console.log("[TypeCheck] No code changes, skipping type checks"),{passed:!0};let u=[];c&&u.push("backend"),l&&u.push("frontend"),console.log(`[TypeCheck] Checking ${u.join(" & ")}...`);let d=[];if(c){let g=await n.checkBackendBuild();!g.success&&g.errors&&d.push(`## Backend Build Errors (in ${s})
1355
+ `)}`:"";m.backendError||(m.backendError=`Backend failed to start.${P}`)}return _&&!j.web&&(m.success=!1,m.frontendError||(m.frontendError="Frontend failed to start")),m},vt=async()=>{if(!l||!T.existsSync(l))return{success:!0};try{return oe(w,{cwd:l,stdio:"pipe",timeout:12e4,encoding:"utf-8"}),{success:!0}}catch(y){let m=y;return{success:!1,errors:m.stdout||m.stderr||"Build failed"}}},Ct=async()=>{if(!u||!T.existsSync(ee.join(u,"package.json")))return{success:!0};try{return oe(A,{cwd:u,stdio:"pipe",timeout:6e4,encoding:"utf-8"}),{success:!0}}catch(y){let m=y;return{success:!1,errors:m.stdout||m.stderr||"Type check failed"}}},sn=async()=>{let[y,m]=await Promise.all([vt(),Ct()]);return{backend:y,frontend:m}},_t=async(y,m)=>{let S=y==="backend"?D:b;if(!T.existsSync(S))return[`Log file not found: ${S}`];try{return oe(`tail -n ${m} ${S}`,{encoding:"utf-8"}).split(`
1356
+ `).filter(Boolean)}catch(_){return[`Error reading logs: ${_ instanceof Error?_.message:String(_)}`]}};return{startBackend:C,startFrontend:L,stopBackend:ce,stopFrontend:me,restartServices:on,checkHealth:Ge,waitForHealth:kt,getProcesses:()=>({backend:f,frontend:O}),checkBackendBuild:vt,checkFrontendTypes:Ct,runTypeChecks:sn,tailLogs:_t,checkSwaggerEndpoints:async y=>{let m=ee.join(e,"swagger.json");if(!T.existsSync(m))return{foundEndpoints:["Error: swagger.json not found"],totalEndpoints:0};try{let S=JSON.parse(T.readFileSync(m,"utf-8")),_=Object.keys(S.paths||{}),j=[];for(let E of _)if(E.toLowerCase().includes(y.toLowerCase())){let P=Object.keys(S.paths[E]);for(let J of P)j.push(`${J.toUpperCase()} ${E}`)}return{foundEndpoints:j,totalEndpoints:_.length}}catch(S){return{foundEndpoints:[`Error parsing swagger.json: ${S instanceof Error?S.message:String(S)}`],totalEndpoints:0}}}}}function An(n){let e=n.toLowerCase();return e.includes("exception")||e.includes("fail:")||e.includes("[err]")||e.includes("[error]")}import{execSync as se}from"child_process";function Ne(n){let e=async()=>{try{return se("git status --porcelain",{cwd:n,encoding:"utf-8"}).trim().length>0}catch{return!1}},t=async()=>{try{return se("git branch --show-current",{cwd:n,encoding:"utf-8"}).trim()}catch{return"unknown"}};return{hasChanges:e,commitAndPush:async(s,r)=>{try{if(!await e())return{success:!0,noChanges:!0};let i=s.length>60?s.substring(0,60)+"...":s,c=`${r?"[agent] (partial)":"[agent]"} ${i}`;se("git add -A",{cwd:n}),se(`git commit -m "${c.replace(/"/g,'\\"')}"`,{cwd:n,encoding:"utf-8"});let l=se("git rev-parse --short HEAD",{cwd:n,encoding:"utf-8"}).trim();try{se("git push",{cwd:n,stdio:"pipe"})}catch(u){let d=u instanceof Error?u.message:String(u);if(d.includes("no upstream branch")){let g=await t();se(`git push --set-upstream origin ${g}`,{cwd:n,stdio:"pipe"})}else return console.error("[Git] Push failed:",d),{success:!1,commitHash:l,commitSucceeded:!0,pushFailed:!0,error:d}}return{success:!0,commitHash:l}}catch(i){let a=i instanceof Error?i.message:String(i);return console.error("[Git] Error:",a),{success:!1,error:a}}},getCurrentBranch:t}}import*as te from"@microsoft/signalr";import*as Gt from"fs";import*as Wt from"os";import*as Kt from"path";import{exec as xn}from"child_process";import{promisify as Dn}from"util";var Q=class{constructor(e,t){this.connection=e;this.receiverMethod=t}dispose=()=>{for(let e of this.receiverMethod)this.connection.off(e.methodName,e.method)}},Bt=n=>{if(n==="IDeploymentWatcherHub")return Ze.Instance;if(n==="IDeploymentHub")return tt.Instance;if(n==="IKanbanHub")return ot.Instance;if(n==="IAgentHub")return rt.Instance;if(n==="ISlaveHub")return at.Instance;if(n==="ITestHub")return lt.Instance},qt=n=>{if(n==="IDeploymentWatcherClient")return dt.Instance;if(n==="IDeploymentHubClient")return ut.Instance;if(n==="IKanbanBoardClient")return gt.Instance;if(n==="IAgentReceiver")return ft.Instance;if(n==="IBackofficeReceiver")return mt.Instance;if(n==="ISlaveHubClient")return ht.Instance;if(n==="ITestHubClient")return yt.Instance},Ze=class n{static Instance=new n;constructor(){}createHubProxy=e=>new et(e)},et=class{constructor(e){this.connection=e}watchMachine=async e=>await this.connection.invoke("WatchMachine",e);unwatchMachine=async e=>await this.connection.invoke("UnwatchMachine",e);startStreamingLogs=async e=>await this.connection.invoke("StartStreamingLogs",e);stopStreamingLogs=async e=>await this.connection.invoke("StopStreamingLogs",e)},tt=class n{static Instance=new n;constructor(){}createHubProxy=e=>new nt(e)},nt=class{constructor(e){this.connection=e}registerMachine=async(e,t)=>await this.connection.invoke("RegisterMachine",e,t);reportDeploymentStatus=async e=>await this.connection.invoke("ReportDeploymentStatus",e);reportHealth=async e=>await this.connection.invoke("ReportHealth",e);reportMachineStatus=async e=>await this.connection.invoke("ReportMachineStatus",e);sendDeploymentLog=async e=>await this.connection.invoke("SendDeploymentLog",e)},ot=class n{static Instance=new n;constructor(){}createHubProxy=e=>new st(e)},st=class{constructor(e){this.connection=e}joinBoard=async e=>await this.connection.invoke("JoinBoard",e);leaveBoard=async e=>await this.connection.invoke("LeaveBoard",e)},rt=class n{static Instance=new n;constructor(){}createHubProxy=e=>new it(e)},it=class{constructor(e){this.connection=e}registerAgent=async e=>await this.connection.invoke("RegisterAgent",e);getSecrets=async()=>await this.connection.invoke("GetSecrets");reportStatus=async(e,t)=>await this.connection.invoke("ReportStatus",e,t);reportSessionOutput=async(e,t,o)=>await this.connection.invoke("ReportSessionOutput",e,t,o);reportSessionCost=async(e,t,o)=>await this.connection.invoke("ReportSessionCost",e,t,o);reportInsight=async(e,t)=>await this.connection.invoke("ReportInsight",e,t);setClaudeSessionId=async(e,t)=>await this.connection.invoke("SetClaudeSessionId",e,t);sessionCompleted=async(e,t,o)=>await this.connection.invoke("SessionCompleted",e,t,o);initSessionCompleted=async(e,t,o,s)=>await this.connection.invoke("InitSessionCompleted",e,t,o,s);reportPreviewBuild=async(e,t,o)=>await this.connection.invoke("ReportPreviewBuild",e,t,o);saveSpecification=async(e,t,o,s)=>await this.connection.invoke("SaveSpecification",e,t,o,s);getSpecification=async(e,t)=>await this.connection.invoke("GetSpecification",e,t);listSpecifications=async e=>await this.connection.invoke("ListSpecifications",e);deleteSpecification=async(e,t)=>await this.connection.invoke("DeleteSpecification",e,t);watchContainer=async e=>await this.connection.invoke("WatchContainer",e);watchSession=async e=>await this.connection.invoke("WatchSession",e);watchSlaves=async()=>await this.connection.invoke("WatchSlaves");unwatchSlaves=async()=>await this.connection.invoke("UnwatchSlaves");sendPrompt=async(e,t,o,s)=>await this.connection.invoke("SendPrompt",e,t,o,s);stopSession=async e=>await this.connection.invoke("StopSession",e);switchSession=async(e,t)=>await this.connection.invoke("SwitchSession",e,t);createSession=async e=>await this.connection.invoke("CreateSession",e);refreshGitHubToken=async()=>await this.connection.invoke("RefreshGitHubToken");reportError=async(e,t)=>await this.connection.invoke("ReportError",e,t)},at=class n{static Instance=new n;constructor(){}createHubProxy=e=>new ct(e)},ct=class{constructor(e){this.connection=e}register=async(e,t)=>await this.connection.invoke("Register",e,t);getSecrets=async()=>await this.connection.invoke("GetSecrets");containerCreated=async e=>await this.connection.invoke("ContainerCreated",e);containerReady=async e=>await this.connection.invoke("ContainerReady",e);reportCapacity=async e=>await this.connection.invoke("ReportCapacity",e);reportError=async e=>await this.connection.invoke("ReportError",e)},lt=class n{static Instance=new n;constructor(){}createHubProxy=e=>new pt(e)},pt=class{constructor(e){this.connection=e}joinProject=async e=>await this.connection.invoke("JoinProject",e);leaveProject=async e=>await this.connection.invoke("LeaveProject",e)},dt=class n{static Instance=new n;constructor(){}register=(e,t)=>{let o=(...a)=>t.deploymentStatusUpdated(...a),s=(...a)=>t.deploymentLogReceived(...a),r=(...a)=>t.machineStatusUpdated(...a);e.on("DeploymentStatusUpdated",o),e.on("DeploymentLogReceived",s),e.on("MachineStatusUpdated",r);let i=[{methodName:"DeploymentStatusUpdated",method:o},{methodName:"DeploymentLogReceived",method:s},{methodName:"MachineStatusUpdated",method:r}];return new Q(e,i)}},ut=class n{static Instance=new n;constructor(){}register=(e,t)=>{let o=(...c)=>t.deploy(...c),s=(...c)=>t.stop(...c),r=(...c)=>t.startLogStreaming(...c),i=(...c)=>t.stopLogStreaming(...c);e.on("Deploy",o),e.on("Stop",s),e.on("StartLogStreaming",r),e.on("StopLogStreaming",i);let a=[{methodName:"Deploy",method:o},{methodName:"Stop",method:s},{methodName:"StartLogStreaming",method:r},{methodName:"StopLogStreaming",method:i}];return new Q(e,a)}},gt=class n{static Instance=new n;constructor(){}register=(e,t)=>{let o=(...f)=>t.boardUpdated(...f),s=(...f)=>t.boardDeleted(...f),r=(...f)=>t.columnCreated(...f),i=(...f)=>t.columnUpdated(...f),a=(...f)=>t.columnDeleted(...f),c=(...f)=>t.cardCreated(...f),l=(...f)=>t.cardUpdated(...f),u=(...f)=>t.cardDeleted(...f),d=(...f)=>t.subtaskCreated(...f),g=(...f)=>t.subtaskUpdated(...f),w=(...f)=>t.subtaskDeleted(...f),v=(...f)=>t.noteCreated(...f),A=(...f)=>t.noteUpdated(...f),D=(...f)=>t.noteDeleted(...f);e.on("BoardUpdated",o),e.on("BoardDeleted",s),e.on("ColumnCreated",r),e.on("ColumnUpdated",i),e.on("ColumnDeleted",a),e.on("CardCreated",c),e.on("CardUpdated",l),e.on("CardDeleted",u),e.on("SubtaskCreated",d),e.on("SubtaskUpdated",g),e.on("SubtaskDeleted",w),e.on("NoteCreated",v),e.on("NoteUpdated",A),e.on("NoteDeleted",D);let b=[{methodName:"BoardUpdated",method:o},{methodName:"BoardDeleted",method:s},{methodName:"ColumnCreated",method:r},{methodName:"ColumnUpdated",method:i},{methodName:"ColumnDeleted",method:a},{methodName:"CardCreated",method:c},{methodName:"CardUpdated",method:l},{methodName:"CardDeleted",method:u},{methodName:"SubtaskCreated",method:d},{methodName:"SubtaskUpdated",method:g},{methodName:"SubtaskDeleted",method:w},{methodName:"NoteCreated",method:v},{methodName:"NoteUpdated",method:A},{methodName:"NoteDeleted",method:D}];return new Q(e,b)}},ft=class n{static Instance=new n;constructor(){}register=(e,t)=>{let o=(...d)=>t.initSession(...d),s=(...d)=>t.runPrompt(...d),r=(...d)=>t.setModel(...d),i=()=>t.stopAgent(),a=()=>t.ping(),c=(...d)=>t.switchSession(...d),l=(...d)=>t.projectPromptUpdated(...d);e.on("InitSession",o),e.on("RunPrompt",s),e.on("SetModel",r),e.on("StopAgent",i),e.on("Ping",a),e.on("SwitchSession",c),e.on("ProjectPromptUpdated",l);let u=[{methodName:"InitSession",method:o},{methodName:"RunPrompt",method:s},{methodName:"SetModel",method:r},{methodName:"StopAgent",method:i},{methodName:"Ping",method:a},{methodName:"SwitchSession",method:c},{methodName:"ProjectPromptUpdated",method:l}];return new Q(e,u)}},mt=class n{static Instance=new n;constructor(){}register=(e,t)=>{let o=(...b)=>t.sessionOutput(...b),s=(...b)=>t.sessionCost(...b),r=(...b)=>t.sessionCompleted(...b),i=(...b)=>t.containerStatus(...b),a=(...b)=>t.slaveCapacityUpdate(...b),c=(...b)=>t.previewBuildStatus(...b),l=(...b)=>t.previewReload(...b),u=(...b)=>t.questionsReceived(...b),d=(...b)=>t.specificationUpdated(...b),g=(...b)=>t.singleQuestionReceived(...b),w=(...b)=>t.questionSessionEnded(...b),v=(...b)=>t.creditsUpdated(...b),A=(...b)=>t.insufficientCredits(...b);e.on("SessionOutput",o),e.on("SessionCost",s),e.on("SessionCompleted",r),e.on("ContainerStatus",i),e.on("SlaveCapacityUpdate",a),e.on("PreviewBuildStatus",c),e.on("PreviewReload",l),e.on("QuestionsReceived",u),e.on("SpecificationUpdated",d),e.on("SingleQuestionReceived",g),e.on("QuestionSessionEnded",w),e.on("CreditsUpdated",v),e.on("InsufficientCredits",A);let D=[{methodName:"SessionOutput",method:o},{methodName:"SessionCost",method:s},{methodName:"SessionCompleted",method:r},{methodName:"ContainerStatus",method:i},{methodName:"SlaveCapacityUpdate",method:a},{methodName:"PreviewBuildStatus",method:c},{methodName:"PreviewReload",method:l},{methodName:"QuestionsReceived",method:u},{methodName:"SpecificationUpdated",method:d},{methodName:"SingleQuestionReceived",method:g},{methodName:"QuestionSessionEnded",method:w},{methodName:"CreditsUpdated",method:v},{methodName:"InsufficientCredits",method:A}];return new Q(e,D)}},ht=class n{static Instance=new n;constructor(){}register=(e,t)=>{let o=(...c)=>t.startContainer(...c),s=(...c)=>t.terminateContainer(...c),r=()=>t.reconnect(),i=(...c)=>t.getContainerLogs(...c);e.on("StartContainer",o),e.on("TerminateContainer",s),e.on("Reconnect",r),e.on("GetContainerLogs",i);let a=[{methodName:"StartContainer",method:o},{methodName:"TerminateContainer",method:s},{methodName:"Reconnect",method:r},{methodName:"GetContainerLogs",method:i}];return new Q(e,a)}},yt=class n{static Instance=new n;constructor(){}register=(e,t)=>{let o=(...l)=>t.testRunCreated(...l),s=(...l)=>t.testRunUpdated(...l),r=(...l)=>t.testSuiteCreated(...l),i=(...l)=>t.testCreated(...l),a=(...l)=>t.testUpdated(...l);e.on("TestRunCreated",o),e.on("TestRunUpdated",s),e.on("TestSuiteCreated",r),e.on("TestCreated",i),e.on("TestUpdated",a);let c=[{methodName:"TestRunCreated",method:o},{methodName:"TestRunUpdated",method:s},{methodName:"TestSuiteCreated",method:r},{methodName:"TestCreated",method:i},{methodName:"TestUpdated",method:a}];return new Q(e,c)}};var jn=Dn(xn),Ue=class{constructor(e){this.config=e;let t={"X-Container-Id":e.containerId,"X-Project-Key":e.projectKey};e.isByok&&(t["X-Is-Byok"]="true"),this.connection=new te.HubConnectionBuilder().withUrl(`${e.masterUrl}/api/hubs/agent`,{headers:t}).withAutomaticReconnect({nextRetryDelayInMilliseconds:o=>{let s=o.previousRetryCount+1,r=Math.min(1e3*Math.pow(2,o.previousRetryCount),6e4);return console.log(`[SignalR] Reconnect attempt ${s} (will retry in ${r}ms)`),r}}).withServerTimeout(3e5).withKeepAliveInterval(1e4).configureLogging(te.LogLevel.Information).build(),this.hubProxy=Bt("IAgentHub").createHubProxy(this.connection),this.connection.onreconnecting(o=>{console.warn("[SignalR] Connection lost, attempting to reconnect...",o?.message)}),this.connection.onreconnected(async o=>{console.log("[SignalR] Reconnected to gateway (connectionId:",o,")");try{await this.hubProxy.registerAgent(this.config.containerId),console.log(`[SignalR] Re-registered as agent for container: ${this.config.containerId}`),await this.reportStatus(this.currentStatus,void 0,this.currentSessionId??void 0,this.currentProjectId??void 0)}catch(s){console.error("[SignalR] Failed to re-register agent after reconnect:",s instanceof Error?s.message:s)}}),this.connection.onclose(o=>{console.error("[SignalR] Connection closed:",o?.message),console.error("[SignalR] Connection state at close:",this.connection.state),process.exit(1)})}connection;hubProxy;receiverSubscription=null;currentStatus="WarmingUp";currentSessionId=null;currentProjectId=null;tunnelUrl=null;tokenRefreshInterval=null;currentRepoFullName=null;heartbeatInterval=null;async connect(){console.log(`[SignalR] Connecting to gateway: ${this.config.masterUrl}/api/hubs/agent`),this.config.isByok&&console.log("[SignalR] BYOK mode enabled - credits will not be deducted"),await this.connection.start();let e=this.connection.connection?.transport;console.log("[SignalR] Connected to gateway!"),console.log(`[SignalR] Transport: ${e?.constructor?.name||"unknown"}`),console.log(`[SignalR] Connection ID: ${this.connection.connectionId}`),await this.hubProxy.registerAgent(this.config.containerId),console.log(`[SignalR] Registered as agent for container: ${this.config.containerId}`)}registerReceiver(e){this.receiverSubscription&&this.receiverSubscription.dispose(),this.receiverSubscription=qt("IAgentReceiver").register(this.connection,e)}getHubProxy(){return this.hubProxy}getMasterUrl(){return this.config.masterUrl}getProjectKey(){return this.config.projectKey}getConnection(){return this.connection}setTunnelUrl(e){this.tunnelUrl=e}async reportStatus(e,t,o,s){if(this.currentStatus=e,o&&(this.currentSessionId=o),s&&(this.currentProjectId=s),this.connection.state===te.HubConnectionState.Connected)try{let r={status:e,error:t,sessionId:o,projectId:s,tunnelUrl:this.tunnelUrl??void 0};await this.hubProxy.reportStatus(this.config.containerId,r),console.log(`[Status] ${e}${t?` (${t})`:""}${this.tunnelUrl?` [${this.tunnelUrl}]`:""}${o?` [session: ${o}]`:""}`)}catch(r){console.error("[SignalR] Failed to report status:",r)}}async getSecrets(){let e=await this.hubProxy.getSecrets();if(!e.success)throw new Error(`Failed to get secrets: ${e.error}`);return e.secrets||{}}startHeartbeat(e=3e4){this.heartbeatInterval||(this.heartbeatInterval=setInterval(async()=>{if(this.connection.state===te.HubConnectionState.Connected)try{await this.hubProxy.reportStatus(this.config.containerId,{status:this.currentStatus,sessionId:this.currentSessionId??void 0,projectId:this.currentProjectId??void 0,tunnelUrl:this.tunnelUrl??void 0})}catch(t){console.error("[Heartbeat] Failed:",t instanceof Error?t.message:t)}},e),console.log(`[Heartbeat] Started (every ${e/1e3}s)`))}stopHeartbeat(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null,console.log("[Heartbeat] Stopped"))}async startTokenRefresh(){await this.refreshGitHubToken(),this.tokenRefreshInterval=setInterval(async()=>{await this.refreshGitHubToken()},3e6),console.log("[TokenRefresh] Started (refreshing every 50 minutes)")}stopTokenRefresh(){this.tokenRefreshInterval&&(clearInterval(this.tokenRefreshInterval),this.tokenRefreshInterval=null,console.log("[TokenRefresh] Stopped"))}async refreshGitHubToken(){try{let e=await this.hubProxy.refreshGitHubToken();if(!e.success){console.error(`[TokenRefresh] Failed: ${e.error}`);return}if(!e.token){console.error("[TokenRefresh] No token returned");return}if(await this.updateGitCredentials(e.token,e.repoFullName??void 0),e.expiresAt){let t=new Date(e.expiresAt).toISOString();console.log(`[TokenRefresh] Refreshed, expires: ${t}${e.repoFullName?` (repo: ${e.repoFullName})`:""}`)}else console.log("[TokenRefresh] Token refreshed (PAT mode, no expiry)");this.currentRepoFullName=e.repoFullName??null}catch(e){console.error("[TokenRefresh] Error:",e instanceof Error?e.message:e)}}async reportError(e){if(this.connection.state!==te.HubConnectionState.Connected){console.error("[SignalR] Cannot report error - not connected");return}try{let t={message:e.message,stackTrace:e.stackTrace,errorType:e.errorType,operation:e.operation,sessionId:e.sessionId??this.currentSessionId??void 0,isFatal:e.isFatal??!1},o=await this.hubProxy.reportError(this.config.containerId,t);o.success?console.log(`[Error Report] Reported: ${e.errorType??"Error"} - ${e.message}`):console.error(`[Error Report] Failed to report: ${o.error}`)}catch(t){console.error("[SignalR] Failed to report error:",t instanceof Error?t.message:t)}}async updateGitCredentials(e,t){let o=Kt.join(Wt.homedir(),".git-credentials"),s=`https://x-access-token:${e}@github.com
1357
+ `;if(await Gt.promises.writeFile(o,s,{mode:384}),t)try{let r=`https://x-access-token:${e}@github.com/${t}.git`;await jn(`git remote set-url origin "${r}"`,{cwd:"/workspace"})}catch(r){console.error("[TokenRefresh] Could not update remote URL:",r instanceof Error?r.message:r)}}};function On(n){let e=n.match(/name:\s*"([^"]+)"/);if(e)return e[1];let t=n.match(/^#\s+(.+)$/m);return t?t[1].trim():"Untitled Specification"}var Me=class{constructor(e,t){this.hubProxy=e;this.projectId=t}async saveSpecification(e,t){let o=On(t),s=await this.hubProxy.saveSpecification(this.projectId,e,o,t);if(!s.success)throw new Error(s.error||"Failed to save specification")}async getSpecification(e){let t=await this.hubProxy.getSpecification(this.projectId,e);return t.success&&t.content||null}async listSpecifications(){let e=await this.hubProxy.listSpecifications(this.projectId);return!e.success||!e.specifications?[]:e.specifications.map(t=>({slug:t.slug,name:t.name,status:t.status,version:"1.0.0"}))}async deleteSpecification(e){return(await this.hubProxy.deleteSpecification(this.projectId,e)).success}async specificationExists(e){let t=await this.hubProxy.getSpecification(this.projectId,e);return t.success&&t.content!=null}};import{exec as Nn,execSync as Un,spawn as Mn}from"child_process";import{promisify as Fn}from"util";import{createHash as Yt}from"crypto";import*as k from"fs";import*as U from"path";var Fe=class{domain;accountId;tunnelId;apiToken;zoneId;tunnelApiBase;constructor(){this.domain=process.env.CLOUDFLARE_DEPLOY_DOMAIN||process.env.DEPLOY_DOMAIN||"vibecodementor.net",this.accountId=process.env.CLOUDFLARE_ACCOUNT_ID||"",this.tunnelId=process.env.CLOUDFLARE_TUNNEL_ID||"",this.apiToken=process.env.CLOUDFLARE_API_TOKEN||"",this.zoneId=process.env.CLOUDFLARE_ZONE_ID||"",this.tunnelApiBase=`https://api.cloudflare.com/client/v4/accounts/${this.accountId}/cfd_tunnel/${this.tunnelId}/configurations`}isConfigured(){return!!(this.accountId&&this.tunnelId&&this.apiToken&&this.zoneId)}buildHostname(e){let t=this.domain.split("."),o=t.length>2?t.slice(-2).join("."):this.domain;return`${e}.${o}`}async addRoute(e,t){let o=this.buildHostname(e);if(console.log(`[TunnelManager] Adding route: ${o} -> localhost:${t}`),!this.isConfigured())return console.log("[TunnelManager] Not configured, skipping route addition"),`https://${o}`;try{let s=await this.getConfig(),r=s.ingress.findIndex(a=>a.hostname===o);if(r!==-1)s.ingress[r].service=`http://localhost:${t}`;else{let a=s.ingress.findIndex(l=>!l.hostname),c={hostname:o,service:`http://localhost:${t}`};a!==-1?s.ingress.splice(a,0,c):(s.ingress.push(c),s.ingress.push({service:"http_status:404"}))}await this.putConfig(s),await this.ensureDnsPointsToTunnel(o);let i=`https://${o}`;return console.log(`[TunnelManager] \u2713 Route added: ${i}`),i}catch(s){throw console.error("[TunnelManager] Failed to add route:",s),s}}async removeRoute(e){let t=this.buildHostname(e);if(console.log(`[TunnelManager] Removing route: ${t}`),!this.isConfigured()){console.log("[TunnelManager] Not configured, skipping route removal");return}try{let o=await this.getConfig();o.ingress=o.ingress.filter(s=>s.hostname!==t),o.ingress.some(s=>!s.hostname)||o.ingress.push({service:"http_status:404"}),await this.putConfig(o),console.log(`[TunnelManager] \u2713 Route removed: ${t}`)}catch(o){throw console.error("[TunnelManager] Failed to remove route:",o),o}}async getConfig(){let t=await(await fetch(this.tunnelApiBase,{method:"GET",headers:{Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"}})).json();if(!t.success)throw new Error(`Cloudflare API error: ${t.errors.map(o=>o.message).join(", ")}`);return t.result?.config||{ingress:[{service:"http_status:404"}]}}async putConfig(e){let o=await(await fetch(this.tunnelApiBase,{method:"PUT",headers:{Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},body:JSON.stringify({config:e})})).json();if(!o.success)throw new Error(`Cloudflare API error: ${o.errors.map(s=>s.message).join(", ")}`);console.log("[TunnelManager] Configuration updated via Cloudflare API")}async ensureDnsPointsToTunnel(e){let t=`${this.tunnelId}.cfargotunnel.com`,o=`https://api.cloudflare.com/client/v4/zones/${this.zoneId}/dns_records`;try{let r=await(await fetch(`${o}?name=${e}&type=CNAME`,{method:"GET",headers:{Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"}})).json();if(!r.success||!r.result?.length){console.log(`[TunnelManager] No DNS record found for ${e}, skipping DNS update`);return}let i=r.result[0];if(i.content===t){console.log(`[TunnelManager] DNS already points to correct tunnel: ${e}`);return}console.log(`[TunnelManager] Updating DNS: ${e} from ${i.content} to ${t}`);let c=await(await fetch(`${o}/${i.id}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.apiToken}`,"Content-Type":"application/json"},body:JSON.stringify({type:"CNAME",name:e,content:t,proxied:!0})})).json();c.success?console.log(`[TunnelManager] \u2713 DNS updated: ${e} -> ${t}`):console.error(`[TunnelManager] Failed to update DNS: ${c.errors.map(l=>l.message).join(", ")}`)}catch(s){console.error(`[TunnelManager] Error updating DNS for ${e}:`,s)}}};var Qt=Fn(Nn),I=class{start;label;constructor(e){this.label=e,this.start=Date.now(),console.log(`[TIMING] \u23F1 START: ${e}`)}stop(){let e=Date.now()-this.start,t=(e/1e3).toFixed(2);return console.log(`[TIMING] \u2713 DONE: ${this.label} (${t}s)`),e}};function N(n,e={}){return new Promise((t,o)=>{let s=Mn(n,[],{shell:!0,stdio:"inherit",cwd:e.cwd}),r=null;e.timeout&&(r=setTimeout(()=>{s.kill(),o(new Error(`Command timed out: ${n}`))},e.timeout)),s.on("close",i=>{r&&clearTimeout(r),i===0?t():o(new Error(`Command failed with code ${i}: ${n}`))}),s.on("error",i=>{r&&clearTimeout(r),o(i)})})}var Vt="main",Le=class{constructor(e,t,o,s){this.connection=e;this.serviceManager=t;this.workspaceDir=o;this.gitHubPat=s}currentBranchName=Vt;currentRepoUrl="";lastLockfileHash=null;tunnelManager=null;currentPreviewSubdomain=null;getTunnelManager(){return this.tunnelManager||(this.tunnelManager=new Fe),this.tunnelManager}async prewarmWorkspace(){let e=new I("TOTAL INIT"),t=process.env.REPO_URL,o=process.env.BRANCH_NAME||Vt,s=process.env.PREVIEW_SUBDOMAIN,r=process.env.PREVIEW_HOSTNAME,i=process.env.PROJECT_GITHUB_PAT;if(console.log("[Init] Starting single-phase init..."),console.log(`[Init] Repo: ${t?this.extractRepoPath(t):"NOT SET"}`),console.log(`[Init] Branch: ${o}`),console.log(`[Init] Preview: ${s||"none"}`),!t)throw console.error("[Init] \u274C REPO_URL not set - cannot initialize workspace"),new Error("REPO_URL environment variable is required");i&&(this.gitHubPat=i);let a=new I("Clean workspace");Un("rm -rf /workspace/* /workspace/.* 2>/dev/null || true",{stdio:"inherit"}),a.stop();let c=new I("Clone repository");await this.cloneRepository(t,o),this.currentRepoUrl=t,this.currentBranchName=o,c.stop(),await this.installDependencies(),this.lastLockfileHash=this.getLockfileHash(),console.log("[Init] Starting services...");let l=new I("Start backend (dotnet)");await this.serviceManager.startBackend(),l.stop();let u=new I("Start frontend (vite)");await this.serviceManager.startFrontend(),u.stop();let d=new I("Wait for health check");await this.serviceManager.waitForHealth(3e4),d.stop(),s&&r&&await this.setupPreviewSubdomainFromEnv(s,r),await this.connection.startTokenRefresh(),e.stop(),console.log("[Init] \u2713 Workspace ready")}async handleInitSession(e){console.log(`[InitSession] Session ${e.sessionId} starting...`);let t=this.extractRepoPath(e.repoUrl),o=this.extractRepoPath(this.currentRepoUrl),s=t!==o,r=e.branchName!==this.currentBranchName;s||r?(console.log("[InitSession] Repo/branch mismatch - updating workspace..."),console.log(`[InitSession] Current: ${o}@${this.currentBranchName}`),console.log(`[InitSession] Requested: ${t}@${e.branchName}`),await this.connection.reportStatus("Ready",void 0,e.sessionId,e.projectId),await this.connection.getHubProxy().initSessionCompleted(process.env.CONTAINER_ID||"unknown",e.sessionId,!0,""),this.handleRepoChange(e).catch(async a=>{let c=a instanceof Error?a.message:"Unknown error";console.error("[InitSession] Background update failed:",c),await this.connection.reportStatus("Error",c,e.sessionId,e.projectId)})):(console.log("[InitSession] Workspace already matches - ready immediately"),await this.connection.reportStatus("Ready",void 0,e.sessionId,e.projectId),await this.connection.getHubProxy().initSessionCompleted(process.env.CONTAINER_ID||"unknown",e.sessionId,!0,"")),console.log(`[InitSession] \u2713 Ready for session ${e.sessionId}`)}async setupPreviewSubdomainFromEnv(e,t){let o=new I("Setup preview subdomain");console.log(`[Preview] Setting up preview subdomain: ${e} (${t})`);let s=this.getTunnelManager();if(!s){console.log("[Preview] TunnelManager not available, skipping subdomain setup"),o.stop();return}if(!s.isConfigured()){console.log("[Preview] Cloudflare not configured, skipping subdomain setup"),o.stop();return}try{let r=parseInt(process.env.ALLOCATED_HOST_PORT||"5173"),i=await s.addRoute(e,r);this.currentPreviewSubdomain=e,this.connection.setTunnelUrl(i),o.stop(),console.log(`[Preview] \u2713 Preview subdomain configured: ${i}`)}catch(r){o.stop(),console.error("[Preview] Failed to set up subdomain route:",r)}}async handleRepoChange(e){let t=new I("TOTAL REPO CHANGE");e.gitHubPat&&e.gitHubPat!==this.gitHubPat&&(console.log("[RepoChange] Updating git credentials"),this.gitHubPat=e.gitHubPat,await N(`echo "https://${e.gitHubPat}@github.com" > ~/.git-credentials`));let o=this.extractRepoPath(e.repoUrl),s=this.extractRepoPath(this.currentRepoUrl);if(o!==s){let i=new I("Clone new repository");await this.cloneRepository(e.repoUrl,e.branchName),this.currentRepoUrl=e.repoUrl,this.currentBranchName=e.branchName,i.stop(),await this.installDependencies();let a=new I("Restart services");await this.serviceManager.restartServices("both"),a.stop()}else{let i=new I(`Switch branch to ${e.branchName}`);await this.switchBranch(e.branchName),i.stop(),await this.checkNeedsReinstall()&&await this.installDependencies();let c=new I("Restart services");await this.serviceManager.restartServices("both"),c.stop()}e.previewSubdomain&&e.previewHostname&&await this.setupPreviewSubdomainFromEnv(e.previewSubdomain,e.previewHostname),t.stop(),console.log("[RepoChange] \u2713 Workspace updated")}extractRepoPath(e){let t=e.match(/github\.com[:/]([^/]+\/[^/]+?)(?:\.git)?$/);return t?t[1]:e}async cloneRepository(e,t){console.log(`[Clone] Clearing workspace and cloning ${this.extractRepoPath(e)} @ ${t}`),await N("rm -rf /workspace/* /workspace/.* 2>/dev/null || true");try{await N(`git clone -b ${t} "${e}" /workspace`,{timeout:12e4})}catch(o){let s=o instanceof Error?o.message:String(o);throw await this.connection.reportError({message:`Git clone failed: ${s}`,errorType:"GitCloneError",operation:"cloneRepository",isFatal:!0}),o}await N('cd /workspace && git config user.email "agent@dotnetmentor.se" && git config user.name "Agent"'),console.log("[Clone] \u2713 Repository cloned")}async switchBranch(e){if(console.log(`[Branch] Switching from ${this.currentBranchName} to ${e}`),e===this.currentBranchName)console.log(`[Branch] Already on ${e}, pulling latest...`),await N(`git pull origin ${e}`,{cwd:this.workspaceDir,timeout:6e4});else{await N("git fetch origin",{cwd:this.workspaceDir,timeout:6e4});let{stdout:t}=await Qt(`git ls-remote --heads origin ${e}`,{cwd:this.workspaceDir,timeout:3e4});t.trim().length>0?await N(`git checkout -B ${e} origin/${e}`,{cwd:this.workspaceDir,timeout:3e4}):(console.log(`[Branch] Branch ${e} doesn't exist on remote, creating from main...`),await N(`git checkout -b ${e}`,{cwd:this.workspaceDir,timeout:3e4})),this.currentBranchName=e}console.log(`[Branch] \u2713 Now on ${e}`)}getLockfileHash(){let e=U.join(this.workspaceDir,"packages/backoffice-web/package-lock.json");return k.existsSync(e)?Yt("sha256").update(k.readFileSync(e)).digest("hex"):null}async checkNeedsReinstall(){let e=this.getLockfileHash();return!e||!this.lastLockfileHash?!0:e!==this.lastLockfileHash}async checkCodeDiff(e,t){if(e===t)return!1;try{let{stdout:o}=await Qt(`git diff ${e}..HEAD --name-only`,{cwd:this.workspaceDir,timeout:3e4}),s=o.trim();if(!s)return console.log(`[CodeDiff] No file differences between ${e} and ${t}`),!1;let r=s.split(`
1358
+ `).filter(c=>c.length>0);console.log(`[CodeDiff] ${r.length} files changed between ${e} and ${t}`);let i=[".cs",".tsx",".ts",".json",".csproj"],a=r.some(c=>i.some(l=>c.endsWith(l)));return a&&console.log("[CodeDiff] Found code changes that require service restart"),a}catch(o){return console.error("[CodeDiff] Failed to check diff:",o instanceof Error?o.message:o),!0}}async installDependencies(){let e=new I("TOTAL INSTALL DEPENDENCIES");if(k.existsSync(U.join(this.workspaceDir,"packages/dotnet-api"))){let t=new I("dotnet restore");await N("dotnet restore",{cwd:U.join(this.workspaceDir,"packages/dotnet-api"),timeout:12e4}),t.stop()}if(k.existsSync(U.join(this.workspaceDir,"packages/backoffice-web/package.json"))){let t=U.join(this.workspaceDir,"packages/backoffice-web"),o=U.join(t,"node_modules"),s=U.join(t,"package-lock.json"),r=U.join(o,".lockhash"),i="/opt/cache";k.mkdirSync(i,{recursive:!0});let a=k.existsSync(s)?Yt("sha256").update(k.readFileSync(s)).digest("hex"):null,c=k.existsSync(r)?k.readFileSync(r,"utf-8").trim():null,l=U.join(i,"node_modules","current_hash"),u=k.existsSync(l)?k.readFileSync(l,"utf-8").trim():null,d=u?U.join(i,"node_modules",u):null,g=a?U.join(i,"node_modules",a):null;if(console.log(`[Install] node_modules exists: ${k.existsSync(o)}`),console.log(`[Install] lockHash (current branch): ${a?.substring(0,8)||"null"}`),console.log(`[Install] installedHash: ${c?.substring(0,8)||"null"}`),console.log(`[Install] dockerCacheHash (from image): ${u?.substring(0,8)||"null"}`),console.log(`[Install] exactMatchCache exists: ${g?k.existsSync(g):!1}`),console.log(`[Install] dockerCachedNodeModules exists: ${d?k.existsSync(d):!1}`),!k.existsSync(o)){if(g&&k.existsSync(g)){let v=new I("Copy exact-match cached node_modules");console.log(`[Install] Copying exact-match cached node_modules (hash ${a?.substring(0,8)})...`),await N(`cp -r "${g}" "${o}"`),a&&k.writeFileSync(r,a),c=a,v.stop()}else if(d&&k.existsSync(d)){let v=new I("Copy Docker-cached node_modules (as base)");console.log(`[Install] Copying Docker-cached node_modules as base (hash ${u?.substring(0,8)}, need ${a?.substring(0,8)})...`),await N(`cp -r "${d}" "${o}"`),v.stop()}}let w=!k.existsSync(o)||a&&a!==c;if(console.log(`[Install] needsInstall: ${w}`),!w)console.log("[Install] npm install skipped (cache OK)");else{let v=new I("npm install --prefer-offline");await N("npm install --prefer-offline --no-progress --fund=false",{cwd:t,timeout:18e4}),v.stop(),a&&(k.mkdirSync(o,{recursive:!0}),k.writeFileSync(r,a))}this.lastLockfileHash=a}e.stop()}};function zt(n,e,t){let o=n.getHubProxy(),s=process.env.CONTAINER_ID||"unknown";return{onAssistantText:async r=>{let i={type:"Text",content:r,isError:!1};await o.reportSessionOutput(s,e,i).catch(a=>{console.error("Failed to report assistant text:",a)})},onAssistantToolUse:async(r,i)=>{if(["Write","Edit","MultiEdit"].includes(r)){let c=i,l=c.file_path||c.target_file;l&&t.onFileModified(l)}let a={type:"ToolUse",toolName:r,toolInput:JSON.stringify(i),isError:!1};await o.reportSessionOutput(s,e,a).catch(c=>{console.error("Failed to report tool use:",c)})},onResult:async(r,i)=>{let a={type:"System",event:"completed",content:r,cost:i,isError:!1};await o.reportSessionOutput(s,e,a).catch(c=>{console.error("Failed to report result:",c)})},onError:async r=>{let i={type:"System",event:"error",content:r,isError:!0};await o.reportSessionOutput(s,e,i).catch(a=>{console.error("Failed to report error:",a)})},onAborted:async()=>{let r={type:"System",event:"aborted",content:"Agent stopped by user",isError:!1};await o.reportSessionOutput(s,e,r).catch(i=>{console.error("Failed to report abort:",i)})},onSystemInit:async r=>{console.log(`[Callbacks] Claude session initialized: ${r}`),t.onClaudeSessionId(r),await o.setClaudeSessionId(e,r).catch(i=>{console.error("Failed to set Claude session ID:",i)})},onRawMessage:r=>{if(r.type==="assistant"&&r.message?.usage){let i=r.message.usage,a={totalCostUsd:Ln(i),inputTokens:i.input_tokens||0,outputTokens:i.output_tokens||0,cacheCreationTokens:i.cache_creation_input_tokens||0,cacheReadTokens:i.cache_read_input_tokens||0};o.reportSessionCost(s,e,a).catch(c=>{console.error("Failed to report cost:",c)})}}}}var $e={inputPerMillion:3,outputPerMillion:15,cacheReadPerMillion:.3,cacheCreationPerMillion:3.75};function Ln(n){return(n.input_tokens||0)/1e6*$e.inputPerMillion+(n.output_tokens||0)/1e6*$e.outputPerMillion+(n.cache_read_input_tokens||0)/1e6*$e.cacheReadPerMillion+(n.cache_creation_input_tokens||0)/1e6*$e.cacheCreationPerMillion}import*as ae from"fs";import*as Jt from"path";function Xt(n,e){let t=Jt.join(n,`.agent-questions-${e}.json`);if(!ae.existsSync(t))return null;try{let o=ae.readFileSync(t,"utf-8");return ae.unlinkSync(t),JSON.parse(o)}catch(o){return console.error("Failed to read questions file:",o),null}}async function Zt(n,e,t,o){if(e.size===0)return console.log("[TypeCheck] No code changes, skipping type checks"),{passed:!0};let s=o?B(o):`${t}/packages/dotnet-api`,r=o?q(o):`${t}/packages/backoffice-web`,i=o?.services?.backend?.extensions??[".cs",".csproj"],a=o?.services?.frontend?.extensions??[".ts",".tsx"],c=s&&[...e].some(g=>g.includes(s)||i.some(w=>g.endsWith(w))),l=r&&[...e].some(g=>g.includes(r)||a.some(w=>g.endsWith(w)));if(!c&&!l)return console.log("[TypeCheck] No code changes, skipping type checks"),{passed:!0};let u=[];c&&u.push("backend"),l&&u.push("frontend"),console.log(`[TypeCheck] Checking ${u.join(" & ")}...`);let d=[];if(c){let g=await n.checkBackendBuild();!g.success&&g.errors&&d.push(`## Backend Build Errors (in ${s})
1359
1359
  \`\`\`
1360
1360
  ${g.errors}
1361
1361
  \`\`\``)}if(l){let g=await n.checkFrontendTypes();!g.success&&g.errors&&d.push(`## Frontend Type Errors (in ${r})
@@ -1369,24 +1369,24 @@ ${d.join(`
1369
1369
 
1370
1370
  `)}
1371
1371
 
1372
- File paths like "src/..." are relative to the package directory shown in parentheses.`}):(console.log("[TypeCheck] \u2713 All type checks passed"),{passed:!0})}async function ht(n,e,t,o,s){if(!await n.hasChanges()){console.log("[Git] No changes to commit");return}console.log("[Git] Committing changes...");let i=await n.commitAndPush(o,s);if(i.noChanges)console.log("[Git] No changes to commit");else if(i.pushFailed){let a=await n.getCurrentBranch();console.log(`[Git] \u2713 Committed ${i.commitHash||""}`),console.error(`[Git] \u274C Push failed: ${i.error}`),await e.getHubProxy().reportSessionOutput(process.env.CONTAINER_ID||"unknown",t,{type:"System",event:"push_failed",content:`Committed locally but failed to push to ${a}. Your changes are NOT on GitHub. Error: ${i.error}`,isError:!0}).catch(l=>{console.error("[Git] Failed to report push failure:",l)})}else if(i.success){let a=await n.getCurrentBranch();console.log(`[Git] \u2713 Committed ${i.commitHash||""}`),console.log(`[Git] \u2192 Pushed to ${a}`),await e.getHubProxy().reportSessionOutput(process.env.CONTAINER_ID||"unknown",t,{type:"System",event:"committed",content:`Changes committed to ${a}`,isError:!1}).catch(l=>{console.error("[Git] Failed to report commit:",l)})}else console.error(`[Git] \u274C Git error: ${i.error}`)}var $e=class{constructor(e,t,o,s,r=!0,i=!0,a,c,l=!0){this.connection=e;this.lifecycle=t;this.serviceManager=o;this.workspaceDir=s;this.enableAutoTypecheck=r;this.enableAutoCommit=i;this.setupPlanningTransport=a;this.projectConfig=c;this.useDefaultStack=l;this.gitManager=Oe(s)}currentSession=null;claudeSessionIdMap=new Map;currentAbortController=null;gitManager;async initSession(e){console.log(`[Receiver] InitSession for session ${e.sessionId}`),this.setupPlanningTransport&&e.projectId&&this.setupPlanningTransport(e.projectId),e.projectId&&await this.fetchProjectPrompt(e.projectId),this.currentSession={sessionId:e.sessionId,projectId:e.projectId,branchName:e.branchName,model:e.model==="auto"?void 0:e.model||"claude-haiku-4-5-20251001",debugMode:e.debugMode},await this.lifecycle.handleInitSession(e),e.prompt&&await this.runPrompt(e.sessionId,e.prompt,e.claudeSessionId)}async runPrompt(e,t,o,s=!1){let r=ue(t);if(console.log(`[Receiver] RunPrompt for session ${e}${o?` (ClaudeSessionId: ${o})`:""}${s?" [DEBUG MODE]":""}: ${r.substring(0,50)}...`),(!this.currentSession||this.currentSession.sessionId!==e)&&(console.log(`[Receiver] Session mismatch: expected ${this.currentSession?.sessionId}, got ${e}, switching...`),await this.switchSession(e),!this.currentSession)){console.error("[Receiver] Failed to create session context");return}let i=this.claudeSessionIdMap.get(e);if(o&&i!==o){console.warn(`[Receiver] Claude session not found in container: ${o}`);let l=this.connection.getHubProxy();await l.reportSessionOutput(process.env.CONTAINER_ID||"unknown",e,{type:"System",event:"sessionNotFound",content:o,isError:!0}),await this.connection.reportStatus("Ready","Session lost - summary needed",e,this.currentSession.projectId),await l.sessionCompleted(process.env.CONTAINER_ID||"unknown",e,0);return}await this.connection.reportStatus("Active",void 0,e,this.currentSession.projectId),this.currentSession.debugMode=s,this.currentAbortController=new AbortController;let a=i||null,c=new Set;try{let l=await De(r,{model:this.currentSession.model,sessionId:a||null,projectId:this.currentSession.projectId||null,apiUrl:this.connection.getMasterUrl(),debugLog:!0,debugMode:s,abortController:this.currentAbortController,projectConfig:this.projectConfig,useDefaultStack:this.useDefaultStack,callbacks:Qt(this.connection,e,{onClaudeSessionId:g=>{this.claudeSessionIdMap.set(e,g)},onFileModified:g=>{c.add(g)}})}),u=zt(this.workspaceDir,e);if(u&&u.length>0){console.log(`[Receiver] ${u.length} pending questions found, waiting for user answers`),await this.connection.reportStatus("Ready",void 0,e,this.currentSession.projectId),await this.connection.getHubProxy().sessionCompleted(process.env.CONTAINER_ID||"unknown",e,0);return}if(this.enableAutoTypecheck&&!l.error&&!l.aborted){let g=await Jt(this.serviceManager,c,this.workspaceDir,this.projectConfig);if(!g.passed&&g.errorPrompt){console.log("[Receiver] Type errors detected, auto-correcting..."),await this.runPrompt(e,g.errorPrompt,o);return}}this.enableAutoCommit&&!l.error&&!l.aborted?await ht(this.gitManager,this.connection,e,t,!1):(l.error||l.aborted)&&this.enableAutoCommit&&await ht(this.gitManager,this.connection,e,t,!0),await this.connection.reportStatus("Ready",void 0,e,this.currentSession.projectId),await this.connection.getHubProxy().sessionCompleted(process.env.CONTAINER_ID||"unknown",e,l.error?1:0)}catch(l){let u=l instanceof Error&&l.name==="AbortError",d=l instanceof Error?l.message:"Unknown error";u?console.log(`[Receiver] Agent aborted for session ${e}`):(console.error("[Receiver] Agent error:",d),await this.connection.reportStatus("Error",d,e,this.currentSession.projectId)),await this.connection.getHubProxy().sessionCompleted(process.env.CONTAINER_ID||"unknown",e,u?0:1)}finally{this.currentAbortController=null}}async setModel(e){console.log(`[Receiver] Model changed to: ${e}`),this.currentSession&&(this.currentSession.model=e==="auto"?void 0:e)}async stopAgent(){console.log("[Receiver] Stop command received"),this.currentAbortController&&this.currentAbortController.abort()}async ping(){await this.connection.getConnection().invoke("Pong",process.env.CONTAINER_ID||"unknown")}async switchSession(e){console.log(`[Receiver] SwitchSession to ${e}`),this.currentSession?this.currentSession.sessionId=e:(console.log(`[Receiver] Creating new session context for ${e}`),this.currentSession={sessionId:e,projectId:process.env.PROJECT_ID||"unknown",branchName:"main",model:void 0,debugMode:!1})}async projectPromptUpdated(e){console.log(`[Receiver] ProjectPromptUpdated received (${e.length} chars)`),Qe(e)}async fetchProjectPrompt(e){try{let t=this.connection.getMasterUrl(),o=this.connection.getProjectKey(),s=await fetch(`${t}/api/projects/${e}/prompt`,{method:"GET",headers:{"Content-Type":"application/json","X-Project-Key":o}});if(!s.ok){console.log(`[Receiver] Failed to fetch project prompt: ${s.status}`);return}let r=await s.json();r.prompt?(Qe(r.prompt),console.log(`[Receiver] Initial project prompt loaded (${r.prompt.length} chars)`)):console.log(`[Receiver] No project prompt set for project ${e}`)}catch(t){console.error("[Receiver] Error fetching project prompt:",t)}}};process.env.CLAUDE_CODE_STREAM_CLOSE_TIMEOUT=process.env.CLAUDE_CODE_STREAM_CLOSE_TIMEOUT||"60000";var Xt=V.dirname(Mn(import.meta.url));function Ln(){let n=[V.resolve(Xt,"../package.json"),V.resolve(Xt,"../../../package.json")];for(let e of n)try{if(F.existsSync(e)){let t=JSON.parse(F.readFileSync(e,"utf-8"));if(t.name==="glenn-code")return t.version||"unknown"}}catch{}return"unknown"}function $n(n){let{useDefaultStack:e,projectConfig:t,configSource:o,tunnelPort:s,enableAutoTypecheck:r,enableAutoCommit:i}=n;if(console.log(`
1372
+ File paths like "src/..." are relative to the package directory shown in parentheses.`}):(console.log("[TypeCheck] \u2713 All type checks passed"),{passed:!0})}async function bt(n,e,t,o,s){if(!await n.hasChanges()){console.log("[Git] No changes to commit");return}console.log("[Git] Committing changes...");let i=await n.commitAndPush(o,s);if(i.noChanges)console.log("[Git] No changes to commit");else if(i.pushFailed){let a=await n.getCurrentBranch();console.log(`[Git] \u2713 Committed ${i.commitHash||""}`),console.error(`[Git] \u274C Push failed: ${i.error}`),await e.getHubProxy().reportSessionOutput(process.env.CONTAINER_ID||"unknown",t,{type:"System",event:"push_failed",content:`Committed locally but failed to push to ${a}. Your changes are NOT on GitHub. Error: ${i.error}`,isError:!0}).catch(l=>{console.error("[Git] Failed to report push failure:",l)})}else if(i.success){let a=await n.getCurrentBranch();console.log(`[Git] \u2713 Committed ${i.commitHash||""}`),console.log(`[Git] \u2192 Pushed to ${a}`),await e.getHubProxy().reportSessionOutput(process.env.CONTAINER_ID||"unknown",t,{type:"System",event:"committed",content:`Changes committed to ${a}`,isError:!1}).catch(l=>{console.error("[Git] Failed to report commit:",l)})}else console.error(`[Git] \u274C Git error: ${i.error}`)}import*as V from"fs";import*as Be from"path";var He=class{constructor(e,t,o,s,r=!0,i=!0,a,c,l=!0){this.connection=e;this.lifecycle=t;this.serviceManager=o;this.workspaceDir=s;this.enableAutoTypecheck=r;this.enableAutoCommit=i;this.setupPlanningTransport=a;this.projectConfig=c;this.useDefaultStack=l;this.gitManager=Ne(s),this.claudeSessionIdMap=this.loadSessionMap()}currentSession=null;claudeSessionIdMap=new Map;currentAbortController=null;gitManager;get sessionMapPath(){return Be.join(this.workspaceDir,".sdd","claude-session-map.json")}loadSessionMap(){try{if(V.existsSync(this.sessionMapPath)){let e=JSON.parse(V.readFileSync(this.sessionMapPath,"utf-8")),t=new Map(Object.entries(e));return console.log(`[Receiver] Loaded ${t.size} claude session mappings from disk`),t}}catch(e){console.warn("[Receiver] Failed to load session map from disk:",e)}return new Map}persistSessionMap(){try{let e=Be.dirname(this.sessionMapPath);V.existsSync(e)||V.mkdirSync(e,{recursive:!0});let t=Object.fromEntries(this.claudeSessionIdMap);V.writeFileSync(this.sessionMapPath,JSON.stringify(t,null,2))}catch(e){console.warn("[Receiver] Failed to persist session map to disk:",e)}}async initSession(e){console.log(`[Receiver] InitSession for session ${e.sessionId}`),this.setupPlanningTransport&&e.projectId&&this.setupPlanningTransport(e.projectId),e.projectId&&await this.fetchProjectPrompt(e.projectId),this.currentSession={sessionId:e.sessionId,projectId:e.projectId,branchName:e.branchName,model:e.model==="auto"?void 0:e.model||"claude-haiku-4-5-20251001",debugMode:e.debugMode},await this.lifecycle.handleInitSession(e),e.prompt&&await this.runPrompt(e.sessionId,e.prompt,e.claudeSessionId)}async runPrompt(e,t,o,s=!1){let r=ge(t);if(console.log(`[Receiver] RunPrompt for session ${e}${o?` (ClaudeSessionId: ${o})`:""}${s?" [DEBUG MODE]":""}: ${r.substring(0,50)}...`),(!this.currentSession||this.currentSession.sessionId!==e)&&(console.log(`[Receiver] Session mismatch: expected ${this.currentSession?.sessionId}, got ${e}, switching...`),await this.switchSession(e),!this.currentSession)){console.error("[Receiver] Failed to create session context");return}let i=this.claudeSessionIdMap.get(e);if(o&&i!==o){console.warn(`[Receiver] Claude session not found in container: ${o}`);let l=this.connection.getHubProxy();await l.reportSessionOutput(process.env.CONTAINER_ID||"unknown",e,{type:"System",event:"sessionNotFound",content:o,isError:!0}),await this.connection.reportStatus("Ready","Session lost - summary needed",e,this.currentSession.projectId),await l.sessionCompleted(process.env.CONTAINER_ID||"unknown",e,0);return}await this.connection.reportStatus("Active",void 0,e,this.currentSession.projectId),this.currentSession.debugMode=s,this.currentAbortController=new AbortController;let a=i||null,c=new Set;try{let l=await je(r,{model:this.currentSession.model,sessionId:a||null,projectId:this.currentSession.projectId||null,apiUrl:this.connection.getMasterUrl(),debugLog:!0,debugMode:s,abortController:this.currentAbortController,projectConfig:this.projectConfig,useDefaultStack:this.useDefaultStack,callbacks:zt(this.connection,e,{onClaudeSessionId:g=>{this.claudeSessionIdMap.set(e,g),this.persistSessionMap()},onFileModified:g=>{c.add(g)}})}),u=Xt(this.workspaceDir,e);if(u&&u.length>0){console.log(`[Receiver] ${u.length} pending questions found, waiting for user answers`),await this.connection.reportStatus("Ready",void 0,e,this.currentSession.projectId),await this.connection.getHubProxy().sessionCompleted(process.env.CONTAINER_ID||"unknown",e,0);return}if(this.enableAutoTypecheck&&!l.error&&!l.aborted){let g=await Zt(this.serviceManager,c,this.workspaceDir,this.projectConfig);if(!g.passed&&g.errorPrompt){console.log("[Receiver] Type errors detected, auto-correcting..."),await this.runPrompt(e,g.errorPrompt,o);return}}this.enableAutoCommit&&!l.error&&!l.aborted?await bt(this.gitManager,this.connection,e,t,!1):(l.error||l.aborted)&&this.enableAutoCommit&&await bt(this.gitManager,this.connection,e,t,!0),await this.connection.reportStatus("Ready",void 0,e,this.currentSession.projectId),await this.connection.getHubProxy().sessionCompleted(process.env.CONTAINER_ID||"unknown",e,l.error?1:0)}catch(l){let u=l instanceof Error&&l.name==="AbortError",d=l instanceof Error?l.message:"Unknown error";u?console.log(`[Receiver] Agent aborted for session ${e}`):(console.error("[Receiver] Agent error:",d),await this.connection.reportStatus("Error",d,e,this.currentSession.projectId)),await this.connection.getHubProxy().sessionCompleted(process.env.CONTAINER_ID||"unknown",e,u?0:1)}finally{this.currentAbortController=null}}async setModel(e){console.log(`[Receiver] Model changed to: ${e}`),this.currentSession&&(this.currentSession.model=e==="auto"?void 0:e)}async stopAgent(){console.log("[Receiver] Stop command received"),this.currentAbortController&&this.currentAbortController.abort()}async ping(){await this.connection.getConnection().invoke("Pong",process.env.CONTAINER_ID||"unknown")}async switchSession(e){console.log(`[Receiver] SwitchSession to ${e}`),this.currentSession?this.currentSession.sessionId=e:(console.log(`[Receiver] Creating new session context for ${e}`),this.currentSession={sessionId:e,projectId:process.env.PROJECT_ID||"unknown",branchName:"main",model:void 0,debugMode:!1})}async projectPromptUpdated(e){console.log(`[Receiver] ProjectPromptUpdated received (${e.length} chars)`),ze(e)}async fetchProjectPrompt(e){try{let t=this.connection.getMasterUrl(),o=this.connection.getProjectKey(),s=await fetch(`${t}/api/projects/${e}/prompt`,{method:"GET",headers:{"Content-Type":"application/json","X-Project-Key":o}});if(!s.ok){console.log(`[Receiver] Failed to fetch project prompt: ${s.status}`);return}let r=await s.json();r.prompt?(ze(r.prompt),console.log(`[Receiver] Initial project prompt loaded (${r.prompt.length} chars)`)):console.log(`[Receiver] No project prompt set for project ${e}`)}catch(t){console.error("[Receiver] Error fetching project prompt:",t)}}};process.env.CLAUDE_CODE_STREAM_CLOSE_TIMEOUT=process.env.CLAUDE_CODE_STREAM_CLOSE_TIMEOUT||"60000";var en=z.dirname($n(import.meta.url));function Hn(){let n=[z.resolve(en,"../package.json"),z.resolve(en,"../../../package.json")];for(let e of n)try{if(M.existsSync(e)){let t=JSON.parse(M.readFileSync(e,"utf-8"));if(t.name==="glenn-code")return t.version||"unknown"}}catch{}return"unknown"}function Bn(n){let{useDefaultStack:e,projectConfig:t,configSource:o,tunnelPort:s,enableAutoTypecheck:r,enableAutoCommit:i}=n;if(console.log(`
1373
1373
  \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557`),console.log("\u2551 AGENT CONFIGURATION \u2551"),console.log("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),e?(console.log("\u2551 Mode: DEFAULT STACK (.NET/React) \u2551"),console.log("\u2551 Agents: scaffolding, backend, frontend, debugger, \u2551"),console.log("\u2551 planning, project-context \u2551")):(console.log("\u2551 Mode: CUSTOM STACK (generic agents only) \u2551"),console.log("\u2551 Agents: debugger, planning, project-context \u2551")),console.log("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),console.log(`\u2551 Config source: ${o.padEnd(42)}\u2551`),console.log("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),console.log("\u2551 SERVICES: \u2551"),t.services?.backend){let a=t.services.backend;console.log(`\u2551 Backend: port ${a.port}, extensions: ${a.extensions?.join(", ")||"N/A"}`.padEnd(62)+"\u2551")}else console.log("\u2551 Backend: not configured \u2551");if(t.services?.frontend){let a=t.services.frontend;console.log(`\u2551 Frontend: port ${a.port}, extensions: ${a.extensions?.join(", ")||"N/A"}`.padEnd(62)+"\u2551")}else console.log("\u2551 Frontend: not configured \u2551");t.techStack&&(console.log("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),console.log("\u2551 TECH STACK: \u2551"),t.techStack.backend?.length&&console.log(`\u2551 Backend: ${t.techStack.backend.join(", ")}`.padEnd(62)+"\u2551"),t.techStack.frontend?.length&&console.log(`\u2551 Frontend: ${t.techStack.frontend.join(", ")}`.padEnd(62)+"\u2551"),t.techStack.patterns?.length&&console.log(`\u2551 Patterns: ${t.techStack.patterns.join(", ")}`.padEnd(62)+"\u2551")),console.log("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),console.log("\u2551 SETTINGS: \u2551"),console.log(`\u2551 Tunnel port: ${s}`.padEnd(62)+"\u2551"),console.log(`\u2551 Auto-typecheck: ${r?"enabled":"disabled"}`.padEnd(62)+"\u2551"),console.log(`\u2551 Auto-commit: ${i?"enabled":"disabled"}`.padEnd(62)+"\u2551"),console.log(`\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D
1374
- `)}var Hn=".sdd/local-signalr-config.json";function bt(n){return V.join(n,Hn)}function Bn(n){try{let e=bt(n);if(!F.existsSync(e))return null;let t=F.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return null}}function yt(n,e){let t=V.dirname(bt(n));F.existsSync(t)||F.mkdirSync(t,{recursive:!0}),F.writeFileSync(bt(n),JSON.stringify(e,null,2))}function He(){return`local-${en.hostname().toLowerCase().replace(/[^a-z0-9]/g,"-")}-${Date.now().toString(36)}`}function qn(n){return!!(n.version||n.paths||n.services||n.techStack)}function Gn(n,e){return qn(n)?{version:n.version||"1.0",paths:n.paths||{workspace:e},services:n.services,techStack:n.techStack,tunnel:n.tunnel,scaffold:n.scaffold,git:n.git}:null}async function Wn(n){console.log(`
1374
+ `)}var qn=".sdd/local-signalr-config.json";function wt(n){return z.join(n,qn)}function Gn(n){try{let e=wt(n);if(!M.existsSync(e))return null;let t=M.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return null}}function St(n,e){let t=z.dirname(wt(n));M.existsSync(t)||M.mkdirSync(t,{recursive:!0}),M.writeFileSync(wt(n),JSON.stringify(e,null,2))}function qe(){return`local-${nn.hostname().toLowerCase().replace(/[^a-z0-9]/g,"-")}-${Date.now().toString(36)}`}function Wn(n){return!!(n.version||n.paths||n.services||n.techStack)}function Kn(n,e){return Wn(n)?{version:n.version||"1.0",paths:n.paths||{workspace:e},services:n.services,techStack:n.techStack,tunnel:n.tunnel,scaffold:n.scaffold,git:n.git}:null}async function Yn(n){console.log(`
1375
1375
  \u{1F527} Interactive Project Config Builder
1376
1376
  `),console.log(" Answer the following questions to configure your project."),console.log(` Press Enter to skip optional questions.
1377
1377
  `);let{projectType:e}=await G.prompt([{type:"select",name:"projectType",message:"What type of project is this?",choices:[{name:"Frontend only (React, Next.js, Vue, etc.)",value:"frontend"},{name:"Backend only (Node, Python, Go, etc.)",value:"backend"},{name:"Fullstack (Frontend + Backend)",value:"fullstack"},{name:"Skip - use default .NET/React stack",value:"skip"}]}]);if(e==="skip")return null;let t={version:"1.0",paths:{workspace:"."}};if(e==="frontend"||e==="fullstack"){console.log(`
1378
1378
  \u{1F4F1} Frontend Configuration:`);let s=await G.prompt([{type:"input",name:"path",message:"Frontend path (relative to workspace):",default:e==="fullstack"?"./frontend":"."},{type:"number",name:"port",message:"Dev server port:",default:3e3},{type:"input",name:"startCommand",message:"Start command (or Enter to skip):",default:"npm run dev"},{type:"input",name:"typecheckCommand",message:"Typecheck command (or Enter to skip):",default:"npx tsc --noEmit"},{type:"input",name:"extensions",message:"File extensions (comma-separated):",default:".ts,.tsx,.js,.jsx"}]);t.paths={workspace:t.paths?.workspace||".",...t.paths,frontend:s.path||"."},t.services={...t.services,frontend:{port:s.port||3e3,startCommand:s.startCommand||"npm run dev",typecheckCommand:s.typecheckCommand||void 0,extensions:s.extensions?s.extensions.split(",").map(r=>r.trim()):[".ts",".tsx",".js",".jsx"]}},t.tunnel={enabled:!0,port:s.port||3e3}}if(e==="backend"||e==="fullstack"){console.log(`
1379
1379
  \u2699\uFE0F Backend Configuration:`);let s=await G.prompt([{type:"input",name:"path",message:"Backend path (relative to workspace):",default:e==="fullstack"?"./backend":"."},{type:"number",name:"port",message:"API server port:",default:8080},{type:"input",name:"startCommand",message:"Start command (or Enter to skip):",default:""},{type:"input",name:"buildCommand",message:"Build command (or Enter to skip):",default:""},{type:"input",name:"extensions",message:"File extensions (comma-separated):",default:".ts,.js"}]);t.paths={workspace:t.paths?.workspace||".",...t.paths,backend:s.path||"."},t.services={...t.services,backend:{port:s.port||8080,startCommand:s.startCommand||void 0,buildCommand:s.buildCommand||void 0,extensions:s.extensions?s.extensions.split(",").map(r=>r.trim()):[".ts",".js"]}},e==="backend"&&(t.tunnel={enabled:!0,port:s.port||8080})}console.log(`
1380
- \u{1F4DA} Tech Stack (optional - helps AI understand your project):`);let{addTechStack:o}=await G.prompt([{type:"confirm",name:"addTechStack",message:"Add tech stack info?",default:!1}]);if(o){let s=await G.prompt([{type:"input",name:"frontend",message:"Frontend technologies (comma-separated, or Enter to skip):",default:""},{type:"input",name:"backend",message:"Backend technologies (comma-separated, or Enter to skip):",default:""},{type:"input",name:"patterns",message:"Patterns/practices (comma-separated, or Enter to skip):",default:""}]);t.techStack={},s.frontend&&(t.techStack.frontend=s.frontend.split(",").map(r=>r.trim())),s.backend&&(t.techStack.backend=s.backend.split(",").map(r=>r.trim())),s.patterns&&(t.techStack.patterns=s.patterns.split(",").map(r=>r.trim()))}return t}function Zt(n){try{let e={},t=n.match(/MASTER_URL=(\S+)/);t&&(e.masterUrl=t[1].trim());let o=n.match(/PROJECT_ID=(\S+)/);o&&(e.projectId=o[1].trim());let s=n.match(/PROJECT_KEY=(\S+)/);return s&&(e.projectKey=s[1].trim()),e.masterUrl&&e.projectId&&e.projectKey?e:null}catch{return null}}async function Kn(n){let e=Bn(n);console.log(`
1380
+ \u{1F4DA} Tech Stack (optional - helps AI understand your project):`);let{addTechStack:o}=await G.prompt([{type:"confirm",name:"addTechStack",message:"Add tech stack info?",default:!1}]);if(o){let s=await G.prompt([{type:"input",name:"frontend",message:"Frontend technologies (comma-separated, or Enter to skip):",default:""},{type:"input",name:"backend",message:"Backend technologies (comma-separated, or Enter to skip):",default:""},{type:"input",name:"patterns",message:"Patterns/practices (comma-separated, or Enter to skip):",default:""}]);t.techStack={},s.frontend&&(t.techStack.frontend=s.frontend.split(",").map(r=>r.trim())),s.backend&&(t.techStack.backend=s.backend.split(",").map(r=>r.trim())),s.patterns&&(t.techStack.patterns=s.patterns.split(",").map(r=>r.trim()))}return t}function tn(n){try{let e={},t=n.match(/MASTER_URL=(\S+)/);t&&(e.masterUrl=t[1].trim());let o=n.match(/PROJECT_ID=(\S+)/);o&&(e.projectId=o[1].trim());let s=n.match(/PROJECT_KEY=(\S+)/);return s&&(e.projectKey=s[1].trim()),e.masterUrl&&e.projectId&&e.projectKey?e:null}catch{return null}}async function Qn(n){let e=Gn(n);console.log(`
1381
1381
  \u{1F3E0} Local SignalR Mode - Jack into the real system
1382
- `);let t=e?.masterUrl&&e?.projectId&&e?.projectKey,{configMethod:o}=await G.prompt([{type:"select",name:"configMethod",message:"How would you like to configure?",choices:[...t?[{name:`Use saved config (${e.projectId})`,value:"saved"}]:[],{name:"Paste config from frontend",value:"paste"},{name:"Enter manually",value:"manual"},{name:"Build project config interactively",value:"interactive"}]}]);if(o==="saved"&&t){let a=Gn(e,n),c=a?.tunnel?.port||e.tunnelPort||5173;return console.log(`
1383
- \u{1F4CB} Using saved configuration:`),console.log(` Master URL: ${e.masterUrl}`),console.log(` Project ID: ${e.projectId}`),console.log(` Project Key: ${e.projectKey.substring(0,16)}...`),console.log(` Container ID: ${e.containerId}`),console.log(` Tunnel: ${e.enableTunnel!==!1?`enabled (port ${c})`:"disabled"}`),a&&console.log(" Project config: embedded in local-signalr-config.json"),{masterUrl:e.masterUrl,projectId:e.projectId,projectKey:e.projectKey,containerId:e.containerId||He(),enableTunnel:e.enableTunnel!==!1,tunnelPort:c,embeddedProjectConfig:a}}if(o==="paste"){let{pastedConfig:a}=await G.prompt([{type:"input",name:"pastedConfig",message:"Paste the config (MASTER_URL=... PROJECT_ID=... PROJECT_KEY=...):",validate:g=>Zt(g)?!0:"Could not parse config. Make sure it contains MASTER_URL=..., PROJECT_ID=..., and PROJECT_KEY=..."}]),c=Zt(a),l=e?.containerId||He(),u=e?.tunnelPort||5173,d={masterUrl:c.masterUrl,projectId:c.projectId,projectKey:c.projectKey,containerId:l,enableTunnel:!0,tunnelPort:u};return console.log(`
1384
- \u{1F4CB} Parsed configuration:`),console.log(` Master URL: ${d.masterUrl}`),console.log(` Project ID: ${d.projectId}`),console.log(` Project Key: ${d.projectKey.substring(0,16)}...`),console.log(` Container ID: ${d.containerId}`),console.log(` Tunnel: enabled (port ${u})`),yt(n,d),{...d,embeddedProjectConfig:null}}if(o==="interactive"){console.log(`
1385
- \u{1F50C} Connection Configuration:`);let a=await G.prompt([{type:"input",name:"masterUrl",message:"Master URL (backend):",default:e?.masterUrl||process.env.MASTER_URL||"http://localhost:5338",validate:g=>{if(!g.trim())return"Master URL is required";try{return new URL(g),!0}catch{return"Please enter a valid URL"}}},{type:"input",name:"projectId",message:"Project ID:",default:e?.projectId||process.env.PROJECT_ID,validate:g=>g.trim()?!0:"Project ID is required"},{type:"password",name:"projectKey",message:"Project Key (pk_proj_...):",mask:"*",default:e?.projectKey||process.env.PROJECT_KEY,validate:g=>g.trim()?g.startsWith("pk_proj_")?!0:"Project Key must start with pk_proj_":"Project Key is required"}]),c=await Wn(n),l=e?.containerId||He(),u=c?.tunnel?.port||e?.tunnelPort||5173,d={masterUrl:a.masterUrl,projectId:a.projectId,projectKey:a.projectKey,containerId:l,enableTunnel:!0,tunnelPort:u,...c&&{version:c.version,paths:c.paths,services:c.services,techStack:c.techStack,tunnel:c.tunnel}};return console.log(`
1386
- \u{1F4CB} Configuration built:`),console.log(` Master URL: ${d.masterUrl}`),console.log(` Project ID: ${d.projectId}`),console.log(` Project Key: ${d.projectKey.substring(0,16)}...`),console.log(` Container ID: ${d.containerId}`),console.log(` Tunnel: enabled (port ${u})`),console.log(c?" Project config: custom stack":" Project config: default .NET/React stack"),yt(n,d),{masterUrl:d.masterUrl,projectId:d.projectId,projectKey:d.projectKey,containerId:d.containerId,enableTunnel:d.enableTunnel,tunnelPort:d.tunnelPort,embeddedProjectConfig:c}}let s=await G.prompt([{type:"input",name:"masterUrl",message:"Master URL (backend):",default:e?.masterUrl||process.env.MASTER_URL||"http://localhost:5338",validate:a=>{if(!a.trim())return"Master URL is required";try{return new URL(a),!0}catch{return"Please enter a valid URL"}}},{type:"input",name:"projectId",message:"Project ID:",default:e?.projectId||process.env.PROJECT_ID,validate:a=>a.trim()?!0:"Project ID is required"},{type:"password",name:"projectKey",message:"Project Key (pk_proj_...):",mask:"*",default:e?.projectKey||process.env.PROJECT_KEY,validate:a=>a.trim()?a.startsWith("pk_proj_")?!0:"Project Key must start with pk_proj_":"Project Key is required"},{type:"input",name:"containerId",message:"Container ID (unique identifier for this agent):",default:e?.containerId||He()},{type:"confirm",name:"enableTunnel",message:"Enable preview URL reporting (report local dev server URL to backend)?",default:e?.enableTunnel!==!1}]),r=e?.tunnelPort||5173;s.enableTunnel&&(r=(await G.prompt([{type:"number",name:"tunnelPort",message:"Preview port (local dev server port to report):",default:r}])).tunnelPort||r);let i={...s,tunnelPort:r};return yt(n,i),{...i,embeddedProjectConfig:null}}async function Yn(){let n=process.env.LOCAL_MODE==="true",e=process.env.WORKSPACE_DIR||process.cwd(),t=Ln();console.log(n?`=== Glenn Code v${t} ===`:`=== SignalR Agent v${t} ===`),console.log(`Workspace: ${e}`),n&&!F.existsSync(V.join(e,".git"))&&console.warn("\u26A0\uFE0F Warning: Not a git repository. Some features may not work.");let o,s,r=!1,i=5173,a=null;if(n){let p=await Kn(e);o={masterUrl:p.masterUrl,containerId:p.containerId,projectKey:p.projectKey,workspaceDir:e,isByok:!0},s=p.projectId,r=p.enableTunnel,i=p.tunnelPort,a=p.embeddedProjectConfig,process.env.PROJECT_ID=p.projectId,process.env.CONTAINER_ID=p.containerId,process.env.PROJECT_KEY=p.projectKey}else{let p=process.env.PROJECT_KEY;p||(console.error("\u274C PROJECT_KEY environment variable is required"),process.exit(1)),o={masterUrl:process.env.MASTER_URL||"http://host.docker.internal:5338",containerId:process.env.CONTAINER_ID||"unknown",projectKey:p,workspaceDir:e}}console.log(`
1387
- \u{1F50C} Connecting to backend...`),console.log(` Container ID: ${o.containerId}`),console.log(` Project Key: ${o.projectKey.substring(0,16)}...`),console.log(` Gateway URL: ${o.masterUrl}`);let c=new Ue(o),l=0,u=10;for(;l<u;)try{await c.connect();break}catch(p){if(l++,console.error(`Connection attempt ${l} failed:`,p instanceof Error?p.message:p),l<u){let C=Math.min(1e3*Math.pow(2,l),3e4);await new Promise(L=>setTimeout(L,C))}}l>=u&&(console.error("\u274C Failed to connect to gateway after max retries"),process.exit(1)),n&&console.log("\u2705 Connected to backend");let d=await c.getSecrets();n?(console.log("\u2705 Handshake complete"),d.gitHubPat&&console.log(" GitHub PAT received from backend")):console.log("\u2705 Secrets received");let g,w=!0,v="default";if(n){if(a)g=a,v="embedded in local-signalr-config.json",w=!1,console.log("[Config] Using embedded project config from local-signalr-config.json");else{let p=await Pe({workspaceDir:o.workspaceDir});g=p.config,v=p.source==="file"?p.configPath||".sdd/project-config.json":"default (no config file)",p.source==="file"&&(w=!1)}w||g.tunnel?.port&&(i=g.tunnel.port)}let A=je({workspaceDir:o.workspaceDir,projectConfig:g});be(A);let D=pe(o.workspaceDir);ce(D);let b=p=>{console.log(`[Planning] Setting up SignalR transport for project ${p}`),D=new Ne(c.getHubProxy(),p),ce(D)};n&&s&&b(s);let f;n?f={prewarmWorkspace:async()=>{console.log("[LocalMode] Skipping prewarm - using existing workspace")},handleInitSession:async p=>{console.log(`[LocalMode] Session init for ${p.sessionId}`),console.log("[LocalMode] Skipping branch switch - using current branch"),await c.reportStatus("Ready",void 0,p.sessionId,p.projectId),await c.getHubProxy().initSessionCompleted(o.containerId,p.sessionId,!0,"")}}:f=new Me(c,A,o.workspaceDir,d.gitHubPat||null);let O=process.env.DISABLE_AUTO_TYPECHECK!=="true",W=process.env.DISABLE_AUTO_COMMIT!=="true"&&!n;n&&g?$n({useDefaultStack:w,projectConfig:g,configSource:v,tunnelPort:i,enableAutoTypecheck:O,enableAutoCommit:W}):(console.log(`[Config] Auto-typecheck: ${O?"enabled":"disabled"}`),console.log(`[Config] Auto-commit: ${W?"enabled":"disabled"}`));let M=new $e(c,f,A,o.workspaceDir,O,W,b,g,w);if(c.registerReceiver(M),n){if(r){let p=`http://localhost:${i}`;c.setTunnelUrl(p),console.log(`
1382
+ `);let t=e?.masterUrl&&e?.projectId&&e?.projectKey,{configMethod:o}=await G.prompt([{type:"select",name:"configMethod",message:"How would you like to configure?",choices:[...t?[{name:`Use saved config (${e.projectId})`,value:"saved"}]:[],{name:"Paste config from frontend",value:"paste"},{name:"Enter manually",value:"manual"},{name:"Build project config interactively",value:"interactive"}]}]);if(o==="saved"&&t){let a=Kn(e,n),c=a?.tunnel?.port||e.tunnelPort||5173;return console.log(`
1383
+ \u{1F4CB} Using saved configuration:`),console.log(` Master URL: ${e.masterUrl}`),console.log(` Project ID: ${e.projectId}`),console.log(` Project Key: ${e.projectKey.substring(0,16)}...`),console.log(` Container ID: ${e.containerId}`),console.log(` Tunnel: ${e.enableTunnel!==!1?`enabled (port ${c})`:"disabled"}`),a&&console.log(" Project config: embedded in local-signalr-config.json"),{masterUrl:e.masterUrl,projectId:e.projectId,projectKey:e.projectKey,containerId:e.containerId||qe(),enableTunnel:e.enableTunnel!==!1,tunnelPort:c,embeddedProjectConfig:a}}if(o==="paste"){let{pastedConfig:a}=await G.prompt([{type:"input",name:"pastedConfig",message:"Paste the config (MASTER_URL=... PROJECT_ID=... PROJECT_KEY=...):",validate:g=>tn(g)?!0:"Could not parse config. Make sure it contains MASTER_URL=..., PROJECT_ID=..., and PROJECT_KEY=..."}]),c=tn(a),l=e?.containerId||qe(),u=e?.tunnelPort||5173,d={masterUrl:c.masterUrl,projectId:c.projectId,projectKey:c.projectKey,containerId:l,enableTunnel:!0,tunnelPort:u};return console.log(`
1384
+ \u{1F4CB} Parsed configuration:`),console.log(` Master URL: ${d.masterUrl}`),console.log(` Project ID: ${d.projectId}`),console.log(` Project Key: ${d.projectKey.substring(0,16)}...`),console.log(` Container ID: ${d.containerId}`),console.log(` Tunnel: enabled (port ${u})`),St(n,d),{...d,embeddedProjectConfig:null}}if(o==="interactive"){console.log(`
1385
+ \u{1F50C} Connection Configuration:`);let a=await G.prompt([{type:"input",name:"masterUrl",message:"Master URL (backend):",default:e?.masterUrl||process.env.MASTER_URL||"http://localhost:5338",validate:g=>{if(!g.trim())return"Master URL is required";try{return new URL(g),!0}catch{return"Please enter a valid URL"}}},{type:"input",name:"projectId",message:"Project ID:",default:e?.projectId||process.env.PROJECT_ID,validate:g=>g.trim()?!0:"Project ID is required"},{type:"password",name:"projectKey",message:"Project Key (pk_proj_...):",mask:"*",default:e?.projectKey||process.env.PROJECT_KEY,validate:g=>g.trim()?g.startsWith("pk_proj_")?!0:"Project Key must start with pk_proj_":"Project Key is required"}]),c=await Yn(n),l=e?.containerId||qe(),u=c?.tunnel?.port||e?.tunnelPort||5173,d={masterUrl:a.masterUrl,projectId:a.projectId,projectKey:a.projectKey,containerId:l,enableTunnel:!0,tunnelPort:u,...c&&{version:c.version,paths:c.paths,services:c.services,techStack:c.techStack,tunnel:c.tunnel}};return console.log(`
1386
+ \u{1F4CB} Configuration built:`),console.log(` Master URL: ${d.masterUrl}`),console.log(` Project ID: ${d.projectId}`),console.log(` Project Key: ${d.projectKey.substring(0,16)}...`),console.log(` Container ID: ${d.containerId}`),console.log(` Tunnel: enabled (port ${u})`),console.log(c?" Project config: custom stack":" Project config: default .NET/React stack"),St(n,d),{masterUrl:d.masterUrl,projectId:d.projectId,projectKey:d.projectKey,containerId:d.containerId,enableTunnel:d.enableTunnel,tunnelPort:d.tunnelPort,embeddedProjectConfig:c}}let s=await G.prompt([{type:"input",name:"masterUrl",message:"Master URL (backend):",default:e?.masterUrl||process.env.MASTER_URL||"http://localhost:5338",validate:a=>{if(!a.trim())return"Master URL is required";try{return new URL(a),!0}catch{return"Please enter a valid URL"}}},{type:"input",name:"projectId",message:"Project ID:",default:e?.projectId||process.env.PROJECT_ID,validate:a=>a.trim()?!0:"Project ID is required"},{type:"password",name:"projectKey",message:"Project Key (pk_proj_...):",mask:"*",default:e?.projectKey||process.env.PROJECT_KEY,validate:a=>a.trim()?a.startsWith("pk_proj_")?!0:"Project Key must start with pk_proj_":"Project Key is required"},{type:"input",name:"containerId",message:"Container ID (unique identifier for this agent):",default:e?.containerId||qe()},{type:"confirm",name:"enableTunnel",message:"Enable preview URL reporting (report local dev server URL to backend)?",default:e?.enableTunnel!==!1}]),r=e?.tunnelPort||5173;s.enableTunnel&&(r=(await G.prompt([{type:"number",name:"tunnelPort",message:"Preview port (local dev server port to report):",default:r}])).tunnelPort||r);let i={...s,tunnelPort:r};return St(n,i),{...i,embeddedProjectConfig:null}}async function Vn(){let n=process.env.LOCAL_MODE==="true",e=process.env.WORKSPACE_DIR||process.cwd(),t=Hn();console.log(n?`=== Glenn Code v${t} ===`:`=== SignalR Agent v${t} ===`),console.log(`Workspace: ${e}`),n&&!M.existsSync(z.join(e,".git"))&&console.warn("\u26A0\uFE0F Warning: Not a git repository. Some features may not work.");let o,s,r=!1,i=5173,a=null;if(n){let p=await Qn(e);o={masterUrl:p.masterUrl,containerId:p.containerId,projectKey:p.projectKey,workspaceDir:e,isByok:!0},s=p.projectId,r=p.enableTunnel,i=p.tunnelPort,a=p.embeddedProjectConfig,process.env.PROJECT_ID=p.projectId,process.env.CONTAINER_ID=p.containerId,process.env.PROJECT_KEY=p.projectKey}else{let p=process.env.PROJECT_KEY;p||(console.error("\u274C PROJECT_KEY environment variable is required"),process.exit(1)),o={masterUrl:process.env.MASTER_URL||"http://host.docker.internal:5338",containerId:process.env.CONTAINER_ID||"unknown",projectKey:p,workspaceDir:e}}console.log(`
1387
+ \u{1F50C} Connecting to backend...`),console.log(` Container ID: ${o.containerId}`),console.log(` Project Key: ${o.projectKey.substring(0,16)}...`),console.log(` Gateway URL: ${o.masterUrl}`);let c=new Ue(o),l=0,u=10;for(;l<u;)try{await c.connect();break}catch(p){if(l++,console.error(`Connection attempt ${l} failed:`,p instanceof Error?p.message:p),l<u){let C=Math.min(1e3*Math.pow(2,l),3e4);await new Promise(L=>setTimeout(L,C))}}l>=u&&(console.error("\u274C Failed to connect to gateway after max retries"),process.exit(1)),n&&console.log("\u2705 Connected to backend");let d=await c.getSecrets();n?(console.log("\u2705 Handshake complete"),d.gitHubPat&&console.log(" GitHub PAT received from backend")):console.log("\u2705 Secrets received");let g,w=!0,v="default";if(n){if(a)g=a,v="embedded in local-signalr-config.json",w=!1,console.log("[Config] Using embedded project config from local-signalr-config.json");else{let p=await Te({workspaceDir:o.workspaceDir});g=p.config,v=p.source==="file"?p.configPath||".sdd/project-config.json":"default (no config file)",p.source==="file"&&(w=!1)}w||g.tunnel?.port&&(i=g.tunnel.port)}let A=Oe({workspaceDir:o.workspaceDir,projectConfig:g});Se(A);let D=de(o.workspaceDir);le(D);let b=p=>{console.log(`[Planning] Setting up SignalR transport for project ${p}`),D=new Me(c.getHubProxy(),p),le(D)};n&&s&&b(s);let f;n?f={prewarmWorkspace:async()=>{console.log("[LocalMode] Skipping prewarm - using existing workspace")},handleInitSession:async p=>{console.log(`[LocalMode] Session init for ${p.sessionId}`),console.log("[LocalMode] Skipping branch switch - using current branch"),await c.reportStatus("Ready",void 0,p.sessionId,p.projectId),await c.getHubProxy().initSessionCompleted(o.containerId,p.sessionId,!0,"")}}:f=new Le(c,A,o.workspaceDir,d.gitHubPat||null);let O=process.env.DISABLE_AUTO_TYPECHECK!=="true",W=process.env.DISABLE_AUTO_COMMIT!=="true"&&!n;n&&g?Bn({useDefaultStack:w,projectConfig:g,configSource:v,tunnelPort:i,enableAutoTypecheck:O,enableAutoCommit:W}):(console.log(`[Config] Auto-typecheck: ${O?"enabled":"disabled"}`),console.log(`[Config] Auto-commit: ${W?"enabled":"disabled"}`));let F=new He(c,f,A,o.workspaceDir,O,W,b,g,w);if(c.registerReceiver(F),n){if(r){let p=`http://localhost:${i}`;c.setTunnelUrl(p),console.log(`
1388
1388
  \u{1F310} Preview available at: ${p}`)}await c.reportStatus("Ready",void 0,void 0,s),console.log(`
1389
1389
  \u2705 Agent ready and waiting for commands`),console.log(` Open the frontend and select this agent to start working
1390
1390
  `),console.log(` Press Ctrl+C to disconnect
1391
1391
  `),c.startHeartbeat(3e4),process.on("SIGINT",async()=>{console.log(`
1392
- \u{1F44B} Disconnecting...`),c.stopHeartbeat(),await c.reportStatus("Error"),process.exit(0)})}else{let p=process.env.SESSION_ID,C=process.env.PROJECT_ID;await c.reportStatus("Initiating",void 0,p,C);try{await f.prewarmWorkspace()}catch(L){let ae=L instanceof Error?L.message:String(L),fe=L instanceof Error?L.stack:void 0;throw await c.reportError({message:`Container initialization failed: ${ae}`,stackTrace:fe,errorType:"ContainerInitError",operation:"prewarmWorkspace",sessionId:p,isFatal:!0}),await c.reportStatus("Error",ae,p,C),L}await c.reportStatus("WarmedUp",void 0,p,C),console.log("\u2705 Agent initialized, waiting for InitSession"),console.log(` Session: ${p||"none"}`),console.log(` Repo: ${process.env.REPO_URL?"configured":"NOT SET"}`)}}import.meta.url===`file://${process.argv[1]}`&&Yn().catch(n=>{console.error("Fatal error:",n),process.exit(1)});export{Yn as startSignalRAgent};
1392
+ \u{1F44B} Disconnecting...`),c.stopHeartbeat(),await c.reportStatus("Error"),process.exit(0)})}else{let p=process.env.SESSION_ID,C=process.env.PROJECT_ID;await c.reportStatus("Initiating",void 0,p,C);try{await f.prewarmWorkspace()}catch(L){let ce=L instanceof Error?L.message:String(L),me=L instanceof Error?L.stack:void 0;throw await c.reportError({message:`Container initialization failed: ${ce}`,stackTrace:me,errorType:"ContainerInitError",operation:"prewarmWorkspace",sessionId:p,isFatal:!0}),await c.reportStatus("Error",ce,p,C),L}await c.reportStatus("WarmedUp",void 0,p,C),console.log("\u2705 Agent initialized, waiting for InitSession"),console.log(` Session: ${p||"none"}`),console.log(` Repo: ${process.env.REPO_URL?"configured":"NOT SET"}`)}}import.meta.url===`file://${process.argv[1]}`&&Vn().catch(n=>{console.error("Fatal error:",n),process.exit(1)});export{Vn as startSignalRAgent};